diff --git a/HBC/META.XML b/HBC/META.XML index e50ebdb1..67f1eed1 100644 --- a/HBC/META.XML +++ b/HBC/META.XML @@ -2,8 +2,8 @@ USB Loader GX USB Loader GX Team - 1.0 r961 - 201009222057 + 1.0 r962 + 201009232353 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/FontSystem.cpp b/source/FontSystem.cpp index 66b12ca0..aeb82a88 100644 --- a/source/FontSystem.cpp +++ b/source/FontSystem.cpp @@ -27,55 +27,52 @@ #include "filelist.h" FreeTypeGX * fontSystem = NULL; -static FT_Byte * MainFont = ( FT_Byte * ) font_ttf; +static FT_Byte * MainFont = (FT_Byte *) font_ttf; static u32 MainFontSize = font_ttf_size; void ClearFontData() { - if ( fontSystem ) - delete fontSystem; + if (fontSystem) delete fontSystem; fontSystem = NULL; - if ( MainFont != ( FT_Byte * ) font_ttf ) + if (MainFont != (FT_Byte *) font_ttf) { - if ( MainFont != NULL ) - delete [] MainFont; - MainFont = ( FT_Byte * ) font_ttf; + if (MainFont != NULL) delete[] MainFont; + MainFont = (FT_Byte *) font_ttf; MainFontSize = font_ttf_size; } } -bool SetupDefaultFont( const char *path ) +bool SetupDefaultFont(const char *path) { bool result = false; FILE *pfile = NULL; ClearFontData(); - if ( path ) - pfile = fopen( path, "rb" ); + if (path) pfile = fopen(path, "rb"); - if ( pfile ) + if (pfile) { - fseek( pfile, 0, SEEK_END ); - MainFontSize = ftell( pfile ); - rewind( pfile ); + fseek(pfile, 0, SEEK_END); + MainFontSize = ftell(pfile); + rewind(pfile); - MainFont = new ( std::nothrow ) FT_Byte[MainFontSize]; - if ( !MainFont ) + MainFont = new (std::nothrow) FT_Byte[MainFontSize]; + if (!MainFont) { - MainFont = ( FT_Byte * ) font_ttf; + MainFont = (FT_Byte *) font_ttf; MainFontSize = font_ttf_size; } else { - fread( MainFont, 1, MainFontSize, pfile ); + fread(MainFont, 1, MainFontSize, pfile); result = true; } - fclose( pfile ); + fclose(pfile); } - fontSystem = new FreeTypeGX( MainFont, MainFontSize ); + fontSystem = new FreeTypeGX(MainFont, MainFontSize); return result; } diff --git a/source/FontSystem.h b/source/FontSystem.h index 9bd679f4..e68b43a9 100644 --- a/source/FontSystem.h +++ b/source/FontSystem.h @@ -26,7 +26,7 @@ #ifndef FONTSYSTEM_H_ #define FONTSYSTEM_H_ -bool SetupDefaultFont( const char *path ); +bool SetupDefaultFont(const char *path); void ClearFontData(); #endif diff --git a/source/FreeTypeGX.cpp b/source/FreeTypeGX.cpp index 317674ca..6dd2a95a 100644 --- a/source/FreeTypeGX.cpp +++ b/source/FreeTypeGX.cpp @@ -34,24 +34,23 @@ using namespace std; * @return Wide character representation of supplied character string. */ -wchar_t* charToWideChar( const char* strChar ) +wchar_t* charToWideChar(const char* strChar) { - if ( !strChar ) - return NULL; + if (!strChar) return NULL; - wchar_t *strWChar = new ( std::nothrow ) wchar_t[strlen( strChar ) + 1]; - if ( !strWChar ) - return NULL; + wchar_t *strWChar = new (std::nothrow) wchar_t[strlen(strChar) + 1]; + if (!strWChar) return NULL; - int bt = mbstowcs( strWChar, strChar, strlen( strChar ) ); - if ( bt > 0 ) + int bt = mbstowcs(strWChar, strChar, strlen(strChar)); + if (bt > 0) { strWChar[bt] = 0; return strWChar; } wchar_t *tempDest = strWChar; - while ( ( *tempDest++ = *strChar++ ) ); + while ((*tempDest++ = *strChar++)) + ; return strWChar; } @@ -59,14 +58,14 @@ wchar_t* charToWideChar( const char* strChar ) /** * Default constructor for the FreeTypeGX class for WiiXplorer. */ -FreeTypeGX::FreeTypeGX( const uint8_t* fontBuffer, FT_Long bufferSize ) +FreeTypeGX::FreeTypeGX(const uint8_t* fontBuffer, FT_Long bufferSize) { ftPointSize = 0; - FT_Init_FreeType( &ftLibrary ); - FT_New_Memory_Face( ftLibrary, ( FT_Byte * )fontBuffer, bufferSize, 0, &ftFace ); + FT_Init_FreeType(&ftLibrary); + FT_New_Memory_Face(ftLibrary, (FT_Byte *) fontBuffer, bufferSize, 0, &ftFace); - setVertexFormat( GX_VTXFMT1 ); + setVertexFormat(GX_VTXFMT1); ftKerningEnabled = FT_HAS_KERNING( ftFace ); } @@ -76,8 +75,8 @@ FreeTypeGX::FreeTypeGX( const uint8_t* fontBuffer, FT_Long bufferSize ) FreeTypeGX::~FreeTypeGX() { unloadFont(); - FT_Done_Face( ftFace ); - FT_Done_FreeType( ftLibrary ); + FT_Done_Face(ftFace); + FT_Done_FreeType(ftLibrary); } /** @@ -88,13 +87,13 @@ FreeTypeGX::~FreeTypeGX() * vertex format index is modified. * * @param vertexIndex Vertex format index (GX_VTXFMT*) of the glyph textures as defined by the libogc gx.h header file. -*/ -void FreeTypeGX::setVertexFormat( uint8_t vertexInd ) + */ +void FreeTypeGX::setVertexFormat(uint8_t vertexInd) { vertexIndex = vertexInd; - GX_SetVtxAttrFmt( vertexIndex, GX_VA_POS, GX_POS_XYZ, GX_S16, 0 ); - GX_SetVtxAttrFmt( vertexIndex, GX_VA_TEX0, GX_TEX_ST, GX_F32, 0 ); - GX_SetVtxAttrFmt( vertexIndex, GX_VA_CLR0, GX_CLR_RGBA, GX_RGBA8, 0 ); + GX_SetVtxAttrFmt(vertexIndex, GX_VA_POS, GX_POS_XYZ, GX_S16, 0); + GX_SetVtxAttrFmt(vertexIndex, GX_VA_TEX0, GX_TEX_ST, GX_F32, 0); + GX_SetVtxAttrFmt(vertexIndex, GX_VA_CLR0, GX_CLR_RGBA, GX_RGBA8, 0); } /** @@ -104,16 +103,15 @@ void FreeTypeGX::setVertexFormat( uint8_t vertexInd ) */ void FreeTypeGX::unloadFont() { - if ( this->fontData.size() == 0 ) - return; + if (this->fontData.size() == 0) return; map >::iterator itr; map::iterator itr2; - for ( itr = fontData.begin(); itr != fontData.end(); itr++ ) + for (itr = fontData.begin(); itr != fontData.end(); itr++) { - for ( itr2 = itr->second.begin(); itr2 != itr->second.end(); itr2++ ) - free( itr2->second.glyphDataTexture ); + for (itr2 = itr->second.begin(); itr2 != itr->second.end(); itr2++) + free(itr2->second.glyphDataTexture); itr->second.clear(); } @@ -131,17 +129,17 @@ void FreeTypeGX::unloadFont() * @param charCode The requested glyph's character code. * @return A pointer to the allocated font structure. */ -ftgxCharData * FreeTypeGX::cacheGlyphData( wchar_t charCode, int16_t pixelSize ) +ftgxCharData * FreeTypeGX::cacheGlyphData(wchar_t charCode, int16_t pixelSize) { map >::iterator itr; map::iterator itr2; - itr = fontData.find( pixelSize ); - if ( itr != fontData.end() ) + itr = fontData.find(pixelSize); + if (itr != fontData.end()) { - itr2 = itr->second.find( charCode ); + itr2 = itr->second.find(charCode); - if ( itr2 != itr->second.end() ) + if (itr2 != itr->second.end()) { return &itr2->second; } @@ -150,43 +148,43 @@ ftgxCharData * FreeTypeGX::cacheGlyphData( wchar_t charCode, int16_t pixelSize ) FT_UInt gIndex; uint16_t textureWidth = 0, textureHeight = 0; - if ( ftPointSize != pixelSize ) + if (ftPointSize != pixelSize) { ftPointSize = pixelSize; - FT_Set_Pixel_Sizes( ftFace, 0, ftPointSize ); + FT_Set_Pixel_Sizes(ftFace, 0, ftPointSize); //!Cache ascender and decender as well - map::iterator itrAlign = ftgxAlign.find( ftPointSize ); - if ( itrAlign == ftgxAlign.end() ) + map::iterator itrAlign = ftgxAlign.find(ftPointSize); + if (itrAlign == ftgxAlign.end()) { - ftgxAlign[ftPointSize].ascender = ( int16_t ) ftFace->size->metrics.ascender >> 6; - ftgxAlign[ftPointSize].descender = ( int16_t ) ftFace->size->metrics.descender >> 6; + ftgxAlign[ftPointSize].ascender = (int16_t) ftFace->size->metrics.ascender >> 6; + ftgxAlign[ftPointSize].descender = (int16_t) ftFace->size->metrics.descender >> 6; ftgxAlign[ftPointSize].max = 0; ftgxAlign[ftPointSize].min = 0; } } - gIndex = FT_Get_Char_Index( ftFace, ( FT_ULong ) charCode ); - if ( gIndex != 0 && FT_Load_Glyph( ftFace, gIndex, FT_LOAD_DEFAULT | FT_LOAD_RENDER ) == 0 ) + gIndex = FT_Get_Char_Index(ftFace, (FT_ULong) charCode); + if (gIndex != 0 && FT_Load_Glyph(ftFace, gIndex, FT_LOAD_DEFAULT | FT_LOAD_RENDER) == 0) { - if ( ftFace->glyph->format == FT_GLYPH_FORMAT_BITMAP ) + if (ftFace->glyph->format == FT_GLYPH_FORMAT_BITMAP) { FT_Bitmap *glyphBitmap = &ftFace->glyph->bitmap; - textureWidth = glyphBitmap->width + ( 4 - glyphBitmap->width % 4 ) % 4; - textureHeight = glyphBitmap->rows + ( 4 - glyphBitmap->rows % 4 ) % 4; + textureWidth = glyphBitmap->width + (4 - glyphBitmap->width % 4) % 4; + textureHeight = glyphBitmap->rows + (4 - glyphBitmap->rows % 4) % 4; - fontData[pixelSize][charCode].renderOffsetX = ( int16_t ) ftFace->glyph->bitmap_left; - fontData[pixelSize][charCode].glyphAdvanceX = ( uint16_t ) ( ftFace->glyph->advance.x >> 6 ); - fontData[pixelSize][charCode].glyphIndex = ( uint32_t ) gIndex; - fontData[pixelSize][charCode].textureWidth = ( uint16_t ) textureWidth; - fontData[pixelSize][charCode].textureHeight = ( uint16_t ) textureHeight; - fontData[pixelSize][charCode].renderOffsetY = ( int16_t ) ftFace->glyph->bitmap_top; - fontData[pixelSize][charCode].renderOffsetMax = ( int16_t ) ftFace->glyph->bitmap_top; - fontData[pixelSize][charCode].renderOffsetMin = ( int16_t ) glyphBitmap->rows - ftFace->glyph->bitmap_top; + fontData[pixelSize][charCode].renderOffsetX = (int16_t) ftFace->glyph->bitmap_left; + fontData[pixelSize][charCode].glyphAdvanceX = (uint16_t) (ftFace->glyph->advance.x >> 6); + fontData[pixelSize][charCode].glyphIndex = (uint32_t) gIndex; + fontData[pixelSize][charCode].textureWidth = (uint16_t) textureWidth; + fontData[pixelSize][charCode].textureHeight = (uint16_t) textureHeight; + fontData[pixelSize][charCode].renderOffsetY = (int16_t) ftFace->glyph->bitmap_top; + fontData[pixelSize][charCode].renderOffsetMax = (int16_t) ftFace->glyph->bitmap_top; + fontData[pixelSize][charCode].renderOffsetMin = (int16_t) glyphBitmap->rows - ftFace->glyph->bitmap_top; fontData[pixelSize][charCode].glyphDataTexture = NULL; - loadGlyphData( glyphBitmap, &fontData[pixelSize][charCode] ); + loadGlyphData(glyphBitmap, &fontData[pixelSize][charCode]); return &fontData[pixelSize][charCode]; } @@ -200,19 +198,18 @@ ftgxCharData * FreeTypeGX::cacheGlyphData( wchar_t charCode, int16_t pixelSize ) * This routine locates each character in the configured font face and renders the glyph's bitmap. * Each bitmap and relevant information is loaded into its own quickly addressible structure within an instance-specific map. */ -uint16_t FreeTypeGX::cacheGlyphDataComplete( int16_t pixelSize ) +uint16_t FreeTypeGX::cacheGlyphDataComplete(int16_t pixelSize) { uint32_t i = 0; FT_UInt gIndex; - FT_ULong charCode = FT_Get_First_Char( ftFace, &gIndex ); - while ( gIndex != 0 ) + FT_ULong charCode = FT_Get_First_Char(ftFace, &gIndex); + while (gIndex != 0) { - if ( cacheGlyphData( charCode, pixelSize ) != NULL ) - ++i; - charCode = FT_Get_Next_Char( ftFace, charCode, &gIndex ); + if (cacheGlyphData(charCode, pixelSize) != NULL) ++i; + charCode = FT_Get_Next_Char(ftFace, charCode, &gIndex); } - return ( uint16_t )( i ); + return (uint16_t) (i); } /** @@ -227,32 +224,32 @@ uint16_t FreeTypeGX::cacheGlyphDataComplete( int16_t pixelSize ) * * Optimized for RGBA8 use by Dimok. */ -void FreeTypeGX::loadGlyphData( FT_Bitmap *bmp, ftgxCharData *charData ) +void FreeTypeGX::loadGlyphData(FT_Bitmap *bmp, ftgxCharData *charData) { - int length = ( ( ( ( charData->textureWidth + 3 ) >> 2 ) * ( ( charData->textureHeight + 3 ) >> 2 ) * 32 * 2 + 31 ) & ~31 ); + int length = ((((charData->textureWidth + 3) >> 2) * ((charData->textureHeight + 3) >> 2) * 32 * 2 + 31) & ~31); - uint8_t * glyphData = ( uint8_t * ) memalign( 32, length ); - if ( !glyphData ) - return; + uint8_t * glyphData = (uint8_t *) memalign(32, length); + if (!glyphData) return; - memset( glyphData, 0x00, length ); + memset(glyphData, 0x00, length); - uint8_t *src = ( uint8_t * )bmp->buffer; + uint8_t *src = (uint8_t *) bmp->buffer; uint32_t offset; - for ( int imagePosY = 0; imagePosY < bmp->rows; ++imagePosY ) + for (int imagePosY = 0; imagePosY < bmp->rows; ++imagePosY) { - for ( int imagePosX = 0; imagePosX < bmp->width; ++imagePosX ) + for (int imagePosX = 0; imagePosX < bmp->width; ++imagePosX) { - offset = ( ( ( ( imagePosY >> 2 ) * ( charData->textureWidth >> 2 ) + ( imagePosX >> 2 ) ) << 5 ) + ( ( imagePosY & 3 ) << 2 ) + ( imagePosX & 3 ) ) << 1; + offset = ((((imagePosY >> 2) * (charData->textureWidth >> 2) + (imagePosX >> 2)) << 5) + ((imagePosY & 3) + << 2) + (imagePosX & 3)) << 1; glyphData[offset] = *src; - glyphData[offset+1] = *src; - glyphData[offset+32] = *src; - glyphData[offset+33] = *src; + glyphData[offset + 1] = *src; + glyphData[offset + 32] = *src; + glyphData[offset + 33] = *src; ++src; } } - DCFlushRange( glyphData, length ); + DCFlushRange(glyphData, length); charData->glyphDataTexture = glyphData; } @@ -265,14 +262,13 @@ void FreeTypeGX::loadGlyphData( FT_Bitmap *bmp, ftgxCharData *charData ) * @param width Current pixel width of the string. * @param format Positional format of the string. */ -int16_t FreeTypeGX::getStyleOffsetWidth( uint16_t width, uint16_t format ) +int16_t FreeTypeGX::getStyleOffsetWidth(uint16_t width, uint16_t format) { - if ( format & FTGX_JUSTIFY_LEFT ) + if (format & FTGX_JUSTIFY_LEFT) return 0; - else if ( format & FTGX_JUSTIFY_CENTER ) - return -( width >> 1 ); - else if ( format & FTGX_JUSTIFY_RIGHT ) - return -width; + else if (format & FTGX_JUSTIFY_CENTER) + return -(width >> 1); + else if (format & FTGX_JUSTIFY_RIGHT) return -width; return 0; } @@ -284,20 +280,19 @@ int16_t FreeTypeGX::getStyleOffsetWidth( uint16_t width, uint16_t format ) * @param offset Current pixel offset data of the string. * @param format Positional format of the string. */ -int16_t FreeTypeGX::getStyleOffsetHeight( int16_t format, uint16_t pixelSize ) +int16_t FreeTypeGX::getStyleOffsetHeight(int16_t format, uint16_t pixelSize) { - map::iterator itrAlign = ftgxAlign.find( pixelSize ); - if ( itrAlign == ftgxAlign.end() ) - return 0; + map::iterator itrAlign = ftgxAlign.find(pixelSize); + if (itrAlign == ftgxAlign.end()) return 0; - switch ( format & FTGX_ALIGN_MASK ) + switch (format & FTGX_ALIGN_MASK) { case FTGX_ALIGN_TOP: return itrAlign->second.ascender; case FTGX_ALIGN_MIDDLE: default: - return ( itrAlign->second.ascender + itrAlign->second.descender + 1 ) >> 1; + return (itrAlign->second.ascender + itrAlign->second.descender + 1) >> 1; case FTGX_ALIGN_BOTTOM: return itrAlign->second.descender; @@ -309,7 +304,7 @@ int16_t FreeTypeGX::getStyleOffsetHeight( int16_t format, uint16_t pixelSize ) return itrAlign->second.max; case FTGX_ALIGN_GLYPH_MIDDLE: - return ( itrAlign->second.max + itrAlign->second.min + 1 ) >> 1; + return (itrAlign->second.max + itrAlign->second.min + 1) >> 1; case FTGX_ALIGN_GLYPH_BOTTOM: return itrAlign->second.min; @@ -330,45 +325,47 @@ int16_t FreeTypeGX::getStyleOffsetHeight( int16_t format, uint16_t pixelSize ) * @param textStyle Flags which specify any styling which should be applied to the rendered string. * @return The number of characters printed. */ -uint16_t FreeTypeGX::drawText( int16_t x, int16_t y, int16_t z, const wchar_t *text, int16_t pixelSize, GXColor color, uint16_t textStyle, uint16_t textWidth, uint16_t widthLimit ) +uint16_t FreeTypeGX::drawText(int16_t x, int16_t y, int16_t z, const wchar_t *text, int16_t pixelSize, GXColor color, + uint16_t textStyle, uint16_t textWidth, uint16_t widthLimit) { - if ( !text ) - return 0; + if (!text) return 0; - uint16_t fullTextWidth = textWidth > 0 ? textWidth : getWidth( text, pixelSize ); + uint16_t fullTextWidth = textWidth > 0 ? textWidth : getWidth(text, pixelSize); uint16_t x_pos = x, printed = 0; uint16_t x_offset = 0, y_offset = 0; GXTexObj glyphTexture; FT_Vector pairDelta; - if ( textStyle & FTGX_JUSTIFY_MASK ) + if (textStyle & FTGX_JUSTIFY_MASK) { - x_offset = getStyleOffsetWidth( fullTextWidth, textStyle ); + x_offset = getStyleOffsetWidth(fullTextWidth, textStyle); } - if ( textStyle & FTGX_ALIGN_MASK ) + if (textStyle & FTGX_ALIGN_MASK) { - y_offset = getStyleOffsetHeight( textStyle, pixelSize ); + y_offset = getStyleOffsetHeight(textStyle, pixelSize); } int i = 0; - while ( text[i] ) + while (text[i]) { - if ( widthLimit > 0 && ( x_pos - x ) > widthLimit ) - break; + if (widthLimit > 0 && (x_pos - x) > widthLimit) break; - ftgxCharData* glyphData = cacheGlyphData( text[i], pixelSize ); + ftgxCharData* glyphData = cacheGlyphData(text[i], pixelSize); - if ( glyphData != NULL ) + if (glyphData != NULL) { - if ( ftKerningEnabled && i > 0 ) + if (ftKerningEnabled && i > 0) { - FT_Get_Kerning( ftFace, fontData[pixelSize][text[i - 1]].glyphIndex, glyphData->glyphIndex, FT_KERNING_DEFAULT, &pairDelta ); + FT_Get_Kerning(ftFace, fontData[pixelSize][text[i - 1]].glyphIndex, glyphData->glyphIndex, + FT_KERNING_DEFAULT, &pairDelta); x_pos += pairDelta.x >> 6; } - GX_InitTexObj( &glyphTexture, glyphData->glyphDataTexture, glyphData->textureWidth, glyphData->textureHeight, GX_TF_RGBA8, GX_CLAMP, GX_CLAMP, GX_FALSE ); - copyTextureToFramebuffer( &glyphTexture, glyphData->textureWidth, glyphData->textureHeight, x_pos + glyphData->renderOffsetX + x_offset, y - glyphData->renderOffsetY + y_offset, z, color ); + GX_InitTexObj(&glyphTexture, glyphData->glyphDataTexture, glyphData->textureWidth, + glyphData->textureHeight, GX_TF_RGBA8, GX_CLAMP, GX_CLAMP, GX_FALSE); + copyTextureToFramebuffer(&glyphTexture, glyphData->textureWidth, glyphData->textureHeight, x_pos + + glyphData->renderOffsetX + x_offset, y - glyphData->renderOffsetY + y_offset, z, color); x_pos += glyphData->glyphAdvanceX; ++printed; @@ -376,24 +373,25 @@ uint16_t FreeTypeGX::drawText( int16_t x, int16_t y, int16_t z, const wchar_t *t ++i; } - if ( textStyle & FTGX_STYLE_MASK ) + if (textStyle & FTGX_STYLE_MASK) { - getOffset( text, pixelSize, widthLimit ); - drawTextFeature( x + x_offset, y + y_offset, z, pixelSize, fullTextWidth, &ftgxAlign[pixelSize], textStyle, color ); + getOffset(text, pixelSize, widthLimit); + drawTextFeature(x + x_offset, y + y_offset, z, pixelSize, fullTextWidth, &ftgxAlign[pixelSize], textStyle, + color); } return printed; } -void FreeTypeGX::drawTextFeature( int16_t x, int16_t y, int16_t z, int16_t pixelSize, uint16_t width, ftgxDataOffset *offsetData, uint16_t format, GXColor color ) +void FreeTypeGX::drawTextFeature(int16_t x, int16_t y, int16_t z, int16_t pixelSize, uint16_t width, + ftgxDataOffset *offsetData, uint16_t format, GXColor color) { uint16_t featureHeight = pixelSize >> 4 > 0 ? pixelSize >> 4 : 1; - if ( format & FTGX_STYLE_UNDERLINE ) - this->copyFeatureToFramebuffer( width, featureHeight, x, y + 1, z, color ); + if (format & FTGX_STYLE_UNDERLINE) this->copyFeatureToFramebuffer(width, featureHeight, x, y + 1, z, color); - if ( format & FTGX_STYLE_STRIKE ) - this->copyFeatureToFramebuffer( width, featureHeight, x, y - ( ( offsetData->max ) >> 1 ), z, color ); + if (format & FTGX_STYLE_STRIKE) this->copyFeatureToFramebuffer(width, featureHeight, x, y + - ((offsetData->max) >> 1), z, color); } /** @@ -405,24 +403,24 @@ void FreeTypeGX::drawTextFeature( int16_t x, int16_t y, int16_t z, int16_t pixel * @param text NULL terminated string to calculate. * @return The width of the text string in pixels. */ -uint16_t FreeTypeGX::getWidth( const wchar_t *text, int16_t pixelSize ) +uint16_t FreeTypeGX::getWidth(const wchar_t *text, int16_t pixelSize) { - if ( !text ) - return 0; + if (!text) return 0; uint16_t strWidth = 0; FT_Vector pairDelta; int i = 0; - while ( text[i] ) + while (text[i]) { - ftgxCharData* glyphData = cacheGlyphData( text[i], pixelSize ); + ftgxCharData* glyphData = cacheGlyphData(text[i], pixelSize); - if ( glyphData != NULL ) + if (glyphData != NULL) { - if ( ftKerningEnabled && ( i > 0 ) ) + if (ftKerningEnabled && (i > 0)) { - FT_Get_Kerning( ftFace, fontData[pixelSize][text[i - 1]].glyphIndex, glyphData->glyphIndex, FT_KERNING_DEFAULT, &pairDelta ); + FT_Get_Kerning(ftFace, fontData[pixelSize][text[i - 1]].glyphIndex, glyphData->glyphIndex, + FT_KERNING_DEFAULT, &pairDelta); strWidth += pairDelta.x >> 6; } @@ -435,18 +433,19 @@ uint16_t FreeTypeGX::getWidth( const wchar_t *text, int16_t pixelSize ) /** * Single char width -*/ -uint16_t FreeTypeGX::getCharWidth( const wchar_t wChar, int16_t pixelSize, const wchar_t prevChar ) + */ +uint16_t FreeTypeGX::getCharWidth(const wchar_t wChar, int16_t pixelSize, const wchar_t prevChar) { uint16_t strWidth = 0; - ftgxCharData * glyphData = cacheGlyphData( wChar, pixelSize ); + ftgxCharData * glyphData = cacheGlyphData(wChar, pixelSize); - if ( glyphData != NULL ) + if (glyphData != NULL) { - if ( ftKerningEnabled && prevChar != 0x0000 ) + if (ftKerningEnabled && prevChar != 0x0000) { FT_Vector pairDelta; - FT_Get_Kerning( ftFace, fontData[pixelSize][prevChar].glyphIndex, glyphData->glyphIndex, FT_KERNING_DEFAULT, &pairDelta ); + FT_Get_Kerning(ftFace, fontData[pixelSize][prevChar].glyphIndex, glyphData->glyphIndex, FT_KERNING_DEFAULT, + &pairDelta); strWidth += pairDelta.x >> 6; } strWidth += glyphData->glyphAdvanceX; @@ -464,9 +463,9 @@ uint16_t FreeTypeGX::getCharWidth( const wchar_t wChar, int16_t pixelSize, const * @param text NULL terminated string to calculate. * @return The height of the text string in pixels. */ -uint16_t FreeTypeGX::getHeight( const wchar_t *text, int16_t pixelSize ) +uint16_t FreeTypeGX::getHeight(const wchar_t *text, int16_t pixelSize) { - getOffset( text, pixelSize ); + getOffset(text, pixelSize); return ftgxAlign[pixelSize].max - ftgxAlign[pixelSize].min; } @@ -481,24 +480,22 @@ uint16_t FreeTypeGX::getHeight( const wchar_t *text, int16_t pixelSize ) * @param offset returns the max and min values above and below the font origin line * */ -void FreeTypeGX::getOffset( const wchar_t *text, int16_t pixelSize, uint16_t widthLimit ) +void FreeTypeGX::getOffset(const wchar_t *text, int16_t pixelSize, uint16_t widthLimit) { - if ( ftgxAlign.find( pixelSize ) != ftgxAlign.end() ) - return; + if (ftgxAlign.find(pixelSize) != ftgxAlign.end()) return; int16_t strMax = 0, strMin = 9999; uint16_t currWidth = 0; int i = 0; - while ( text[i] ) + while (text[i]) { - if ( widthLimit > 0 && currWidth >= widthLimit ) - break; + if (widthLimit > 0 && currWidth >= widthLimit) break; - ftgxCharData* glyphData = cacheGlyphData( text[i], pixelSize ); + ftgxCharData* glyphData = cacheGlyphData(text[i], pixelSize); - if ( glyphData != NULL ) + if (glyphData != NULL) { strMax = glyphData->renderOffsetMax > strMax ? glyphData->renderOffsetMax : strMax; strMin = glyphData->renderOffsetMin < strMin ? glyphData->renderOffsetMin : strMin; @@ -508,10 +505,10 @@ void FreeTypeGX::getOffset( const wchar_t *text, int16_t pixelSize, uint16_t wid ++i; } - if ( ftPointSize != pixelSize ) + if (ftPointSize != pixelSize) { ftPointSize = pixelSize; - FT_Set_Pixel_Sizes( ftFace, 0, ftPointSize ); + FT_Set_Pixel_Sizes(ftFace, 0, ftPointSize); } ftgxAlign[pixelSize].ascender = ftFace->size->metrics.ascender >> 6; @@ -532,34 +529,35 @@ void FreeTypeGX::getOffset( const wchar_t *text, int16_t pixelSize, uint16_t wid * @param screenY The screen Y coordinate at which to output the rendered texture. * @param color Color to apply to the texture. */ -void FreeTypeGX::copyTextureToFramebuffer( GXTexObj *texObj, f32 texWidth, f32 texHeight, int16_t screenX, int16_t screenY, int16_t screenZ, GXColor color ) +void FreeTypeGX::copyTextureToFramebuffer(GXTexObj *texObj, f32 texWidth, f32 texHeight, int16_t screenX, + int16_t screenY, int16_t screenZ, GXColor color) { - GX_LoadTexObj( texObj, GX_TEXMAP0 ); + GX_LoadTexObj(texObj, GX_TEXMAP0); GX_InvalidateTexAll(); - GX_SetTevOp ( GX_TEVSTAGE0, GX_MODULATE ); - GX_SetVtxDesc ( GX_VA_TEX0, GX_DIRECT ); + GX_SetTevOp(GX_TEVSTAGE0, GX_MODULATE); + GX_SetVtxDesc(GX_VA_TEX0, GX_DIRECT); - GX_Begin( GX_QUADS, this->vertexIndex, 4 ); - GX_Position3s16( screenX, screenY, screenZ ); - GX_Color4u8( color.r, color.g, color.b, color.a ); - GX_TexCoord2f32( 0.0f, 0.0f ); + GX_Begin(GX_QUADS, this->vertexIndex, 4); + GX_Position3s16(screenX, screenY, screenZ); + GX_Color4u8(color.r, color.g, color.b, color.a); + GX_TexCoord2f32(0.0f, 0.0f); - GX_Position3s16( texWidth + screenX, screenY, screenZ ); - GX_Color4u8( color.r, color.g, color.b, color.a ); - GX_TexCoord2f32( 1.0f, 0.0f ); + GX_Position3s16(texWidth + screenX, screenY, screenZ); + GX_Color4u8(color.r, color.g, color.b, color.a); + GX_TexCoord2f32(1.0f, 0.0f); - GX_Position3s16( texWidth + screenX, texHeight + screenY, screenZ ); - GX_Color4u8( color.r, color.g, color.b, color.a ); - GX_TexCoord2f32( 1.0f, 1.0f ); + GX_Position3s16(texWidth + screenX, texHeight + screenY, screenZ); + GX_Color4u8(color.r, color.g, color.b, color.a); + GX_TexCoord2f32(1.0f, 1.0f); - GX_Position3s16( screenX, texHeight + screenY, screenZ ); - GX_Color4u8( color.r, color.g, color.b, color.a ); - GX_TexCoord2f32( 0.0f, 1.0f ); + GX_Position3s16(screenX, texHeight + screenY, screenZ); + GX_Color4u8(color.r, color.g, color.b, color.a); + GX_TexCoord2f32(0.0f, 1.0f); GX_End(); - GX_SetTevOp( GX_TEVSTAGE0, GX_PASSCLR ); - GX_SetVtxDesc( GX_VA_TEX0, GX_NONE ); + GX_SetTevOp(GX_TEVSTAGE0, GX_PASSCLR); + GX_SetVtxDesc(GX_VA_TEX0, GX_NONE); } /** @@ -573,25 +571,26 @@ void FreeTypeGX::copyTextureToFramebuffer( GXTexObj *texObj, f32 texWidth, f32 t * @param screenY The screen Y coordinate at which to output the quad. * @param color Color to apply to the texture. */ -void FreeTypeGX::copyFeatureToFramebuffer( f32 featureWidth, f32 featureHeight, int16_t screenX, int16_t screenY, int16_t screenZ, GXColor color ) +void FreeTypeGX::copyFeatureToFramebuffer(f32 featureWidth, f32 featureHeight, int16_t screenX, int16_t screenY, + int16_t screenZ, GXColor color) { - GX_SetTevOp ( GX_TEVSTAGE0, GX_PASSCLR ); - GX_SetVtxDesc ( GX_VA_TEX0, GX_NONE ); + GX_SetTevOp(GX_TEVSTAGE0, GX_PASSCLR); + GX_SetVtxDesc(GX_VA_TEX0, GX_NONE); - GX_Begin( GX_QUADS, this->vertexIndex, 4 ); - GX_Position3s16( screenX, screenY, screenZ ); - GX_Color4u8( color.r, color.g, color.b, color.a ); + GX_Begin(GX_QUADS, this->vertexIndex, 4); + GX_Position3s16(screenX, screenY, screenZ); + GX_Color4u8(color.r, color.g, color.b, color.a); - GX_Position3s16( featureWidth + screenX, screenY, screenZ ); - GX_Color4u8( color.r, color.g, color.b, color.a ); + GX_Position3s16(featureWidth + screenX, screenY, screenZ); + GX_Color4u8(color.r, color.g, color.b, color.a); - GX_Position3s16( featureWidth + screenX, featureHeight + screenY, screenZ ); - GX_Color4u8( color.r, color.g, color.b, color.a ); + GX_Position3s16(featureWidth + screenX, featureHeight + screenY, screenZ); + GX_Color4u8(color.r, color.g, color.b, color.a); - GX_Position3s16( screenX, featureHeight + screenY, screenZ ); - GX_Color4u8( color.r, color.g, color.b, color.a ); + GX_Position3s16(screenX, featureHeight + screenY, screenZ); + GX_Color4u8(color.r, color.g, color.b, color.a); GX_End(); - GX_SetTevOp( GX_TEVSTAGE0, GX_PASSCLR ); - GX_SetVtxDesc( GX_VA_TEX0, GX_NONE ); + GX_SetTevOp(GX_TEVSTAGE0, GX_PASSCLR); + GX_SetVtxDesc(GX_VA_TEX0, GX_NONE); } diff --git a/source/FreeTypeGX.h b/source/FreeTypeGX.h index 6c639a99..7b50215d 100644 --- a/source/FreeTypeGX.h +++ b/source/FreeTypeGX.h @@ -39,18 +39,18 @@ */ typedef struct ftgxCharData_ { - int16_t renderOffsetX; /**< Texture X axis bearing offset. */ - uint16_t glyphAdvanceX; /**< Character glyph X coordinate advance in pixels. */ - uint32_t glyphIndex; /**< Charachter glyph index in the font face. */ + int16_t renderOffsetX; /**< Texture X axis bearing offset. */ + uint16_t glyphAdvanceX; /**< Character glyph X coordinate advance in pixels. */ + uint32_t glyphIndex; /**< Charachter glyph index in the font face. */ - uint16_t textureWidth; /**< Texture width in pixels/bytes. */ - uint16_t textureHeight; /**< Texture glyph height in pixels/bytes. */ + uint16_t textureWidth; /**< Texture width in pixels/bytes. */ + uint16_t textureHeight; /**< Texture glyph height in pixels/bytes. */ - int16_t renderOffsetY; /**< Texture Y axis bearing offset. */ - int16_t renderOffsetMax; /**< Texture Y axis bearing maximum value. */ - int16_t renderOffsetMin; /**< Texture Y axis bearing minimum value. */ + int16_t renderOffsetY; /**< Texture Y axis bearing offset. */ + int16_t renderOffsetMax; /**< Texture Y axis bearing maximum value. */ + int16_t renderOffsetMin; /**< Texture Y axis bearing minimum value. */ - uint8_t* glyphDataTexture; /**< Glyph texture bitmap data buffer. */ + uint8_t* glyphDataTexture; /**< Glyph texture bitmap data buffer. */ } ftgxCharData; /*! \struct ftgxDataOffset_ @@ -59,10 +59,10 @@ typedef struct ftgxCharData_ */ typedef struct ftgxDataOffset_ { - int16_t ascender; /**< Maximum data offset. */ - int16_t descender; /**< Minimum data offset. */ - int16_t max; /**< Maximum data offset. */ - int16_t min; /**< Minimum data offset. */ + int16_t ascender; /**< Maximum data offset. */ + int16_t descender; /**< Minimum data offset. */ + int16_t max; /**< Maximum data offset. */ + int16_t min; /**< Minimum data offset. */ } ftgxDataOffset; typedef struct ftgxCharData_ ftgxCharData; @@ -89,9 +89,10 @@ typedef struct ftgxDataOffset_ ftgxDataOffset; #define FTGX_STYLE_STRIKE 0x2000 #define FTGX_STYLE_MASK 0xf000 -const GXColor ftgxWhite = ( GXColor ) {0xff, 0xff, 0xff, 0xff}; /**< Constant color value used only to sanitize Doxygen documentation. */ +const GXColor ftgxWhite = ( GXColor ) +{ 0xff, 0xff, 0xff, 0xff}; /**< Constant color value used only to sanitize Doxygen documentation. */ -wchar_t* charToWideChar( const char* p ); +wchar_t* charToWideChar(const char* p); /*! \class FreeTypeGX * \brief Wrapper class for the libFreeType library with GX rendering. @@ -105,40 +106,44 @@ wchar_t* charToWideChar( const char* p ); class FreeTypeGX { private: - FT_Library ftLibrary; /**< FreeType FT_Library instance. */ - FT_Face ftFace; /**< FreeType reusable FT_Face typographic object. */ - int16_t ftPointSize; /**< Current set size of the rendered font. */ - bool ftKerningEnabled; /**< Flag indicating the availability of font kerning data. */ - uint8_t vertexIndex; /**< Vertex format descriptor index. */ + FT_Library ftLibrary; /**< FreeType FT_Library instance. */ + FT_Face ftFace; /**< FreeType reusable FT_Face typographic object. */ + int16_t ftPointSize; /**< Current set size of the rendered font. */ + bool ftKerningEnabled; /**< Flag indicating the availability of font kerning data. */ + uint8_t vertexIndex; /**< Vertex format descriptor index. */ std::map > fontData; /**< Map which holds the glyph data structures for the corresponding characters in one size. */ std::map ftgxAlign; /**< Map which holds the ascender and decender for different sizes. */ - int16_t getStyleOffsetWidth( uint16_t width, uint16_t format ); - int16_t getStyleOffsetHeight( int16_t format, uint16_t pixelSize ); + int16_t getStyleOffsetWidth(uint16_t width, uint16_t format); + int16_t getStyleOffsetHeight(int16_t format, uint16_t pixelSize); void unloadFont(); - ftgxCharData *cacheGlyphData( wchar_t charCode, int16_t pixelSize ); - uint16_t cacheGlyphDataComplete( int16_t pixelSize ); - void loadGlyphData( FT_Bitmap *bmp, ftgxCharData *charData ); + ftgxCharData *cacheGlyphData(wchar_t charCode, int16_t pixelSize); + uint16_t cacheGlyphDataComplete(int16_t pixelSize); + void loadGlyphData(FT_Bitmap *bmp, ftgxCharData *charData); void setDefaultMode(); - void drawTextFeature( int16_t x, int16_t y, int16_t z, int16_t pixelSize, uint16_t width, ftgxDataOffset *offsetData, uint16_t format, GXColor color ); - void copyTextureToFramebuffer( GXTexObj *texObj, f32 texWidth, f32 texHeight, int16_t screenX, int16_t screenY, int16_t screenZ, GXColor color ); - void copyFeatureToFramebuffer( f32 featureWidth, f32 featureHeight, int16_t screenX, int16_t screenY, int16_t screenZ, GXColor color ); + void drawTextFeature(int16_t x, int16_t y, int16_t z, int16_t pixelSize, uint16_t width, + ftgxDataOffset *offsetData, uint16_t format, GXColor color); + void copyTextureToFramebuffer(GXTexObj *texObj, f32 texWidth, f32 texHeight, int16_t screenX, int16_t screenY, + int16_t screenZ, GXColor color); + void copyFeatureToFramebuffer(f32 featureWidth, f32 featureHeight, int16_t screenX, int16_t screenY, + int16_t screenZ, GXColor color); public: - FreeTypeGX( const uint8_t* fontBuffer, FT_Long bufferSize ); + FreeTypeGX(const uint8_t* fontBuffer, FT_Long bufferSize); ~FreeTypeGX(); - void setVertexFormat( uint8_t vertexIndex ); + void setVertexFormat(uint8_t vertexIndex); - uint16_t drawText( int16_t x, int16_t y, int16_t z, const wchar_t *text, int16_t pixelSize, GXColor color = ftgxWhite, uint16_t textStyling = FTGX_NULL, uint16_t textWidth = 0, uint16_t widthLimit = 0 ); + uint16_t drawText(int16_t x, int16_t y, int16_t z, const wchar_t *text, int16_t pixelSize, GXColor color = + ftgxWhite, uint16_t textStyling = FTGX_NULL, uint16_t textWidth = 0, uint16_t widthLimit = 0); - uint16_t getWidth( const wchar_t *text, int16_t pixelSize ); - uint16_t getCharWidth( const wchar_t wChar, int16_t pixelSize, const wchar_t prevChar = 0x0000 ); - uint16_t getHeight( const wchar_t *text, int16_t pixelSize ); - void getOffset( const wchar_t *text, int16_t pixelSize, uint16_t widthLimit = 0 ); + uint16_t getWidth(const wchar_t *text, int16_t pixelSize); + uint16_t getCharWidth(const wchar_t wChar, int16_t pixelSize, const wchar_t prevChar = 0x0000); + uint16_t getHeight(const wchar_t *text, int16_t pixelSize); + void getOffset(const wchar_t *text, int16_t pixelSize, uint16_t widthLimit = 0); }; #endif /* FREETYPEGX_H_ */ diff --git a/source/ZipFile.cpp b/source/ZipFile.cpp index 8e093249..86521aac 100644 --- a/source/ZipFile.cpp +++ b/source/ZipFile.cpp @@ -39,16 +39,15 @@ #include "ZipFile.h" #include "language/gettext.h" -ZipFile::ZipFile( const char *filepath ) +ZipFile::ZipFile(const char *filepath) { - File = unzOpen( filepath ); - if ( File ) - this->LoadList(); + File = unzOpen(filepath); + if (File) this->LoadList(); } ZipFile::~ZipFile() { - unzClose( File ); + unzClose(File); } bool ZipFile::LoadList() @@ -56,83 +55,76 @@ bool ZipFile::LoadList() return true; } -bool ZipFile::ExtractAll( const char *dest ) +bool ZipFile::ExtractAll(const char *dest) { - if ( !File ) - return false; + if (!File) return false; bool Stop = false; u32 blocksize = 1024 * 50; u8 *buffer = new u8[blocksize]; - if ( !buffer ) - return false; + if (!buffer) return false; char writepath[MAXPATHLEN]; char filename[MAXPATHLEN]; - memset( filename, 0, sizeof( filename ) ); + memset(filename, 0, sizeof(filename)); - int ret = unzGoToFirstFile( File ); - if ( ret != UNZ_OK ) - Stop = true; + int ret = unzGoToFirstFile(File); + if (ret != UNZ_OK) Stop = true; - while ( !Stop ) + while (!Stop) { - if ( unzGetCurrentFileInfo( File, &cur_file_info, filename, sizeof( filename ), NULL, NULL, NULL, NULL ) != UNZ_OK ) - Stop = true; + 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; char *pointer = NULL; - ret = unzOpenCurrentFile( File ); + ret = unzOpenCurrentFile(File); - snprintf( writepath, sizeof( writepath ), "%s/%s", dest, filename ); + snprintf(writepath, sizeof(writepath), "%s/%s", dest, filename); - pointer = strrchr( writepath, '/' ); + pointer = strrchr(writepath, '/'); int position = pointer - writepath + 2; - char temppath[strlen( writepath )]; - snprintf( temppath, position, "%s", writepath ); + char temppath[strlen(writepath)]; + snprintf(temppath, position, "%s", writepath); - subfoldercreate( temppath ); + subfoldercreate(temppath); - if ( ret == UNZ_OK ) + if (ret == UNZ_OK) { - FILE *pfile = fopen( writepath, "wb" ); + FILE *pfile = fopen(writepath, "wb"); do { - ShowProgress( tr( "Extracting files..." ), 0, pointer + 1, done, uncompressed_size ); + ShowProgress(tr( "Extracting files..." ), 0, pointer + 1, done, uncompressed_size); - if ( uncompressed_size - done < blocksize ) - blocksize = uncompressed_size - done; + if (uncompressed_size - done < blocksize) blocksize = uncompressed_size - done; - ret = unzReadCurrentFile( File, buffer, blocksize ); + ret = unzReadCurrentFile(File, buffer, blocksize); - if ( ret == 0 ) - break; + if (ret == 0) break; - fwrite( buffer, 1, blocksize, pfile ); + fwrite(buffer, 1, blocksize, pfile); done += ret; - } - while ( done < uncompressed_size ); + } while (done < uncompressed_size); - fclose( pfile ); - unzCloseCurrentFile( File ); + fclose(pfile); + unzCloseCurrentFile(File); } } - if ( unzGoToNextFile( File ) != UNZ_OK ) - Stop = true; + if (unzGoToNextFile(File) != UNZ_OK) Stop = true; } - delete [] buffer; + delete[] buffer; buffer = NULL; ProgressStop(); diff --git a/source/ZipFile.h b/source/ZipFile.h index 302aa77a..1bb29b18 100644 --- a/source/ZipFile.h +++ b/source/ZipFile.h @@ -32,22 +32,22 @@ 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 + 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 ); + 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 ); + bool ExtractAll(const char *dest); protected: bool LoadList(); unzFile File; diff --git a/source/audio.cpp b/source/audio.cpp index 0a2431ef..e1e3acae 100644 --- a/source/audio.cpp +++ b/source/audio.cpp @@ -17,9 +17,9 @@ ***************************************************************************/ void InitAudio() { - AUDIO_Init( NULL ); + AUDIO_Init(NULL); ASND_Init(); - ASND_Pause( 0 ); + ASND_Pause(0); } /**************************************************************************** @@ -30,6 +30,6 @@ void InitAudio() ***************************************************************************/ void ShutdownAudio() { - ASND_Pause( 1 ); + ASND_Pause(1); ASND_End(); } diff --git a/source/banner/MD5.c b/source/banner/MD5.c index 4c0b98c7..c672db10 100644 --- a/source/banner/MD5.c +++ b/source/banner/MD5.c @@ -86,7 +86,6 @@ #include "MD5.h" - /* -------------------------------------------------------------------------- ** * Static Constants: * @@ -110,46 +109,34 @@ * array. They're divided up into four groups of 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 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] = -{ - { 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 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] = { { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, /* Round 1 */ +0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, + 0xa679438e, 0x49b40821 }, -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 }, +{ 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, /* Round 2 */ +0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, + 0x676f02d9, 0x8d2a4c8a }, - { 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, /* Round 2 */ - 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, - 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, - 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a }, - - { 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, /* Round 3 */ - 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, - 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, - 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665 }, - - { 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, /* Round 4 */ - 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, - 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, - 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }, -}; +{ 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, /* Round 3 */ +0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, + 0x1fa27cf8, 0xc4ac5665 }, +{ 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, /* Round 4 */ +0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, + 0x2ad7d2bb, 0xeb86d391 }, }; /* -------------------------------------------------------------------------- ** * Macros: @@ -172,12 +159,11 @@ static const uint32_t T[4][16] = #define STR2HEX(x) ((x >= 0x30) && (x <= 0x39)) ? x - 0x30 : toupper((int)x)-0x37 - /* -------------------------------------------------------------------------- ** * Static Functions: */ -static void Permute( uint32_t ABCD[4], const unsigned char block[64] ) +static void Permute(uint32_t ABCD[4], const unsigned char block[64]) /* ------------------------------------------------------------------------ ** * Permute the ABCD "registers" using the 64-byte as a driver. * @@ -211,28 +197,28 @@ static void Permute( uint32_t ABCD[4], const unsigned char block[64] ) * ------------------------------------------------------------------------ ** */ { - int round; - int i, j; - uint8_t s; + 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++ ) + 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++ ) + 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 ); + 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. @@ -249,21 +235,21 @@ static void Permute( uint32_t ABCD[4], const unsigned char block[64] ) * (My implementation appears to be a poor compromise between speed, size, * and clarity. Ugh. [crh]) */ - for ( round = 0; round < 4; round++ ) + for (round = 0; round < 4; round++) { - for ( i = 0; i < 16; i++ ) + 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. */ + 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 ) + switch (round) { case 0: /* round 1 */ @@ -271,36 +257,35 @@ static void Permute( uint32_t ABCD[4], const unsigned char block[64] ) break; case 1: /* round 2 */ - a = md5G( b, c, d ) + X[ K[0][i] ]; + a = md5G( b, c, d ) + X[K[0][i]]; break; case 2: /* round 3 */ - a = md5H( b, c, d ) + X[ K[1][i] ]; + a = md5H( b, c, d ) + X[K[1][i]]; break; default: /* round 4 */ - a = md5I( b, c, d ) + X[ K[2][i] ]; + 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 ) ) ) ); + 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] ); + for (i = 0; i < 4; i++) + ABCD[i] = 0xFFFFFFFF & (ABCD[i] + KeepABCD[i]); } /* Permute */ - /* -------------------------------------------------------------------------- ** * Functions: */ -auth_md5Ctx *auth_md5InitCtx( auth_md5Ctx *ctx ) +auth_md5Ctx *auth_md5InitCtx(auth_md5Ctx *ctx) /* ------------------------------------------------------------------------ ** * Initialize an MD5 context. * @@ -329,13 +314,13 @@ auth_md5Ctx *auth_md5InitCtx( auth_md5Ctx *ctx ) * ------------------------------------------------------------------------ ** */ { - ctx->len = 0; - ctx->b_used = 0; + 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 */ + 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 */ @@ -344,13 +329,10 @@ auth_md5Ctx *auth_md5InitCtx( auth_md5Ctx *ctx ) /* 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 ); + return (ctx); } /* auth_md5InitCtx */ - -auth_md5Ctx *auth_md5SumCtx( auth_md5Ctx *ctx, - const unsigned char *src, - const int len ) +auth_md5Ctx *auth_md5SumCtx(auth_md5Ctx *ctx, const unsigned char *src, const int len) /* ------------------------------------------------------------------------ ** * Build an MD5 Message Digest within the given context. * @@ -371,29 +353,28 @@ auth_md5Ctx *auth_md5SumCtx( auth_md5Ctx *ctx, /* Add the new block's length to the total length. */ - ctx->len += ( uint32_t )len; + 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++ ) + for (i = 0; i < len; i++) { - ctx->block[ ctx->b_used ] = src[i]; - ( ctx->b_used )++; - if ( 64 == ctx->b_used ) + ctx->block[ctx->b_used] = src[i]; + (ctx->b_used)++; + if (64 == ctx->b_used) { - Permute( ctx->ABCD, ctx->block ); + Permute(ctx->ABCD, ctx->block); ctx->b_used = 0; } } /* Return the updated context. */ - return( ctx ); + return (ctx); } /* auth_md5SumCtx */ - -auth_md5Ctx *auth_md5CloseCtx( auth_md5Ctx *ctx, unsigned char *dst ) +auth_md5Ctx *auth_md5CloseCtx(auth_md5Ctx *ctx, unsigned char *dst) /* ------------------------------------------------------------------------ ** * Close an MD5 Message Digest context and generate the final MD5 sum. * @@ -413,7 +394,7 @@ auth_md5Ctx *auth_md5CloseCtx( auth_md5Ctx *ctx, unsigned char *dst ) * ------------------------------------------------------------------------ ** */ { - int i; + int i; uint32_t l; /* Add the required 0x80 padding initiator byte. @@ -422,20 +403,20 @@ auth_md5Ctx *auth_md5CloseCtx( auth_md5Ctx *ctx, unsigned char *dst ) * free byte in the context block. */ ctx->block[ctx->b_used] = 0x80; - ( ctx->b_used )++; + (ctx->b_used)++; /* Zero out any remaining free bytes in the context block. */ - for ( i = ctx->b_used; i < 64; i++ ) + 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 ) + if (56 < ctx->b_used) { - Permute( ctx->ABCD, ctx->block ); - for ( i = 0; i < 64; i++ ) + Permute(ctx->ABCD, ctx->block); + for (i = 0; i < 64; i++) ctx->block[i] = 0; } @@ -445,29 +426,28 @@ auth_md5Ctx *auth_md5CloseCtx( auth_md5Ctx *ctx, unsigned char *dst ) * 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 ); + 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++ ) + 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 ); + 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 ); + return (ctx); } /* auth_md5CloseCtx */ - -unsigned char * MD5( unsigned char *dst, const unsigned char *src, const int len ) +unsigned char * MD5(unsigned char *dst, const unsigned char *src, const int len) /* ------------------------------------------------------------------------ ** * Compute an MD5 message digest. * @@ -503,16 +483,14 @@ unsigned char * MD5( unsigned char *dst, const unsigned char *src, const int len { 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. */ + (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. */ + return (dst); /* Makes life easy. */ } /* auth_md5Sum */ - - -unsigned char * MD5fromFile( unsigned char *dst, const char *src ) +unsigned char * MD5fromFile(unsigned char *dst, const char *src) /* ------------------------------------------------------------------------ ** * Compute an MD5 message digest. * @@ -550,58 +528,55 @@ unsigned char * MD5fromFile( unsigned char *dst, const char *src ) unsigned int blksize = 0; unsigned int read = 0; - file = fopen( src, "rb" ); + file = fopen(src, "rb"); - if ( file == NULL ) + if (file == NULL) { return NULL; } - ( void )auth_md5InitCtx( ctx ); /* Open a context. */ + (void) auth_md5InitCtx(ctx); /* Open a context. */ - fseek ( file , 0 , SEEK_END ); - unsigned long long filesize = ftell( file ); - rewind ( file ); + fseek(file, 0, SEEK_END); + unsigned long long filesize = ftell(file); + rewind(file); - if ( filesize < 1048576 ) //1MB cache for files bigger than 1 MB + if (filesize < 1048576) //1MB cache for files bigger than 1 MB blksize = filesize; - else - blksize = 1048576; + else blksize = 1048576; - unsigned char * buffer = malloc( blksize ); + unsigned char * buffer = malloc(blksize); - if ( buffer == NULL ) + if (buffer == NULL) { //no memory - fclose( file ); + fclose(file); return NULL; } do { - read = fread( buffer, 1, blksize, file ); - ( void )auth_md5SumCtx( ctx, buffer, read ); /* Pass only one block. */ + read = fread(buffer, 1, blksize, file); + (void) auth_md5SumCtx(ctx, buffer, read); /* Pass only one block. */ - } - while ( read > 0 ); + } while (read > 0); - fclose( file ); - free( buffer ); + fclose(file); + free(buffer); - ( void )auth_md5CloseCtx( ctx, dst ); /* Close the context. */ + (void) auth_md5CloseCtx(ctx, dst); /* Close the context. */ - return( dst ); /* Makes life easy. */ + return (dst); /* Makes life easy. */ } /* auth_md5Sum */ - -const char * MD5ToString( const unsigned char * hash, char * dst ) +const char * MD5ToString(const unsigned char * hash, char * dst) { char hexchar[3]; short i = 0, n = 0; - for ( i = 0; i < 16; i++ ) + for (i = 0; i < 16; i++) { - sprintf( hexchar, "%02X", hash[i] ); + sprintf(hexchar, "%02X", hash[i]); dst[n++] = hexchar[0]; dst[n++] = hexchar[1]; @@ -612,12 +587,12 @@ const char * MD5ToString( const unsigned char * hash, char * dst ) return dst; } -unsigned char * StringToMD5( const char * hash, unsigned char * dst ) +unsigned char * StringToMD5(const char * hash, unsigned char * dst) { char hexchar[2]; short i = 0, n = 0; - for ( i = 0; i < 16; i++ ) + for (i = 0; i < 16; i++) { hexchar[0] = hash[n++]; hexchar[1] = hash[n++]; @@ -630,5 +605,4 @@ unsigned char * StringToMD5( const char * hash, unsigned char * dst ) return dst; } - /* ========================================================================== */ diff --git a/source/banner/MD5.h b/source/banner/MD5.h index df4d9e6b..1faa9fa0 100644 --- a/source/banner/MD5.h +++ b/source/banner/MD5.h @@ -5,242 +5,237 @@ 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; - - - /* -------------------------------------------------------------------------- ** - * 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_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: , - * - * ------------------------------------------------------------------------ ** - */ - - - 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: - * - * ------------------------------------------------------------------------ ** - */ - - const char * MD5ToString( const unsigned char *hash, char *dst ); - unsigned char * StringToMD5( const char * hash, unsigned char * dst ); - - /* ========================================================================== */ - -#ifdef __cplusplus -} -#endif -#endif /* AUTH_MD5_H */ + * 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; + + /* -------------------------------------------------------------------------- ** + * 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_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: , + * + * ------------------------------------------------------------------------ ** + */ + + 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: + * + * ------------------------------------------------------------------------ ** + */ + + const char * MD5ToString(const unsigned char *hash, char *dst); + unsigned char * StringToMD5(const char * hash, unsigned char * dst); + +/* ========================================================================== */ + +#ifdef __cplusplus +} +#endif +#endif /* AUTH_MD5_H */ diff --git a/source/banner/banner.c b/source/banner/banner.c index e7ce9dca..dc098d6d 100644 --- a/source/banner/banner.c +++ b/source/banner/banner.c @@ -22,106 +22,102 @@ #include "patches/fst.h" #include "usbloader/fstfile.h" -s32 dump_banner( const u8* discid, const char * dest ) +s32 dump_banner(const u8* discid, const char * dest) { // Mount the disc //Disc_SetWBFS(1, (u8*)discid); - Disc_SetUSB( discid ); + Disc_SetUSB(discid); Disc_Open(); 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 ) + 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 ); + u32 *buffer = memalign(32, 0x20); - if ( buffer == NULL ) + 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; + void *fstbuffer = memalign(32, buffer[2] * 4); + FST_ENTRY *fst = (FST_ENTRY *) fstbuffer; - if ( fst == NULL ) + if (fst == NULL) { //Out of memory - free( buffer ); + 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; - for ( i = 1; i < count; i++ ) + for (i = 1; i < count; i++) { - if ( strstr( fstfiles( fst, i ), "opening.bnr" ) != NULL ) + if (strstr(fstfiles(fst, i), "opening.bnr") != NULL) { index = i; } } - if ( index == 0 ) + if (index == 0) { //opening.bnr not found - free( fstbuffer ); + free(fstbuffer); return -1; } // Load the .bnr - u8 *banner = memalign( 32, fst[index].filelen ); + u8 *banner = memalign(32, fst[index].filelen); - if ( banner == NULL ) + if (banner == NULL) { //Out of memory - free( fstbuffer ); + free(fstbuffer); return -1; } - ret = WDVD_Read( ( void * )banner, fst[index].filelen, fst[index].fileoffset * 4 ); - if ( ret < 0 ) - return ret; + ret = WDVD_Read((void *) banner, fst[index].filelen, fst[index].fileoffset * 4); + if (ret < 0) return ret; WDVD_Reset(); WDVD_ClosePartition(); //fatInitDefault(); //SDCard_Init(); - WDVD_SetUSBMode( NULL, 0 ); - FILE *fp = fopen( dest, "wb" ); - if ( fp ) + WDVD_SetUSBMode(NULL, 0); + FILE *fp = fopen(dest, "wb"); + if (fp) { - fwrite( banner, 1, fst[index].filelen, fp ); - fclose( fp ); + fwrite(banner, 1, fst[index].filelen, fp); + fclose(fp); } - free( fstbuffer ); - free( banner ); + free(fstbuffer); + free(banner); return 1; } diff --git a/source/banner/banner.h b/source/banner/banner.h index df7e67cb..2fe2e7c7 100644 --- a/source/banner/banner.h +++ b/source/banner/banner.h @@ -13,7 +13,7 @@ extern "C" { #endif - s32 dump_banner( const u8 *discid, const char * dest ); + s32 dump_banner(const u8 *discid, const char * dest); #ifdef __cplusplus } diff --git a/source/banner/gui_banner.cpp b/source/banner/gui_banner.cpp index 2e7ffb54..200d5095 100644 --- a/source/banner/gui_banner.cpp +++ b/source/banner/gui_banner.cpp @@ -6,118 +6,117 @@ ***************************************************************************/ #include "gui_banner.h" -GuiBanner::GuiBanner( const char *tplfilepath ) +GuiBanner::GuiBanner(const char *tplfilepath) { memory = NULL; tplfilesize = 0; - width = 0; - height = 0; - - FILE *tplfp = fopen( tplfilepath, "rb" ); - - if ( tplfp != NULL ) - { - - unsigned short heighttemp = 0; - unsigned short widthtemp = 0; - - fseek( tplfp , 0x14, SEEK_SET ); - fread( ( void* )&heighttemp, 1, 2, tplfp ); - fread( ( void* )&widthtemp, 1, 2, tplfp ); - fseek ( tplfp , 0 , SEEK_END ); - tplfilesize = ftell ( tplfp ); - rewind ( tplfp ); - memory = memalign( 32, tplfilesize ); - if ( !memory ) - { - fclose( tplfp ); - return; - } - fread( memory, 1, tplfilesize, tplfp ); - fclose( tplfp ); - - TPLFile tplfile; - int ret; - - ret = TPL_OpenTPLFromMemory( &tplfile, memory, tplfilesize ); - if ( ret < 0 ) - { - free( memory ); - memory = NULL; - return; - } - ret = TPL_GetTexture( &tplfile, 0, &texObj ); - if ( ret < 0 ) - { - free( memory ); - memory = NULL; - return; - } - TPL_CloseTPLFile( &tplfile ); - - width = widthtemp; - height = heighttemp; - widescreen = 0; - filecheck = true; - - } - else - { - filecheck = false; - fclose( tplfp ); - } -} - -GuiBanner::GuiBanner( void *mem, u32 len, int w, int h ) -{ - if ( !mem || !len ) - return; - memory = mem; - tplfilesize = len; - width = w; - height = h; - - TPLFile tplfile; - - int ret; - - ret = TPL_OpenTPLFromMemory( &tplfile, memory, tplfilesize ); - if ( ret < 0 ) - { - free( memory ); - memory = NULL; - return; - } - ret = TPL_GetTexture( &tplfile, 0, &texObj ); - if ( ret < 0 ) - { - free( memory ); - memory = NULL; - return; - } - TPL_CloseTPLFile( &tplfile ); - - filecheck = true; -} - -GuiBanner::~GuiBanner() -{ - if ( memory != NULL ) - { - free( memory ); - memory = NULL; - } -} - -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(); -} + width = 0; + height = 0; + + FILE *tplfp = fopen(tplfilepath, "rb"); + + if (tplfp != NULL) + { + + unsigned short heighttemp = 0; + unsigned short widthtemp = 0; + + fseek(tplfp, 0x14, SEEK_SET); + fread((void*) &heighttemp, 1, 2, tplfp); + fread((void*) &widthtemp, 1, 2, tplfp); + fseek(tplfp, 0, SEEK_END); + tplfilesize = ftell(tplfp); + rewind(tplfp); + memory = memalign(32, tplfilesize); + if (!memory) + { + fclose(tplfp); + return; + } + fread(memory, 1, tplfilesize, tplfp); + fclose(tplfp); + + TPLFile tplfile; + int ret; + + ret = TPL_OpenTPLFromMemory(&tplfile, memory, tplfilesize); + if (ret < 0) + { + free(memory); + memory = NULL; + return; + } + ret = TPL_GetTexture(&tplfile, 0, &texObj); + if (ret < 0) + { + free(memory); + memory = NULL; + return; + } + TPL_CloseTPLFile(&tplfile); + + width = widthtemp; + height = heighttemp; + widescreen = 0; + filecheck = true; + + } + else + { + filecheck = false; + fclose(tplfp); + } +} + +GuiBanner::GuiBanner(void *mem, u32 len, int w, int h) +{ + if (!mem || !len) return; + memory = mem; + tplfilesize = len; + width = w; + height = h; + + TPLFile tplfile; + + int ret; + + ret = TPL_OpenTPLFromMemory(&tplfile, memory, tplfilesize); + if (ret < 0) + { + free(memory); + memory = NULL; + return; + } + ret = TPL_GetTexture(&tplfile, 0, &texObj); + if (ret < 0) + { + free(memory); + memory = NULL; + return; + } + TPL_CloseTPLFile(&tplfile); + + filecheck = true; +} + +GuiBanner::~GuiBanner() +{ + if (memory != NULL) + { + free(memory); + memory = NULL; + } +} + +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(); +} diff --git a/source/banner/gui_banner.h b/source/banner/gui_banner.h index 85dfd5af..42a9cb67 100644 --- a/source/banner/gui_banner.h +++ b/source/banner/gui_banner.h @@ -10,18 +10,18 @@ #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(); diff --git a/source/banner/openingbnr.c b/source/banner/openingbnr.c index 5edc1545..083c8bba 100644 --- a/source/banner/openingbnr.c +++ b/source/banner/openingbnr.c @@ -28,55 +28,54 @@ #include "../ramdisk/ramdisk.h" #include "../listfiles.h" -u16 be16( const u8 *p ) +u16 be16(const u8 *p) { - return ( p[0] << 8 ) | p[1]; + return (p[0] << 8) | p[1]; } -u32 be32( const u8 *p ) +u32 be32(const u8 *p) { - return ( p[0] << 24 ) | ( p[1] << 16 ) | ( p[2] << 8 ) | p[3]; + return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; } -u64 be64( const u8 *p ) +u64 be64(const u8 *p) { - return ( ( u64 )be32( p ) << 32 ) | be32( p + 4 ); + return ((u64) be32(p) << 32) | be32(p + 4); } -u64 be34( const u8 *p ) +u64 be34(const u8 *p) { - return 4 * ( u64 )be32( p ); + return 4 * (u64) be32(p); } -void wbe16( u8 *p, u16 x ) +void wbe16(u8 *p, u16 x) { p[0] = x >> 8; p[1] = x; } -void wbe32( u8 *p, u32 x ) +void wbe32(u8 *p, u32 x) { - wbe16( p, x >> 16 ); - wbe16( p + 2, x ); + wbe16(p, x >> 16); + wbe16(p + 2, x); } -void wbe64( u8 *p, u64 x ) +void wbe64(u8 *p, u64 x) { - wbe32( p, x >> 32 ); - wbe32( p + 4, x ); + wbe32(p, x >> 32); + wbe32(p + 4, x); } -void md5( u8 *data, u32 len, u8 *hash ) +void md5(u8 *data, u32 len, u8 *hash) { - MD5( hash, data, len ); + MD5(hash, data, len); } - typedef struct { u8 zeroes[0x40]; u32 imet; // "IMET" - u8 zero_six_zero_three[8]; // fixed, unknown purpose + u8 zero_six_zero_three[8]; // fixed, unknown purpose u32 sizes[3]; u32 flag1; u16 name_jp[0x2a]; // might be empty @@ -93,12 +92,12 @@ typedef struct typedef struct { u32 imd5_tag; // 0x494D4435 "IMD5"; - u32 size; // size of the rest of part B, starting from next field. + 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; +} imd5_header_t; typedef struct { @@ -117,20 +116,20 @@ typedef struct u8 zeroes[16]; } U8_archive_header; -static int write_file( void* data, size_t size, char* name ) +static int write_file(void* data, size_t size, char* name) { size_t written = 0; FILE *out; - out = fopen( name, "wb" ); - if ( out ) + out = fopen(name, "wb"); + if (out) { - written = fwrite( data, 1, size, out ); - fclose( out ); + written = fwrite(data, 1, size, out); + fclose(out); } - return ( written == size ) ? 1 : -1; + return (written == size) ? 1 : -1; } -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) { u8 *data_end; u8 *decompressed_data; @@ -145,43 +144,43 @@ u8* decompress_lz77( u8 *data, size_t data_size, size_t* decompressed_size ) // Assume this for now and grow when needed unpacked_size = data_size; - decompressed_data = malloc( unpacked_size ); + decompressed_data = malloc(unpacked_size); out_end = decompressed_data + unpacked_size; out_ptr = decompressed_data; - while ( in_ptr < data_end ) + while (in_ptr < data_end) { int bit; u8 bitmask = *in_ptr; in_ptr++; - for ( bit = 0x80; bit != 0; bit >>= 1 ) + for (bit = 0x80; bit != 0; bit >>= 1) { - if ( bitmask & bit ) + if (bitmask & bit) { // Next section is compressed u8 rep_length; u16 rep_offset; - rep_length = ( *in_ptr >> 4 ) + 3; + rep_length = (*in_ptr >> 4) + 3; rep_offset = *in_ptr & 0x0f; in_ptr++; - rep_offset = *in_ptr | ( rep_offset << 8 ); + rep_offset = *in_ptr | (rep_offset << 8); in_ptr++; - if ( out_ptr - decompressed_data < rep_offset ) + if (out_ptr - decompressed_data < rep_offset) { return NULL; } - for ( ; rep_length > 0; rep_length-- ) + for (; rep_length > 0; rep_length--) { - *out_ptr = out_ptr[-rep_offset-1]; + *out_ptr = out_ptr[-rep_offset - 1]; out_ptr++; - if ( out_ptr >= out_end ) + if (out_ptr >= out_end) { // Need to grow buffer - decompressed_data = realloc( decompressed_data, unpacked_size * 2 ); + decompressed_data = realloc(decompressed_data, unpacked_size * 2); out_ptr = decompressed_data + unpacked_size; unpacked_size *= 2; out_end = decompressed_data + unpacked_size; @@ -193,10 +192,10 @@ u8* decompress_lz77( u8 *data, size_t data_size, size_t* decompressed_size ) // Just copy byte *out_ptr = *in_ptr; out_ptr++; - if ( out_ptr >= out_end ) + if (out_ptr >= out_end) { // Need to grow buffer - decompressed_data = realloc( decompressed_data, unpacked_size * 2 ); + decompressed_data = realloc(decompressed_data, unpacked_size * 2); out_ptr = decompressed_data + unpacked_size; unpacked_size *= 2; out_end = decompressed_data + unpacked_size; @@ -206,58 +205,58 @@ u8* decompress_lz77( u8 *data, size_t data_size, size_t* decompressed_size ) } } - *decompressed_size = ( out_ptr - decompressed_data ); + *decompressed_size = (out_ptr - decompressed_data); return decompressed_data; } -static int write_imd5_lz77( u8* data, size_t size, char* outname ) +static int write_imd5_lz77(u8* data, size_t size, char* outname) { - imd5_header_t* header = ( imd5_header_t* ) data; + 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; - tag = be32( ( u8* ) & header->imd5_tag ); - if ( tag != 0x494D4435 ) + 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 ) ) + 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 ) + size_in_imd5 = be32((u8*) &header->size); + if (size_in_imd5 != size - 32) { return -6; } - tag = be32( ( u8* ) & header->payload_tag ); - if ( tag == 0x4C5A3737 ) + 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 ); + 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 ); + free(decompressed_data); } else { - write_file( &header->payload_tag, size - 32, outname ); + write_file(&header->payload_tag, size - 32, outname); //printf(", md5 ok"); } return 0; } -static int do_U8_archive( FILE *fp ) +static int do_U8_archive(FILE *fp) { U8_archive_header header; U8_node root_node; @@ -272,42 +271,42 @@ static int do_U8_archive( FILE *fp ) u16 dir_stack[16]; int dir_index = 0; - fread( &header, 1, sizeof header, fp ); - tag = be32( ( u8* ) & header.tag ); - if ( tag != 0x55AA382D ) + 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; + 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++ ) + 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]; + 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 ) + if (type == 0x0100) { // Directory - mkdir( name, 0777 ); - chdir( name ); + mkdir(name, 0777); + chdir(name); dir_stack[++dir_index] = size; //printf("%*s%s/\n", dir_index, "", name); } @@ -316,59 +315,59 @@ static int do_U8_archive( FILE *fp ) // Normal file u8 padding[32]; - if ( type != 0x0000 ) + if (type != 0x0000) { - free( string_table ); + free(string_table); return -2; } - if ( current_offset < my_data_offset ) + if (current_offset < my_data_offset) { int diff = my_data_offset - current_offset; - if ( diff > 32 ) + if (diff > 32) { - free( string_table ); + free(string_table); return -3; } - fread( padding, 1, diff, fp ); + fread(padding, 1, diff, fp); current_offset += diff; } - file_data = malloc( size ); - fread( file_data, 1, size, fp ); + 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 ) + result = write_imd5_lz77(file_data, size, name); + if (result < 0) { - free( string_table ); + free(string_table); return result; } //printf(")\n"); current_offset += size; } - while ( dir_stack[dir_index] == i + 2 && dir_index > 0 ) + while (dir_stack[dir_index] == i + 2 && dir_index > 0) { - chdir( ".." ); + chdir(".."); dir_index--; } } - free( string_table ); + free(string_table); return 0; } -static void do_imet_header( FILE *fp ) +static void do_imet_header(FILE *fp) { imet_data_t header; - fread( &header, 1, sizeof header, fp ); + fread(&header, 1, sizeof header, fp); - write_file( &header, sizeof( header ), "header.imet" ); + write_file(&header, sizeof(header), "header.imet"); } -void do_U8_archivebanner( FILE *fp ) +void do_U8_archivebanner(FILE *fp) { U8_archive_header header; U8_node root_node; @@ -382,42 +381,42 @@ void do_U8_archivebanner( FILE *fp ) u16 dir_stack[16]; int dir_index = 0; - fread( &header, 1, sizeof header, fp ); - tag = be32( ( u8* ) & header.tag ); - if ( tag != 0x55AA382D ) + fread(&header, 1, sizeof header, fp); + tag = be32((u8*) &header.tag); + if (tag != 0x55AA382D) { //printf("No U8 tag"); - exit( 0 ); + 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 ); + 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); - for ( i = 0; i < num_nodes; i++ ) + 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]; + 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 ) + if (type == 0x0100) { // Directory - mkdir( name, 0777 ); - chdir( name ); + mkdir(name, 0777); + chdir(name); dir_stack[++dir_index] = size; //printf("%*s%s/\n", dir_index, "", name); } @@ -425,56 +424,57 @@ void do_U8_archivebanner( FILE *fp ) { // Normal file - if ( type != 0x0000 ) + if (type != 0x0000) { - printf( "Unknown type" ); - exit( 0 ); + 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 ); + 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 ) + while (dir_stack[dir_index] == i + 2 && dir_index > 0) { - chdir( ".." ); + chdir(".."); dir_index--; } } - free( string_table ); + free(string_table); } -int extractbnrfile( const char * filepath, const char * destpath ) +int extractbnrfile(const char * filepath, const char * destpath) { int ret = -1; - FILE *fp = fopen( filepath, "rb" ); - if ( fp ) + FILE *fp = fopen(filepath, "rb"); + if (fp) { - subfoldercreate( destpath ); - chdir( destpath ); + subfoldercreate(destpath); + chdir(destpath); - do_imet_header( fp ); - ret = do_U8_archive( fp ); + do_imet_header(fp); + ret = do_U8_archive(fp); - fclose( fp ); + fclose(fp); } return ret; } -int unpackBin( const char * filename, const char * outdir ) +int unpackBin(const char * filename, const char * outdir) { - FILE *fp = fopen( filename, "rb" );; - if ( fp ) + FILE *fp = fopen(filename, "rb"); + ; + if (fp) { - subfoldercreate( outdir ); - chdir( outdir ); + subfoldercreate(outdir); + chdir(outdir); - do_U8_archivebanner( fp ); - fclose( fp ); + do_U8_archivebanner(fp); + fclose(fp); return 1; } return 0; @@ -483,81 +483,79 @@ int unpackBin( const char * filename, const char * outdir ) #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; + if (!ramdiskMount("BANNER", NULL)) return -1; - subfoldercreate( TMP_PATH( "/" ) ); - s32 ret = dump_banner( gameid, TMP_PATH( "/opening.bnr" ) ); - if ( ret != 1 ) + 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 = extractbnrfile(TMP_PATH( "/opening.bnr" ), TMP_PATH( "/" )); + if (ret != 0) { ret = -1; goto error2; } - if ( what & UNPACK_BANNER_BIN ) + if (what & UNPACK_BANNER_BIN) { - snprintf( path, sizeof( path ), "%sbanner/", outdir ); - ret = unpackBin( TMP_PATH( "/meta/banner.bin" ), path ); - if ( ret != 1 ) + 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 ) + if (what & UNPACK_ICON_BIN) { - snprintf( path, sizeof( path ), "%sicon/", outdir ); - ret = unpackBin( TMP_PATH( "/meta/icon.bin" ), path ); - if ( ret != 1 ) + 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 ) + if (what & UNPACK_SOUND_BIN) { - snprintf( path, sizeof( path ), "%ssound.bin", outdir ); - FILE *fp = fopen( TMP_PATH( "/meta/sound.bin" ), "rb" ); - if ( fp ) + 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 ) + 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 ) + fseek(fp, 0, SEEK_SET); + data = (u8 *) malloc(size); + if (!data) { ret = -1; goto error; } - if ( fread( data, 1, size, fp ) != size ) + if (fread(data, 1, size, fp) != size) { ret = -1; goto error; } - ret = write_file( data, size, path ); + ret = write_file(data, size, path); } -error: fclose( fp ); + error: fclose(fp); } - ramdiskUnmount( "BANNER" ); -error2: - if ( ret < 0 ) - return ret; + ramdiskUnmount("BANNER"); + error2: if (ret < 0) return ret; return 1; } diff --git a/source/banner/openingbnr.h b/source/banner/openingbnr.h index 806327cd..dafe18ce 100644 --- a/source/banner/openingbnr.h +++ b/source/banner/openingbnr.h @@ -14,31 +14,31 @@ 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 ); + //! 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); #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 ); -//! Extract the lz77 compressed banner, icon and sound .bin - u8* decompress_lz77( u8 *data, size_t data_size, size_t* decompressed_size ); + 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); - 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 4ef64f32..cb034844 100644 --- a/source/bannersound.cpp +++ b/source/bannersound.cpp @@ -10,104 +10,100 @@ #include "language/gettext.h" #include "bannersound.h" - struct IMD5Header { - u32 fcc; - u32 filesize; - u8 zeroes[8]; - u8 crypto[16]; -} __attribute__( ( packed ) ); + 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]; -} __attribute__( ( packed ) ); + 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]; -} __attribute__( ( packed ) ); + 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; - }; -} __attribute__( ( packed ) ); + struct + { + u32 fileType :8; + u32 nameOffset :24; + }; + u32 fileOffset; + union + { + u32 fileLength; + u32 numEntries; + }; +}__attribute__( ( packed ) ); struct LZ77Info { - u16 length : 4; - u16 offset : 12; -} __attribute__( ( packed ) ); + u16 length :4; + u16 offset :12; +}__attribute__( ( packed ) ); -static char *u8Filename( const U8Entry *fst, int i ) +static char *u8Filename(const U8Entry *fst, int i) { - return ( char * )( fst + fst[0].numEntries ) + fst[i].nameOffset; + return (char *) (fst + fst[0].numEntries) + fst[i].nameOffset; } -inline u32 le32( u32 i ) +inline u32 le32(u32 i) { - return ( ( i & 0xFF ) << 24 ) | ( ( i & 0xFF00 ) << 8 ) | ( ( i & 0xFF0000 ) >> 8 ) | ( ( i & 0xFF000000 ) >> 24 ); + return ((i & 0xFF) << 24) | ((i & 0xFF00) << 8) | ((i & 0xFF0000) >> 8) | ((i & 0xFF000000) >> 24); } -inline u16 le16( u16 i ) +inline u16 le16(u16 i) { - return ( ( i & 0xFF ) << 8 ) | ( ( i & 0xFF00 ) >> 8 ); + return ((i & 0xFF) << 8) | ((i & 0xFF00) >> 8); } -static u8 *uncompressLZ77( const u8 *inBuf, u32 inLength, u32 &size ) +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 ); + 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; + buffer = new (std::nothrow) u8[uncSize]; + if (!buffer) return buffer; u8 *bufCur = buffer; u8 *bufEnd = buffer + uncSize; - while ( bufCur < bufEnd && inBuf < inBufEnd ) + while (bufCur < bufEnd && inBuf < inBufEnd) { u8 flags = *inBuf; ++inBuf; - for ( int i = 0; i < 8 && bufCur < bufEnd && inBuf < inBufEnd; ++i ) + for (int i = 0; i < 8 && bufCur < bufEnd && inBuf < inBufEnd; ++i) { - if ( ( flags & 0x80 ) != 0 ) + if ((flags & 0x80) != 0) { - const LZ77Info &info = *( const LZ77Info * )inBuf; - inBuf += sizeof ( LZ77Info ); + 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 ); + if (bufCur - info.offset - 1 < buffer || bufCur + length > bufEnd) return buffer; + memcpy(bufCur, bufCur - info.offset - 1, length); bufCur += length; } else @@ -123,87 +119,86 @@ static u8 *uncompressLZ77( const u8 *inBuf, u32 inLength, u32 &size ) return buffer; } -const u8 *LoadBannerSound( const u8 *discid, u32 *size ) +const u8 *LoadBannerSound(const u8 *discid, u32 *size) { - if ( !discid ) - return NULL; + if (!discid) return NULL; - Disc_SetUSB( NULL ); - wbfs_disc_t *disc = WBFS_OpenDisc( ( u8 * ) discid ); - if ( !disc ) + 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 ) + 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 ) + 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 IMETHeader *imetHdr = ( IMETHeader * )opening_bnr; - if ( imetHdr->fcc != 0x494D4554 /*"IMET"*/ ) + const IMETHeader *imetHdr = (IMETHeader *) opening_bnr; + if (imetHdr->fcc != 0x494D4554 /*"IMET"*/) { // WindowPrompt(tr("IMET Header wrong."), 0, tr("OK")); - free( opening_bnr ); + 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 ); + 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 ) + 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 ); + free(opening_bnr); return NULL; } - const u8 *sound_bin = ( ( const u8 * )bnrArcHdr ) + fst[i].fileOffset; - if ( ( ( IMD5Header * )sound_bin )->fcc != 0x494D4435 /*"IMD5"*/ ) + 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 ); + 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"*/ ) + if (*((u32*) soundChunk) == 0x4C5A3737 /*"LZ77"*/) { u32 uncSize = NULL; - u8 * uncompressed_data = uncompressLZ77( soundChunk, soundChunkSize, uncSize ); - if ( !uncompressed_data ) + u8 * uncompressed_data = uncompressLZ77(soundChunk, soundChunkSize, uncSize); + if (!uncompressed_data) { // WindowPrompt(tr("Can't decompress LZ77"), 0, tr("OK")); - free( opening_bnr ); + free(opening_bnr); return NULL; } - if ( size ) *size = uncSize; - free( opening_bnr ); + if (size) *size = uncSize; + free(opening_bnr); return uncompressed_data; } - u8 *out = new( std::nothrow ) u8[soundChunkSize]; - if ( out ) + u8 *out = new (std::nothrow) u8[soundChunkSize]; + if (out) { - memcpy( out, soundChunk, soundChunkSize ); - if ( size ) *size = soundChunkSize; + memcpy(out, soundChunk, soundChunkSize); + if (size) *size = soundChunkSize; } - free( opening_bnr ); + free(opening_bnr); return out; } diff --git a/source/bannersound.h b/source/bannersound.h index a91223f9..6cf7b526 100644 --- a/source/bannersound.h +++ b/source/bannersound.h @@ -1,6 +1,6 @@ #ifndef BANNERSOUND_H #define BANNERSOUND_H -const u8 *LoadBannerSound( const u8 *discid, u32 *size ); +const u8 *LoadBannerSound(const u8 *discid, u32 *size); #endif /* BANNERSOUND_H */ diff --git a/source/cheats/cheatmenu.cpp b/source/cheats/cheatmenu.cpp index 8a364e2d..b3723065 100644 --- a/source/cheats/cheatmenu.cpp +++ b/source/cheats/cheatmenu.cpp @@ -23,148 +23,148 @@ extern GuiWindow * mainWindow; /**************************************************************************** * CheatMenu ***************************************************************************/ -int CheatMenu( const char * gameID ) +int CheatMenu(const char * gameID) { 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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%ssettings_background.png", Settings.theme_path ); - GuiImageData settingsbg( imgPath, settings_background_png ); - GuiImage settingsbackground( &settingsbg ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", Settings.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 ); + 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 ); + 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 ); + snprintf(txtfilename, sizeof(txtfilename), "%s%s.txt", Settings.TxtCheatcodespath, gameID); GCTCheats c; - int check = c.openTxtfile( txtfilename ); + int check = c.openTxtfile(txtfilename); int download = 0; - switch ( check ) + switch (check) { case -1: - WindowPrompt( tr( "Error" ), tr( "Cheatfile is blank" ), tr( "OK" ) ); + 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 = 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; + download = CodeDownload(gameID); + if (download < 0 || c.openTxtfile(txtfilename) != 1) break; } - else - break; + else break; case 1: int cntcheats = c.getCnt(); - customOptionList cheatslst( cntcheats ); - GuiCustomOptionBrowser chtBrowser( 400, 280, &cheatslst, Settings.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 ); + customOptionList cheatslst(cntcheats); + GuiCustomOptionBrowser chtBrowser(400, 280, &cheatslst, Settings.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, SCROLL_HORIZONTAL ); - 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, SCROLL_HORIZONTAL); + 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" ); + 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 ); + 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 ) + while (!exit) { - VIDEO_WaitVSync (); + VIDEO_WaitVSync(); ret = chtBrowser.GetClickedOption(); - if ( ret != -1 ) + if (ret != -1) { - const char *strCheck = cheatslst.GetName( ret ); - if ( strncmp( strCheck, "ON", 2 ) == 0 ) + const char *strCheck = cheatslst.GetName(ret); + if (strncmp(strCheck, "ON", 2) == 0) { - cheatslst.SetName( ret, "%s", "OFF" ); + cheatslst.SetName(ret, "%s", "OFF"); } - else if ( strncmp( strCheck, "OFF", 3 ) == 0 ) + else if (strncmp(strCheck, "OFF", 3) == 0) { - cheatslst.SetName( ret, "%s", "ON" ); + cheatslst.SetName(ret, "%s", "ON"); } } - if ( createBtn.GetState() == STATE_CLICKED ) + if (createBtn.GetState() == STATE_CLICKED) { createBtn.ResetState(); - if ( cntcheats > 0 ) + if (cntcheats > 0) { int selectednrs[30]; int x = 0; - for ( int i = 0; i <= cntcheats; i++ ) + for (int i = 0; i <= cntcheats; i++) { - const char *strCheck = cheatslst.GetName( i ); - if ( strncmp( strCheck, "ON", 2 ) == 0 ) + const char *strCheck = cheatslst.GetName(i); + if (strncmp(strCheck, "ON", 2) == 0) { selectednrs[x] = i; x++; } } - if ( x == 0 ) + if (x == 0) { - WindowPrompt( tr( "Error" ), tr( "No cheats were selected" ), tr( "OK" ) ); + WindowPrompt(tr( "Error" ), tr( "No cheats were selected" ), tr( "OK" )); } else { - subfoldercreate( Settings.Cheatcodespath ); + 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" ) ); + 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" ) ); + else WindowPrompt(tr( "Error" ), tr( "Could not create GCT file" ), tr( "OK" )); } - if ( backBtn.GetState() == STATE_CLICKED ) + if (backBtn.GetState() == STATE_CLICKED) { backBtn.ResetState(); exit = true; @@ -172,8 +172,8 @@ int CheatMenu( const char * gameID ) } } HaltGui(); - mainWindow->SetState( STATE_DEFAULT ); - mainWindow->Remove( &w ); + mainWindow->SetState(STATE_DEFAULT); + mainWindow->Remove(&w); ResumeGui(); break; } diff --git a/source/cheats/cheatmenu.h b/source/cheats/cheatmenu.h index 6755be86..d087d9c6 100644 --- a/source/cheats/cheatmenu.h +++ b/source/cheats/cheatmenu.h @@ -8,6 +8,6 @@ #ifndef _CHEATMENU_H_ #define _CHEATMENU_H_ -int CheatMenu( const char * gameID ); +int CheatMenu(const char * gameID); #endif diff --git a/source/cheats/gct.cpp b/source/cheats/gct.cpp index aef475bd..b2a71f20 100644 --- a/source/cheats/gct.cpp +++ b/source/cheats/gct.cpp @@ -12,19 +12,19 @@ #define ERRORRANGE "Error: CheatNr out of range" -GCTCheats::GCTCheats( void ) +GCTCheats::GCTCheats(void) { iCntCheats = 0; } -GCTCheats::~GCTCheats( void ) +GCTCheats::~GCTCheats(void) { string sGameID = ""; string sGameTitle = ""; /*string sCheatName[MAXCHEATS]; - string sCheats[MAXCHEATS]; - string sCheatComment[MAXCHEATS];*/ + string sCheats[MAXCHEATS]; + string sCheatComment[MAXCHEATS];*/ } int GCTCheats::getCnt() @@ -32,19 +32,19 @@ int GCTCheats::getCnt() return iCntCheats; } -string GCTCheats::getGameName( void ) +string GCTCheats::getGameName(void) { return sGameTitle; } -string GCTCheats::getGameID( void ) +string GCTCheats::getGameID(void) { return sGameID; } -string GCTCheats::getCheat( int nr ) +string GCTCheats::getCheat(int nr) { - if ( nr <= ( iCntCheats - 1 ) ) + if (nr <= (iCntCheats - 1)) { return sCheats[nr]; } @@ -54,9 +54,9 @@ string GCTCheats::getCheat( int nr ) } } -string GCTCheats::getCheatName( int nr ) +string GCTCheats::getCheatName(int nr) { - if ( nr <= ( iCntCheats - 1 ) ) + if (nr <= (iCntCheats - 1)) { return sCheatName[nr]; } @@ -66,9 +66,9 @@ string GCTCheats::getCheatName( int nr ) } } -string GCTCheats::getCheatComment( int nr ) +string GCTCheats::getCheatComment(int nr) { - if ( nr <= ( iCntCheats - 1 ) ) + if (nr <= (iCntCheats - 1)) { return sCheatComment[nr]; } @@ -78,210 +78,200 @@ string GCTCheats::getCheatComment( int nr ) } } -int GCTCheats::createGCT( int nr, const char * filename ) +int GCTCheats::createGCT(int nr, const char * filename) { - if ( nr == 0 ) - return 0; + if (nr == 0) return 0; ofstream filestr; - filestr.open( filename ); + filestr.open(filename); - if ( filestr.fail() ) - return 0; + if (filestr.fail()) return 0; //Header and Footer - char header[] = { 0x00, 0xd0, 0xc0, 0xde, 0x00, 0xd0, 0xc0, 0xde}; - char footer[] = { 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + char header[] = { 0x00, 0xd0, 0xc0, 0xde, 0x00, 0xd0, 0xc0, 0xde }; + char footer[] = { 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - string buf = getCheat( nr ); - filestr.write( header, sizeof( header ) ); + string buf = getCheat(nr); + filestr.write(header, sizeof(header)); int x = 0; long int li; int len = buf.size(); - while ( x < len ) + while (x < len) { - string temp = buf.substr( x, 2 ); - li = strtol( temp.c_str(), NULL, 16 ); + string temp = buf.substr(x, 2); + li = strtol(temp.c_str(), NULL, 16); temp = li; - filestr.write( temp.c_str(), 1 ); + filestr.write(temp.c_str(), 1); x += 2; } - filestr.write( footer, sizeof( footer ) ); + filestr.write(footer, sizeof(footer)); filestr.close(); return 1; } -int GCTCheats::createGCT( const char * chtbuffer, const char * filename ) +int GCTCheats::createGCT(const char * chtbuffer, const char * filename) { ofstream filestr; - filestr.open( filename ); + filestr.open(filename); - if ( filestr.fail() ) - return 0; + if (filestr.fail()) return 0; //Header and Footer - char header[] = { 0x00, 0xd0, 0xc0, 0xde, 0x00, 0xd0, 0xc0, 0xde}; - char footer[] = { 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + char header[] = { 0x00, 0xd0, 0xc0, 0xde, 0x00, 0xd0, 0xc0, 0xde }; + char footer[] = { 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; string buf = chtbuffer; - filestr.write( header, sizeof( header ) ); + filestr.write(header, sizeof(header)); int x = 0; long int li; int len = buf.size(); - while ( x < len ) + while (x < len) { - string temp = buf.substr( x, 2 ); - li = strtol( temp.c_str(), NULL, 16 ); + string temp = buf.substr(x, 2); + li = strtol(temp.c_str(), NULL, 16); temp = li; - filestr.write( temp.c_str(), 1 ); + filestr.write(temp.c_str(), 1); x += 2; } - filestr.write( footer, sizeof( footer ) ); + filestr.write(footer, sizeof(footer)); filestr.close(); return 1; } -int GCTCheats::createGCT( int nr[], int cnt, 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 ); + filestr.open(filename); - if ( filestr.fail() ) - return 0; + if (filestr.fail()) return 0; //Header and Footer - char header[] = { 0x00, 0xd0, 0xc0, 0xde, 0x00, 0xd0, 0xc0, 0xde}; - char footer[] = { 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + char header[] = { 0x00, 0xd0, 0xc0, 0xde, 0x00, 0xd0, 0xc0, 0xde }; + char footer[] = { 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - filestr.write( header, sizeof( header ) ); + filestr.write(header, sizeof(header)); int c = 0; - while ( c != cnt ) + while (c != cnt) { int actnr = nr[c]; - string buf = getCheat( actnr ); + string buf = getCheat(actnr); long int li; int len = buf.size(); int x = 0; - while ( x < len ) + while (x < len) { - string temp = buf.substr( x, 2 ); - li = strtol( temp.c_str(), NULL, 16 ); + string temp = buf.substr(x, 2); + li = strtol(temp.c_str(), NULL, 16); temp = li; - filestr.write( temp.c_str(), 1 ); + filestr.write(temp.c_str(), 1); x += 2; } c++; } - filestr.write( footer, sizeof( footer ) ); + filestr.write(footer, sizeof(footer)); filestr.close(); return 1; } -int GCTCheats::openTxtfile( const char * filename ) +int GCTCheats::openTxtfile(const char * filename) { ifstream filestr; int i = 0; string str; - filestr.open( filename ); + filestr.open(filename); - if ( filestr.fail() ) - return 0; + if (filestr.fail()) return 0; - filestr.seekg( 0, ios_base::end ); + filestr.seekg(0, ios_base::end); int size = filestr.tellg(); - if ( size <= 0 ) return -1; - filestr.seekg( 0, ios_base::beg ); + if (size <= 0) return -1; + filestr.seekg(0, ios_base::beg); - getline( filestr, sGameID ); - if ( sGameID[sGameID.length() - 1] == '\r' ) - sGameID.erase( sGameID.length() - 1 ); + getline(filestr, sGameID); + 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 ); + getline(filestr, sGameTitle); + 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 ); + getline(filestr, sCheatName[i]); // skip first line if file uses CRLF + if (!sGameTitle[sGameTitle.length() - 1] == '\r') filestr.seekg(0, ios_base::beg); - while ( !filestr.eof() ) + 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 ); + getline(filestr, sCheatName[i]); // '\n' delimiter by default + 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' ) + if (str == "" || str[0] == '\r' || str[0] == '\n') { emptyline = true; break; } - if ( IsCode( str ) ) + if (IsCode(str)) { // remove any garbage (comment) after code - while ( str.size() > 17 ) + while (str.size() > 17) { - str.erase( str.length() - 1 ); + str.erase(str.length() - 1); } - cheatdata.append( str ); - size_t found = cheatdata.find( ' ' ); - cheatdata.replace( found, 1, "" ); + cheatdata.append(str); + size_t found = cheatdata.find(' '); + cheatdata.replace(found, 1, ""); } else { //printf("%i",str.size()); sCheatComment[i] = str; } - if ( filestr.eof() ) break; + if (filestr.eof()) break; - } - while ( !emptyline ); + } while (!emptyline); sCheats[i] = cheatdata; i++; - if ( i == MAXCHEATS ) break; + if (i == MAXCHEATS) break; } iCntCheats = i; filestr.close(); return 1; } -bool GCTCheats::IsCode( const std::string& str ) +bool GCTCheats::IsCode(const std::string& str) { - if ( str[8] == ' ' && str.size() >= 17 ) + 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( part2, 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 ) ) + 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(part2, 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; } diff --git a/source/cheats/gct.h b/source/cheats/gct.h index 0206f5fe..d7f0ad20 100644 --- a/source/cheats/gct.h +++ b/source/cheats/gct.h @@ -26,50 +26,50 @@ class GCTCheats public: //!Constructor - GCTCheats( void ); + GCTCheats(void); //!Destructor - ~GCTCheats( void ); + ~GCTCheats(void); //!Open txt file with cheats //!\param filename name of TXT file //!\return error code - int openTxtfile( const char * filename ); + int openTxtfile(const char * filename); //!Creates GCT file for one cheat //!\param nr selected Cheat Numbers //!\param filename name of GCT file //!\return error code - int createGCT( int nr, const char * filename ); + int createGCT(int nr, const char * filename); //!Creates GCT file from a buffer //!\param chtbuffer buffer that holds the cheat data //!\param filename name of GCT file //!\return error code - int createGCT( const char * chtbuffer, const char * filename ); + int createGCT(const char * chtbuffer, const char * filename); //!Creates GCT file //!\param nr[] array of selected Cheat Numbers //!\param cnt size of array //!\param filename name of GCT file //!\return error code - int createGCT( int nr[], int cnt, const char * filename ); + int createGCT(int nr[], int cnt, const char * filename); //!Gets Count cheats //!\return Count cheats int getCnt(); //!Gets Game Name //!\return Game Name - string getGameName( void ); + string getGameName(void); //!Gets GameID //!\return GameID - string getGameID( void ); + string getGameID(void); //!Gets cheat data //!\return cheat data - string getCheat( int nr ); + string getCheat(int nr); //!Gets Cheat Name //!\return Cheat Name - string getCheatName( int nr ); + string getCheatName(int nr); //!Gets Cheat Comment //!\return Cheat Comment - string getCheatComment( int nr ); + string getCheatComment(int nr); //!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/fatmounter.c b/source/fatmounter.c index 62e671ea..acfbef68 100644 --- a/source/fatmounter.c +++ b/source/fatmounter.c @@ -32,43 +32,43 @@ extern sec_t _FAT_startSector; extern s32 wbfsDev; -int fat_sd_mount = MOUNT_NONE; +int fat_sd_mount = MOUNT_NONE; sec_t fat_sd_sec = 0; // u32 -int fat_usb_mount = 0; +int fat_usb_mount = 0; sec_t fat_usb_sec = 0; -int fat_wbfs_mount = 0; +int fat_wbfs_mount = 0; sec_t fat_wbfs_sec = 0; -int fs_ntfs_mount = 0; +int fs_ntfs_mount = 0; sec_t fs_ntfs_sec = 0; int USBDevice_Init() { #ifdef DEBUG_FAT - gprintf( "USBDevice_Init()" ); + gprintf("USBDevice_Init()"); #endif //closing all open Files write back the cache and then shutdown em! - fatUnmount( "USB:/" ); + fatUnmount("USB:/"); //right now mounts first FAT-partition //try first mount with cIOS -// if (!fatMount("USB", &__io_wiiums, 0, CACHE, SECTORS)) { -// //try now mount with libogc - if ( !fatMount( "USB", &__io_usbstorage2, 0, CACHE, SECTORS ) ) + // if (!fatMount("USB", &__io_wiiums, 0, CACHE, SECTORS)) { + // //try now mount with libogc + if (!fatMount("USB", &__io_usbstorage2, 0, CACHE, SECTORS)) { #ifdef DEBUG_FAT - gprintf( ":-1\n" ); + gprintf(":-1\n"); #endif return -1; } -// } + // } fat_usb_mount = 1; fat_usb_sec = _FAT_startSector; #ifdef DEBUG_FAT - gprintf( ":0\n" ); + gprintf(":0\n"); #endif return 0; } @@ -76,36 +76,36 @@ int USBDevice_Init() void USBDevice_deInit() { #ifdef DEBUG_FAT - gprintf( "USBDevice_deInit(): " ); + gprintf("USBDevice_deInit(): "); #endif //closing all open Files write back the cache and then shutdown em! - fatUnmount( "USB:/" ); + fatUnmount("USB:/"); fat_usb_mount = 0; fat_usb_sec = 0; #ifdef DEBUG_FAT - gprintf( "ok\n" ); + gprintf("ok\n"); #endif } -int WBFSDevice_Init( u32 sector ) +int WBFSDevice_Init(u32 sector) { //closing all open Files write back the cache and then shutdown em! - fatUnmount( "WBFS:/" ); + fatUnmount("WBFS:/"); //right now mounts first FAT-partition //try first mount with cIOS -// if (!fatMount("WBFS", &__io_wiiums, 0, CACHE, SECTORS)) { + // if (!fatMount("WBFS", &__io_wiiums, 0, CACHE, SECTORS)) { //try now mount with libogc - if ( !fatMount( "WBFS", &__io_usbstorage2, 0, CACHE, SECTORS ) ) + if (!fatMount("WBFS", &__io_usbstorage2, 0, CACHE, SECTORS)) { return -1; } -// } + // } fat_wbfs_mount = 1; fat_wbfs_sec = _FAT_startSector; - if ( sector && fat_wbfs_sec != sector ) + if (sector && fat_wbfs_sec != sector) { // This is an error situation...actually, but is ignored in Config loader also // Should ask Oggzee about it... @@ -116,16 +116,15 @@ int WBFSDevice_Init( u32 sector ) void WBFSDevice_deInit() { //closing all open Files write back the cache and then shutdown em! - fatUnmount( "WBFS:/" ); + fatUnmount("WBFS:/"); fat_wbfs_mount = 0; fat_wbfs_sec = 0; } -int isInserted( const char *path ) +int isInserted(const char *path) { - if ( !strncmp( path, "USB:", 4 ) ) - return 1; + if (!strncmp(path, "USB:", 4)) return 1; return __io_sdhc.isInserted() || __io_wiisd.isInserted(); } @@ -134,33 +133,33 @@ static u8 sdIsInited = 0; int SDCard_Init() { #ifdef DEBUG_FAT - gprintf( "SDCard_Init()" ); + gprintf("SDCard_Init()"); #endif //closing all open Files write back the cache and then shutdown em! - fatUnmount( "SD:/" ); + fatUnmount("SD:/"); //right now mounts first FAT-partition - if ( fatMount( "SD", &__io_wiisd, 0, CACHE, SECTORS ) ) + if (fatMount("SD", &__io_wiisd, 0, CACHE, SECTORS)) { fat_sd_mount = MOUNT_SD; fat_sd_sec = _FAT_startSector; - sdIsInited = 1; + sdIsInited = 1; #ifdef DEBUG_FAT - gprintf( ":1\n" ); + gprintf(":1\n"); #endif return 1; } - else if ( fatMount( "SD", &__io_sdhc, 0, CACHE, SDHC_SECTOR_SIZE ) ) + else if (fatMount("SD", &__io_sdhc, 0, CACHE, SDHC_SECTOR_SIZE)) { fat_sd_mount = MOUNT_SDHC; fat_sd_sec = _FAT_startSector; - sdIsInited = 1; + sdIsInited = 1; #ifdef DEBUG_FAT - gprintf( ":1\n" ); + gprintf(":1\n"); #endif return 1; } #ifdef DEBUG_FAT - gprintf( ":-1\n" ); + gprintf(":-1\n"); #endif return -1; } @@ -168,29 +167,29 @@ int SDCard_Init() void SDCard_deInit() { #ifdef DEBUG_FAT - gprintf( "SDCard_deInit( %d ): ", sdIsInited ); + gprintf("SDCard_deInit( %d ): ", sdIsInited); #endif //closing all open Files write back the cache and then shutdown em! - if( sdIsInited ) + if (sdIsInited) { - fatUnmount( "SD:/" ); + fatUnmount("SD:/"); - fat_sd_mount = MOUNT_NONE; - fat_sd_sec = 0; - sdIsInited = 0; + fat_sd_mount = MOUNT_NONE; + fat_sd_sec = 0; + sdIsInited = 0; } #ifdef DEBUG_FAT - gprintf( "ok\n" ); + gprintf("ok\n"); #endif } void ntfsInit(); -s32 MountNTFS( u32 sector ) +s32 MountNTFS(u32 sector) { s32 ret; - if ( fs_ntfs_mount ) return 0; + if (fs_ntfs_mount) return 0; //printf("mounting NTFS\n"); //Wpad_WaitButtons(); _FAT_mem_init(); @@ -200,39 +199,39 @@ s32 MountNTFS( u32 sector ) // 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" ); + setlocale(LC_CTYPE, "C-UTF-8"); + setlocale(LC_MESSAGES, "C-UTF-8"); - if ( wbfsDev == WBFS_DEVICE_USB ) + if (wbfsDev == WBFS_DEVICE_USB) { /* Initialize WBFS interface */ -// if (!__io_wiiums.startup()) { + // if (!__io_wiiums.startup()) { ret = __io_usbstorage2.startup(); - if ( !ret ) + if (!ret) { return -1; } -// } + // } /* Mount device */ -// if (!ntfsMount("NTFS", &__io_wiiums, sector, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER)) { - ret = ntfsMount( "NTFS", &__io_usbstorage2, sector, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER ); - if ( !ret ) + // if (!ntfsMount("NTFS", &__io_wiiums, sector, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER)) { + ret = ntfsMount("NTFS", &__io_usbstorage2, sector, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER); + if (!ret) { return -2; } -// } + // } } - else if ( wbfsDev == WBFS_DEVICE_SDHC ) + else if (wbfsDev == WBFS_DEVICE_SDHC) { - if ( sdhc_mode_sd == 0 ) + if (sdhc_mode_sd == 0) { - ret = ntfsMount( "NTFS", &__io_sdhc, 0, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER ); + 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 ); + ret = ntfsMount("NTFS", &__io_sdhc, 0, CACHE, SECTORS_SD, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER); } - if ( !ret ) + if (!ret) { return -5; } @@ -244,10 +243,10 @@ s32 MountNTFS( u32 sector ) return 0; } -s32 UnmountNTFS( void ) +s32 UnmountNTFS(void) { /* Unmount device */ - ntfsUnmount( "NTFS:/", true ); + ntfsUnmount("NTFS:/", true); fs_ntfs_mount = 0; fs_ntfs_sec = 0; @@ -259,17 +258,17 @@ void _FAT_mem_init() { } -void* _FAT_mem_allocate( size_t size ) +void* _FAT_mem_allocate(size_t size) { - return malloc( size ); + return malloc(size); } -void* _FAT_mem_align( size_t size ) +void* _FAT_mem_align(size_t size) { - return memalign( 32, size ); + return memalign(32, size); } -void _FAT_mem_free( void *mem ) +void _FAT_mem_free(void *mem) { - free( mem ); + free(mem); } diff --git a/source/fatmounter.h b/source/fatmounter.h index 3ced2ab1..79a00034 100644 --- a/source/fatmounter.h +++ b/source/fatmounter.h @@ -6,29 +6,29 @@ extern "C" { #endif - extern int fat_sd_mount; + extern int fat_sd_mount; extern sec_t fat_sd_sec; - extern int fat_usb_mount; + extern int fat_usb_mount; extern sec_t fat_usb_sec; - extern int fat_wbfs_mount; + extern int fat_wbfs_mount; extern sec_t fat_wbfs_sec; int USBDevice_Init(); void USBDevice_deInit(); - int WBFSDevice_Init( u32 sector ); + int WBFSDevice_Init(u32 sector); void WBFSDevice_deInit(); - int isInserted( const char *path ); + 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 int fat_usb_mount; extern sec_t fat_usb_sec; - extern int fat_wbfs_mount; + extern int fat_wbfs_mount; extern sec_t fat_wbfs_sec; - extern int fs_ntfs_mount; + extern int fs_ntfs_mount; extern sec_t fs_ntfs_sec; #ifdef __cplusplus diff --git a/source/filelist.h b/source/filelist.h index 672c5808..9b6a54a0 100644 --- a/source/filelist.h +++ b/source/filelist.h @@ -11,551 +11,551 @@ #include -extern const u8 font_ttf[]; -extern const u32 font_ttf_size; +extern const u8 font_ttf[]; +extern const u32 font_ttf_size; -extern const u8 clock_ttf[]; -extern const u32 clock_ttf_size; +extern const u8 clock_ttf[]; +extern const u32 clock_ttf_size; -extern const u8 closebutton_png[]; -extern const u32 closebutton_png_size; +extern const u8 closebutton_png[]; +extern const u32 closebutton_png_size; -extern const u8 gxlogo_png[]; -extern const u32 gxlogo_png_size; +extern const u8 gxlogo_png[]; +extern const u32 gxlogo_png_size; -extern const u8 sdcard_png[]; -extern const u32 sdcard_png_size; +extern const u8 sdcard_png[]; +extern const u32 sdcard_png_size; -extern const u8 sdcard_over_png[]; -extern const u32 sdcard_over_png_size; +extern const u8 sdcard_over_png[]; +extern const u32 sdcard_over_png_size; -extern const u8 Wifi_btn_png[]; -extern const u32 Wifi_btn_png_size; +extern const u8 Wifi_btn_png[]; +extern const u32 Wifi_btn_png_size; -extern const u8 Channel_btn_png[]; -extern const u32 Channel_btn_png_size; +extern const u8 Channel_btn_png[]; +extern const u32 Channel_btn_png_size; -extern const u8 wiimote_png[]; -extern const u32 wiimote_png_size; +extern const u8 wiimote_png[]; +extern const u32 wiimote_png_size; -extern const u8 bg_music_ogg[]; -extern const u32 bg_music_ogg_size; +extern const u8 bg_music_ogg[]; +extern const u32 bg_music_ogg_size; -extern const u8 credits_music_ogg[]; -extern const u32 credits_music_ogg_size; +extern const u8 credits_music_ogg[]; +extern const u32 credits_music_ogg_size; -extern const u8 gameinfo1_png[]; -extern const u32 gameinfo1_png_size; +extern const u8 gameinfo1_png[]; +extern const u32 gameinfo1_png_size; -extern const u8 gameinfo2_png[]; -extern const u32 gameinfo2_png_size; +extern const u8 gameinfo2_png[]; +extern const u32 gameinfo2_png_size; -extern const u8 gameinfo1a_png[]; -extern const u32 gameinfo1a_png_size; +extern const u8 gameinfo1a_png[]; +extern const u32 gameinfo1a_png_size; -extern const u8 gameinfo2a_png[]; -extern const u32 gameinfo2a_png_size; +extern const u8 gameinfo2a_png[]; +extern const u32 gameinfo2a_png_size; -extern const u8 menuin_ogg[]; -extern const u32 menuin_ogg_size; +extern const u8 menuin_ogg[]; +extern const u32 menuin_ogg_size; -extern const u8 menuout_ogg[]; -extern const u32 menuout_ogg_size; +extern const u8 menuout_ogg[]; +extern const u32 menuout_ogg_size; -extern const u8 success_ogg[]; -extern const u32 success_ogg_size; +extern const u8 success_ogg[]; +extern const u32 success_ogg_size; -extern const u8 credits_button_png[]; -extern const u32 credits_button_png_size; +extern const u8 credits_button_png[]; +extern const u32 credits_button_png_size; -extern const u8 credits_button_over_png[]; -extern const u32 credits_button_over_png_size; +extern const u8 credits_button_over_png[]; +extern const u32 credits_button_over_png_size; -extern const u8 button_over_pcm[]; -extern const u32 button_over_pcm_size; +extern const u8 button_over_pcm[]; +extern const u32 button_over_pcm_size; -extern const u8 button_click_pcm[]; -extern const u32 button_click_pcm_size; +extern const u8 button_click_pcm[]; +extern const u32 button_click_pcm_size; -extern const u8 button_click2_pcm[]; -extern const u32 button_click2_pcm_size; +extern const u8 button_click2_pcm[]; +extern const u32 button_click2_pcm_size; -extern const u8 tooltip_left_png[]; -extern const u32 tooltip_left_png_size; +extern const u8 tooltip_left_png[]; +extern const u32 tooltip_left_png_size; -extern const u8 tooltip_tile_png[]; -extern const u32 tooltip_tile_png_size; +extern const u8 tooltip_tile_png[]; +extern const u32 tooltip_tile_png_size; -extern const u8 tooltip_right_png[]; -extern const u32 tooltip_right_png_size; +extern const u8 tooltip_right_png[]; +extern const u32 tooltip_right_png_size; -extern const u8 startgame_arrow_left_png[]; -extern const u32 startgame_arrow_left_png_size; +extern const u8 startgame_arrow_left_png[]; +extern const u32 startgame_arrow_left_png_size; -extern const u8 startgame_arrow_right_png[]; -extern const u32 startgame_arrow_right_png_size; +extern const u8 startgame_arrow_right_png[]; +extern const u32 startgame_arrow_right_png_size; -extern const u8 credits_bg_png[]; -extern const u32 credits_bg_png_size; +extern const u8 credits_bg_png[]; +extern const u32 credits_bg_png_size; -extern const u8 little_star_png[]; -extern const u32 little_star_png_size; +extern const u8 little_star_png[]; +extern const u32 little_star_png_size; -extern const u8 background_png[]; -extern const u32 background_png_size; +extern const u8 background_png[]; +extern const u32 background_png_size; -extern const u8 wbackground_png[]; -extern const u32 wbackground_png_size; +extern const u8 wbackground_png[]; +extern const u32 wbackground_png_size; -extern const u8 bg_options_settings_png[]; -extern const u32 bg_options_settings_png_size; +extern const u8 bg_options_settings_png[]; +extern const u32 bg_options_settings_png_size; -extern const u8 settings_background_png[]; -extern const u32 settings_background_png_size; +extern const u8 settings_background_png[]; +extern const u32 settings_background_png_size; -extern const u8 bg_browser_png[]; -extern const u32 bg_browser_png_size; +extern const u8 bg_browser_png[]; +extern const u32 bg_browser_png_size; -extern const u8 icon_archives_png[]; -extern const u32 icon_archives_png_size; +extern const u8 icon_archives_png[]; +extern const u32 icon_archives_png_size; //extern const u8 icon_default_png[]; //extern const u32 icon_default_png_size; -extern const u8 icon_folder_png[]; -extern const u32 icon_folder_png_size; +extern const u8 icon_folder_png[]; +extern const u32 icon_folder_png_size; /* -extern const u8 icon_gfx_png[]; -extern const u32 icon_gfx_png_size; + extern const u8 icon_gfx_png[]; + extern const u32 icon_gfx_png_size; -extern const u8 icon_pls_png[]; -extern const u32 icon_pls_png_size; + extern const u8 icon_pls_png[]; + extern const u32 icon_pls_png_size; -extern const u8 icon_sfx_png[]; -extern const u32 icon_sfx_png_size; + extern const u8 icon_sfx_png[]; + extern const u32 icon_sfx_png_size; -extern const u8 icon_txt_png[]; -extern const u32 icon_txt_png_size; + extern const u8 icon_txt_png[]; + extern const u32 icon_txt_png_size; -extern const u8 icon_xml_png[]; -extern const u32 icon_xml_png_size; -*/ -extern const u8 bg_browser_selection_png[]; -extern const u32 bg_browser_selection_png_size; + extern const u8 icon_xml_png[]; + extern const u32 icon_xml_png_size; + */ +extern const u8 bg_browser_selection_png[]; +extern const u32 bg_browser_selection_png_size; -extern const u8 addressbar_textbox_png[]; -extern const u32 addressbar_textbox_png_size; +extern const u8 addressbar_textbox_png[]; +extern const u32 addressbar_textbox_png_size; -extern const u8 browser_png[]; -extern const u32 browser_png_size; +extern const u8 browser_png[]; +extern const u32 browser_png_size; -extern const u8 browser_over_png[]; -extern const u32 browser_over_png_size; +extern const u8 browser_over_png[]; +extern const u32 browser_over_png_size; -extern const u8 nocover_png[]; -extern const u32 nocover_png_size; +extern const u8 nocover_png[]; +extern const u32 nocover_png_size; -extern const u8 nocoverFlat_png[]; -extern const u32 nocoverFlat_png_size; +extern const u8 nocoverFlat_png[]; +extern const u32 nocoverFlat_png_size; -extern const u8 nodisc_png[]; -extern const u32 nodisc_png_size; +extern const u8 nodisc_png[]; +extern const u32 nodisc_png_size; -extern const u8 theme_dialogue_box_png[]; -extern const u32 theme_dialogue_box_png_size; +extern const u8 theme_dialogue_box_png[]; +extern const u32 theme_dialogue_box_png_size; -extern const u8 button_install_png[]; -extern const u32 button_install_png_size; +extern const u8 button_install_png[]; +extern const u32 button_install_png_size; -extern const u8 button_install_over_png[]; -extern const u32 button_install_over_png_size; +extern const u8 button_install_over_png[]; +extern const u32 button_install_over_png_size; -extern const u8 dialogue_box_startgame_png[]; -extern const u32 dialogue_box_startgame_png_size; +extern const u8 dialogue_box_startgame_png[]; +extern const u32 dialogue_box_startgame_png_size; -extern const u8 wdialogue_box_startgame_png[]; -extern const u32 wdialogue_box_startgame_png_size; +extern const u8 wdialogue_box_startgame_png[]; +extern const u32 wdialogue_box_startgame_png_size; -extern const u8 button_dialogue_box_startgame_png[]; -extern const u32 button_dialogue_box_startgame_size; +extern const u8 button_dialogue_box_startgame_png[]; +extern const u32 button_dialogue_box_startgame_size; -extern const u8 button_dialogue_box_png[]; -extern const u32 button_dialogue_box_size; +extern const u8 button_dialogue_box_png[]; +extern const u32 button_dialogue_box_size; -extern const u8 keyboard_textbox_png[]; -extern const u32 keyboard_textbox_png_size; +extern const u8 keyboard_textbox_png[]; +extern const u32 keyboard_textbox_png_size; -extern const u8 keyboard_key_png[]; -extern const u32 keyboard_key_png_size; +extern const u8 keyboard_key_png[]; +extern const u32 keyboard_key_png_size; -extern const u8 keyboard_key_over_png[]; -extern const u32 keyboard_key_over_png_size; +extern const u8 keyboard_key_over_png[]; +extern const u32 keyboard_key_over_png_size; -extern const u8 keyboard_mediumkey_over_png[]; -extern const u32 keyboard_mediumkey_over_png_size; +extern const u8 keyboard_mediumkey_over_png[]; +extern const u32 keyboard_mediumkey_over_png_size; -extern const u8 keyboard_largekey_over_png[]; -extern const u32 keyboard_largekey_over_png_size; +extern const u8 keyboard_largekey_over_png[]; +extern const u32 keyboard_largekey_over_png_size; -extern const u8 keyboard_backspace_over_png[]; -extern const u32 keyboard_backspace_over_png_size; +extern const u8 keyboard_backspace_over_png[]; +extern const u32 keyboard_backspace_over_png_size; -extern const u8 keyboard_clear_over_png[]; -extern const u32 keyboard_clear_over_png_size; +extern const u8 keyboard_clear_over_png[]; +extern const u32 keyboard_clear_over_png_size; -extern const u8 menu_button_png[]; -extern const u32 menu_button_size; +extern const u8 menu_button_png[]; +extern const u32 menu_button_size; -extern const u8 menu_button_over_png[]; -extern const u32 menu_button_over_size; +extern const u8 menu_button_over_png[]; +extern const u32 menu_button_over_size; -extern const u8 settings_button_png[]; -extern const u32 settings_button_size; +extern const u8 settings_button_png[]; +extern const u32 settings_button_size; -extern const u8 settings_button_over_png[]; -extern const u32 settings_button_over_size; +extern const u8 settings_button_over_png[]; +extern const u32 settings_button_over_size; -extern const u8 settings_menu_button_png[]; -extern const u32 settings_menu_button_size; +extern const u8 settings_menu_button_png[]; +extern const u32 settings_menu_button_size; -extern const u8 wiimote_poweroff_png[]; -extern const u32 wiimote_poweroff_png_size; +extern const u8 wiimote_poweroff_png[]; +extern const u32 wiimote_poweroff_png_size; -extern const u8 dialogue_box_png[]; -extern const u32 dialogue_box_png_size; +extern const u8 dialogue_box_png[]; +extern const u32 dialogue_box_png_size; -extern const u8 theme_box_png[]; -extern const u32 theme_box_png_size; +extern const u8 theme_box_png[]; +extern const u32 theme_box_png_size; -extern const u8 wiimote_poweroff_over_png[]; -extern const u32 wiimote_poweroff_over_png_size; +extern const u8 wiimote_poweroff_over_png[]; +extern const u32 wiimote_poweroff_over_png_size; -extern const u8 bg_options_png[]; -extern const u32 bg_options_png_size; +extern const u8 bg_options_png[]; +extern const u32 bg_options_png_size; -extern const u8 bg_options_entry_png[]; -extern const u32 bg_options_entry_png_size; +extern const u8 bg_options_entry_png[]; +extern const u32 bg_options_entry_png_size; -extern const u8 scrollbar_png[]; -extern const u32 scrollbar_png_size; +extern const u8 scrollbar_png[]; +extern const u32 scrollbar_png_size; -extern const u8 scrollbar_arrowup_png[]; -extern const u32 scrollbar_arrowup_png_size; +extern const u8 scrollbar_arrowup_png[]; +extern const u32 scrollbar_arrowup_png_size; -extern const u8 scrollbar_arrowup_over_png[]; -extern const u32 scrollbar_arrowup_over_png_size; +extern const u8 scrollbar_arrowup_over_png[]; +extern const u32 scrollbar_arrowup_over_png_size; -extern const u8 scrollbar_arrowdown_png[]; -extern const u32 scrollbar_arrowdown_png_size; +extern const u8 scrollbar_arrowdown_png[]; +extern const u32 scrollbar_arrowdown_png_size; -extern const u8 scrollbar_arrowdown_over_png[]; -extern const u32 scrollbar_arrowdown_over_png_size; +extern const u8 scrollbar_arrowdown_over_png[]; +extern const u32 scrollbar_arrowdown_over_png_size; -extern const u8 scrollbar_box_png[]; -extern const u32 scrollbar_box_png_size; +extern const u8 scrollbar_box_png[]; +extern const u32 scrollbar_box_png_size; -extern const u8 scrollbar_box_over_png[]; -extern const u32 scrollbar_box_over_png_size; +extern const u8 scrollbar_box_over_png[]; +extern const u32 scrollbar_box_over_png_size; -extern const u8 progressbar_png[]; -extern const u32 progressbar_png_size; +extern const u8 progressbar_png[]; +extern const u32 progressbar_png_size; -extern const u8 progressbar_empty_png[]; -extern const u32 progressbar_empty_png_size; +extern const u8 progressbar_empty_png[]; +extern const u32 progressbar_empty_png_size; -extern const u8 progressbar_outline_png[]; -extern const u32 progressbar_outline_png_size; +extern const u8 progressbar_outline_png[]; +extern const u32 progressbar_outline_png_size; -extern const u8 player1_point_png[]; -extern const u32 player1_point_png_size; +extern const u8 player1_point_png[]; +extern const u32 player1_point_png_size; -extern const u8 player2_point_png[]; -extern const u32 player2_point_png_size; +extern const u8 player2_point_png[]; +extern const u32 player2_point_png_size; -extern const u8 player3_point_png[]; -extern const u32 player3_point_png_size; +extern const u8 player3_point_png[]; +extern const u32 player3_point_png_size; -extern const u8 player4_point_png[]; -extern const u32 player4_point_png_size; +extern const u8 player4_point_png[]; +extern const u32 player4_point_png_size; -extern const u8 rplayer1_point_png[]; -extern const u32 rplayer1_point_png_size; +extern const u8 rplayer1_point_png[]; +extern const u32 rplayer1_point_png_size; -extern const u8 rplayer2_point_png[]; -extern const u32 rplayer2_point_png_size; +extern const u8 rplayer2_point_png[]; +extern const u32 rplayer2_point_png_size; -extern const u8 rplayer3_point_png[]; -extern const u32 rplayer3_point_png_size; +extern const u8 rplayer3_point_png[]; +extern const u32 rplayer3_point_png_size; -extern const u8 rplayer4_point_png[]; -extern const u32 rplayer4_point_png_size; +extern const u8 rplayer4_point_png[]; +extern const u32 rplayer4_point_png_size; -extern const u8 battery_png[]; -extern const u32 battery_png_size; +extern const u8 battery_png[]; +extern const u32 battery_png_size; -extern const u8 battery_bar_png[]; -extern const u32 battery_bar_png_size; +extern const u8 battery_bar_png[]; +extern const u32 battery_bar_png_size; -extern const u8 battery_white_png[]; -extern const u32 battery_white_png_size; +extern const u8 battery_white_png[]; +extern const u32 battery_white_png_size; -extern const u8 battery_bar_white_png[]; -extern const u32 battery_bar_white_png_size; +extern const u8 battery_bar_white_png[]; +extern const u32 battery_bar_white_png_size; -extern const u8 battery_red_png[]; -extern const u32 battery_red_png_size; +extern const u8 battery_red_png[]; +extern const u32 battery_red_png_size; -extern const u8 battery_bar_red_png[]; -extern const u32 battery_bar_red_png_size; +extern const u8 battery_bar_red_png[]; +extern const u32 battery_bar_red_png_size; -extern const u8 arrow_next_png[]; -extern const u32 arrow_next_png_size; +extern const u8 arrow_next_png[]; +extern const u32 arrow_next_png_size; -extern const u8 arrow_previous_png[]; -extern const u32 arrow_previous_png_size; +extern const u8 arrow_previous_png[]; +extern const u32 arrow_previous_png_size; -extern const u8 mp3_pause_png[]; -extern const u32 mp3_pause_png_size; +extern const u8 mp3_pause_png[]; +extern const u32 mp3_pause_png_size; -extern const u8 exit_top_png[]; -extern const u32 exit_top_png_size; +extern const u8 exit_top_png[]; +extern const u32 exit_top_png_size; -extern const u8 exit_top_over_png[]; -extern const u32 exit_top_over_png_size; +extern const u8 exit_top_over_png[]; +extern const u32 exit_top_over_png_size; -extern const u8 exit_bottom_png[]; -extern const u32 exit_bottom_png_size; +extern const u8 exit_bottom_png[]; +extern const u32 exit_bottom_png_size; -extern const u8 exit_bottom_over_png[]; -extern const u32 exit_bottom_over_png_size; +extern const u8 exit_bottom_over_png[]; +extern const u32 exit_bottom_over_png_size; -extern const u8 exit_button_png[]; -extern const u32 exit_button_png_size; +extern const u8 exit_button_png[]; +extern const u32 exit_button_png_size; -extern const u8 mp3_stop_png[]; -extern const u32 mp3_stop_png_size; +extern const u8 mp3_stop_png[]; +extern const u32 mp3_stop_png_size; -extern const u8 favorite_png[]; -extern const u32 favorite_png_size; +extern const u8 favorite_png[]; +extern const u32 favorite_png_size; -extern const u8 not_favorite_png[]; -extern const u32 not_favorite_png_size; +extern const u8 not_favorite_png[]; +extern const u32 not_favorite_png_size; -extern const u8 favIcon_png[]; -extern const u32 favIcon_png_size; +extern const u8 favIcon_png[]; +extern const u32 favIcon_png_size; -extern const u8 searchIcon_png[]; -extern const u32 searchIcon_png_size; +extern const u8 searchIcon_png[]; +extern const u32 searchIcon_png_size; -extern const u8 abcIcon_png[]; -extern const u32 abcIcon_png_size; +extern const u8 abcIcon_png[]; +extern const u32 abcIcon_png_size; -extern const u8 rankIcon_png[]; -extern const u32 rankIcon_png_size; +extern const u8 rankIcon_png[]; +extern const u32 rankIcon_png_size; -extern const u8 playCountIcon_png[]; -extern const u32 playCountIcon_png_size; +extern const u8 playCountIcon_png[]; +extern const u32 playCountIcon_png_size; -extern const u8 arrangeList_png[]; -extern const u32 arrangeList_png_size; +extern const u8 arrangeList_png[]; +extern const u32 arrangeList_png_size; -extern const u8 arrangeGrid_png[]; -extern const u32 arrangeGrid_png_size; +extern const u8 arrangeGrid_png[]; +extern const u32 arrangeGrid_png_size; -extern const u8 arrangeCarousel_png[]; -extern const u32 arrangeCarousel_png_size; +extern const u8 arrangeCarousel_png[]; +extern const u32 arrangeCarousel_png_size; -extern const u8 settings_title_png[]; -extern const u32 settings_title_png_size; +extern const u8 settings_title_png[]; +extern const u32 settings_title_png_size; -extern const u8 settings_title_over_png[]; -extern const u32 settings_title_over_png_size; +extern const u8 settings_title_over_png[]; +extern const u32 settings_title_over_png_size; -extern const u8 pageindicator_png[]; -extern const u32 pageindicator_png_size; +extern const u8 pageindicator_png[]; +extern const u32 pageindicator_png_size; -extern const u8 Wiimote1_png[]; -extern const u32 Wiimote1_png_size; +extern const u8 Wiimote1_png[]; +extern const u32 Wiimote1_png_size; -extern const u8 Wiimote2_png[]; -extern const u32 Wiimote2_png_size; +extern const u8 Wiimote2_png[]; +extern const u32 Wiimote2_png_size; -extern const u8 Wiimote4_png[]; -extern const u32 Wiimote4_png_size; +extern const u8 Wiimote4_png[]; +extern const u32 Wiimote4_png_size; -extern const u8 wifi1_png[]; -extern const u32 wifi1_png_size; +extern const u8 wifi1_png[]; +extern const u32 wifi1_png_size; -extern const u8 wifi2_png[]; -extern const u32 wifi2png_size; +extern const u8 wifi2_png[]; +extern const u32 wifi2png_size; -extern const u8 wifi3_png[]; -extern const u32 wifi3_png_size; +extern const u8 wifi3_png[]; +extern const u32 wifi3_png_size; -extern const u8 wifi4_png[]; -extern const u32 wifi4_png_size; +extern const u8 wifi4_png[]; +extern const u32 wifi4_png_size; //extern const u8 wifi6_png[]; //extern const u32 wifi6_png_size; -extern const u8 wifi8_png[]; -extern const u32 wifi8_png_size; +extern const u8 wifi8_png[]; +extern const u32 wifi8_png_size; -extern const u8 wifi12_png[]; -extern const u32 wifi12_png_size; +extern const u8 wifi12_png[]; +extern const u32 wifi12_png_size; -extern const u8 wifi16_png[]; -extern const u32 wifi16_png_size; +extern const u8 wifi16_png[]; +extern const u32 wifi16_png_size; -extern const u8 wifi32_png[]; -extern const u32 wifi32_png_size; +extern const u8 wifi32_png[]; +extern const u32 wifi32_png_size; -extern const u8 norating_png[]; -extern const u32 norating_png_size; +extern const u8 norating_png[]; +extern const u32 norating_png_size; -extern const u8 guitar_png[]; -extern const u32 guitar_png_size; -extern const u8 guitarR_png[]; -extern const u32 guitarR_png_size; +extern const u8 guitar_png[]; +extern const u32 guitar_png_size; +extern const u8 guitarR_png[]; +extern const u32 guitarR_png_size; -extern const u8 microphone_png[]; -extern const u32 microphone_png_size; -extern const u8 microphoneR_png[]; -extern const u32 microphoneR_png_size; +extern const u8 microphone_png[]; +extern const u32 microphone_png_size; +extern const u8 microphoneR_png[]; +extern const u32 microphoneR_png_size; -extern const u8 gcncontroller_png[]; -extern const u32 gcncontroller_png_size; -extern const u8 gcncontrollerR_png[]; -extern const u32 gcncontrollerR_png_size; +extern const u8 gcncontroller_png[]; +extern const u32 gcncontroller_png_size; +extern const u8 gcncontrollerR_png[]; +extern const u32 gcncontrollerR_png_size; -extern const u8 classiccontroller_png[]; -extern const u32 classiccontroller_png_size; -extern const u8 classiccontrollerR_png[]; -extern const u32 classiccontrollerR_png_size; +extern const u8 classiccontroller_png[]; +extern const u32 classiccontroller_png_size; +extern const u8 classiccontrollerR_png[]; +extern const u32 classiccontrollerR_png_size; -extern const u8 nunchuk_png[]; -extern const u32 nunchuk_png_size; -extern const u8 nunchukR_png[]; -extern const u32 nunchukR_png_size; +extern const u8 nunchuk_png[]; +extern const u32 nunchuk_png_size; +extern const u8 nunchukR_png[]; +extern const u32 nunchukR_png_size; -extern const u8 dancepadR_png[]; -extern const u32 dancepadR_size; -extern const u8 dancepad_png[]; -extern const u32 dancepad_png_size; +extern const u8 dancepadR_png[]; +extern const u32 dancepadR_size; +extern const u8 dancepad_png[]; +extern const u32 dancepad_png_size; -extern const u8 balanceboard_png[]; -extern const u32 balanceboard_png_size; -extern const u8 balanceboardR_png[]; -extern const u32 balanceboardR_png_size; +extern const u8 balanceboard_png[]; +extern const u32 balanceboard_png_size; +extern const u8 balanceboardR_png[]; +extern const u32 balanceboardR_png_size; -extern const u8 drums_png[]; -extern const u32 drums_png_size; -extern const u8 drumsR_png[]; -extern const u32 drumsR_png_size; +extern const u8 drums_png[]; +extern const u32 drums_png_size; +extern const u8 drumsR_png[]; +extern const u32 drumsR_png_size; -extern const u8 motionplus_png[]; -extern const u32 motionplus_png_size; -extern const u8 motionplusR_png[]; -extern const u32 motionplusR_png_size; +extern const u8 motionplus_png[]; +extern const u32 motionplus_png_size; +extern const u8 motionplusR_png[]; +extern const u32 motionplusR_png_size; -extern const u8 wheel_png[]; -extern const u32 wheel_png_size; -extern const u8 wheelR_png[]; -extern const u32 wheelR_png_size; +extern const u8 wheel_png[]; +extern const u32 wheel_png_size; +extern const u8 wheelR_png[]; +extern const u32 wheelR_png_size; -extern const u8 zapper_png[]; -extern const u32 zapper_png_size; -extern const u8 zapperR_png[]; -extern const u32 zapperR_png_size; +extern const u8 zapper_png[]; +extern const u32 zapper_png_size; +extern const u8 zapperR_png[]; +extern const u32 zapperR_png_size; -extern const u8 wiispeak_png[]; -extern const u32 wiispeak_png_size; -extern const u8 wiispeakR_png[]; -extern const u32 wiispeakR_png_size; +extern const u8 wiispeak_png[]; +extern const u32 wiispeak_png_size; +extern const u8 wiispeakR_png[]; +extern const u32 wiispeakR_png_size; -extern const u8 nintendods_png[]; -extern const u32 nintendods_png_size; -extern const u8 nintendodsR_png[]; -extern const u32 nintendodsR_png_size; +extern const u8 nintendods_png[]; +extern const u32 nintendods_png_size; +extern const u8 nintendodsR_png[]; +extern const u32 nintendodsR_png_size; /* -extern const u8 vitalitysensor_png[]; -extern const u32 vitalitysensor_png_size; -extern const u8 vitalitysensor_png[]; -extern const u32 vitalitysensorR_png_size; -*/ -extern const u8 esrb_ec_png[]; -extern const u32 esrb_ec_png_size; + extern const u8 vitalitysensor_png[]; + extern const u32 vitalitysensor_png_size; + extern const u8 vitalitysensor_png[]; + extern const u32 vitalitysensorR_png_size; + */ +extern const u8 esrb_ec_png[]; +extern const u32 esrb_ec_png_size; -extern const u8 esrb_e_png[]; -extern const u32 esrb_e_png_size; +extern const u8 esrb_e_png[]; +extern const u32 esrb_e_png_size; -extern const u8 esrb_eten_png[]; -extern const u32 esrb_eten_png_size; +extern const u8 esrb_eten_png[]; +extern const u32 esrb_eten_png_size; -extern const u8 esrb_t_png[]; -extern const u32 esrb_t_png_size; +extern const u8 esrb_t_png[]; +extern const u32 esrb_t_png_size; -extern const u8 esrb_m_png[]; -extern const u32 esrb_m_png_size; +extern const u8 esrb_m_png[]; +extern const u32 esrb_m_png_size; -extern const u8 esrb_ao_png[]; -extern const u32 esrb_ao_png_size; +extern const u8 esrb_ao_png[]; +extern const u32 esrb_ao_png_size; -extern const u8 cero_a_png[]; -extern const u32 cero_a_png_size; +extern const u8 cero_a_png[]; +extern const u32 cero_a_png_size; -extern const u8 cero_b_png[]; -extern const u32 cero_b_png_size; +extern const u8 cero_b_png[]; +extern const u32 cero_b_png_size; -extern const u8 cero_c_png[]; -extern const u32 cero_c_png_size; +extern const u8 cero_c_png[]; +extern const u32 cero_c_png_size; -extern const u8 cero_d_png[]; -extern const u32 cero_d_png_size; +extern const u8 cero_d_png[]; +extern const u32 cero_d_png_size; -extern const u8 cero_z_png[]; -extern const u32 cero_z_png_size; +extern const u8 cero_z_png[]; +extern const u32 cero_z_png_size; -extern const u8 pegi_3_png[]; -extern const u32 pegi_3_png_size; +extern const u8 pegi_3_png[]; +extern const u32 pegi_3_png_size; -extern const u8 pegi_7_png[]; -extern const u32 pegi_7_png_size; +extern const u8 pegi_7_png[]; +extern const u32 pegi_7_png_size; -extern const u8 pegi_12_png[]; -extern const u32 pegi_12_png_size; +extern const u8 pegi_12_png[]; +extern const u32 pegi_12_png_size; -extern const u8 pegi_16_png[]; -extern const u32 pegi_16_png_size; +extern const u8 pegi_16_png[]; +extern const u32 pegi_16_png_size; -extern const u8 pegi_18_png[]; -extern const u32 pegi_18_png_size; +extern const u8 pegi_18_png[]; +extern const u32 pegi_18_png_size; -extern const u8 usbport_png[]; -extern const u32 usbport_png_size; +extern const u8 usbport_png[]; +extern const u32 usbport_png_size; -extern const u8 dvd_png[]; -extern const u32 dvd_png_size; +extern const u8 dvd_png[]; +extern const u32 dvd_png_size; -extern const u8 new_png[]; -extern const u32 new_png_size; +extern const u8 new_png[]; +extern const u32 new_png_size; -extern const u8 lock_png[]; -extern const u32 lock_png_size; +extern const u8 lock_png[]; +extern const u32 lock_png_size; -extern const u8 unlock_png[]; -extern const u32 unlock_png_size; +extern const u8 unlock_png[]; +extern const u32 unlock_png_size; -extern const u8 stub_bin[]; -extern const u32 stub_bin_size; +extern const u8 stub_bin[]; +extern const u32 stub_bin_size; -extern const u8 fatffs_module_bin[]; -extern const u32 fatffs_module_bin_size; +extern const u8 fatffs_module_bin[]; +extern const u32 fatffs_module_bin_size; -extern const u8 ehcmodule_frag_v4_bin[]; -extern const u32 ehcmodule_frag_v4_bin_size; +extern const u8 ehcmodule_frag_v4_bin[]; +extern const u32 ehcmodule_frag_v4_bin_size; -extern const u8 ehcmodule_frag_v5_bin[]; -extern const u32 ehcmodule_frag_v5_bin_size; +extern const u8 ehcmodule_frag_v5_bin[]; +extern const u32 ehcmodule_frag_v5_bin_size; #endif diff --git a/source/gecko.c b/source/gecko.c index e07d49c1..9e56a12e 100644 --- a/source/gecko.c +++ b/source/gecko.c @@ -10,72 +10,66 @@ bool textVideoInit = false; #include //using the gprintf from crediar because it is smaller than mine -void gprintf( const char *str, ... ) +void gprintf(const char *str, ...) { - if ( !( geckoinit ) )return; + if (!(geckoinit)) return; - char astr[ 0x100 ]; + char astr[0x100]; va_list ap; va_start( ap, str ); - vsprintf( astr, str, ap ); + vsprintf(astr, str, ap); va_end( ap ); - usb_sendbuffer( 1, astr, strlen( astr ) ); + usb_sendbuffer(1, astr, strlen(astr)); //usb_sendbuffer_safe( 1, astr, strlen(astr) ); } bool InitGecko() { - u32 geckoattached = usb_isgeckoalive( EXI_CHANNEL_1 ); - if ( geckoattached ) + u32 geckoattached = usb_isgeckoalive(EXI_CHANNEL_1); + if (geckoattached) { - usb_flush( EXI_CHANNEL_1 ); - CON_EnableGecko( 1, true ); + usb_flush(EXI_CHANNEL_1); + CON_EnableGecko(1, true); return true; } else return false; } -char ascii( char s ) +char ascii(char s) { - if ( s < 0x20 ) - return '.'; - if ( s > 0x7E ) - return '.'; + if (s < 0x20) return '.'; + if (s > 0x7E) return '.'; return s; } -void hexdump( void *d, int len ) +void hexdump(void *d, int len) { u8 *data; int i, off; - data = ( u8* )d; + data = (u8*) d; - gprintf( "\n 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF" ); - gprintf( "\n==== =============================================== ================\n" ); + gprintf("\n 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF"); + gprintf("\n==== =============================================== ================\n"); - for ( off = 0; off < len; off += 16 ) + for (off = 0; off < len; off += 16) { - gprintf( "%04x ", off ); - for ( i = 0; i < 16; i++ ) - if ( ( i + off ) >= len ) - gprintf( " " ); - else - gprintf( "%02x ", data[off+i] ); + gprintf("%04x ", off); + for (i = 0; i < 16; i++) + if ((i + off) >= len) + gprintf(" "); + else gprintf("%02x ", data[off + i]); - gprintf( " " ); - for ( i = 0; i < 16; i++ ) - if ( ( i + off ) >= len ) - gprintf( " " ); - else - gprintf( "%c", ascii( data[off+i] ) ); - gprintf( "\n" ); + gprintf(" "); + for (i = 0; i < 16; i++) + if ((i + off) >= len) + gprintf(" "); + else gprintf("%c", ascii(data[off + i])); + gprintf("\n"); } } - - #endif /* NO_DEBUG */ diff --git a/source/gecko.h b/source/gecko.h index e4dacd41..aa4d9793 100644 --- a/source/gecko.h +++ b/source/gecko.h @@ -1,5 +1,4 @@ - #ifndef _GECKO_H_ #define _GECKO_H_ @@ -8,21 +7,19 @@ extern "C" { #endif - char ascii( char s ); + char ascii(char s); #ifndef NO_DEBUG //use this just like printf(); - void gprintf( const char *str, ... ); + void gprintf(const char *str, ...); bool InitGecko(); - void hexdump( void *d, int len ); + void hexdump(void *d, int len); #else #define gprintf(...) #define InitGecko() false #define hexdump( x, y ) #endif /* NO_DEBUG */ - - #ifdef __cplusplus } #endif diff --git a/source/homebrewboot/BootHomebrew.cpp b/source/homebrewboot/BootHomebrew.cpp index 36412251..a10c05b5 100644 --- a/source/homebrewboot/BootHomebrew.cpp +++ b/source/homebrewboot/BootHomebrew.cpp @@ -44,7 +44,7 @@ void FreeHomebrewBuffer() static int SetupARGV( struct __argv * args ) { if ( !args ) - return -1; + return -1; bzero( args, sizeof( struct __argv ) ); args->argvMagic = ARGV_MAGIC; @@ -60,7 +60,7 @@ static int SetupARGV( struct __argv * args ) args->length = stringlength; args->commandLine = ( char* ) malloc( args->length ); if ( !args->commandLine ) - return -1; + return -1; u32 argc = 0; u32 position = 0; @@ -87,7 +87,7 @@ static int SetupARGV( struct __argv * args ) int BootHomebrew() { if ( homebrewsize <= 0 ) - Sys_BackToLoader(); + Sys_BackToLoader(); SDCard_deInit(); USBDevice_deInit(); @@ -101,7 +101,7 @@ int BootHomebrew() entrypoint entry = ( entrypoint ) load_dol( app_booter_dol, &args ); if ( !entry ) - Sys_BackToLoader(); + Sys_BackToLoader(); VIDEO_SetBlack( true ); VIDEO_Flush(); @@ -120,7 +120,7 @@ int BootHomebrew( const char * filepath ) { FILE * file = fopen( filepath, "rb" ); if ( !file ) - Sys_BackToLoader(); + Sys_BackToLoader(); fseek( file, 0, SEEK_END ); @@ -153,83 +153,79 @@ int BootHomebrew( const char * filepath ) #include "fatmounter.h" #include "dolloader.h" - void *innetbuffer = NULL; -static u8 *homebrewbuffer = ( u8 * )0x92000000; +static u8 *homebrewbuffer = (u8 *) 0x92000000; u32 homebrewsize = 0; static std::vector Arguments; -extern const u8 app_booter_dol[]; +extern const u8 app_booter_dol[]; -int AllocHomebrewMemory( u32 filesize ) +int AllocHomebrewMemory(u32 filesize) { - innetbuffer = malloc( filesize ); + innetbuffer = malloc(filesize); - if ( !innetbuffer ) - return -1; + if (!innetbuffer) return -1; homebrewsize = filesize; return 1; } -void AddBootArgument( const char * argv ) +void AddBootArgument(const char * argv) { - std::string arg( argv ); - Arguments.push_back( arg ); + std::string arg(argv); + Arguments.push_back(arg); } -int CopyHomebrewMemory( u8 *temp, u32 pos, u32 len ) +int CopyHomebrewMemory(u8 *temp, u32 pos, u32 len) { homebrewsize += len; - memcpy( ( homebrewbuffer ) + pos, temp, len ); + memcpy((homebrewbuffer) + pos, temp, len); return 1; } void FreeHomebrewBuffer() { - homebrewbuffer = ( u8 * ) 0x92000000; + homebrewbuffer = (u8 *) 0x92000000; homebrewsize = 0; - if ( innetbuffer ) + if (innetbuffer) { - free( innetbuffer ); + free(innetbuffer); innetbuffer = NULL; } Arguments.clear(); } -static int SetupARGV( struct __argv * args ) +static int SetupARGV(struct __argv * args) { - if ( !args ) - return -1; + if (!args) return -1; - bzero( args, sizeof( struct __argv ) ); + bzero(args, sizeof(struct __argv)); args->argvMagic = ARGV_MAGIC; u32 stringlength = 1; /** Append Arguments **/ - for ( u32 i = 0; i < Arguments.size(); i++ ) + for (u32 i = 0; i < Arguments.size(); i++) { stringlength += Arguments[i].size() + 1; } args->length = stringlength; - args->commandLine = ( char* ) malloc( args->length ); + args->commandLine = (char*) malloc(args->length); - if ( !args->commandLine ) - return -1; + if (!args->commandLine) return -1; u32 argc = 0; u32 position = 0; /** Append Arguments **/ - for ( u32 i = 0; i < Arguments.size(); i++ ) + for (u32 i = 0; i < Arguments.size(); i++) { - strcpy( &args->commandLine[position], Arguments[i].c_str() ); + strcpy(&args->commandLine[position], Arguments[i].c_str()); position += Arguments[i].size() + 1; argc++; } @@ -247,17 +243,16 @@ static int SetupARGV( struct __argv * args ) static int RunAppbooter() { - if ( homebrewsize == 0 ) - return -1; + if (homebrewsize == 0) return -1; struct __argv args; - SetupARGV( &args ); + SetupARGV(&args); u32 cpu_isr; - entrypoint entry = ( entrypoint ) load_dol( ( void* ) app_booter_dol, &args ); + entrypoint entry = (entrypoint) load_dol((void*) app_booter_dol, &args); - if ( !entry ) + if (!entry) { FreeHomebrewBuffer(); return -1; @@ -266,25 +261,24 @@ static int RunAppbooter() u64 currentStub = getStubDest(); loadStub(); - if ( Set_Stub_Split( 0x00010001, "UNEO" ) < 0 ) + if (Set_Stub_Split(0x00010001, "UNEO") < 0) { - if ( Set_Stub_Split( 0x00010001, "ULNR" ) < 0 ) + if (Set_Stub_Split(0x00010001, "ULNR") < 0) { - if ( !currentStub ) - currentStub = 0x100000002ULL; + if (!currentStub) currentStub = 0x100000002ULL; - Set_Stub( currentStub ); + Set_Stub(currentStub); } } SDCard_deInit(); USBDevice_deInit(); - WPAD_Flush( 0 ); - WPAD_Disconnect( 0 ); + WPAD_Flush(0); + WPAD_Disconnect(0); WPAD_Shutdown(); - SYS_ResetSystem( SYS_SHUTDOWN, 0, 0 ); + SYS_ResetSystem(SYS_SHUTDOWN, 0, 0); _CPU_ISR_Disable( cpu_isr ); __exception_closeall(); entry(); @@ -293,59 +287,58 @@ static int RunAppbooter() return 0; } -int BootHomebrew( char * filepath ) +int BootHomebrew(char * filepath) { void *buffer = NULL; u32 filesize = 0; - FILE *file = fopen( filepath, "rb" ); + FILE *file = fopen(filepath, "rb"); - if ( !file ) - Sys_BackToLoader(); + if (!file) Sys_BackToLoader(); - fseek( file, 0, SEEK_END ); - filesize = ftell( file ); - rewind( file ); + fseek(file, 0, SEEK_END); + filesize = ftell(file); + rewind(file); - buffer = malloc( filesize ); + buffer = malloc(filesize); - if ( fread( buffer, 1, filesize, file ) != filesize ) + if (fread(buffer, 1, filesize, file) != filesize) { - fclose( file ); - free( buffer ); + fclose(file); + free(buffer); SDCard_deInit(); USBDevice_deInit(); Sys_BackToLoader(); } - fclose( file ); + fclose(file); - CopyHomebrewMemory( ( u8* ) buffer, 0, filesize ); + CopyHomebrewMemory((u8*) buffer, 0, filesize); - if ( buffer ) + if (buffer) { - free( buffer ); + free(buffer); buffer = NULL; } - AddBootArgument( filepath ); + AddBootArgument(filepath); return RunAppbooter(); } int BootHomebrewFromMem() { - gprintf( "BootHomebrewFromMem()\n %p, %08x\n", innetbuffer, homebrewsize ); + gprintf("BootHomebrewFromMem()\n %p, %08x\n", innetbuffer, homebrewsize); - if ( !innetbuffer ) + if (!innetbuffer) { - gprintf( "!innetbuffer\n" ); + gprintf("!innetbuffer\n"); SDCard_deInit(); USBDevice_deInit(); Sys_BackToLoader(); } - CopyHomebrewMemory( ( u8* ) innetbuffer, 0, homebrewsize ); - free( innetbuffer ); + CopyHomebrewMemory((u8*) innetbuffer, 0, homebrewsize); + free(innetbuffer); return RunAppbooter(); } diff --git a/source/homebrewboot/BootHomebrew.h b/source/homebrewboot/BootHomebrew.h index 1ab47762..7de0b58b 100644 --- a/source/homebrewboot/BootHomebrew.h +++ b/source/homebrewboot/BootHomebrew.h @@ -3,12 +3,12 @@ //int BootHomebrew(); int BootHomebrewFromMem(); -int BootHomebrew( char * filepath ); -int CopyHomebrewMemory( u8 *temp, u32 pos, u32 len ); -void AddBootArgument( const char * arg ); +int BootHomebrew(char * filepath); +int CopyHomebrewMemory(u8 *temp, u32 pos, u32 len); +void AddBootArgument(const char * arg); void FreeHomebrewBuffer(); -int LoadHomebrew( const char * filepath ); -int AllocHomebrewMemory( u32 filesize ); +int LoadHomebrew(const char * filepath); +int AllocHomebrewMemory(u32 filesize); extern void *innetbuffer; extern u32 homebrewsize; diff --git a/source/homebrewboot/HomebrewBrowse.cpp b/source/homebrewboot/HomebrewBrowse.cpp index c4b33c6e..a466a23c 100644 --- a/source/homebrewboot/HomebrewBrowse.cpp +++ b/source/homebrewboot/HomebrewBrowse.cpp @@ -47,12 +47,11 @@ u8 boothomebrew = 0; /**************************************************************************** * roundup Function ***************************************************************************/ -int roundup( float number ) +int roundup(float number) { - if ( number == ( int ) number ) - return ( int ) number; - else - return ( int ) ( number + 1 ); + if (number == (int) number) + return (int) number; + else return (int) (number + 1); } /**************************************************************************** @@ -63,284 +62,292 @@ int MenuHomebrewBrowse() int menu = MENU_NONE; int choice = 0; - HomebrewFiles HomebrewFiles( Settings.homebrewapps_path ); + HomebrewFiles HomebrewFiles(Settings.homebrewapps_path); u32 filecount = HomebrewFiles.GetFilecount(); - if ( !filecount ) + if (!filecount) { - WindowPrompt( tr( "No .dol or .elf files found." ), 0, tr( "OK" ) ); + WindowPrompt(tr( "No .dol or .elf files found." ), 0, tr( "OK" )); return MENU_DISCLIST; } enum { - FADE, - LEFT, - RIGHT + FADE, LEFT, RIGHT }; - if ( IsNetworkInit() ) - ResumeNetworkWait(); + if (IsNetworkInit()) ResumeNetworkWait(); int slidedirection = FADE; /*** Sound Variables ***/ - GuiSound btnSoundOver( button_over_pcm, button_over_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 ); + 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 btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); /*** Image Variables ***/ char imgPath[150]; - snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf( imgPath, sizeof( imgPath ), "%ssettings_background.png", Settings.theme_path ); - GuiImageData bgData( imgPath, settings_background_png ); + snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", Settings.theme_path); + GuiImageData bgData(imgPath, settings_background_png); - snprintf( imgPath, sizeof( imgPath ), "%ssettings_title.png", Settings.theme_path ); - GuiImageData MainButtonImgData( imgPath, settings_title_png ); + snprintf(imgPath, sizeof(imgPath), "%ssettings_title.png", Settings.theme_path); + GuiImageData MainButtonImgData(imgPath, settings_title_png); - snprintf( imgPath, sizeof( imgPath ), "%ssettings_title_over.png", Settings.theme_path ); - GuiImageData MainButtonImgOverData( imgPath, settings_title_over_png ); + snprintf(imgPath, sizeof(imgPath), "%ssettings_title_over.png", Settings.theme_path); + GuiImageData MainButtonImgOverData(imgPath, settings_title_over_png); - snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_left.png", Settings.theme_path ); - GuiImageData arrow_left( imgPath, startgame_arrow_left_png ); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", Settings.theme_path); + GuiImageData arrow_left(imgPath, startgame_arrow_left_png); - snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_right.png", Settings.theme_path ); - GuiImageData arrow_right( imgPath, startgame_arrow_right_png ); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", Settings.theme_path); + GuiImageData arrow_right(imgPath, startgame_arrow_right_png); - snprintf( imgPath, sizeof( imgPath ), "%sWifi_btn.png", Settings.theme_path ); - GuiImageData wifiImgData( imgPath, Wifi_btn_png ); + snprintf(imgPath, sizeof(imgPath), "%sWifi_btn.png", Settings.theme_path); + GuiImageData wifiImgData(imgPath, Wifi_btn_png); - snprintf( imgPath, sizeof( imgPath ), "%sChannel_btn.png", Settings.theme_path ); - GuiImageData channelImgData( imgPath, Channel_btn_png ); + snprintf(imgPath, sizeof(imgPath), "%sChannel_btn.png", Settings.theme_path); + GuiImageData channelImgData(imgPath, Channel_btn_png); - - GuiImage background( &bgData ); + GuiImage background(&bgData); /*** Trigger Variables ***/ GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + trigMinus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0); GuiTrigger trigPlus; - trigPlus.SetButtonOnlyTrigger( -1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0 ); + trigPlus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0); - GuiText titleTxt( tr( "Homebrew Launcher" ), 28, ( GXColor ) {0, 0, 0, 255} ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( 0, 40 ); + GuiText titleTxt(tr( "Homebrew Launcher" ), 28, ( GXColor ) + { 0, 0, 0, 255}); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0, 40); GuiImageData *IconData[4]; GuiImage *IconImg[4]; - for ( int i = 0; i < 4; i++ ) + for (int i = 0; i < 4; i++) { IconData[i] = NULL; IconImg[i] = NULL; } /*** Buttons ***/ - GuiText backBtnTxt( tr( "Back" ) , 22, THEME.prompttext ); - backBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); - GuiImage backBtnImg( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText backBtnTxt(tr( "Back" ), 22, THEME.prompttext); + backBtnTxt.SetMaxWidth(btnOutline.GetWidth() - 30); + GuiImage backBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - backBtnTxt.SetWidescreen( Settings.widescreen ); - backBtnImg.SetWidescreen( Settings.widescreen ); + backBtnTxt.SetWidescreen(Settings.widescreen); + backBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton backBtn( &backBtnImg, &backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2, 1 ); - backBtn.SetLabel( &backBtnTxt ); - backBtn.SetTrigger( &trigB ); + 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 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 ); + 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 ); + 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 ); + 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 ); + GoRightBtn.SetTrigger(&trigA); + GoRightBtn.SetTrigger(&trigR); + GoRightBtn.SetTrigger(&trigPlus); char MainButtonText[50]; - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", " " ); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", " "); - GuiImage MainButton1Img( &MainButtonImgData ); - GuiImage MainButton1ImgOver( &MainButtonImgOverData ); - GuiText MainButton1Txt( MainButtonText, 18, ( GXColor ) {0, 0, 0, 255} ); - MainButton1Txt.SetMaxWidth( MainButton1Img.GetWidth() - 150, DOTTED ); - MainButton1Txt.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - MainButton1Txt.SetPosition( 148, -12 ); - GuiText MainButton1DescTxt( MainButtonText, 18, ( GXColor ) {0, 0, 0, 255} ); - MainButton1DescTxt.SetMaxWidth( MainButton1Img.GetWidth() - 150, DOTTED ); - MainButton1DescTxt.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - MainButton1DescTxt.SetPosition( 148, 15 ); - GuiText MainButton1DescOverTxt( MainButtonText, 18, ( GXColor ) { 0, 0, 0, 255} ); - MainButton1DescOverTxt.SetMaxWidth( MainButton1Img.GetWidth() - 150, SCROLL_HORIZONTAL ); - MainButton1DescOverTxt.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - MainButton1DescOverTxt.SetPosition( 148, 15 ); - 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.SetLabel( &MainButton1DescTxt, 1 ); - MainButton1.SetLabelOver( &MainButton1DescOverTxt, 1 ); - MainButton1.SetSoundOver( &btnSoundOver ); - MainButton1.SetSoundClick( &btnClick1 ); + GuiImage MainButton1Img(&MainButtonImgData); + GuiImage MainButton1ImgOver(&MainButtonImgOverData); + GuiText MainButton1Txt(MainButtonText, 18, ( GXColor ) + { 0, 0, 0, 255}); + MainButton1Txt.SetMaxWidth(MainButton1Img.GetWidth() - 150, DOTTED); + MainButton1Txt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + MainButton1Txt.SetPosition(148, -12); + GuiText MainButton1DescTxt(MainButtonText, 18, ( GXColor ) + { 0, 0, 0, 255}); + MainButton1DescTxt.SetMaxWidth(MainButton1Img.GetWidth() - 150, DOTTED); + MainButton1DescTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + MainButton1DescTxt.SetPosition(148, 15); + GuiText MainButton1DescOverTxt(MainButtonText, 18, ( GXColor ) + { 0, 0, 0, 255}); + MainButton1DescOverTxt.SetMaxWidth(MainButton1Img.GetWidth() - 150, SCROLL_HORIZONTAL); + MainButton1DescOverTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + MainButton1DescOverTxt.SetPosition(148, 15); + 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.SetLabel(&MainButton1DescTxt, 1); + MainButton1.SetLabelOver(&MainButton1DescOverTxt, 1); + MainButton1.SetSoundOver(&btnSoundOver); + MainButton1.SetSoundClick(&btnClick1); MainButton1.SetEffectGrow(); - MainButton1.SetTrigger( &trigA ); + MainButton1.SetTrigger(&trigA); - GuiImage MainButton2Img( &MainButtonImgData ); - GuiImage MainButton2ImgOver( &MainButtonImgOverData ); - GuiText MainButton2Txt( MainButtonText, 18, ( GXColor ) {0, 0, 0, 255 } ); - MainButton2Txt.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - MainButton2Txt.SetPosition( 148, -12 ); - MainButton2Txt.SetMaxWidth( MainButton2Img.GetWidth() - 150, DOTTED ); - GuiText MainButton2DescTxt( MainButtonText, 18, ( GXColor ) { 0, 0, 0, 255} ); - MainButton2DescTxt.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - MainButton2DescTxt.SetPosition( 148, 15 ); - MainButton2DescTxt.SetMaxWidth( MainButton2Img.GetWidth() - 150, DOTTED ); - GuiText MainButton2DescOverTxt( MainButtonText, 18, ( GXColor ) {0, 0, 0, 255} ); - MainButton2DescOverTxt.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - MainButton2DescOverTxt.SetPosition( 148, 15 ); - MainButton2DescOverTxt.SetMaxWidth( MainButton2Img.GetWidth() - 150, SCROLL_HORIZONTAL ); - 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.SetLabel( &MainButton2DescTxt, 1 ); - MainButton2.SetLabelOver( &MainButton2DescOverTxt, 1 ); - MainButton2.SetSoundOver( &btnSoundOver ); - MainButton2.SetSoundClick( &btnClick1 ); + GuiImage MainButton2Img(&MainButtonImgData); + GuiImage MainButton2ImgOver(&MainButtonImgOverData); + GuiText MainButton2Txt(MainButtonText, 18, ( GXColor ) + { 0, 0, 0, 255}); + MainButton2Txt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + MainButton2Txt.SetPosition(148, -12); + MainButton2Txt.SetMaxWidth(MainButton2Img.GetWidth() - 150, DOTTED); + GuiText MainButton2DescTxt(MainButtonText, 18, ( GXColor ) + { 0, 0, 0, 255}); + MainButton2DescTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + MainButton2DescTxt.SetPosition(148, 15); + MainButton2DescTxt.SetMaxWidth(MainButton2Img.GetWidth() - 150, DOTTED); + GuiText MainButton2DescOverTxt(MainButtonText, 18, ( GXColor ) + { 0, 0, 0, 255}); + MainButton2DescOverTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + MainButton2DescOverTxt.SetPosition(148, 15); + MainButton2DescOverTxt.SetMaxWidth(MainButton2Img.GetWidth() - 150, SCROLL_HORIZONTAL); + 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.SetLabel(&MainButton2DescTxt, 1); + MainButton2.SetLabelOver(&MainButton2DescOverTxt, 1); + MainButton2.SetSoundOver(&btnSoundOver); + MainButton2.SetSoundClick(&btnClick1); MainButton2.SetEffectGrow(); - MainButton2.SetTrigger( &trigA ); + MainButton2.SetTrigger(&trigA); - GuiImage MainButton3Img( &MainButtonImgData ); - GuiImage MainButton3ImgOver( &MainButtonImgOverData ); - GuiText MainButton3Txt( MainButtonText, 18, ( GXColor ) {0, 0, 0, 255} ); - MainButton3Txt.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - MainButton3Txt.SetPosition( 148, -12 ); - MainButton3Txt.SetMaxWidth( MainButton3Img.GetWidth() - 150, DOTTED ); - GuiText MainButton3DescTxt( MainButtonText, 18, ( GXColor ) { 0, 0, 0, 255} ); - MainButton3DescTxt.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - MainButton3DescTxt.SetPosition( 148, 15 ); - MainButton3DescTxt.SetMaxWidth( MainButton3Img.GetWidth() - 150, DOTTED ); - GuiText MainButton3DescOverTxt( MainButtonText, 18, ( GXColor ) {0, 0, 0, 255 } ); - MainButton3DescOverTxt.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - MainButton3DescOverTxt.SetPosition( 148, 15 ); - MainButton3DescOverTxt.SetMaxWidth( MainButton3Img.GetWidth() - 150, SCROLL_HORIZONTAL ); - 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.SetLabel( &MainButton3DescTxt, 1 ); - MainButton3.SetLabelOver( &MainButton3DescOverTxt, 1 ); - MainButton3.SetSoundOver( &btnSoundOver ); - MainButton3.SetSoundClick( &btnClick1 ); + GuiImage MainButton3Img(&MainButtonImgData); + GuiImage MainButton3ImgOver(&MainButtonImgOverData); + GuiText MainButton3Txt(MainButtonText, 18, ( GXColor ) + { 0, 0, 0, 255}); + MainButton3Txt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + MainButton3Txt.SetPosition(148, -12); + MainButton3Txt.SetMaxWidth(MainButton3Img.GetWidth() - 150, DOTTED); + GuiText MainButton3DescTxt(MainButtonText, 18, ( GXColor ) + { 0, 0, 0, 255}); + MainButton3DescTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + MainButton3DescTxt.SetPosition(148, 15); + MainButton3DescTxt.SetMaxWidth(MainButton3Img.GetWidth() - 150, DOTTED); + GuiText MainButton3DescOverTxt(MainButtonText, 18, ( GXColor ) + { 0, 0, 0, 255}); + MainButton3DescOverTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + MainButton3DescOverTxt.SetPosition(148, 15); + MainButton3DescOverTxt.SetMaxWidth(MainButton3Img.GetWidth() - 150, SCROLL_HORIZONTAL); + 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.SetLabel(&MainButton3DescTxt, 1); + MainButton3.SetLabelOver(&MainButton3DescOverTxt, 1); + MainButton3.SetSoundOver(&btnSoundOver); + MainButton3.SetSoundClick(&btnClick1); MainButton3.SetEffectGrow(); - MainButton3.SetTrigger( &trigA ); + MainButton3.SetTrigger(&trigA); - GuiImage MainButton4Img( &MainButtonImgData ); - GuiImage MainButton4ImgOver( &MainButtonImgOverData ); - GuiText MainButton4Txt( MainButtonText, 18, ( GXColor ) {0, 0, 0, 255} ); - MainButton4Txt.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - MainButton4Txt.SetPosition( 148, -12 ); - MainButton4Txt.SetMaxWidth( MainButton4Img.GetWidth() - 150, DOTTED ); - GuiText MainButton4DescTxt( MainButtonText, 18, ( GXColor ) {0, 0, 0, 255} ); - MainButton4DescTxt.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - MainButton4DescTxt.SetPosition( 148, 15 ); - MainButton4DescTxt.SetMaxWidth( MainButton4Img.GetWidth() - 150, DOTTED ); - GuiText MainButton4DescOverTxt( MainButtonText, 18, ( GXColor ) { 0, 0, 0, 255} ); - MainButton4DescOverTxt.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - MainButton4DescOverTxt.SetPosition( 148, 15 ); - MainButton4DescOverTxt.SetMaxWidth( MainButton4Img.GetWidth() - 150, SCROLL_HORIZONTAL ); - 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.SetLabel( &MainButton4DescTxt, 1 ); - MainButton4.SetLabelOver( &MainButton4DescOverTxt, 1 ); - MainButton4.SetSoundOver( &btnSoundOver ); - MainButton4.SetSoundClick( &btnClick1 ); + GuiImage MainButton4Img(&MainButtonImgData); + GuiImage MainButton4ImgOver(&MainButtonImgOverData); + GuiText MainButton4Txt(MainButtonText, 18, ( GXColor ) + { 0, 0, 0, 255}); + MainButton4Txt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + MainButton4Txt.SetPosition(148, -12); + MainButton4Txt.SetMaxWidth(MainButton4Img.GetWidth() - 150, DOTTED); + GuiText MainButton4DescTxt(MainButtonText, 18, ( GXColor ) + { 0, 0, 0, 255}); + MainButton4DescTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + MainButton4DescTxt.SetPosition(148, 15); + MainButton4DescTxt.SetMaxWidth(MainButton4Img.GetWidth() - 150, DOTTED); + GuiText MainButton4DescOverTxt(MainButtonText, 18, ( GXColor ) + { 0, 0, 0, 255}); + MainButton4DescOverTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + MainButton4DescOverTxt.SetPosition(148, 15); + MainButton4DescOverTxt.SetMaxWidth(MainButton4Img.GetWidth() - 150, SCROLL_HORIZONTAL); + 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.SetLabel(&MainButton4DescTxt, 1); + MainButton4.SetLabelOver(&MainButton4DescOverTxt, 1); + MainButton4.SetSoundOver(&btnSoundOver); + MainButton4.SetSoundClick(&btnClick1); MainButton4.SetEffectGrow(); - MainButton4.SetTrigger( &trigA ); + MainButton4.SetTrigger(&trigA); - GuiImage wifiImg( &wifiImgData ); - if ( Settings.wsprompt == yes ) + GuiImage wifiImg(&wifiImgData); + if (Settings.wsprompt == yes) { - wifiImg.SetWidescreen( Settings.widescreen ); + wifiImg.SetWidescreen(Settings.widescreen); } - GuiButton wifiBtn( wifiImg.GetWidth(), wifiImg.GetHeight() ); - wifiBtn.SetImage( &wifiImg ); - wifiBtn.SetPosition( 500, 400 ); - wifiBtn.SetSoundOver( &btnSoundOver ); - wifiBtn.SetSoundClick( &btnClick1 ); + GuiButton wifiBtn(wifiImg.GetWidth(), wifiImg.GetHeight()); + wifiBtn.SetImage(&wifiImg); + wifiBtn.SetPosition(500, 400); + wifiBtn.SetSoundOver(&btnSoundOver); + wifiBtn.SetSoundClick(&btnClick1); wifiBtn.SetEffectGrow(); - wifiBtn.SetAlpha( 80 ); - wifiBtn.SetTrigger( &trigA ); + wifiBtn.SetAlpha(80); + wifiBtn.SetTrigger(&trigA); - GuiImage channelBtnImg( &channelImgData ); - channelBtnImg.SetWidescreen( Settings.widescreen ); - GuiButton channelBtn( channelBtnImg.GetWidth(), channelBtnImg.GetHeight() ); - channelBtn.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - channelBtn.SetPosition( 440, 400 ); - channelBtn.SetImage( &channelBtnImg ); - channelBtn.SetSoundOver( &btnSoundOver ); - channelBtn.SetSoundClick( btnClick2 ); + GuiImage channelBtnImg(&channelImgData); + channelBtnImg.SetWidescreen(Settings.widescreen); + GuiButton channelBtn(channelBtnImg.GetWidth(), channelBtnImg.GetHeight()); + channelBtn.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + channelBtn.SetPosition(440, 400); + channelBtn.SetImage(&channelBtnImg); + channelBtn.SetSoundOver(&btnSoundOver); + channelBtn.SetSoundClick(btnClick2); channelBtn.SetEffectGrow(); - channelBtn.SetTrigger( &trigA ); + channelBtn.SetTrigger(&trigA); GuiTooltip * titleTT = NULL; - - GuiWindow w( screenwidth, screenheight ); + GuiWindow w(screenwidth, screenheight); /*** XML Variables ***/ HomebrewXML XMLInfo[4]; int pageToDisplay = 1; - const int pages = roundup( filecount / 4.0f ); + const int pages = roundup(filecount / 4.0f); bool wifi_btn_loaded = false; - while ( menu == MENU_NONE ) //set pageToDisplay to 0 to quit + while (menu == MENU_NONE) //set pageToDisplay to 0 to quit { - VIDEO_WaitVSync (); + VIDEO_WaitVSync(); menu = MENU_NONE; bool changed = false; @@ -352,21 +359,23 @@ int MenuHomebrewBrowse() MainButton3.StopEffect(); MainButton4.StopEffect(); - if ( slidedirection == RIGHT ) + if (slidedirection == RIGHT) { - MainButton1.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 60 ); - MainButton2.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 60 ); - MainButton3.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 60 ); - MainButton4.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 60 ); - while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 60); + MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 60); + MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 60); + MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 60); + while (MainButton1.GetEffect() > 0) + usleep(50); } - else if ( slidedirection == LEFT ) + else if (slidedirection == LEFT) { - MainButton1.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 60 ); - MainButton2.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 60 ); - MainButton3.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 60 ); - MainButton4.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 60 ); - while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 60); + MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 60); + MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 60); + MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 60); + while (MainButton1.GetEffect() > 0) + usleep(50); } HaltGui(); @@ -374,162 +383,166 @@ int MenuHomebrewBrowse() mainWindow->RemoveAll(); /** Set new icons **/ - for ( int i = 0; i < 4; i++ ) + for (int i = 0; i < 4; i++) { - if ( IconData[i] != NULL ) + if (IconData[i] != NULL) { delete IconData[i]; IconData[i] = NULL; } - if ( IconImg[i] != NULL ) + if (IconImg[i] != NULL) { delete IconImg[i]; IconImg[i] = NULL; } - if ( fileoffset + i < ( int ) filecount ) + if (fileoffset + i < (int) filecount) { char iconpath[200]; - snprintf( iconpath, sizeof( iconpath ), "%sicon.png", HomebrewFiles.GetFilepath( fileoffset + i ) ); - IconData[i] = new GuiImageData( iconpath, 0 ); - if ( IconData[i]->GetImage() ) + snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset + i)); + IconData[i] = new GuiImageData(iconpath, 0); + if (IconData[i]->GetImage()) { - IconImg[i] = new GuiImage( IconData[i] ); - IconImg[i]->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - IconImg[i]->SetPosition( 12, 0 ); - IconImg[i]->SetScale( 0.95 ); + IconImg[i] = new GuiImage(IconData[i]); + IconImg[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + IconImg[i]->SetPosition(12, 0); + IconImg[i]->SetScale(0.95); } } } - if ( IconImg[0] != 0 ) - MainButton1.SetIcon( IconImg[0] ); - else - MainButton1.SetIcon( NULL ); - if ( IconImg[1] != 0 ) - MainButton2.SetIcon( IconImg[1] ); - else - MainButton2.SetIcon( NULL ); - if ( IconImg[2] != 0 ) - MainButton3.SetIcon( IconImg[2] ); - else - MainButton3.SetIcon( NULL ); - if ( IconImg[3] != 0 ) - MainButton4.SetIcon( IconImg[3] ); - else - MainButton4.SetIcon( NULL ); + if (IconImg[0] != 0) + MainButton1.SetIcon(IconImg[0]); + else MainButton1.SetIcon(NULL); + if (IconImg[1] != 0) + MainButton2.SetIcon(IconImg[1]); + else MainButton2.SetIcon(NULL); + if (IconImg[2] != 0) + MainButton3.SetIcon(IconImg[2]); + else MainButton3.SetIcon(NULL); + if (IconImg[3] != 0) + MainButton4.SetIcon(IconImg[3]); + else MainButton4.SetIcon(NULL); - mainWindow->Append( &w ); + mainWindow->Append(&w); w.RemoveAll(); - w.Append( &background ); - w.Append( &titleTxt ); - w.Append( &backBtn ); - w.Append( &homo ); - w.Append( &wifiBtn ); - w.Append( &channelBtn ); - w.Append( &GoRightBtn ); - w.Append( &GoLeftBtn ); + w.Append(&background); + w.Append(&titleTxt); + w.Append(&backBtn); + w.Append(&homo); + w.Append(&wifiBtn); + w.Append(&channelBtn); + w.Append(&GoRightBtn); + w.Append(&GoLeftBtn); - if ( pageToDisplay == pages ) + if (pageToDisplay == pages) { - int buttonsleft = filecount - ( pages - 1 ) * 4; + int buttonsleft = filecount - (pages - 1) * 4; char * shortpath = NULL; char temp[200]; - if ( buttonsleft > 0 ) + if (buttonsleft > 0) { - snprintf( temp, sizeof( temp ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset ) ); - if ( XMLInfo[0].LoadHomebrewXMLData( temp ) > 0 ) + snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset)); + if (XMLInfo[0].LoadHomebrewXMLData(temp) > 0) { - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[0].GetName() ); - MainButton1Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[0].GetShortDescription() ); - MainButton1DescTxt.SetText( MainButtonText ); - MainButton1DescOverTxt.SetText( MainButtonText ); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[0].GetName()); + MainButton1Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[0].GetShortDescription()); + MainButton1DescTxt.SetText(MainButtonText); + MainButton1DescOverTxt.SetText(MainButtonText); } else { - snprintf( temp, strlen( HomebrewFiles.GetFilepath( fileoffset ) ), "%s", HomebrewFiles.GetFilepath( fileoffset ) ); - shortpath = strrchr( temp, '/' ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s/%s", shortpath, HomebrewFiles.GetFilename( fileoffset ) ); - XMLInfo[0].SetName( MainButtonText ); - MainButton1Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), " " ); - MainButton1DescTxt.SetText( MainButtonText ); - MainButton1DescOverTxt.SetText( MainButtonText ); + snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset)), "%s", HomebrewFiles.GetFilepath( + fileoffset)); + shortpath = strrchr(temp, '/'); + snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename( + fileoffset)); + XMLInfo[0].SetName(MainButtonText); + MainButton1Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), " "); + MainButton1DescTxt.SetText(MainButtonText); + MainButton1DescOverTxt.SetText(MainButtonText); } - w.Append( &MainButton1 ); + w.Append(&MainButton1); } - if ( buttonsleft > 1 ) + if (buttonsleft > 1) { - snprintf( temp, sizeof( temp ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset + 1 ) ); - if ( XMLInfo[1].LoadHomebrewXMLData( temp ) > 0 ) + snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset + 1)); + if (XMLInfo[1].LoadHomebrewXMLData(temp) > 0) { - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[1].GetName() ); - MainButton2Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[1].GetShortDescription() ); - MainButton2DescTxt.SetText( MainButtonText ); - MainButton2DescOverTxt.SetText( MainButtonText ); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[1].GetName()); + MainButton2Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[1].GetShortDescription()); + MainButton2DescTxt.SetText(MainButtonText); + MainButton2DescOverTxt.SetText(MainButtonText); } else { - snprintf( temp, strlen( HomebrewFiles.GetFilepath( fileoffset + 1 ) ), "%s", HomebrewFiles.GetFilepath( fileoffset + 1 ) ); - shortpath = strrchr( temp, '/' ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s/%s", shortpath, HomebrewFiles.GetFilename( fileoffset + 1 ) ); - XMLInfo[1].SetName( MainButtonText ); - MainButton2Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), " " ); - MainButton2DescTxt.SetText( MainButtonText ); - MainButton2DescOverTxt.SetText( MainButtonText ); + snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset + 1)), "%s", HomebrewFiles.GetFilepath( + fileoffset + 1)); + shortpath = strrchr(temp, '/'); + snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename( + fileoffset + 1)); + XMLInfo[1].SetName(MainButtonText); + MainButton2Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), " "); + MainButton2DescTxt.SetText(MainButtonText); + MainButton2DescOverTxt.SetText(MainButtonText); } - w.Append( &MainButton2 ); + w.Append(&MainButton2); } - if ( buttonsleft > 2 ) + if (buttonsleft > 2) { - snprintf( temp, sizeof( temp ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset + 2 ) ); - if ( XMLInfo[3].LoadHomebrewXMLData( temp ) > 0 ) + snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset + 2)); + if (XMLInfo[3].LoadHomebrewXMLData(temp) > 0) { - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[3].GetName() ); - MainButton3Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[3].GetShortDescription() ); - MainButton3DescTxt.SetText( MainButtonText ); - MainButton3DescOverTxt.SetText( MainButtonText ); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetName()); + MainButton3Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetShortDescription()); + MainButton3DescTxt.SetText(MainButtonText); + MainButton3DescOverTxt.SetText(MainButtonText); } else { - snprintf( temp, strlen( HomebrewFiles.GetFilepath( fileoffset + 2 ) ), "%s", HomebrewFiles.GetFilepath( fileoffset + 2 ) ); - shortpath = strrchr( temp, '/' ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s/%s", shortpath, HomebrewFiles.GetFilename( fileoffset + 2 ) ); - XMLInfo[2].SetName( MainButtonText ); - MainButton3Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), " " ); - MainButton3DescTxt.SetText( MainButtonText ); - MainButton3DescOverTxt.SetText( MainButtonText ); + snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset + 2)), "%s", HomebrewFiles.GetFilepath( + fileoffset + 2)); + shortpath = strrchr(temp, '/'); + snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename( + fileoffset + 2)); + XMLInfo[2].SetName(MainButtonText); + MainButton3Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), " "); + MainButton3DescTxt.SetText(MainButtonText); + MainButton3DescOverTxt.SetText(MainButtonText); } - w.Append( &MainButton3 ); + w.Append(&MainButton3); } - if ( buttonsleft > 3 ) + if (buttonsleft > 3) { - snprintf( temp, sizeof( temp ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset + 3 ) ); - if ( XMLInfo[3].LoadHomebrewXMLData( temp ) > 0 ) + snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset + 3)); + if (XMLInfo[3].LoadHomebrewXMLData(temp) > 0) { - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[3].GetName() ); - MainButton4Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[3].GetShortDescription() ); - MainButton4DescTxt.SetText( MainButtonText ); - MainButton4DescOverTxt.SetText( MainButtonText ); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetName()); + MainButton4Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetShortDescription()); + MainButton4DescTxt.SetText(MainButtonText); + MainButton4DescOverTxt.SetText(MainButtonText); } else { - snprintf( temp, strlen( HomebrewFiles.GetFilepath( fileoffset + 3 ) ), "%s", HomebrewFiles.GetFilepath( fileoffset + 3 ) ); - shortpath = strrchr( temp, '/' ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s/%s", shortpath, HomebrewFiles.GetFilename( fileoffset + 3 ) ); - XMLInfo[3].SetName( MainButtonText ); - MainButton4Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), " " ); - MainButton4DescTxt.SetText( MainButtonText ); - MainButton4DescOverTxt.SetText( MainButtonText ); + snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset + 3)), "%s", HomebrewFiles.GetFilepath( + fileoffset + 3)); + shortpath = strrchr(temp, '/'); + snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename( + fileoffset + 3)); + XMLInfo[3].SetName(MainButtonText); + MainButton4Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), " "); + MainButton4DescTxt.SetText(MainButtonText); + MainButton4DescOverTxt.SetText(MainButtonText); } - w.Append( &MainButton4 ); + w.Append(&MainButton4); } } else @@ -537,96 +550,104 @@ int MenuHomebrewBrowse() char temp[200]; char *shortpath = NULL; - snprintf( temp, sizeof( temp ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset ) ); - if ( XMLInfo[0].LoadHomebrewXMLData( temp ) > 0 ) + snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset)); + if (XMLInfo[0].LoadHomebrewXMLData(temp) > 0) { - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[0].GetName() ); - MainButton1Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[0].GetShortDescription() ); - MainButton1DescTxt.SetText( MainButtonText ); - MainButton1DescOverTxt.SetText( MainButtonText ); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[0].GetName()); + MainButton1Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[0].GetShortDescription()); + MainButton1DescTxt.SetText(MainButtonText); + MainButton1DescOverTxt.SetText(MainButtonText); } else { - snprintf( temp, strlen( HomebrewFiles.GetFilepath( fileoffset ) ), "%s", HomebrewFiles.GetFilepath( fileoffset ) ); - shortpath = strrchr( temp, '/' ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s/%s", shortpath, HomebrewFiles.GetFilename( fileoffset ) ); - XMLInfo[0].SetName( MainButtonText ); - MainButton1Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), " " ); - MainButton1DescTxt.SetText( MainButtonText ); - MainButton1DescOverTxt.SetText( MainButtonText ); + snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset)), "%s", HomebrewFiles.GetFilepath( + fileoffset)); + shortpath = strrchr(temp, '/'); + snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename( + fileoffset)); + XMLInfo[0].SetName(MainButtonText); + MainButton1Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), " "); + MainButton1DescTxt.SetText(MainButtonText); + MainButton1DescOverTxt.SetText(MainButtonText); } - w.Append( &MainButton1 ); + w.Append(&MainButton1); - snprintf( temp, sizeof( temp ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset + 1 ) ); - if ( XMLInfo[1].LoadHomebrewXMLData( temp ) > 0 ) + snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset + 1)); + if (XMLInfo[1].LoadHomebrewXMLData(temp) > 0) { - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[1].GetName() ); - MainButton2Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[1].GetShortDescription() ); - MainButton2DescTxt.SetText( MainButtonText ); - MainButton2DescOverTxt.SetText( MainButtonText ); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[1].GetName()); + MainButton2Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[1].GetShortDescription()); + MainButton2DescTxt.SetText(MainButtonText); + MainButton2DescOverTxt.SetText(MainButtonText); } else { - snprintf( temp, strlen( HomebrewFiles.GetFilepath( fileoffset + 1 ) ), "%s", HomebrewFiles.GetFilepath( fileoffset + 1 ) ); - shortpath = strrchr( temp, '/' ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s/%s", shortpath, HomebrewFiles.GetFilename( fileoffset + 1 ) ); - XMLInfo[1].SetName( MainButtonText ); - MainButton2Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), " " ); - MainButton2DescTxt.SetText( MainButtonText ); - MainButton2DescOverTxt.SetText( MainButtonText ); + snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset + 1)), "%s", HomebrewFiles.GetFilepath( + fileoffset + 1)); + shortpath = strrchr(temp, '/'); + snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename( + fileoffset + 1)); + XMLInfo[1].SetName(MainButtonText); + MainButton2Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), " "); + MainButton2DescTxt.SetText(MainButtonText); + MainButton2DescOverTxt.SetText(MainButtonText); } - w.Append( &MainButton2 ); + w.Append(&MainButton2); - snprintf( temp, sizeof( temp ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset + 2 ) ); - if ( XMLInfo[3].LoadHomebrewXMLData( temp ) > 0 ) + snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset + 2)); + if (XMLInfo[3].LoadHomebrewXMLData(temp) > 0) { - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[3].GetName() ); - MainButton3Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[3].GetShortDescription() ); - MainButton3DescTxt.SetText( MainButtonText ); - MainButton3DescOverTxt.SetText( MainButtonText ); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetName()); + MainButton3Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetShortDescription()); + MainButton3DescTxt.SetText(MainButtonText); + MainButton3DescOverTxt.SetText(MainButtonText); } else { - snprintf( temp, strlen( HomebrewFiles.GetFilepath( fileoffset + 2 ) ), "%s", HomebrewFiles.GetFilepath( fileoffset + 2 ) ); - shortpath = strrchr( temp, '/' ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s/%s", shortpath, HomebrewFiles.GetFilename( fileoffset + 2 ) ); - XMLInfo[2].SetName( MainButtonText ); - MainButton3Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), " " ); - MainButton3DescTxt.SetText( MainButtonText ); - MainButton3DescOverTxt.SetText( MainButtonText ); + snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset + 2)), "%s", HomebrewFiles.GetFilepath( + fileoffset + 2)); + shortpath = strrchr(temp, '/'); + snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename( + fileoffset + 2)); + XMLInfo[2].SetName(MainButtonText); + MainButton3Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), " "); + MainButton3DescTxt.SetText(MainButtonText); + MainButton3DescOverTxt.SetText(MainButtonText); } - w.Append( &MainButton3 ); + w.Append(&MainButton3); - snprintf( temp, sizeof( temp ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset + 3 ) ); - if ( XMLInfo[3].LoadHomebrewXMLData( temp ) > 0 ) + snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset + 3)); + if (XMLInfo[3].LoadHomebrewXMLData(temp) > 0) { - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[3].GetName() ); - MainButton4Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", XMLInfo[3].GetShortDescription() ); - MainButton4DescTxt.SetText( MainButtonText ); - MainButton4DescOverTxt.SetText( MainButtonText ); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetName()); + MainButton4Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetShortDescription()); + MainButton4DescTxt.SetText(MainButtonText); + MainButton4DescOverTxt.SetText(MainButtonText); } else { - snprintf( temp, strlen( HomebrewFiles.GetFilepath( fileoffset + 3 ) ), "%s", HomebrewFiles.GetFilepath( fileoffset + 3 ) ); - shortpath = strrchr( temp, '/' ); - snprintf( MainButtonText, sizeof( MainButtonText ), "%s/%s", shortpath, HomebrewFiles.GetFilename( fileoffset + 3 ) ); - XMLInfo[3].SetName( MainButtonText ); - MainButton4Txt.SetText( MainButtonText ); - snprintf( MainButtonText, sizeof( MainButtonText ), " " ); - MainButton4DescTxt.SetText( MainButtonText ); - MainButton4DescOverTxt.SetText( MainButtonText ); + snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset + 3)), "%s", HomebrewFiles.GetFilepath( + fileoffset + 3)); + shortpath = strrchr(temp, '/'); + snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename( + fileoffset + 3)); + XMLInfo[3].SetName(MainButtonText); + MainButton4Txt.SetText(MainButtonText); + snprintf(MainButtonText, sizeof(MainButtonText), " "); + MainButton4DescTxt.SetText(MainButtonText); + MainButton4DescOverTxt.SetText(MainButtonText); } - w.Append( &MainButton4 ); + w.Append(&MainButton4); } MainButton1.StopEffect(); @@ -639,39 +660,40 @@ int MenuHomebrewBrowse() MainButton3.SetEffectGrow(); MainButton4.SetEffectGrow(); - if ( slidedirection == FADE ) + if (slidedirection == FADE) { - 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); } - else if ( slidedirection == LEFT ) + else if (slidedirection == LEFT) { - MainButton1.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 60 ); - MainButton2.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 60 ); - MainButton3.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 60 ); - MainButton4.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 60 ); + MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 60); + MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 60); + MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 60); + MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 60); } - else if ( slidedirection == RIGHT ) + else if (slidedirection == RIGHT) { - MainButton1.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 60 ); - MainButton2.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 60 ); - MainButton3.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 60 ); - MainButton4.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 60 ); + MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 60); + MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 60); + MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 60); + MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 60); } - mainWindow->Append( &w ); + mainWindow->Append(&w); ResumeGui(); - while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + while (MainButton1.GetEffect() > 0) + usleep(50); - while ( !changed ) + while (!changed) { - VIDEO_WaitVSync (); + VIDEO_WaitVSync(); - if ( MainButton1.GetState() == STATE_CLICKED ) + if (MainButton1.GetState() == STATE_CLICKED) { char temp[200]; char iconpath[200]; @@ -679,29 +701,32 @@ int MenuHomebrewBrowse() char * shortpath = NULL; //write iconpath - snprintf( metapath, sizeof( metapath ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset ) ); + snprintf(metapath, sizeof(metapath), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset)); //write iconpath - snprintf( iconpath, sizeof( iconpath ), "%sicon.png", HomebrewFiles.GetFilepath( fileoffset ) ); + snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset)); //get filesize - u64 filesize = HomebrewFiles.GetFilesize( fileoffset ); + u64 filesize = HomebrewFiles.GetFilesize(fileoffset); //write short filename - snprintf( temp, strlen( HomebrewFiles.GetFilepath( fileoffset ) ), "%s", HomebrewFiles.GetFilepath( fileoffset ) ); - shortpath = strrchr( temp, '/' ); - snprintf( temp, sizeof( temp ), "%s/%s", shortpath, HomebrewFiles.GetFilename( fileoffset ) ); + snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset)), "%s", HomebrewFiles.GetFilepath( + fileoffset)); + shortpath = strrchr(temp, '/'); + snprintf(temp, sizeof(temp), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset)); - int choice = HBCWindowPrompt( XMLInfo[0].GetName(), XMLInfo[0].GetCoder(), XMLInfo[0].GetVersion(), XMLInfo[0].GetReleasedate(), XMLInfo[0].GetLongDescription(), iconpath, filesize ); - if ( choice == 1 ) + int choice = HBCWindowPrompt(XMLInfo[0].GetName(), XMLInfo[0].GetCoder(), XMLInfo[0].GetVersion(), + XMLInfo[0].GetReleasedate(), XMLInfo[0].GetLongDescription(), iconpath, filesize); + if (choice == 1) { boothomebrew = 1; menu = MENU_EXIT; - snprintf( Settings.selected_homebrew, sizeof( Settings.selected_homebrew ), "%s%s", HomebrewFiles.GetFilepath( fileoffset ), HomebrewFiles.GetFilename( fileoffset ) ); + snprintf(Settings.selected_homebrew, sizeof(Settings.selected_homebrew), "%s%s", + HomebrewFiles.GetFilepath(fileoffset), HomebrewFiles.GetFilename(fileoffset)); break; } MainButton1.ResetState(); } - else if ( MainButton2.GetState() == STATE_CLICKED ) + else if (MainButton2.GetState() == STATE_CLICKED) { char temp[200]; char iconpath[200]; @@ -709,29 +734,32 @@ int MenuHomebrewBrowse() char * shortpath = NULL; //write iconpath - snprintf( metapath, sizeof( metapath ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset + 1 ) ); + snprintf(metapath, sizeof(metapath), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset + 1)); //write iconpath - snprintf( iconpath, sizeof( iconpath ), "%sicon.png", HomebrewFiles.GetFilepath( fileoffset + 1 ) ); + snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset + 1)); //get filesize - u64 filesize = HomebrewFiles.GetFilesize( fileoffset + 1 ); + u64 filesize = HomebrewFiles.GetFilesize(fileoffset + 1); //write short filename - snprintf( temp, strlen( HomebrewFiles.GetFilepath( fileoffset + 1 ) ), "%s", HomebrewFiles.GetFilepath( fileoffset + 1 ) ); - shortpath = strrchr( temp, '/' ); - snprintf( temp, sizeof( temp ), "%s/%s", shortpath, HomebrewFiles.GetFilename( fileoffset + 1 ) ); + snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset + 1)), "%s", HomebrewFiles.GetFilepath( + fileoffset + 1)); + shortpath = strrchr(temp, '/'); + snprintf(temp, sizeof(temp), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset + 1)); - int choice = HBCWindowPrompt( XMLInfo[1].GetName(), XMLInfo[1].GetCoder(), XMLInfo[1].GetVersion(), XMLInfo[1].GetReleasedate(), XMLInfo[1].GetLongDescription(), iconpath, filesize ); - if ( choice == 1 ) + int choice = HBCWindowPrompt(XMLInfo[1].GetName(), XMLInfo[1].GetCoder(), XMLInfo[1].GetVersion(), + XMLInfo[1].GetReleasedate(), XMLInfo[1].GetLongDescription(), iconpath, filesize); + if (choice == 1) { boothomebrew = 1; menu = MENU_EXIT; - snprintf( Settings.selected_homebrew, sizeof( Settings.selected_homebrew ), "%s%s", HomebrewFiles.GetFilepath( fileoffset + 1 ), HomebrewFiles.GetFilename( fileoffset + 1 ) ); + snprintf(Settings.selected_homebrew, sizeof(Settings.selected_homebrew), "%s%s", + HomebrewFiles.GetFilepath(fileoffset + 1), HomebrewFiles.GetFilename(fileoffset + 1)); break; } MainButton2.ResetState(); } - else if ( MainButton3.GetState() == STATE_CLICKED ) + else if (MainButton3.GetState() == STATE_CLICKED) { char temp[200]; char iconpath[200]; @@ -739,29 +767,32 @@ int MenuHomebrewBrowse() char * shortpath = NULL; //write iconpath - snprintf( metapath, sizeof( metapath ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset + 2 ) ); + snprintf(metapath, sizeof(metapath), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset + 2)); //write iconpath - snprintf( iconpath, sizeof( iconpath ), "%sicon.png", HomebrewFiles.GetFilepath( fileoffset + 2 ) ); + snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset + 2)); //get filesize - u64 filesize = HomebrewFiles.GetFilesize( fileoffset + 2 ); + u64 filesize = HomebrewFiles.GetFilesize(fileoffset + 2); //write short filename - snprintf( temp, strlen( HomebrewFiles.GetFilepath( fileoffset + 2 ) ), "%s", HomebrewFiles.GetFilepath( fileoffset + 2 ) ); - shortpath = strrchr( temp, '/' ); - snprintf( temp, sizeof( temp ), "%s/%s", shortpath, HomebrewFiles.GetFilename( fileoffset + 2 ) ); + snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset + 2)), "%s", HomebrewFiles.GetFilepath( + fileoffset + 2)); + shortpath = strrchr(temp, '/'); + snprintf(temp, sizeof(temp), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset + 2)); - int choice = HBCWindowPrompt( XMLInfo[2].GetName(), XMLInfo[2].GetCoder(), XMLInfo[2].GetVersion(), XMLInfo[2].GetReleasedate(), XMLInfo[2].GetLongDescription(), iconpath, filesize ); - if ( choice == 1 ) + int choice = HBCWindowPrompt(XMLInfo[2].GetName(), XMLInfo[2].GetCoder(), XMLInfo[2].GetVersion(), + XMLInfo[2].GetReleasedate(), XMLInfo[2].GetLongDescription(), iconpath, filesize); + if (choice == 1) { boothomebrew = 1; menu = MENU_EXIT; - snprintf( Settings.selected_homebrew, sizeof( Settings.selected_homebrew ), "%s%s", HomebrewFiles.GetFilepath( fileoffset + 2 ), HomebrewFiles.GetFilename( fileoffset + 2 ) ); + snprintf(Settings.selected_homebrew, sizeof(Settings.selected_homebrew), "%s%s", + HomebrewFiles.GetFilepath(fileoffset + 2), HomebrewFiles.GetFilename(fileoffset + 2)); break; } MainButton3.ResetState(); } - else if ( MainButton4.GetState() == STATE_CLICKED ) + else if (MainButton4.GetState() == STATE_CLICKED) { char temp[200]; char iconpath[200]; @@ -769,81 +800,82 @@ int MenuHomebrewBrowse() char * shortpath = NULL; //write iconpath - snprintf( metapath, sizeof( metapath ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset + 3 ) ); + snprintf(metapath, sizeof(metapath), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset + 3)); //write iconpath - snprintf( iconpath, sizeof( iconpath ), "%sicon.png", HomebrewFiles.GetFilepath( fileoffset + 3 ) ); + snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset + 3)); //get filesize - u64 filesize = HomebrewFiles.GetFilesize( fileoffset + 3 ); + u64 filesize = HomebrewFiles.GetFilesize(fileoffset + 3); //write short filename - snprintf( temp, strlen( HomebrewFiles.GetFilepath( fileoffset + 3 ) ), "%s", HomebrewFiles.GetFilepath( fileoffset + 3 ) ); - shortpath = strrchr( temp, '/' ); - snprintf( temp, sizeof( temp ), "%s/%s", shortpath, HomebrewFiles.GetFilename( fileoffset + 3 ) ); + snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset + 3)), "%s", HomebrewFiles.GetFilepath( + fileoffset + 3)); + shortpath = strrchr(temp, '/'); + snprintf(temp, sizeof(temp), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset + 3)); - int choice = HBCWindowPrompt( XMLInfo[3].GetName(), XMLInfo[3].GetCoder(), XMLInfo[3].GetVersion(), XMLInfo[3].GetReleasedate(), XMLInfo[3].GetLongDescription(), iconpath, filesize ); - if ( choice == 1 ) + int choice = HBCWindowPrompt(XMLInfo[3].GetName(), XMLInfo[3].GetCoder(), XMLInfo[3].GetVersion(), + XMLInfo[3].GetReleasedate(), XMLInfo[3].GetLongDescription(), iconpath, filesize); + if (choice == 1) { boothomebrew = 1; menu = MENU_EXIT; - snprintf( Settings.selected_homebrew, sizeof( Settings.selected_homebrew ), "%s%s", HomebrewFiles.GetFilepath( fileoffset + 3 ), HomebrewFiles.GetFilename( fileoffset + 3 ) ); + snprintf(Settings.selected_homebrew, sizeof(Settings.selected_homebrew), "%s%s", + HomebrewFiles.GetFilepath(fileoffset + 3), HomebrewFiles.GetFilename(fileoffset + 3)); break; } MainButton4.ResetState(); } - else if ( shutdown == 1 ) + else if (shutdown == 1) Sys_Shutdown(); - else if ( reset == 1 ) + else if (reset == 1) Sys_Reboot(); - else if ( backBtn.GetState() == STATE_CLICKED ) + else if (backBtn.GetState() == STATE_CLICKED) { menu = MENU_DISCLIST; changed = true; } - else if ( GoLeftBtn.GetState() == STATE_CLICKED ) + else if (GoLeftBtn.GetState() == STATE_CLICKED) { pageToDisplay--; /** Change direction of the flying buttons **/ - if ( pageToDisplay < 1 ) - pageToDisplay = pages; + if (pageToDisplay < 1) pageToDisplay = pages; slidedirection = LEFT; changed = true; GoLeftBtn.ResetState(); } - else if ( GoRightBtn.GetState() == STATE_CLICKED ) + else if (GoRightBtn.GetState() == STATE_CLICKED) { pageToDisplay++; /** Change direction of the flying buttons **/ - if ( pageToDisplay > pages ) - pageToDisplay = 1; + if (pageToDisplay > pages) pageToDisplay = 1; slidedirection = RIGHT; changed = true; GoRightBtn.ResetState(); } - else if ( wifiBtn.GetState() == STATE_CLICKED ) + else if (wifiBtn.GetState() == STATE_CLICKED) { ResumeNetworkWait(); wifiBtn.ResetState(); } - else if ( homo.GetState() == STATE_CLICKED ) + else if (homo.GetState() == STATE_CLICKED) { Settings.Save(); bgMusic->Pause(); choice = WindowExitPrompt(); bgMusic->Resume(); - if ( choice == 3 ) + if (choice == 3) { Sys_LoadMenu(); // Back to System Menu } - else if ( choice == 2 ) + else if (choice == 2) { Sys_BackToLoader(); } @@ -853,58 +885,56 @@ int MenuHomebrewBrowse() } } - else if ( infilesize > 0 ) + else if (infilesize > 0) { char filesizetxt[50]; char temp[50]; - 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 ); + 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() ); + snprintf(temp, sizeof(temp), tr( "Load file from: %s ?" ), GetIncommingIP()); - int choice = WindowPrompt( filesizetxt, temp, tr( "OK" ), tr( "Cancel" ) ); + int choice = WindowPrompt(filesizetxt, temp, tr( "OK" ), tr( "Cancel" )); - if ( choice == 1 ) + if (choice == 1) { - int res = AllocHomebrewMemory( infilesize ); + int res = AllocHomebrewMemory(infilesize); - if ( res < 0 ) + if (res < 0) { CloseConnection(); - WindowPrompt( tr( "Not enough free memory." ), 0, tr( "OK" ) ); + WindowPrompt(tr( "Not enough free memory." ), 0, tr( "OK" )); } else { u32 read = 0; u8 *temp = NULL; int len = NETWORKBLOCKSIZE; - temp = ( u8 * ) malloc( infilesize ); + temp = (u8 *) malloc(infilesize); bool error = false; u8 *ptr = temp; - while ( read < infilesize ) + while (read < infilesize) { - ShowProgress( tr( "Receiving file from:" ), GetIncommingIP(), NULL, read, infilesize, true ); + ShowProgress(tr( "Receiving file from:" ), GetIncommingIP(), NULL, read, infilesize, true); - if ( infilesize - read < ( u32 ) len ) + if (infilesize - read < (u32) len) len = infilesize - read; - else - len = NETWORKBLOCKSIZE; + else len = NETWORKBLOCKSIZE; - int result = network_read( ptr, len ); + int result = network_read(ptr, len); - if ( result < 0 ) + if (result < 0) { - WindowPrompt( tr( "Error while transfering data." ), 0, tr( "OK" ) ); + WindowPrompt(tr( "Error while transfering data." ), 0, tr( "OK" )); error = true; break; } - if ( !result ) + if (!result) { break; } @@ -915,42 +945,42 @@ int MenuHomebrewBrowse() } char filename[101]; - if ( !error ) + if (!error) { - network_read( ( u8* ) &filename, 100 ); + network_read((u8*) &filename, 100); // Do we need to unzip this thing? - if ( wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4 ) + if (wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4) { // We need to unzip... - if ( temp[0] == 'P' && temp[1] == 'K' && temp[2] == 0x03 && temp[3] == 0x04 ) + 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 ); + sprintf((char *) &zippath, "%s%s", Settings.homebrewapps_path, filename); - FILE *fp = fopen( zippath, "wb" ); - if ( fp != NULL ) + FILE *fp = fopen(zippath, "wb"); + if (fp != NULL) { - fwrite( temp, 1, infilesize, fp ); - fclose( fp ); + fwrite(temp, 1, infilesize, fp); + fclose(fp); // Now unzip the zip file... - unzFile uf = unzOpen( zippath ); - if ( uf == NULL ) + unzFile uf = unzOpen(zippath); + if (uf == NULL) { error = true; } else { - extractZip( uf, 0, 1, 0, Settings.homebrewapps_path ); - unzCloseCurrentFile( uf ); + extractZip(uf, 0, 1, 0, Settings.homebrewapps_path); + unzCloseCurrentFile(uf); - remove( zippath ); + remove(zippath); // Reload this menu here... menu = MENU_HOMEBREWBROWSE; @@ -962,21 +992,21 @@ int MenuHomebrewBrowse() error = true; } } - else if ( uncfilesize != 0 ) // if uncfilesize == 0, it's not compressed + else if (uncfilesize != 0) // if uncfilesize == 0, it's not compressed { // It's compressed, uncompress - u8 *unc = ( u8 * ) malloc( uncfilesize ); + u8 *unc = (u8 *) malloc(uncfilesize); uLongf f = uncfilesize; - error = uncompress( unc, &f, temp, infilesize ) != Z_OK; + error = uncompress(unc, &f, temp, infilesize) != Z_OK; uncfilesize = f; homebrewsize = uncfilesize; - free( temp ); + free(temp); temp = unc; } } - if ( !error && strstr( filename, ".zip" ) == NULL ) + if (!error && strstr(filename, ".zip") == NULL) { innetbuffer = temp; @@ -985,31 +1015,32 @@ int MenuHomebrewBrowse() ProgressStop(); - if ( error || read != infilesize ) + if (error || read != infilesize) { - WindowPrompt( tr( "Error:" ), tr( "No data could be read." ), tr( "OK" ) ); + WindowPrompt(tr( "Error:" ), tr( "No data could be read." ), tr( "OK" )); FreeHomebrewBuffer(); } else { - if ( strstr( filename, ".dol" ) || strstr( filename, ".DOL" ) - || strstr( filename, ".elf" ) || strstr( filename, ".ELF" ) ) + if (strstr(filename, ".dol") || strstr(filename, ".DOL") || strstr(filename, ".elf") + || strstr(filename, ".ELF")) { boothomebrew = 2; - AddBootArgument( filename ); + AddBootArgument(filename); menu = MENU_EXIT; CloseConnection(); break; } - else if ( strstr( filename, ".zip" ) ) + else if (strstr(filename, ".zip")) { - WindowPrompt( tr( "Success:" ), tr( "Uploaded ZIP file installed to homebrew directory." ), tr( "OK" ) ); + WindowPrompt(tr( "Success:" ), + tr( "Uploaded ZIP file installed to homebrew directory." ), tr( "OK" )); CloseConnection(); } else { FreeHomebrewBuffer(); - WindowPrompt( tr( "ERROR:" ), tr( "Not a DOL/ELF file." ), tr( "OK" ) ); + WindowPrompt(tr( "ERROR:" ), tr( "Not a DOL/ELF file." ), tr( "OK" )); } } } @@ -1018,46 +1049,46 @@ int MenuHomebrewBrowse() ResumeNetworkWait(); } - else if ( channelBtn.GetState() == STATE_CLICKED ) + else if (channelBtn.GetState() == STATE_CLICKED) { - w.SetState( STATE_DISABLED ); + w.SetState(STATE_DISABLED); //10001 are the channels that are installed as channels, not including shop channel/mii channel etc TitleBrowser(); //if they didn't boot a channel reset this window - w.SetState( STATE_DEFAULT ); + w.SetState(STATE_DEFAULT); channelBtn.ResetState(); - } - if ( IsNetworkInit() ) + if (IsNetworkInit()) { - if ( !wifi_btn_loaded ) + if (!wifi_btn_loaded) { - wifiBtn.SetAlpha( 255 ); + wifiBtn.SetAlpha(255); - titleTT = new GuiTooltip( GetNetworkIP() ); - titleTT->SetAlpha( THEME.tooltipAlpha ); - wifiBtn.SetToolTip( titleTT, 0, -50, 0, 5 ); + titleTT = new GuiTooltip(GetNetworkIP()); + titleTT->SetAlpha(THEME.tooltipAlpha); + wifiBtn.SetToolTip(titleTT, 0, -50, 0, 5); wifi_btn_loaded = true; } } } } - w.SetEffect( EFFECT_FADE, -20 ); - while ( w.GetEffect() > 0 ) usleep( 50 ); + w.SetEffect(EFFECT_FADE, -20); + while (w.GetEffect() > 0) + usleep(50); HaltGui(); - for ( int i = 0; i < 4; i++ ) + for (int i = 0; i < 4; i++) { - if ( IconData[i] != NULL ) + if (IconData[i] != NULL) { delete IconData[i]; IconData[i] = NULL; } - if ( IconImg[i] != NULL ) + if (IconImg[i] != NULL) { delete IconImg[i]; IconImg[i] = NULL; @@ -1067,11 +1098,10 @@ int MenuHomebrewBrowse() delete titleTT; titleTT = NULL; - if ( IsNetworkInit() ) - HaltNetworkThread(); + if (IsNetworkInit()) HaltNetworkThread(); mainWindow->RemoveAll(); - mainWindow->Append( bgImg ); + mainWindow->Append(bgImg); ResumeGui(); diff --git a/source/homebrewboot/HomebrewBrowse.h b/source/homebrewboot/HomebrewBrowse.h index 8253aaa7..f1605bb3 100644 --- a/source/homebrewboot/HomebrewBrowse.h +++ b/source/homebrewboot/HomebrewBrowse.h @@ -10,7 +10,7 @@ #ifndef _HOMEBREWBROWSE_H_ #define _HOMEBREWBROWSE_H_ -int roundup( float number ); +int roundup(float number); int MenuHomebrewBrowse(); #endif diff --git a/source/homebrewboot/HomebrewFiles.cpp b/source/homebrewboot/HomebrewFiles.cpp index f4a89ab8..3ccee886 100644 --- a/source/homebrewboot/HomebrewFiles.cpp +++ b/source/homebrewboot/HomebrewFiles.cpp @@ -9,113 +9,110 @@ #include "HomebrewFiles.h" -HomebrewFiles::HomebrewFiles( const char * path ) +HomebrewFiles::HomebrewFiles(const char * path) { filecount = 0; - FileInfo = ( FileInfos * ) malloc( sizeof( FileInfos ) ); - if ( !FileInfo ) + FileInfo = (FileInfos *) malloc(sizeof(FileInfos)); + if (!FileInfo) { return; } - memset( &FileInfo[filecount], 0, sizeof( FileInfos ) ); + memset(&FileInfo[filecount], 0, sizeof(FileInfos)); - this->LoadPath( path ); + this->LoadPath(path); this->SortList(); } HomebrewFiles::~HomebrewFiles() { - if ( FileInfo ) + if (FileInfo) { - free( FileInfo ); + free(FileInfo); FileInfo = NULL; } } -bool HomebrewFiles::LoadPath( const char * folderpath ) +bool HomebrewFiles::LoadPath(const char * folderpath) { struct stat st; DIR_ITER *dir = NULL; char filename[1024]; - dir = diropen( folderpath ); - if ( dir == NULL ) + dir = diropen(folderpath); + if (dir == NULL) { return false; } - while ( dirnext( dir, filename, &st ) == 0 ) + while (dirnext(dir, filename, &st) == 0) { - if ( ( st.st_mode & S_IFDIR ) != 0 ) + if ((st.st_mode & S_IFDIR) != 0) { - if ( strcmp( filename, "." ) != 0 && strcmp( filename, ".." ) != 0 ) + if (strcmp(filename, ".") != 0 && strcmp(filename, "..") != 0) { char currentname[200]; - snprintf( currentname, sizeof( currentname ), "%s%s/", folderpath, filename ); - this->LoadPath( currentname ); + snprintf(currentname, sizeof(currentname), "%s%s/", folderpath, filename); + this->LoadPath(currentname); } } else { char temp[5]; - for ( int i = 0; i < 5; i++ ) + for (int i = 0; i < 5; i++) { - temp[i] = filename[strlen( filename )-4+i]; + temp[i] = filename[strlen(filename) - 4 + i]; } - if ( ( strncasecmp( temp, ".dol", 4 ) == 0 || strncasecmp( temp, ".elf", 4 ) == 0 ) - && filecount < MAXHOMEBREWS && filename[0] != '.' ) + if ((strncasecmp(temp, ".dol", 4) == 0 || strncasecmp(temp, ".elf", 4) == 0) && filecount < MAXHOMEBREWS + && filename[0] != '.') { - FileInfo = ( FileInfos * ) realloc( FileInfo, ( filecount + 1 ) * sizeof( FileInfos ) ); + FileInfo = (FileInfos *) realloc(FileInfo, (filecount + 1) * sizeof(FileInfos)); - if ( !FileInfo ) + if (!FileInfo) { - free( FileInfo ); + free(FileInfo); FileInfo = NULL; filecount = 0; - dirclose( dir ); + dirclose(dir); return false; } - memset( &( FileInfo[filecount] ), 0, sizeof( FileInfo ) ); + memset(&(FileInfo[filecount]), 0, sizeof(FileInfo)); - strlcpy( FileInfo[filecount].FilePath, folderpath, sizeof( FileInfo[filecount].FilePath ) ); - strlcpy( FileInfo[filecount].FileName, filename, sizeof( FileInfo[filecount].FileName ) ); + strlcpy(FileInfo[filecount].FilePath, folderpath, sizeof(FileInfo[filecount].FilePath)); + strlcpy(FileInfo[filecount].FileName, filename, sizeof(FileInfo[filecount].FileName)); FileInfo[filecount].FileSize = st.st_size; filecount++; } } } - dirclose( dir ); + dirclose(dir); return true; } -char * HomebrewFiles::GetFilename( int ind ) +char * HomebrewFiles::GetFilename(int ind) { - if ( ind > filecount ) + if (ind > filecount) return NULL; - else - return FileInfo[ind].FileName; + else return FileInfo[ind].FileName; } -char * HomebrewFiles::GetFilepath( int ind ) +char * HomebrewFiles::GetFilepath(int ind) { - if ( ind > filecount ) + if (ind > filecount) return NULL; - else - return FileInfo[ind].FilePath; + else return FileInfo[ind].FilePath; } -unsigned int HomebrewFiles::GetFilesize( int ind ) +unsigned int HomebrewFiles::GetFilesize(int ind) { - if ( ind > filecount || !filecount || !FileInfo ) + if (ind > filecount || !filecount || !FileInfo) return NULL; - else - return FileInfo[ind].FileSize; + else return FileInfo[ind].FileSize; } int HomebrewFiles::GetFilecount() @@ -123,14 +120,14 @@ int HomebrewFiles::GetFilecount() return filecount; } -static int ListCompare( const void *a, const void *b ) +static int ListCompare(const void *a, const void *b) { - FileInfos *ab = ( FileInfos* ) a; - FileInfos *bb = ( FileInfos* ) b; + FileInfos *ab = (FileInfos*) a; + FileInfos *bb = (FileInfos*) b; - return stricmp( ( char * ) ab->FilePath, ( char * ) bb->FilePath ); + return stricmp((char *) ab->FilePath, (char *) bb->FilePath); } void HomebrewFiles::SortList() { - qsort( FileInfo, filecount, sizeof( FileInfos ), ListCompare ); + qsort(FileInfo, filecount, sizeof(FileInfos), ListCompare); } diff --git a/source/homebrewboot/HomebrewFiles.h b/source/homebrewboot/HomebrewFiles.h index 17f4e1a2..dca244ff 100644 --- a/source/homebrewboot/HomebrewFiles.h +++ b/source/homebrewboot/HomebrewFiles.h @@ -9,9 +9,9 @@ typedef struct { - char FileName[100]; - char FilePath[150]; - unsigned int FileSize; + char FileName[100]; + char FilePath[150]; + unsigned int FileSize; } FileInfos; class HomebrewFiles @@ -19,21 +19,21 @@ class HomebrewFiles public: //!Constructor //!\param path Path where to check for homebrew files - HomebrewFiles( const char * path ); + HomebrewFiles(const char * path); //!Destructor ~HomebrewFiles(); //! Load the dol/elf list of a path //!\param path Path where to check for homebrew files - bool LoadPath( const char * path ); + bool LoadPath(const char * path); //! Get the a filename of the list //!\param list index - char * GetFilename( int index ); + char * GetFilename(int index); //! Get the a filepath of the list //!\param list index - char * GetFilepath( int index ); + char * GetFilepath(int index); //! Get the a filesize of the list //!\param list index - unsigned int GetFilesize( int index ); + unsigned int GetFilesize(int index); //! Get the filecount of the whole list int GetFilecount(); //! Sort list by filepath diff --git a/source/homebrewboot/HomebrewXML.cpp b/source/homebrewboot/HomebrewXML.cpp index eb02bc47..d4187913 100644 --- a/source/homebrewboot/HomebrewXML.cpp +++ b/source/homebrewboot/HomebrewXML.cpp @@ -11,60 +11,110 @@ #define ENTRIE_SIZE 8192 -int HomebrewXML::LoadHomebrewXMLData( const char* filename ) +/* Initializes a new instance of the HomebrewXML class. */ +HomebrewXML::HomebrewXML() +{ +} + +/* Finalizes an instance of the HomebrewXML class. */ +HomebrewXML::~HomebrewXML() +{ +} + +/* qparam filename Filepath of the XML file */ +int HomebrewXML::LoadHomebrewXMLData(const char* filename) { mxml_node_t *nodedataHB = NULL; mxml_node_t *nodetreeHB = NULL; /* Load XML file */ FILE *filexml; - filexml = fopen( filename, "rb" ); - if ( !filexml ) - return -1; + filexml = fopen(filename, "rb"); + if (!filexml) return -1; - nodetreeHB = mxmlLoadFile( NULL, filexml, MXML_OPAQUE_CALLBACK ); - fclose( filexml ); + nodetreeHB = mxmlLoadFile(NULL, filexml, MXML_OPAQUE_CALLBACK); + fclose(filexml); - if ( nodetreeHB == NULL ) - return -2; + if (nodetreeHB == NULL) return -2; - nodedataHB = mxmlFindElement( nodetreeHB, nodetreeHB, "app", NULL, NULL, MXML_DESCEND ); - if ( nodedataHB == NULL ) - return -5; + nodedataHB = mxmlFindElement(nodetreeHB, nodetreeHB, "app", NULL, NULL, MXML_DESCEND); + if (nodedataHB == NULL) return -5; char * Entrie = new char[ENTRIE_SIZE]; - GetTextFromNode( nodedataHB, nodedataHB, ( char* ) "name", NULL, NULL, MXML_DESCEND, Entrie, ENTRIE_SIZE ); + GetTextFromNode(nodedataHB, nodedataHB, (char*) "name", NULL, NULL, MXML_DESCEND, Entrie, ENTRIE_SIZE); Name = Entrie; - GetTextFromNode( nodedataHB, nodedataHB, ( char* ) "coder", NULL, NULL, MXML_DESCEND, Entrie, ENTRIE_SIZE ); + GetTextFromNode(nodedataHB, nodedataHB, (char*) "coder", NULL, NULL, MXML_DESCEND, Entrie, ENTRIE_SIZE); Coder = Entrie; - GetTextFromNode( nodedataHB, nodedataHB, ( char* ) "version", NULL, NULL, MXML_DESCEND, Entrie, ENTRIE_SIZE ); + GetTextFromNode(nodedataHB, nodedataHB, (char*) "version", NULL, NULL, MXML_DESCEND, Entrie, ENTRIE_SIZE); Version = Entrie; - GetTextFromNode( nodedataHB, nodedataHB, ( char* ) "short_description", NULL, NULL, MXML_DESCEND, Entrie, ENTRIE_SIZE ); + GetTextFromNode(nodedataHB, nodedataHB, (char*) "short_description", NULL, NULL, MXML_DESCEND, Entrie, ENTRIE_SIZE); ShortDescription = Entrie; - GetTextFromNode( nodedataHB, nodedataHB, ( char* ) "long_description", NULL, NULL, MXML_DESCEND, Entrie, ENTRIE_SIZE ); + GetTextFromNode(nodedataHB, nodedataHB, (char*) "long_description", NULL, NULL, MXML_DESCEND, Entrie, ENTRIE_SIZE); LongDescription = Entrie; - GetTextFromNode( nodedataHB, nodedataHB, ( char* ) "release_date", NULL, NULL, MXML_DESCEND, Entrie, ENTRIE_SIZE ); + GetTextFromNode(nodedataHB, nodedataHB, (char*) "release_date", NULL, NULL, MXML_DESCEND, Entrie, ENTRIE_SIZE); - int len = ( strlen( Entrie ) - 6 ); //length of the date string without the 200000 at the end - if ( len == 8 ) - snprintf( Entrie, ENTRIE_SIZE, "%c%c/%c%c/%c%c%c%c", Entrie[4], Entrie[5], Entrie[6], Entrie[7], Entrie[0], Entrie[1], Entrie[2], Entrie[3] ); - else if ( len == 6 ) - snprintf( Entrie, ENTRIE_SIZE, "%c%c/%c%c%c%c", Entrie[4], Entrie[5], Entrie[0], Entrie[1], Entrie[2], Entrie[3] ); - else - snprintf( Entrie, ENTRIE_SIZE, "%s", Entrie ); + int len = (strlen(Entrie) - 6); //length of the date string without the 200000 at the end + if (len == 8) + snprintf(Entrie, ENTRIE_SIZE, "%c%c/%c%c/%c%c%c%c", Entrie[4], Entrie[5], Entrie[6], Entrie[7], Entrie[0], + Entrie[1], Entrie[2], Entrie[3]); + else if (len == 6) + snprintf(Entrie, ENTRIE_SIZE, "%c%c/%c%c%c%c", Entrie[4], Entrie[5], Entrie[0], Entrie[1], Entrie[2], Entrie[3]); + else snprintf(Entrie, ENTRIE_SIZE, "%s", Entrie); Releasedate = Entrie; - free( nodedataHB ); - free( nodetreeHB ); + free(nodedataHB); + free(nodetreeHB); - delete [] Entrie; + delete[] Entrie; return 1; } + +/* Get name */ +const char * HomebrewXML::GetName() +{ + return Name.c_str(); +} + +/* Set Name */ +void HomebrewXML::SetName(char * newName) +{ + Name = newName; +} + +/* Get coder */ +const char * HomebrewXML::GetCoder() +{ + return Coder.c_str(); +} + +/* Get version */ +const char * HomebrewXML::GetVersion() +{ + return Version.c_str(); +} + +/* Get releasedate */ +const char * HomebrewXML::GetReleasedate() +{ + return Releasedate.c_str(); +} + +/* Get shortdescription */ +const char * HomebrewXML::GetShortDescription() +{ + return ShortDescription.c_str(); +} + +/* Get longdescription */ +const char * HomebrewXML::GetLongDescription() +{ + return LongDescription.c_str(); +} diff --git a/source/homebrewboot/HomebrewXML.h b/source/homebrewboot/HomebrewXML.h index 05bec500..ccafb3ba 100644 --- a/source/homebrewboot/HomebrewXML.h +++ b/source/homebrewboot/HomebrewXML.h @@ -10,27 +10,19 @@ class HomebrewXML { public: - //!Constructor - //!\param path Path for the xml file - HomebrewXML() { }; - //!Destructor - ~HomebrewXML() { }; - //!\param filename Filepath of the XML file - int LoadHomebrewXMLData( const char* filename ); - //! Get name - const char * GetName() { return Name.c_str(); }; - //! Get coder - const char * GetCoder() { return Coder.c_str(); }; - //! Get version - const char * GetVersion() { return Version.c_str(); }; - //! Get releasedate - const char * GetReleasedate() { return Releasedate.c_str(); }; - //! Get shortdescription - const char * GetShortDescription() { return ShortDescription.c_str(); }; - //! Get longdescription - const char * GetLongDescription() { return LongDescription.c_str(); }; - //! Set Name - void SetName( char * newName ) { Name = newName; }; + HomebrewXML(); + ~HomebrewXML(); + + int LoadHomebrewXMLData(const char* filename); + + const char * GetName(); + void SetName(char * newName); + const char * GetCoder(); + const char * GetVersion(); + const char * GetReleasedate(); + const char * GetShortDescription(); + const char * GetLongDescription(); + protected: std::string Name; std::string Coder; diff --git a/source/homebrewboot/dolloader.c b/source/homebrewboot/dolloader.c index 4784798c..32f0ef29 100644 --- a/source/homebrewboot/dolloader.c +++ b/source/homebrewboot/dolloader.c @@ -21,36 +21,36 @@ typedef struct _dolheader u32 entry_point; } dolheader; -u32 load_dol( const void *dolstart, struct __argv *argv ) +u32 load_dol(const void *dolstart, struct __argv *argv) { u32 i; dolheader *dolfile; - if ( dolstart ) + if (dolstart) { - dolfile = ( dolheader * ) dolstart; - for ( i = 0; i < 7; i++ ) + dolfile = (dolheader *) dolstart; + for (i = 0; i < 7; i++) { - if ( ( !dolfile->text_size[i] ) || ( dolfile->text_start[i] < 0x100 ) ) continue; - ICInvalidateRange ( ( void * ) dolfile->text_start[i], dolfile->text_size[i] ); - memcpy( ( void * ) dolfile->text_start[i], dolstart + dolfile->text_pos[i], dolfile->text_size[i] ); + if ((!dolfile->text_size[i]) || (dolfile->text_start[i] < 0x100)) continue; + ICInvalidateRange((void *) dolfile->text_start[i], dolfile->text_size[i]); + memcpy((void *) dolfile->text_start[i], dolstart + dolfile->text_pos[i], dolfile->text_size[i]); } - for ( i = 0; i < 11; i++ ) + for (i = 0; i < 11; i++) { - if ( ( !dolfile->data_size[i] ) || ( dolfile->data_start[i] < 0x100 ) ) continue; - memcpy( ( void * ) dolfile->data_start[i], dolstart + dolfile->data_pos[i], dolfile->data_size[i] ); - DCFlushRangeNoSync ( ( void * ) dolfile->data_start[i], dolfile->data_size[i] ); + if ((!dolfile->data_size[i]) || (dolfile->data_start[i] < 0x100)) continue; + memcpy((void *) dolfile->data_start[i], dolstart + dolfile->data_pos[i], dolfile->data_size[i]); + DCFlushRangeNoSync((void *) dolfile->data_start[i], dolfile->data_size[i]); } - memset ( ( void * ) dolfile->bss_start, 0, dolfile->bss_size ); - DCFlushRange( ( void * ) dolfile->bss_start, dolfile->bss_size ); + memset((void *) dolfile->bss_start, 0, dolfile->bss_size); + DCFlushRange((void *) dolfile->bss_start, dolfile->bss_size); - if ( argv && argv->argvMagic == ARGV_MAGIC ) + if (argv && argv->argvMagic == ARGV_MAGIC) { - void *new_argv = ( void * )( dolfile->entry_point + 8 ); - memcpy( new_argv, argv, sizeof( *argv ) ); - DCFlushRange( new_argv, sizeof( *argv ) ); + void *new_argv = (void *) (dolfile->entry_point + 8); + memcpy(new_argv, argv, sizeof(*argv)); + DCFlushRange(new_argv, sizeof(*argv)); } return dolfile->entry_point; diff --git a/source/homebrewboot/dolloader.h b/source/homebrewboot/dolloader.h index 4dbd49b6..96d2abc8 100644 --- a/source/homebrewboot/dolloader.h +++ b/source/homebrewboot/dolloader.h @@ -7,10 +7,9 @@ extern "C" #endif extern void __exception_closeall(); - typedef void ( *entrypoint ) ( void ); - - u32 load_dol( const void *dolstart, struct __argv *argv ); + typedef void (*entrypoint)(void); + u32 load_dol(const void *dolstart, struct __argv *argv); #ifdef __cplusplus } diff --git a/source/input.cpp b/source/input.cpp index d5fe7194..e657f034 100644 --- a/source/input.cpp +++ b/source/input.cpp @@ -20,9 +20,9 @@ #include "input.h" #include "libwiigui/gui.h" -int rumbleRequest[4] = {0, 0, 0, 0}; +int rumbleRequest[4] = { 0, 0, 0, 0 }; GuiTrigger userInput[4]; -static int rumbleCount[4] = {0, 0, 0, 0}; +static int rumbleCount[4] = { 0, 0, 0, 0 }; /**************************************************************************** * UpdatePads @@ -34,22 +34,21 @@ void UpdatePads() WPAD_ScanPads(); PAD_ScanPads(); - for ( int i = 3; i >= 0; i-- ) + for (int i = 3; i >= 0; i--) { - memcpy( &userInput[i].wpad, WPAD_Data( i ), sizeof( WPADData ) ); + memcpy(&userInput[i].wpad, WPAD_Data(i), sizeof(WPADData)); userInput[i].chan = i; - userInput[i].pad.btns_d = PAD_ButtonsDown( i ); - userInput[i].pad.btns_u = PAD_ButtonsUp( i ); - userInput[i].pad.btns_h = PAD_ButtonsHeld( i ); - userInput[i].pad.stickX = PAD_StickX( i ); - userInput[i].pad.stickY = PAD_StickY( i ); - userInput[i].pad.substickX = PAD_SubStickX( i ); - userInput[i].pad.substickY = PAD_SubStickY( i ); - userInput[i].pad.triggerL = PAD_TriggerL( i ); - userInput[i].pad.triggerR = PAD_TriggerR( i ); + userInput[i].pad.btns_d = PAD_ButtonsDown(i); + userInput[i].pad.btns_u = PAD_ButtonsUp(i); + userInput[i].pad.btns_h = PAD_ButtonsHeld(i); + userInput[i].pad.stickX = PAD_StickX(i); + userInput[i].pad.stickY = PAD_StickY(i); + userInput[i].pad.substickX = PAD_SubStickX(i); + userInput[i].pad.substickY = PAD_SubStickY(i); + userInput[i].pad.triggerL = PAD_TriggerL(i); + userInput[i].pad.triggerR = PAD_TriggerR(i); - if ( Settings.rumble == RumbleOn ) - DoRumble( i ); + if (Settings.rumble == RumbleOn) DoRumble(i); } } @@ -64,10 +63,10 @@ void SetupPads() WPAD_Init(); // read wiimote accelerometer and IR data - WPAD_SetDataFormat( WPAD_CHAN_ALL, WPAD_FMT_BTNS_ACC_IR ); - WPAD_SetVRes( WPAD_CHAN_ALL, screenwidth, screenheight ); + WPAD_SetDataFormat(WPAD_CHAN_ALL, WPAD_FMT_BTNS_ACC_IR); + WPAD_SetVRes(WPAD_CHAN_ALL, screenwidth, screenheight); - for ( int i = 0; i < 4; i++ ) + for (int i = 0; i < 4; i++) { userInput[i].chan = i; } @@ -79,9 +78,9 @@ void SetupPads() void ShutoffRumble() { - for ( int i = 0; i < 4; i++ ) + for (int i = 0; i < 4; i++) { - WPAD_Rumble( i, 0 ); + WPAD_Rumble(i, 0); rumbleCount[i] = 0; } } @@ -90,23 +89,22 @@ void ShutoffRumble() * DoRumble ***************************************************************************/ -void DoRumble( int i ) +void DoRumble(int i) { - if ( rumbleRequest[i] && rumbleCount[i] < 3 ) + if (rumbleRequest[i] && rumbleCount[i] < 3) { - WPAD_Rumble( i, 1 ); // rumble on + WPAD_Rumble(i, 1); // rumble on rumbleCount[i]++; } - else if ( rumbleRequest[i] ) + else if (rumbleRequest[i]) { rumbleCount[i] = 20; rumbleRequest[i] = 0; } else { - if ( rumbleCount[i] ) - rumbleCount[i]--; - WPAD_Rumble( i, 0 ); // rumble off + if (rumbleCount[i]) rumbleCount[i]--; + WPAD_Rumble(i, 0); // rumble off } } @@ -116,17 +114,17 @@ void DoRumble( int i ) * Get X/Y value from Wii Joystick (classic, nunchuk) input ***************************************************************************/ -s8 WPAD_Stick( u8 chan, u8 right, int axis ) +s8 WPAD_Stick(u8 chan, u8 right, int axis) { float mag = 0.0; float ang = 0.0; - WPADData *data = WPAD_Data( chan ); + WPADData *data = WPAD_Data(chan); - switch ( data->exp.type ) + switch (data->exp.type) { case WPAD_EXP_NUNCHUK: case WPAD_EXP_GUITARHERO3: - if ( right == 0 ) + if (right == 0) { mag = data->exp.nunchuk.js.mag; ang = data->exp.nunchuk.js.ang; @@ -134,7 +132,7 @@ s8 WPAD_Stick( u8 chan, u8 right, int axis ) break; case WPAD_EXP_CLASSIC: - if ( right == 0 ) + if (right == 0) { mag = data->exp.classic.ljs.mag; ang = data->exp.classic.ljs.ang; @@ -151,14 +149,15 @@ s8 WPAD_Stick( u8 chan, u8 right, int axis ) } /* 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; + 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 ); + if (axis == 0) // x-axis + val = mag * sin((PI * ang) / 180.0f); else // y-axis - val = mag * cos( ( PI * ang ) / 180.0f ); + val = mag * cos((PI * ang) / 180.0f); - return ( s8 )( val * 128.0f ); + return (s8) (val * 128.0f); } diff --git a/source/input.h b/source/input.h index 94d71139..37d417a4 100644 --- a/source/input.h +++ b/source/input.h @@ -20,6 +20,6 @@ extern int rumbleRequest[4]; void SetupPads(); void UpdatePads(); void ShutoffRumble(); -void DoRumble( int i ); +void DoRumble(int i); #endif diff --git a/source/language/UpdateLanguage.cpp b/source/language/UpdateLanguage.cpp index 9337fe3b..aa84602d 100644 --- a/source/language/UpdateLanguage.cpp +++ b/source/language/UpdateLanguage.cpp @@ -18,48 +18,49 @@ int updateLanguageFiles() char languageFiles[50][MAXLANGUAGEFILES]; //get all the files in the language path - int countfiles = GetAllDirFiles( Settings.languagefiles_path ); + int countfiles = GetAllDirFiles(Settings.languagefiles_path); //give up now if we didn't find any - if ( !countfiles ) return -2; + if (!countfiles) return -2; //now from the files we got, get only the .lang files - for ( int cnt = 0; cnt < countfiles; cnt++ ) + for (int cnt = 0; cnt < countfiles; cnt++) { char filename[64]; - strlcpy( filename, GetFileName( cnt ), sizeof( filename ) ); - if ( strcasestr( filename, ".lang" ) ) + strlcpy(filename, GetFileName(cnt), sizeof(filename)); + if (strcasestr(filename, ".lang")) { - strcpy( languageFiles[cnt], filename ); + strcpy(languageFiles[cnt], filename); } } - subfoldercreate( Settings.languagefiles_path ); + subfoldercreate(Settings.languagefiles_path); //we assume that the network will already be init by another function // ( that has gui eletents in it because this one doesn't) int done = 0, j = 0; - if ( IsNetworkInit() ) + if (IsNetworkInit()) { //build the URL, save path, and download each file and save it - while ( j < countfiles ) + while (j < countfiles) { char savepath[150]; char codeurl[200]; - snprintf( codeurl, sizeof( codeurl ), "http://usbloader-gui.googlecode.com/svn/trunk/Languages/%s", languageFiles[j] ); - snprintf( savepath, sizeof( savepath ), "%s%s", Settings.languagefiles_path, languageFiles[j] ); + snprintf(codeurl, sizeof(codeurl), "http://usbloader-gui.googlecode.com/svn/trunk/Languages/%s", + languageFiles[j]); + snprintf(savepath, sizeof(savepath), "%s%s", Settings.languagefiles_path, languageFiles[j]); - struct block file = downloadfile( codeurl ); + struct block file = downloadfile(codeurl); - if ( file.data != NULL ) + if (file.data != NULL) { FILE * pfile; - pfile = fopen( savepath, "wb" ); - if ( pfile != NULL ) + pfile = fopen(savepath, "wb"); + if (pfile != NULL) { - fwrite( file.data, 1, file.size, pfile ); - fclose( pfile ); - free( file.data ); + fwrite(file.data, 1, file.size, pfile); + fclose(pfile); + free(file.data); done++; } } @@ -75,5 +76,3 @@ int updateLanguageFiles() return done; } - - diff --git a/source/language/gettext.c b/source/language/gettext.c index 277b77e9..e48055ed 100644 --- a/source/language/gettext.c +++ b/source/language/gettext.c @@ -12,28 +12,26 @@ typedef struct _MSG } MSG; static MSG *baseMSG = 0; - #define HASHWORDBITS 32 /* Defines the so called `hashpjw' function by P.J. Weinberger - [see Aho/Sethi/Ullman, COMPILERS: Principles, Techniques and Tools, - 1986, 1987 Bell Telephone Laboratories, Inc.] */ -static inline u32 -hash_string ( const char *str_param ) + [see Aho/Sethi/Ullman, COMPILERS: Principles, Techniques and Tools, + 1986, 1987 Bell Telephone Laboratories, Inc.] */ +static inline u32 hash_string(const char *str_param) { u32 hval, g; const char *str = str_param; /* Compute the hash value for the given string. */ hval = 0; - while ( *str != '\0' ) + while (*str != '\0') { hval <<= 4; - hval += ( u8 ) * str++; - g = hval & ( ( u32 ) 0xf << ( HASHWORDBITS - 4 ) ); - if ( g != 0 ) + hval += (u8) *str++; + g = hval & ((u32) 0xf << (HASHWORDBITS - 4)); + if (g != 0) { - hval ^= g >> ( HASHWORDBITS - 8 ); + hval ^= g >> (HASHWORDBITS - 8); hval ^= g; } } @@ -42,54 +40,53 @@ hash_string ( const char *str_param ) /* Expand some escape sequences found in the argument string. */ static char * -expand_escape ( const char *str ) +expand_escape(const char *str) { char *retval, *rp; const char *cp = str; - retval = ( char * ) malloc ( strlen ( str ) + 1 ); - if ( retval == NULL ) return NULL; + retval = (char *) malloc(strlen(str) + 1); + if (retval == NULL) return NULL; rp = retval; - while ( cp[0] != '\0' && cp[0] != '\\' ) + while (cp[0] != '\0' && cp[0] != '\\') *rp++ = *cp++; - if ( cp[0] == '\0' ) - goto terminate; + if (cp[0] == '\0') goto terminate; do { /* Here cp[0] == '\\'. */ - switch ( *++cp ) + switch (*++cp) { - case '\"': /* " */ + case '\"': /* " */ *rp++ = '\"'; ++cp; break; - case 'a': /* alert */ + case 'a': /* alert */ *rp++ = '\a'; ++cp; break; - case 'b': /* backspace */ + case 'b': /* backspace */ *rp++ = '\b'; ++cp; break; - case 'f': /* form feed */ + case 'f': /* form feed */ *rp++ = '\f'; ++cp; break; - case 'n': /* new line */ + case 'n': /* new line */ *rp++ = '\n'; ++cp; break; - case 'r': /* carriage return */ + case 'r': /* carriage return */ *rp++ = '\r'; ++cp; break; - case 't': /* horizontal tab */ + case 't': /* horizontal tab */ *rp++ = '\t'; ++cp; break; - case 'v': /* vertical tab */ + case 'v': /* vertical tab */ *rp++ = '\v'; ++cp; break; @@ -105,147 +102,139 @@ expand_escape ( const char *str ) case '5': case '6': case '7': - { - int ch = *cp++ - '0'; + { + int ch = *cp++ - '0'; - if ( *cp >= '0' && *cp <= '7' ) + if (*cp >= '0' && *cp <= '7') + { + ch *= 8; + ch += *cp++ - '0'; + + if (*cp >= '0' && *cp <= '7') { ch *= 8; ch += *cp++ - '0'; - - if ( *cp >= '0' && *cp <= '7' ) - { - ch *= 8; - ch += *cp++ - '0'; - } } - *rp = ch; } + *rp = ch; + } break; default: *rp = '\\'; break; } - while ( cp[0] != '\0' && cp[0] != '\\' ) + while (cp[0] != '\0' && cp[0] != '\\') *rp++ = *cp++; - } - while ( cp[0] != '\0' ); + } while (cp[0] != '\0'); /* Terminate string. */ -terminate: - *rp = '\0'; + terminate: *rp = '\0'; return retval; } -static MSG *findMSG( u32 id ) +static MSG *findMSG(u32 id) { MSG *msg; - for ( msg = baseMSG; msg; msg = msg->next ) + for (msg = baseMSG; msg; msg = msg->next) { - if ( msg->id == id ) - return msg; + if (msg->id == id) return msg; } return NULL; } -static MSG *setMSG( const char *msgid, const char *msgstr ) +static MSG *setMSG(const char *msgid, const char *msgstr) { - u32 id = hash_string( msgid ); - MSG *msg = findMSG( id ); - if ( !msg ) + u32 id = hash_string(msgid); + MSG *msg = findMSG(id); + if (!msg) { - msg = ( MSG * )malloc( sizeof( MSG ) ); - msg->id = id; + msg = (MSG *) malloc(sizeof(MSG)); + msg->id = id; msg->msgstr = NULL; - msg->next = baseMSG; - baseMSG = msg; + msg->next = baseMSG; + baseMSG = msg; } - if ( msg ) + if (msg) { - if ( msgstr ) + if (msgstr) { - if ( msg->msgstr ) free( msg->msgstr ); + if (msg->msgstr) free(msg->msgstr); //msg->msgstr = strdup(msgstr); - msg->msgstr = expand_escape( msgstr ); + msg->msgstr = expand_escape(msgstr); } return msg; } return NULL; } -void gettextCleanUp( void ) +void gettextCleanUp(void) { - while ( baseMSG ) + while (baseMSG) { MSG *nextMsg = baseMSG->next; - free( baseMSG->msgstr ); - free( baseMSG ); + free(baseMSG->msgstr); + free(baseMSG); baseMSG = nextMsg; } } - -bool gettextLoadLanguage( const char* langFile ) +bool gettextLoadLanguage(const char* langFile) { FILE *f; char line[200]; char *lastID = NULL; gettextCleanUp(); - f = fopen( langFile, "r" ); - if ( !f ) - return false; + f = fopen(langFile, "r"); + if (!f) return false; - while ( fgets( line, sizeof( line ), f ) ) + while (fgets(line, sizeof(line), f)) { // lines starting with # are comments - if ( line[0] == '#' ) + if (line[0] == '#') continue; - else if ( strncmp( line, "msgid \"", 7 ) == 0 ) + else if (strncmp(line, "msgid \"", 7) == 0) { char *msgid, *end; - if ( lastID ) + if (lastID) { - free( lastID ); + free(lastID); lastID = NULL; } msgid = &line[7]; - end = strrchr( msgid, '"' ); - if ( end && end - msgid > 1 ) + end = strrchr(msgid, '"'); + if (end && end - msgid > 1) { *end = 0; - lastID = strdup( msgid ); + lastID = strdup(msgid); } } - else if ( strncmp( line, "msgstr \"", 8 ) == 0 ) + else if (strncmp(line, "msgstr \"", 8) == 0) { char *msgstr, *end; - if ( lastID == NULL ) - continue; + if (lastID == NULL) continue; msgstr = &line[8]; - end = strrchr( msgstr, '"' ); - if ( end && end - msgstr > 1 ) + end = strrchr(msgstr, '"'); + if (end && end - msgstr > 1) { *end = 0; - setMSG( lastID, msgstr ); + setMSG(lastID, msgstr); } - free( lastID ); + free(lastID); lastID = NULL; } } - fclose( f ); + fclose(f); return true; } -const char *gettext( const char *msgid ) +const char *gettext(const char *msgid) { - MSG *msg = findMSG( hash_string( msgid ) ); - if ( msg && msg->msgstr ) return msg->msgstr; + MSG *msg = findMSG(hash_string(msgid)); + if (msg && msg->msgstr) return msg->msgstr; return msgid; } - - diff --git a/source/language/gettext.h b/source/language/gettext.h index d196ce1a..25140c7a 100644 --- a/source/language/gettext.h +++ b/source/language/gettext.h @@ -6,18 +6,16 @@ extern "C" { #endif - - bool gettextLoadLanguage( const char* langFile ); - void gettextCleanUp( void ); + bool gettextLoadLanguage(const char* langFile); + void gettextCleanUp(void); /* * input msg = a text in ASCII * output = the translated msg in utf-8 - */ - const char *gettext( const char *msg ); + */ + const char *gettext(const char *msg); #define tr(s) gettext(s) #define trNOOP(s) (s) - #ifdef __cplusplus } #endif diff --git a/source/libfat/bit_ops.h b/source/libfat/bit_ops.h index 0a25597d..269ed08a 100644 --- a/source/libfat/bit_ops.h +++ b/source/libfat/bit_ops.h @@ -7,13 +7,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -24,7 +24,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef __BIT_OPS_H #define __BIT_OPS_H @@ -32,30 +32,30 @@ #include /*----------------------------------------------------------------- -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 ) + 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 ) +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 ) +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 ) +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/cache.h b/source/libfat/cache.h index f7c70afa..58633831 100644 --- a/source/libfat/cache.h +++ b/source/libfat/cache.h @@ -14,13 +14,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -31,7 +31,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef _CACHE_H #define _CACHE_H @@ -44,91 +44,93 @@ 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; /* -Read data from a sector in the cache -If the sector is not in the cache, it will be swapped in -offset is the position to start reading from -size is the amount of data to read -Precondition: offset + size <= BYTES_PER_READ -*/ -bool _FAT_cache_readPartialSector ( CACHE* cache, void* buffer, sec_t sector, unsigned int offset, size_t size ); + Read data from a sector in the cache + If the sector is not in the cache, it will be swapped in + offset is the position to start reading from + size is the amount of data to read + Precondition: offset + size <= BYTES_PER_READ + */ +bool _FAT_cache_readPartialSector(CACHE* cache, void* buffer, sec_t sector, unsigned int offset, size_t size); -bool _FAT_cache_readLittleEndianValue ( CACHE* cache, uint32_t *value, sec_t sector, unsigned int offset, int num_bytes ); +bool _FAT_cache_readLittleEndianValue(CACHE* cache, uint32_t *value, sec_t sector, unsigned int offset, int num_bytes); /* -Write data to a sector in the cache -If the sector is not in the cache, it will be swapped in. -When the sector is swapped out, the data will be written to the disc -offset is the position to start writing to -size is the amount of data to write -Precondition: offset + size <= BYTES_PER_READ -*/ -bool _FAT_cache_writePartialSector ( CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size ); + Write data to a sector in the cache + If the sector is not in the cache, it will be swapped in. + When the sector is swapped out, the data will be written to the disc + offset is the position to start writing to + size is the amount of data to write + Precondition: offset + size <= BYTES_PER_READ + */ +bool _FAT_cache_writePartialSector(CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size); -bool _FAT_cache_writeLittleEndianValue ( CACHE* cache, const uint32_t value, sec_t sector, unsigned int offset, int num_bytes ); +bool _FAT_cache_writeLittleEndianValue(CACHE* cache, const uint32_t value, sec_t sector, unsigned int offset, + int num_bytes); /* -Write data to a sector in the cache, zeroing the sector first -If the sector is not in the cache, it will be swapped in. -When the sector is swapped out, the data will be written to the disc -offset is the position to start writing to -size is the amount of data to write -Precondition: offset + size <= BYTES_PER_READ -*/ -bool _FAT_cache_eraseWritePartialSector ( CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size ); + Write data to a sector in the cache, zeroing the sector first + If the sector is not in the cache, it will be swapped in. + When the sector is swapped out, the data will be written to the disc + offset is the position to start writing to + size is the amount of data to write + Precondition: offset + size <= BYTES_PER_READ + */ +bool _FAT_cache_eraseWritePartialSector(CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, + size_t size); /* -Read several sectors from the cache -*/ -bool _FAT_cache_readSectors ( CACHE* cache, sec_t sector, sec_t numSectors, void* buffer ); + Read several sectors from the cache + */ +bool _FAT_cache_readSectors(CACHE* cache, sec_t sector, sec_t numSectors, void* buffer); /* -Read a full sector from the cache -*/ -static inline bool _FAT_cache_readSector ( CACHE* cache, void* buffer, sec_t sector ) + 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 ) + 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 ); +bool _FAT_cache_writeSectors(CACHE* cache, sec_t sector, sec_t numSectors, const void* buffer); /* -Write any dirty sectors back to disc and clear out the contents of the cache -*/ -bool _FAT_cache_flush ( CACHE* cache ); + Write any dirty sectors back to disc and clear out the contents of the cache + */ +bool _FAT_cache_flush(CACHE* cache); /* -Clear out the contents of the cache without writing any dirty sectors first -*/ -void _FAT_cache_invalidate ( CACHE* cache ); + Clear out the contents of the cache without writing any dirty sectors first + */ +void _FAT_cache_invalidate(CACHE* cache); -CACHE* _FAT_cache_constructor ( unsigned int numberOfPages, unsigned int sectorsPerPage, const DISC_INTERFACE* discInterface, sec_t endOfPartition ); +CACHE* _FAT_cache_constructor(unsigned int numberOfPages, unsigned int sectorsPerPage, + const DISC_INTERFACE* discInterface, sec_t endOfPartition); -void _FAT_cache_destructor ( CACHE* cache ); +void _FAT_cache_destructor(CACHE* cache); #endif // _CACHE_H - diff --git a/source/libfat/common.h b/source/libfat/common.h index 85d15db9..2b6ded49 100644 --- a/source/libfat/common.h +++ b/source/libfat/common.h @@ -7,13 +7,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -24,7 +24,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef __COMMON_H #define __COMMON_H @@ -34,7 +34,6 @@ #include #include - // Platform specific includes #include #include diff --git a/source/libfat/directory.c b/source/libfat/directory.c index e9f53f50..4b998151 100644 --- a/source/libfat/directory.c +++ b/source/libfat/directory.c @@ -8,13 +8,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -25,7 +25,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #include #include @@ -53,14 +53,14 @@ typedef unsigned short ucs2_t; // Long file name directory entry enum LFN_offset { - LFN_offset_ordinal = 0x00, // Position within LFN + 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_reserved1 = 0x0C, // Always 0x00 LFN_offset_checkSum = 0x0D, // Checksum of short file name (alias) LFN_offset_char5 = 0x0E, LFN_offset_char6 = 0x10, @@ -68,11 +68,12 @@ enum LFN_offset LFN_offset_char8 = 0x14, LFN_offset_char9 = 0x16, LFN_offset_char10 = 0x18, - LFN_offset_reserved2 = 0x1A, // Always 0x0000 + 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 @@ -81,39 +82,39 @@ 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 -*/ + 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 ) +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 ); + nameLength = strnlen(name, MAX_FILENAME_LENGTH); // Make sure the name is short enough to be valid - if ( nameLength >= MAX_FILENAME_LENGTH ) + if (nameLength >= MAX_FILENAME_LENGTH) { return -1; } // Make sure it doesn't contain any invalid characters - if ( strpbrk ( name, ILLEGAL_LFN_CHARACTERS ) != NULL ) + 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++ ) + for (i = 0; i < nameLength; i++) { - if ( name[i] < 0x20 || name[i] >= ABOVE_UCS_RANGE ) + 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 ) + ucsLength = mbsrtowcs(NULL, &tempName, MAX_LFN_LENGTH, NULL); + if (ucsLength < 0 || ucsLength >= MAX_LFN_LENGTH) { return -1; } @@ -123,27 +124,27 @@ static int _FAT_directory_lfnLength ( const char* name ) } /* -Convert a multibyte encoded string into a NUL-terminated UCS-2 string, storing at most len characters -return number of characters stored -*/ -static size_t _FAT_directory_mbstoucs2 ( ucs2_t* dst, const char* src, size_t len ) + Convert a multibyte encoded string into a NUL-terminated UCS-2 string, storing at most len characters + return number of characters stored + */ +static size_t _FAT_directory_mbstoucs2(ucs2_t* dst, const char* src, size_t len) { - mbstate_t ps = {0}; + mbstate_t ps = { 0 }; wchar_t tempChar; int bytes; size_t count = 0; - while ( count < len - 1 && src != '\0' ) + while (count < len - 1 && src != '\0') { - bytes = mbrtowc ( &tempChar, src, MB_CUR_MAX, &ps ); - if ( bytes > 0 ) + bytes = mbrtowc(&tempChar, src, MB_CUR_MAX, &ps); + if (bytes > 0) { - *dst = ( ucs2_t )tempChar; + *dst = (ucs2_t) tempChar; src += bytes; dst++; count++; } - else if ( bytes == 0 ) + else if (bytes == 0) { break; } @@ -158,27 +159,27 @@ static size_t _FAT_directory_mbstoucs2 ( ucs2_t* dst, const char* src, size_t le } /* -Convert a UCS-2 string into a NUL-terminated multibyte string, storing at most len chars -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 ) + Convert a UCS-2 string into a NUL-terminated multibyte string, storing at most len chars + 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}; + mbstate_t ps = { 0 }; size_t count = 0; int bytes; char buff[MB_CUR_MAX]; int i; - while ( count < len - 1 && *src != '\0' ) + while (count < len - 1 && *src != '\0') { - bytes = wcrtomb ( buff, *src, &ps ); - if ( bytes < 0 ) + bytes = wcrtomb(buff, *src, &ps); + if (bytes < 0) { return -1; } - if ( count + bytes < len && bytes > 0 ) + if (count + bytes < len && bytes > 0) { - for ( i = 0; i < bytes; i++ ) + for (i = 0; i < bytes; i++) { *dst++ = buff[i]; } @@ -196,17 +197,17 @@ static size_t _FAT_directory_ucs2tombs ( char* dst, const ucs2_t* src, size_t le } /* -Case-independent comparison of two multibyte encoded strings -*/ -static int _FAT_directory_mbsncasecmp ( const char* s1, const char* s2, size_t len1 ) + 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}; + mbstate_t ps1 = { 0 }; + mbstate_t ps2 = { 0 }; size_t b1 = 0; size_t b2 = 0; - if ( len1 == 0 ) + if (len1 == 0) { return 0; } @@ -215,32 +216,30 @@ static int _FAT_directory_mbsncasecmp ( const char* s1, const char* s2, size_t l { 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 ) + 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 ); + } while (len1 > 0 && towlower(wc1) == towlower(wc2) && wc1 != 0); - return towlower( wc1 ) - towlower( wc2 ); + return towlower(wc1) - towlower(wc2); } - -static bool _FAT_directory_entryGetAlias ( const u8* entryData, char* destName ) +static bool _FAT_directory_entryGetAlias(const u8* entryData, char* destName) { int i = 0; int j = 0; destName[0] = '\0'; - if ( entryData[0] != DIR_ENTRY_FREE ) + if (entryData[0] != DIR_ENTRY_FREE) { - if ( entryData[0] == '.' ) + if (entryData[0] == '.') { destName[0] = '.'; - if ( entryData[1] == '.' ) + if (entryData[1] == '.') { destName[1] = '.'; destName[2] = '\0'; @@ -253,15 +252,15 @@ static bool _FAT_directory_entryGetAlias ( const u8* entryData, char* destName ) else { // Copy the filename from the dirEntry to the string - for ( i = 0; ( i < 8 ) && ( entryData[DIR_ENTRY_name + i] != ' ' ); i++ ) + 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] != ' ' ) + if (entryData[DIR_ENTRY_extension] != ' ') { destName[i++] = '.'; - for ( j = 0; ( j < 3 ) && ( entryData[DIR_ENTRY_extension + j] != ' ' ); j++ ) + for (j = 0; (j < 3) && (entryData[DIR_ENTRY_extension + j] != ' '); j++) { destName[i++] = entryData[DIR_ENTRY_extension + j]; } @@ -270,67 +269,69 @@ static bool _FAT_directory_entryGetAlias ( const u8* entryData, char* destName ) } } - return ( destName[0] != '\0' ); + return (destName[0] != '\0'); } -uint32_t _FAT_directory_entryGetCluster ( PARTITION* partition, const uint8_t* entryData ) +uint32_t _FAT_directory_entryGetCluster(PARTITION* partition, const uint8_t* entryData) { - if ( partition->filesysType == FS_FAT32 ) + 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 ); + 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 ); + return u8array_to_u16(entryData, DIR_ENTRY_cluster); } } -static bool _FAT_directory_incrementDirEntryPosition ( PARTITION* partition, DIR_ENTRY_POSITION* entryPosition, bool extendDirectory ) +static bool _FAT_directory_incrementDirEntryPosition(PARTITION* partition, DIR_ENTRY_POSITION* entryPosition, + bool extendDirectory) { 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; + if (position.offset == BYTES_PER_READ / DIR_ENTRY_DATA_SIZE) { position.offset = 0; // Increment sector when wrapping - ++ position.sector; + ++position.sector; // But wrap at the end of a cluster - if ( ( position.sector == partition->sectorsPerCluster ) && ( position.cluster != FAT16_ROOT_DIR_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 ) + tempCluster = _FAT_fat_nextCluster(partition, position.cluster); + if (tempCluster == CLUSTER_EOF) { - if ( extendDirectory ) + if (extendDirectory) { - tempCluster = _FAT_fat_linkFreeClusterCleared ( partition, position.cluster ); - if ( !_FAT_fat_isValidCluster( partition, tempCluster ) ) + tempCluster = _FAT_fat_linkFreeClusterCleared(partition, position.cluster); + if (!_FAT_fat_isValidCluster(partition, tempCluster)) { - return false; // This will only happen if the disc is full + return false; // This will only happen if the disc is full } } else { - return false; // Got to the end of the directory, not extending it + 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 ) ) ) + 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 + 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 ) +bool _FAT_directory_getNextEntry(PARTITION* partition, DIR_ENTRY* entry) { DIR_ENTRY_POSITION entryStart; DIR_ENTRY_POSITION entryEnd; @@ -347,7 +348,7 @@ bool _FAT_directory_getNextEntry ( PARTITION* partition, DIR_ENTRY* entry ) entryStart = entry->dataEnd; // Make sure we are using the correct root directory, in case of FAT32 - if ( entryStart.cluster == FAT16_ROOT_DIR_CLUSTER ) + if (entryStart.cluster == FAT16_ROOT_DIR_CLUSTER) { entryStart.cluster = partition->rootDirCluster; } @@ -359,83 +360,84 @@ bool _FAT_directory_getNextEntry ( PARTITION* partition, DIR_ENTRY* entry ) found = false; notFound = false; - while ( !found && !notFound ) + while (!found && !notFound) { - if ( _FAT_directory_incrementDirEntryPosition ( partition, &entryEnd, false ) == false ) + 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 ) + if (entryData[DIR_ENTRY_attributes] == ATTRIB_LFN) { // It's an LFN - if ( entryData[LFN_offset_ordinal] & LFN_DEL ) + if (entryData[LFN_offset_ordinal] & LFN_DEL) { lfnExists = false; } - else if ( entryData[LFN_offset_ordinal] & LFN_END ) + 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 + 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 = (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] ) + } + if (lfnChkSum != entryData[LFN_offset_checkSum]) { lfnExists = false; } - if ( lfnExists ) + if (lfnExists) { - lfnPos = ( ( entryData[LFN_offset_ordinal] & ~LFN_END ) - 1 ) * 13; - if ( lfnPos > LAST_LFN_POS ) + 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++ ) + for (i = 0; i < 13; i++) { - lfn[lfnPos + i] = entryData[LFN_offset_table[i]] | ( entryData[LFN_offset_table[i] + 1] << 8 ); + lfn[lfnPos + i] = entryData[LFN_offset_table[i]] | (entryData[LFN_offset_table[i] + 1] << 8); } } } - else if ( entryData[DIR_ENTRY_attributes] & ATTRIB_VOL ) + 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 ) + 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 ) ) + else if ((entryData[0] != DIR_ENTRY_FREE) && (entryData[0] > 0x20) && !(entryData[DIR_ENTRY_attributes] + & ATTRIB_VOL)) { - if ( lfnExists ) + if (lfnExists) { // Calculate file checksum chkSum = 0; - for ( i = 0; i < 11; i++ ) + for (i = 0; i < 11; i++) { // NOTE: The operation is an unsigned char rotate right - chkSum = ( ( chkSum & 1 ) ? 0x80 : 0 ) + ( chkSum >> 1 ) + entryData[i]; + chkSum = ((chkSum & 1) ? 0x80 : 0) + (chkSum >> 1) + entryData[i]; } - if ( chkSum != lfnChkSum ) + if (chkSum != lfnChkSum) { lfnExists = false; entry->filename[0] = '\0'; } } - if ( lfnExists ) + if (lfnExists) { - if ( _FAT_directory_ucs2tombs ( entry->filename, lfn, MAX_FILENAME_LENGTH ) == ( size_t ) - 1 ) + 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; @@ -444,14 +446,14 @@ bool _FAT_directory_getNextEntry ( PARTITION* partition, DIR_ENTRY* entry ) else { entryStart = entryEnd; - _FAT_directory_entryGetAlias ( entryData, entry->filename ); + _FAT_directory_entryGetAlias(entryData, entry->filename); } found = true; } } // If no file is found, return false - if ( notFound ) + if (notFound) { return false; } @@ -460,12 +462,12 @@ bool _FAT_directory_getNextEntry ( PARTITION* partition, DIR_ENTRY* entry ) // Fill in the directory entry struct entry->dataStart = entryStart; entry->dataEnd = entryEnd; - memcpy ( entry->entryData, entryData, DIR_ENTRY_DATA_SIZE ); + memcpy(entry->entryData, entryData, DIR_ENTRY_DATA_SIZE); return true; } } -bool _FAT_directory_getFirstEntry ( PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster ) +bool _FAT_directory_getFirstEntry(PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster) { entry->dataStart.cluster = dirCluster; entry->dataStart.sector = 0; @@ -473,10 +475,10 @@ bool _FAT_directory_getFirstEntry ( PARTITION* partition, DIR_ENTRY* entry, uint 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 ) +bool _FAT_directory_getRootEntry(PARTITION* partition, DIR_ENTRY* entry) { entry->dataStart.cluster = 0; entry->dataStart.sector = 0; @@ -484,22 +486,22 @@ bool _FAT_directory_getRootEntry ( PARTITION* partition, DIR_ENTRY* entry ) entry->dataEnd = entry->dataStart; - memset ( entry->filename, '\0', MAX_FILENAME_LENGTH ); + memset(entry->filename, '\0', MAX_FILENAME_LENGTH); entry->filename[0] = '.'; - memset ( entry->entryData, 0, DIR_ENTRY_DATA_SIZE ); - memset ( entry->entryData, ' ', 11 ); + 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 ); + 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 ) +bool _FAT_directory_entryFromPosition(PARTITION* partition, DIR_ENTRY* entry) { DIR_ENTRY_POSITION entryStart = entry->dataStart; DIR_ENTRY_POSITION entryEnd = entry->dataEnd; @@ -510,51 +512,47 @@ bool _FAT_directory_entryFromPosition ( PARTITION* partition, DIR_ENTRY* entry ) 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 ) ) + 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 ); + _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 ) ) + 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 ); + 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 = ((entryData[LFN_offset_ordinal] & ~LFN_END) - 1) * 13; + if (lfnPos > LAST_LFN_POS) { lfnPos = LAST_LFN_POS_CORRECTION; } - for ( i = 0; i < 13; i++ ) + for (i = 0; i < 13; i++) { - lfn[lfnPos + i] = entryData[LFN_offset_table[i]] | ( entryData[LFN_offset_table[i] + 1] << 8 ); + lfn[lfnPos + i] = entryData[LFN_offset_table[i]] | (entryData[LFN_offset_table[i] + 1] << 8); } } } - if ( !entryStillValid ) + if (!entryStillValid) { return false; } - if ( ( entryStart.cluster == entryEnd.cluster ) - && ( entryStart.sector == entryEnd.sector ) - && ( entryStart.offset == entryEnd.offset ) ) + 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 ) ) + if (!_FAT_directory_entryGetAlias(entry->entryData, entry->filename)) { return false; } @@ -562,7 +560,7 @@ bool _FAT_directory_entryFromPosition ( PARTITION* partition, DIR_ENTRY* entry ) else { // Encode the long file name into a multibyte string - if ( _FAT_directory_ucs2tombs ( entry->filename, lfn, MAX_FILENAME_LENGTH ) == ( size_t ) - 1 ) + if (_FAT_directory_ucs2tombs(entry->filename, lfn, MAX_FILENAME_LENGTH) == (size_t) -1) { return false; } @@ -571,9 +569,7 @@ bool _FAT_directory_entryFromPosition ( PARTITION* partition, DIR_ENTRY* entry ) return true; } - - -bool _FAT_directory_entryFromPath ( PARTITION* partition, DIR_ENTRY* entry, const char* path, const char* pathEnd ) +bool _FAT_directory_entryFromPath(PARTITION* partition, DIR_ENTRY* entry, const char* path, const char* pathEnd) { size_t dirnameLength; const char* pathPosition; @@ -588,25 +584,25 @@ bool _FAT_directory_entryFromPath ( PARTITION* partition, DIR_ENTRY* entry, cons found = false; notFound = false; - if ( pathEnd == NULL ) + if (pathEnd == NULL) { // Set pathEnd to the end of the path string - pathEnd = strchr ( path, '\0' ); + pathEnd = strchr(path, '\0'); } - if ( pathPosition[0] == DIR_SEPARATOR ) + if (pathPosition[0] == DIR_SEPARATOR) { // Start at root directory dirCluster = partition->rootDirCluster; // Consume separator(s) - while ( pathPosition[0] == DIR_SEPARATOR ) + while (pathPosition[0] == DIR_SEPARATOR) { pathPosition++; } // If the path is only specifying a directory in the form of "/" return it - if ( pathPosition >= pathEnd ) + if (pathPosition >= pathEnd) { - _FAT_directory_getRootEntry ( partition, entry ); + _FAT_directory_getRootEntry(partition, entry); found = true; } } @@ -618,85 +614,85 @@ bool _FAT_directory_entryFromPath ( PARTITION* partition, DIR_ENTRY* entry, cons // 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 ) ) + if ((dirCluster == partition->rootDirCluster) && (strcmp(".", pathPosition) == 0)) { - _FAT_directory_getRootEntry ( partition, entry ); + _FAT_directory_getRootEntry(partition, entry); found = true; } - while ( !found && !notFound ) + while (!found && !notFound) { // Get the name of the next required subdirectory within the path - nextPathPosition = strchr ( pathPosition, DIR_SEPARATOR ); - if ( nextPathPosition != NULL ) + nextPathPosition = strchr(pathPosition, DIR_SEPARATOR); + if (nextPathPosition != NULL) { dirnameLength = nextPathPosition - pathPosition; } else { - dirnameLength = strlen( pathPosition ); + dirnameLength = strlen(pathPosition); } - if ( dirnameLength > MAX_FILENAME_LENGTH ) + if (dirnameLength > MAX_FILENAME_LENGTH) { // The path is too long to bother with return false; } // Look for the directory within the path - foundFile = _FAT_directory_getFirstEntry ( partition, entry, dirCluster ); + foundFile = _FAT_directory_getFirstEntry(partition, entry, dirCluster); - while ( foundFile && !found && !notFound ) // It hasn't already found the file + 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 ) ) + if ((dirnameLength == strnlen(entry->filename, MAX_FILENAME_LENGTH)) && (_FAT_directory_mbsncasecmp( + pathPosition, entry->filename, dirnameLength) == 0)) { found = true; } // Check if the alias matches - _FAT_directory_entryGetAlias ( entry->entryData, alias ); - if ( ( dirnameLength == strnlen( alias, MAX_ALIAS_LENGTH ) ) - && ( strncasecmp( pathPosition, alias, dirnameLength ) == 0 ) ) + _FAT_directory_entryGetAlias(entry->entryData, alias); + if ((dirnameLength == strnlen(alias, MAX_ALIAS_LENGTH)) && (strncasecmp(pathPosition, alias, dirnameLength) + == 0)) { found = true; } - if ( found && !( entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR ) && ( nextPathPosition != NULL ) ) + 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 ( !found ) + if (!found) { - foundFile = _FAT_directory_getNextEntry ( partition, entry ); + foundFile = _FAT_directory_getNextEntry(partition, entry); } } - if ( !foundFile ) + 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 ) ) + 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 ) + else if (entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR) { - dirCluster = _FAT_directory_entryGetCluster ( partition, entry->entryData ); + dirCluster = _FAT_directory_entryGetCluster(partition, entry->entryData); pathPosition = nextPathPosition; // Consume separator(s) - while ( pathPosition[0] == DIR_SEPARATOR ) + while (pathPosition[0] == DIR_SEPARATOR) { pathPosition++; } // The requested directory was found - if ( pathPosition >= pathEnd ) + if (pathPosition >= pathEnd) { found = true; } @@ -707,14 +703,14 @@ bool _FAT_directory_entryFromPath ( PARTITION* partition, DIR_ENTRY* entry, cons } } - if ( found && !notFound ) + if (found && !notFound) { - if ( partition->filesysType == FS_FAT32 && ( entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR ) && - _FAT_directory_entryGetCluster ( partition, entry->entryData ) == CLUSTER_ROOT ) + 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 ); + _FAT_directory_getRootEntry(partition, entry); } return true; } @@ -724,7 +720,7 @@ bool _FAT_directory_entryFromPath ( PARTITION* partition, DIR_ENTRY* entry, cons } } -bool _FAT_directory_removeEntry ( PARTITION* partition, DIR_ENTRY* entry ) +bool _FAT_directory_removeEntry(PARTITION* partition, DIR_ENTRY* entry) { DIR_ENTRY_POSITION entryStart = entry->dataStart; DIR_ENTRY_POSITION entryEnd = entry->dataEnd; @@ -733,20 +729,22 @@ bool _FAT_directory_removeEntry ( PARTITION* partition, DIR_ENTRY* entry ) 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 ) ) + 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 ); + _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 ) ) + _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 ) + if (!entryStillValid) { return false; } @@ -754,7 +752,7 @@ bool _FAT_directory_removeEntry ( PARTITION* partition, DIR_ENTRY* entry ) return true; } -static bool _FAT_directory_findEntryGap ( PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster, size_t size ) +static bool _FAT_directory_findEntryGap(PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster, size_t size) { DIR_ENTRY_POSITION gapStart; DIR_ENTRY_POSITION gapEnd; @@ -773,38 +771,37 @@ static bool _FAT_directory_findEntryGap ( PARTITION* partition, DIR_ENTRY* entry dirEntryRemain = size; endOfDirectory = false; - while ( entryStillValid && !endOfDirectory && ( dirEntryRemain > 0 ) ) + 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 ) + _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; + --dirEntryRemain; endOfDirectory = true; } - else if ( entryData[0] == DIR_ENTRY_FREE ) + else if (entryData[0] == DIR_ENTRY_FREE) { - if ( dirEntryRemain == size ) + if (dirEntryRemain == size) { gapStart = gapEnd; } - -- dirEntryRemain; + --dirEntryRemain; } else { dirEntryRemain = size; } - if ( !endOfDirectory && ( dirEntryRemain > 0 ) ) + if (!endOfDirectory && (dirEntryRemain > 0)) { - entryStillValid = _FAT_directory_incrementDirEntryPosition ( partition, &gapEnd, true ); + entryStillValid = _FAT_directory_incrementDirEntryPosition(partition, &gapEnd, true); } } // Make sure the scanning didn't fail - if ( !entryStillValid ) + if (!entryStillValid) { return false; } @@ -812,23 +809,22 @@ static bool _FAT_directory_findEntryGap ( PARTITION* partition, DIR_ENTRY* entry // Save the start entry, since we know it is valid entry->dataStart = gapStart; - if ( endOfDirectory ) + 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 ) + 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; + 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 ); + _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 ) + if (!entryStillValid) { return false; } @@ -841,161 +837,161 @@ static bool _FAT_directory_findEntryGap ( PARTITION* partition, DIR_ENTRY* entry return true; } -static bool _FAT_directory_entryExists ( PARTITION* partition, const char* name, uint32_t dirCluster ) +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; - dirnameLength = strnlen( name, MAX_FILENAME_LENGTH ); + dirnameLength = strnlen(name, MAX_FILENAME_LENGTH); - if ( dirnameLength >= MAX_FILENAME_LENGTH ) + if (dirnameLength >= MAX_FILENAME_LENGTH) { return false; } // Make sure the entry doesn't already exist - foundFile = _FAT_directory_getFirstEntry ( partition, &tempEntry, dirCluster ); + foundFile = _FAT_directory_getFirstEntry(partition, &tempEntry, dirCluster); - while ( foundFile ) // It hasn't already found the file + 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 ) ) + 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 ) ) + _FAT_directory_entryGetAlias(tempEntry.entryData, alias); + if ((strncasecmp(name, alias, MAX_ALIAS_LENGTH) == 0)) { return true; } - foundFile = _FAT_directory_getNextEntry ( partition, &tempEntry ); + 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, -it returns 0. If there was an error, it returns -1. -*/ -static int _FAT_directory_createAlias ( char* alias, const char* lfn ) + 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 + 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}; + mbstate_t ps = { 0 }; int bytesUsed = 0; const char* lfnExt; int aliasExtLen; // Strip leading periods - while ( lfn[lfnPos] == '.' ) + while (lfn[lfnPos] == '.') { - lfnPos ++; + lfnPos++; lossyConversion = true; } // Primary portion of alias - while ( aliasPos < 8 && lfn[lfnPos] != '.' && lfn[lfnPos] != '\0' ) + while (aliasPos < 8 && lfn[lfnPos] != '.' && lfn[lfnPos] != '\0') { - bytesUsed = mbrtowc( &lfnChar, lfn + lfnPos, MAX_FILENAME_LENGTH - lfnPos, &ps ); - if ( bytesUsed < 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 ) + oemChar = wctob(towupper((wint_t) lfnChar)); + if (wctob((wint_t) lfnChar) != oemChar) { // Case of letter was changed lossyConversion = true; } - if ( oemChar == ' ' ) + if (oemChar == ' ') { // Skip spaces in filename lossyConversion = true; lfnPos += bytesUsed; continue; } - if ( oemChar == EOF ) + if (oemChar == EOF) { - oemChar = '_'; // Replace unconvertable characters with underscores + oemChar = '_'; // Replace unconvertable characters with underscores lossyConversion = true; } - if ( strchr ( ILLEGAL_ALIAS_CHARACTERS, oemChar ) != NULL ) + if (strchr(ILLEGAL_ALIAS_CHARACTERS, oemChar) != NULL) { // Invalid Alias character - oemChar = '_'; // Replace illegal characters with underscores + oemChar = '_'; // Replace illegal characters with underscores lossyConversion = true; } - alias[aliasPos] = ( char )oemChar; + alias[aliasPos] = (char) oemChar; aliasPos++; lfnPos += bytesUsed; } - if ( lfn[lfnPos] != '.' && lfn[lfnPos] != '\0' ) + 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, '.' ) ) + lfnExt = strrchr(lfn, '.'); + if (lfnExt != NULL && lfnExt != strchr(lfn, '.')) { // More than one period in name lossyConversion = true; } - if ( lfnExt != NULL && lfnExt[1] != '\0' ) + 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++ ) + 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 ) + 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 ) + oemChar = wctob(towupper((wint_t) lfnChar)); + if (wctob((wint_t) lfnChar) != oemChar) { // Case of letter was changed lossyConversion = true; } - if ( oemChar == ' ' ) + if (oemChar == ' ') { // Skip spaces in alias lossyConversion = true; lfnExt += bytesUsed; continue; } - if ( oemChar == EOF ) + if (oemChar == EOF) { - oemChar = '_'; // Replace unconvertable characters with underscores + oemChar = '_'; // Replace unconvertable characters with underscores lossyConversion = true; } - if ( strchr ( ILLEGAL_ALIAS_CHARACTERS, oemChar ) != NULL ) + if (strchr(ILLEGAL_ALIAS_CHARACTERS, oemChar) != NULL) { // Invalid Alias character - oemChar = '_'; // Replace illegal characters with underscores + oemChar = '_'; // Replace illegal characters with underscores lossyConversion = true; } - alias[aliasPos] = ( char )oemChar; + alias[aliasPos] = (char) oemChar; aliasPos++; lfnExt += bytesUsed; } - if ( *lfnExt != '\0' ) + if (*lfnExt != '\0') { // Extension was more than 3 characters long lossyConversion = true; @@ -1003,7 +999,7 @@ static int _FAT_directory_createAlias ( char* alias, const char* lfn ) } alias[aliasPos] = '\0'; - if ( lossyConversion ) + if (lossyConversion) { return aliasPos; } @@ -1013,7 +1009,7 @@ static int _FAT_directory_createAlias ( char* alias, const char* lfn ) } } -bool _FAT_directory_addEntry ( PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster ) +bool _FAT_directory_addEntry(PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster) { size_t entrySize; uint8_t lfnEntry[DIR_ENTRY_DATA_SIZE]; @@ -1022,55 +1018,56 @@ bool _FAT_directory_addEntry ( PARTITION* partition, DIR_ENTRY* entry, uint32_t DIR_ENTRY_POSITION curEntryPos; bool entryStillValid; uint8_t aliasCheckSum = 0; - char alias [MAX_ALIAS_LENGTH]; + 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 ) + 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 ) + 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 ) + 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 ) + 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 ) ); + 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 ); + 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 ) ) + if (_FAT_directory_entryExists(partition, entry->filename, dirCluster)) { return false; } // Clear out alias, so we can generate a new one - memset ( entry->entryData, ' ', 11 ); + memset(entry->entryData, ' ', 11); - if ( strncmp( entry->filename, ".", MAX_FILENAME_LENGTH ) == 0 ) + if (strncmp(entry->filename, ".", MAX_FILENAME_LENGTH) == 0) { // "." entry entry->entryData[0] = '.'; entrySize = 1; } - else if ( strncmp( entry->filename, "..", MAX_FILENAME_LENGTH ) == 0 ) + else if (strncmp(entry->filename, "..", MAX_FILENAME_LENGTH) == 0) { // ".." entry entry->entryData[0] = '.'; @@ -1080,12 +1077,12 @@ bool _FAT_directory_addEntry ( PARTITION* partition, DIR_ENTRY* entry, uint32_t else { // Normal file name - aliasLen = _FAT_directory_createAlias ( alias, entry->filename ); - if ( aliasLen < 0 ) + aliasLen = _FAT_directory_createAlias(alias, entry->filename); + if (aliasLen < 0) { return false; } - else if ( aliasLen == 0 ) + else if (aliasLen == 0) { // It's a normal short filename entrySize = 1; @@ -1093,44 +1090,45 @@ bool _FAT_directory_addEntry ( PARTITION* partition, DIR_ENTRY* entry, uint32_t else { // It's a long filename with an alias - entrySize = ( ( lfnLen + LFN_ENTRY_LENGTH - 1 ) / LFN_ENTRY_LENGTH ) + 1; + 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 ) ) + 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 ) + 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 ); + memmove(alias + j, alias + i, strlen(alias) - i); // Pad primary component - memset ( alias + i, '_', j - i ); - alias[MAX_ALIAS_LENGTH-1] = 0; + memset(alias + i, '_', j - i); + alias[MAX_ALIAS_LENGTH - 1] = 0; } // Generate numeric tail - for ( i = 1; i <= MAX_NUMERIC_TAIL; i++ ) + for (i = 1; i <= MAX_NUMERIC_TAIL; i++) { j = i; tmpCharPtr = alias + MAX_ALIAS_PRI_LENGTH - 1; - while ( j > 0 ) + while (j > 0) { - *tmpCharPtr = '0' + ( j % 10 ); // ASCII numeric value + *tmpCharPtr = '0' + (j % 10); // ASCII numeric value tmpCharPtr--; j /= 10; } *tmpCharPtr = '~'; - if ( !_FAT_directory_entryExists ( partition, alias, dirCluster ) ) + if (!_FAT_directory_entryExists(partition, alias, dirCluster)) { break; } } - if ( i > MAX_NUMERIC_TAIL ) + if (i > MAX_NUMERIC_TAIL) { // Couldn't get a valid alias return false; @@ -1139,42 +1137,42 @@ bool _FAT_directory_addEntry ( PARTITION* partition, DIR_ENTRY* entry, uint32_t } // Copy alias or short file name into directory entry data - for ( i = 0, j = 0; ( j < 8 ) && ( alias[i] != '.' ) && ( alias[i] != '\0' ); i++, j++ ) + for (i = 0, j = 0; (j < 8) && (alias[i] != '.') && (alias[i] != '\0'); i++, j++) { entry->entryData[j] = alias[i]; } - while ( j < 8 ) + while (j < 8) { entry->entryData[j] = ' '; - ++ j; + ++j; } - if ( alias[i] == '.' ) + if (alias[i] == '.') { // Copy extension - ++ i; - while ( ( alias[i] != '\0' ) && ( j < 11 ) ) + ++i; + while ((alias[i] != '\0') && (j < 11)) { entry->entryData[j] = alias[i]; - ++ i; - ++ j; + ++i; + ++j; } } - while ( j < 11 ) + while (j < 11) { entry->entryData[j] = ' '; - ++ j; + ++j; } // Generate alias checksum - for ( i = 0; i < ALIAS_ENTRY_LENGTH; i++ ) + 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]; + aliasCheckSum = ((aliasCheckSum & 1) ? 0x80 : 0) + (aliasCheckSum >> 1) + entry->entryData[i]; } } // Find or create space for the entry - if ( _FAT_directory_findEntryGap ( partition, entry, dirCluster, entrySize ) == false ) + if (_FAT_directory_findEntryGap(partition, entry, dirCluster, entrySize) == false) { return false; } @@ -1184,45 +1182,49 @@ bool _FAT_directory_addEntry ( PARTITION* partition, DIR_ENTRY* entry, uint32_t { // 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 ); + 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 ) + for (entryStillValid = true, i = entrySize; entryStillValid && i > 0; entryStillValid + = _FAT_directory_incrementDirEntryPosition(partition, &curEntryPos, false), --i) { - if ( i > 1 ) + 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++ ) + 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 (lfn[(i - 2) * 13 + j] == '\0') { - if ( ( j > 1 ) && ( lfn [( i - 2 ) * 13 + ( j-1 )] == '\0' ) ) + if ((j > 1) && (lfn[(i - 2) * 13 + (j - 1)] == '\0')) { - u16_to_u8array ( lfnEntry, LFN_offset_table[j], 0xffff ); // Padding + u16_to_u8array(lfnEntry, LFN_offset_table[j], 0xffff); // Padding } else { - u16_to_u8array ( lfnEntry, LFN_offset_table[j], 0x0000 ); // Terminating null character + 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] ); + 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 ); + 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 ); + _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); } } } @@ -1230,56 +1232,48 @@ bool _FAT_directory_addEntry ( PARTITION* partition, DIR_ENTRY* entry, uint32_t return true; } -bool _FAT_directory_chdir ( PARTITION* partition, const char* path ) +bool _FAT_directory_chdir(PARTITION* partition, const char* path) { DIR_ENTRY entry; - if ( !_FAT_directory_entryFromPath ( partition, &entry, path, NULL ) ) + if (!_FAT_directory_entryFromPath(partition, &entry, path, NULL)) { return false; } - if ( !( entry.entryData[DIR_ENTRY_attributes] & ATTRIB_DIR ) ) + 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; } -void _FAT_directory_entryStat ( PARTITION* partition, DIR_ENTRY* entry, struct stat *st ) +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_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_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_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_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_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 8e314575..1b5291b1 100644 --- a/source/libfat/directory.h +++ b/source/libfat/directory.h @@ -8,13 +8,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -25,7 +25,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef __DIRECTORY_H #define __DIRECTORY_H @@ -56,22 +56,24 @@ #define ATTRIB_SYS 0x04 // System #define ATTRIB_HID 0x02 // Hidden #define ATTRIB_RO 0x01 // Read only - -typedef enum {FT_DIRECTORY, FT_FILE} FILE_TYPE; +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 @@ -93,87 +95,87 @@ enum DIR_ENTRY_offset }; /* -Returns true if the file specified by entry is a directory -*/ -static inline bool _FAT_directory_isDirectory ( DIR_ENTRY* entry ) + 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 ) +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 ) +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'))); } /* -Reads the first directory entry from the directory starting at dirCluster -Places result in entry -entry will be destroyed even if no directory entry is found -Returns true on success, false on failure -*/ -bool _FAT_directory_getFirstEntry ( PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster ); + Reads the first directory entry from the directory starting at dirCluster + Places result in entry + entry will be destroyed even if no directory entry is found + Returns true on success, false on failure + */ +bool _FAT_directory_getFirstEntry(PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster); /* -Reads the next directory entry after the one already pointed to by entry -Places result in entry -entry will be destroyed even if no directory entry is found -Returns true on success, false on failure -*/ -bool _FAT_directory_getNextEntry ( PARTITION* partition, DIR_ENTRY* entry ); + Reads the next directory entry after the one already pointed to by entry + Places result in entry + entry will be destroyed even if no directory entry is found + Returns true on success, false on failure + */ +bool _FAT_directory_getNextEntry(PARTITION* partition, DIR_ENTRY* entry); /* -Gets the directory entry corrsponding to the supplied path -entry will be destroyed even if no directory entry is found -pathEnd specifies the end of the path string, for cutting strings short if needed + Gets the directory entry corrsponding to the supplied path + entry will be destroyed even if no directory entry is found + pathEnd specifies the end of the path string, for cutting strings short if needed specify NULL to use the full length of path pathEnd is only a suggestion, and the path string will be searched up until the next PATH_SEPARATOR after pathEND. -Returns true on success, false on failure -*/ -bool _FAT_directory_entryFromPath ( PARTITION* partition, DIR_ENTRY* entry, const char* path, const char* pathEnd ); + Returns true on success, false on failure + */ +bool _FAT_directory_entryFromPath(PARTITION* partition, DIR_ENTRY* entry, const char* path, const char* pathEnd); /* -Changes the current directory to the one specified by path -Returns true on success, false on failure -*/ -bool _FAT_directory_chdir ( PARTITION* partition, const char* path ); + Changes the current directory to the one specified by path + Returns true on success, false on failure + */ +bool _FAT_directory_chdir(PARTITION* partition, const char* path); /* -Removes the directory entry specified by entry -Assumes that entry is valid -Returns true on success, false on failure -*/ -bool _FAT_directory_removeEntry ( PARTITION* partition, DIR_ENTRY* entry ); + Removes the directory entry specified by entry + Assumes that entry is valid + Returns true on success, false on failure + */ +bool _FAT_directory_removeEntry(PARTITION* partition, DIR_ENTRY* entry); /* -Add a directory entry to the directory specified by dirCluster -The fileData, dataStart and dataEnd elements of the DIR_ENTRY struct are -updated with the new directory entry position and alias. -Returns true on success, false on failure -*/ -bool _FAT_directory_addEntry ( PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster ); + Add a directory entry to the directory specified by dirCluster + The fileData, dataStart and dataEnd elements of the DIR_ENTRY struct are + updated with the new directory entry position and alias. + Returns true on success, false on failure + */ +bool _FAT_directory_addEntry(PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster); /* -Get the start cluster of a file from it's entry data -*/ -uint32_t _FAT_directory_entryGetCluster ( PARTITION* partition, const uint8_t* entryData ); + Get the start cluster of a file from it's entry data + */ +uint32_t _FAT_directory_entryGetCluster(PARTITION* partition, const uint8_t* entryData); /* -Fill in the file name and entry data of DIR_ENTRY* entry. -Assumes that the entry's dataStart and dataEnd are correct -Returns true on success, false on failure -*/ -bool _FAT_directory_entryFromPosition ( PARTITION* partition, DIR_ENTRY* entry ); + Fill in the file name and entry data of DIR_ENTRY* entry. + Assumes that the entry's dataStart and dataEnd are correct + Returns true on success, false on failure + */ +bool _FAT_directory_entryFromPosition(PARTITION* partition, DIR_ENTRY* entry); /* -Fill in a stat struct based on a file entry -*/ -void _FAT_directory_entryStat ( PARTITION* partition, DIR_ENTRY* entry, struct stat *st ); + Fill in a stat struct based on a file entry + */ +void _FAT_directory_entryStat(PARTITION* partition, DIR_ENTRY* entry, struct stat *st); #endif // _DIRECTORY_H diff --git a/source/libfat/disc.h b/source/libfat/disc.h index 27309f7c..a99123c7 100644 --- a/source/libfat/disc.h +++ b/source/libfat/disc.h @@ -8,13 +8,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -25,93 +25,94 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef _DISC_H #define _DISC_H #include "common.h" /* -A list of all default devices to try at startup, -terminated by a {NULL,NULL} entry. -*/ + 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[]; /* -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 ) + 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(); } /* -Read numSectors sectors from a disc, starting at sector. -numSectors is between 1 and LIMIT_SECTORS if LIMIT_SECTORS is defined, -else it is at least 1 -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 ) + Read numSectors sectors from a disc, starting at sector. + numSectors is between 1 and LIMIT_SECTORS if LIMIT_SECTORS is defined, + else it is at least 1 + 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); } /* -Write numSectors sectors to a disc, starting at sector. -numSectors is between 1 and LIMIT_SECTORS if LIMIT_SECTORS is defined, -else it is at least 1 -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 ) + Write numSectors sectors to a disc, starting at sector. + numSectors is between 1 and LIMIT_SECTORS if LIMIT_SECTORS is defined, + else it is at least 1 + 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 ) + Reset the card back to a ready state + */ +static inline bool _FAT_disc_clearStatus(const DISC_INTERFACE* disc) { 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 ) + 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(); } /* -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 ) + 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 a 32 bit value unique to each type of interface -*/ -static inline uint32_t _FAT_disc_hostType ( const DISC_INTERFACE* disc ) + 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 a 32 bit value that specifies the capabilities of the disc -*/ -static inline uint32_t _FAT_disc_features ( const DISC_INTERFACE* disc ) + 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; } diff --git a/source/libfat/disc_fat.c b/source/libfat/disc_fat.c index d52b2054..6b804d1e 100644 --- a/source/libfat/disc_fat.c +++ b/source/libfat/disc_fat.c @@ -8,13 +8,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -25,48 +25,42 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #include "disc_fat.h" /* -The list of interfaces consists of a series of name/interface pairs. -The interface is returned via a simple function. This allows for -platforms where the interface has to be "assembled" before it can -be used, like DLDI on the NDS. For cases where a simple struct -is available, wrapper functions are used. -The list is terminated by a NULL/NULL entry. -*/ + The list of interfaces consists of a series of name/interface pairs. + The interface is returned via a simple function. This allows for + platforms where the interface has to be "assembled" before it can + be used, like DLDI on the NDS. For cases where a simple struct + is available, wrapper functions are used. + The list is terminated by a NULL/NULL entry. + */ /* ====================== Wii ====================== */ #include #include "usbloader/usbstorage2.h" #include -static const DISC_INTERFACE* get_io_wiisd ( void ) +static const DISC_INTERFACE* get_io_wiisd(void) { return &__io_wiisd; } -static const DISC_INTERFACE* get_io_usbstorage ( void ) +static const DISC_INTERFACE* get_io_usbstorage(void) { return &__io_usbstorage2; } -static const DISC_INTERFACE* get_io_gcsda ( void ) +static const DISC_INTERFACE* get_io_gcsda(void) { return &__io_gcsda; } -static const DISC_INTERFACE* get_io_gcsdb ( void ) +static const DISC_INTERFACE* get_io_gcsdb(void) { 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} -}; +const INTERFACE_ID _FAT_disc_interfaces[] = { { "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 792aa5af..3494ba59 100644 --- a/source/libfat/disc_fat.h +++ b/source/libfat/disc_fat.h @@ -8,13 +8,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -25,93 +25,94 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef __DISC_H #define __DISC_H #include "common.h" /* -A list of all default devices to try at startup, -terminated by a {NULL,NULL} entry. -*/ + 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[]; /* -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 ) + 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(); } /* -Read numSectors sectors from a disc, starting at sector. -numSectors is between 1 and LIMIT_SECTORS if LIMIT_SECTORS is defined, -else it is at least 1 -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 ) + Read numSectors sectors from a disc, starting at sector. + numSectors is between 1 and LIMIT_SECTORS if LIMIT_SECTORS is defined, + else it is at least 1 + 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); } /* -Write numSectors sectors to a disc, starting at sector. -numSectors is between 1 and LIMIT_SECTORS if LIMIT_SECTORS is defined, -else it is at least 1 -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 ) + Write numSectors sectors to a disc, starting at sector. + numSectors is between 1 and LIMIT_SECTORS if LIMIT_SECTORS is defined, + else it is at least 1 + 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 ) + Reset the card back to a ready state + */ +static inline bool _FAT_disc_clearStatus(const DISC_INTERFACE* disc) { 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 ) + 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(); } /* -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 ) + 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 a 32 bit value unique to each type of interface -*/ -static inline uint32_t _FAT_disc_hostType ( const DISC_INTERFACE* disc ) + 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 a 32 bit value that specifies the capabilities of the disc -*/ -static inline uint32_t _FAT_disc_features ( const DISC_INTERFACE* disc ) + 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; } diff --git a/source/libfat/fat.h b/source/libfat/fat.h index 10ff108b..0798c23c 100644 --- a/source/libfat/fat.h +++ b/source/libfat/fat.h @@ -1,19 +1,19 @@ /* - fat.h - Simple functionality for startup, mounting and unmounting of FAT-based devices. + fat.h + Simple functionality for startup, mounting and unmounting of FAT-based devices. 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: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -24,8 +24,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - + */ #ifndef _LIBFAT_H #define _LIBFAT_H @@ -39,40 +38,41 @@ extern "C" #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 ); + 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 ); + 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 8e699d21..fc1559a1 100644 --- a/source/libfat/fat_cache.c +++ b/source/libfat/fat_cache.c @@ -14,13 +14,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -31,7 +31,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #include #include @@ -46,24 +46,25 @@ #define CACHE_FREE UINT_MAX -CACHE* _FAT_cache_constructor ( unsigned int numberOfPages, unsigned int sectorsPerPage, const DISC_INTERFACE* discInterface, sec_t endOfPartition ) +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; - if ( numberOfPages < 2 ) + if (numberOfPages < 2) { numberOfPages = 2; } - if ( sectorsPerPage < 8 ) + if (sectorsPerPage < 8) { sectorsPerPage = 8; } - cache = ( CACHE* ) _FAT_mem_allocate ( sizeof( CACHE ) ); - if ( cache == NULL ) + cache = (CACHE*) _FAT_mem_allocate(sizeof(CACHE)); + if (cache == NULL) { return NULL; } @@ -73,21 +74,20 @@ CACHE* _FAT_cache_constructor ( unsigned int numberOfPages, unsigned int sectors cache->numberOfPages = numberOfPages; cache->sectorsPerPage = sectorsPerPage; - - cacheEntries = ( CACHE_ENTRY* ) _FAT_mem_allocate ( sizeof( CACHE_ENTRY ) * numberOfPages ); - if ( cacheEntries == NULL ) + cacheEntries = (CACHE_ENTRY*) _FAT_mem_allocate(sizeof(CACHE_ENTRY) * numberOfPages); + if (cacheEntries == NULL) { - _FAT_mem_free ( cache ); + _FAT_mem_free(cache); return NULL; } - for ( i = 0; i < numberOfPages; i++ ) + 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 ); + cacheEntries[i].cache = (uint8_t*) _FAT_mem_align(sectorsPerPage * BYTES_PER_READ); } cache->cacheEntries = cacheEntries; @@ -95,22 +95,21 @@ CACHE* _FAT_cache_constructor ( unsigned int numberOfPages, unsigned int sectors return cache; } -void _FAT_cache_destructor ( CACHE* cache ) +void _FAT_cache_destructor(CACHE* cache) { unsigned int i; // Clear out cache before destroying it - _FAT_cache_flush( cache ); + _FAT_cache_flush(cache); // Free memory in reverse allocation order - for ( i = 0; i < cache->numberOfPages; i++ ) + for (i = 0; i < cache->numberOfPages; i++) { - _FAT_mem_free ( cache->cacheEntries[i].cache ); + _FAT_mem_free(cache->cacheEntries[i].cache); } - _FAT_mem_free ( cache->cacheEntries ); - _FAT_mem_free ( cache ); + _FAT_mem_free(cache->cacheEntries); + _FAT_mem_free(cache); } - static u32 accessCounter = 0; static u32 accessTime() @@ -119,8 +118,7 @@ static u32 accessTime() return accessCounter; } - -static CACHE_ENTRY* _FAT_cache_getPage( CACHE *cache, sec_t sector ) +static CACHE_ENTRY* _FAT_cache_getPage(CACHE *cache, sec_t sector) { unsigned int i; CACHE_ENTRY* cacheEntries = cache->cacheEntries; @@ -131,60 +129,61 @@ static CACHE_ENTRY* _FAT_cache_getPage( CACHE *cache, sec_t sector ) unsigned int oldUsed = 0; unsigned int oldAccess = UINT_MAX; - for ( i = 0; i < numberOfPages; i++ ) + for (i = 0; i < numberOfPages; i++) { - if ( sector >= cacheEntries[i].sector && sector < ( cacheEntries[i].sector + cacheEntries[i].count ) ) + if (sector >= cacheEntries[i].sector && sector < (cacheEntries[i].sector + cacheEntries[i].count)) { cacheEntries[i].last_access = accessTime(); - return &( cacheEntries[i] ); + return &(cacheEntries[i]); } - if ( foundFree == false && ( cacheEntries[i].sector == CACHE_FREE || cacheEntries[i].last_access < oldAccess ) ) + if (foundFree == false && (cacheEntries[i].sector == CACHE_FREE || cacheEntries[i].last_access < oldAccess)) { - if ( cacheEntries[i].sector == CACHE_FREE ) foundFree = true; + if (cacheEntries[i].sector == CACHE_FREE) foundFree = true; oldUsed = i; oldAccess = cacheEntries[i].last_access; } } - if ( foundFree == false && cacheEntries[oldUsed].dirty == true ) + if (foundFree == false && cacheEntries[oldUsed].dirty == true) { - if ( !_FAT_disc_writeSectors( cache->disc, cacheEntries[oldUsed].sector, cacheEntries[oldUsed].count, cacheEntries[oldUsed].cache ) ) return NULL; + 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 + 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 (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(); - return &( cacheEntries[oldUsed] ); + return &(cacheEntries[oldUsed]); } -bool _FAT_cache_readSectors( CACHE *cache, sec_t sector, sec_t numSectors, void *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 ) + while (numSectors > 0) { - 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; secs_to_read = entry->count - sec; - if ( secs_to_read > numSectors ) secs_to_read = numSectors; + 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 ); + dest += (secs_to_read * BYTES_PER_READ); sector += secs_to_read; numSectors -= secs_to_read; } @@ -193,111 +192,125 @@ bool _FAT_cache_readSectors( CACHE *cache, sec_t sector, sec_t numSectors, void } /* -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 ) + 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; - 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 ); + memcpy(buffer, entry->cache + ((sec * BYTES_PER_READ) + offset), size); return true; } -bool _FAT_cache_readLittleEndianValue ( CACHE* cache, uint32_t *value, sec_t sector, unsigned int offset, int num_bytes ) +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; + if (!_FAT_cache_readPartialSector(cache, buf, sector, offset, num_bytes)) return false; - switch ( num_bytes ) + 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; + 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 ) + 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; - 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 ); + memcpy(entry->cache + ((sec * BYTES_PER_READ) + offset), buffer, size); entry->dirty = true; return true; } -bool _FAT_cache_writeLittleEndianValue ( CACHE* cache, const uint32_t value, sec_t sector, unsigned int offset, int size ) +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 ) + 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; + 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 ) + 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; - 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 ); + 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; } - -static CACHE_ENTRY* _FAT_cache_findPage( CACHE *cache, sec_t sector, sec_t count ) +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; + sec_t lowest = UINT_MAX; - for ( i = 0; i < numberOfPages; i++ ) + for (i = 0; i < numberOfPages; i++) { - if ( cacheEntries[i].sector != CACHE_FREE ) + if (cacheEntries[i].sector != CACHE_FREE) { bool intersect; - if ( sector > cacheEntries[i].sector ) + if (sector > cacheEntries[i].sector) { intersect = sector - cacheEntries[i].sector < cacheEntries[i].count; } @@ -306,7 +319,7 @@ static CACHE_ENTRY* _FAT_cache_findPage( CACHE *cache, sec_t sector, sec_t count intersect = cacheEntries[i].sector - sector < count; } - if ( intersect && ( cacheEntries[i].sector < lowest ) ) + if (intersect && (cacheEntries[i].sector < lowest)) { lowest = cacheEntries[i].sector; entry = &cacheEntries[i]; @@ -317,27 +330,27 @@ static CACHE_ENTRY* _FAT_cache_findPage( CACHE *cache, sec_t sector, sec_t count return entry; } -bool _FAT_cache_writeSectors ( CACHE* cache, sec_t sector, sec_t numSectors, const void* 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 ) + while (numSectors > 0) { - entry = _FAT_cache_findPage( cache, sector, numSectors ); + 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; - _FAT_disc_writeSectors( cache->disc, sector, secs_to_write, src ); - src += ( secs_to_write * BYTES_PER_READ ); + _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; } @@ -345,11 +358,11 @@ bool _FAT_cache_writeSectors ( CACHE* cache, sec_t sector, sec_t numSectors, con 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 ); + src += (secs_to_write * BYTES_PER_READ); sector += secs_to_write; numSectors -= secs_to_write; @@ -358,7 +371,7 @@ bool _FAT_cache_writeSectors ( CACHE* cache, sec_t sector, sec_t numSectors, con } else { - _FAT_disc_writeSectors( cache->disc, sector, numSectors, src ); + _FAT_disc_writeSectors(cache->disc, sector, numSectors, src); numSectors = 0; } } @@ -366,17 +379,18 @@ bool _FAT_cache_writeSectors ( CACHE* cache, sec_t sector, sec_t numSectors, con } /* -Flushes all dirty pages to disc, clearing the dirty flag. -*/ -bool _FAT_cache_flush ( CACHE* cache ) + Flushes all dirty pages to disc, clearing the dirty flag. + */ +bool _FAT_cache_flush(CACHE* cache) { unsigned int i; - for ( i = 0; i < cache->numberOfPages; i++ ) + for (i = 0; i < cache->numberOfPages; i++) { - if ( cache->cacheEntries[i].dirty ) + if (cache->cacheEntries[i].dirty) { - if ( !_FAT_disc_writeSectors ( cache->disc, cache->cacheEntries[i].sector, cache->cacheEntries[i].count, cache->cacheEntries[i].cache ) ) + if (!_FAT_disc_writeSectors(cache->disc, cache->cacheEntries[i].sector, cache->cacheEntries[i].count, + cache->cacheEntries[i].cache)) { return false; } @@ -387,11 +401,11 @@ bool _FAT_cache_flush ( CACHE* cache ) return true; } -void _FAT_cache_invalidate ( CACHE* cache ) +void _FAT_cache_invalidate(CACHE* cache) { unsigned int i; - _FAT_cache_flush( cache ); - for ( i = 0; i < cache->numberOfPages; i++ ) + _FAT_cache_flush(cache); + for (i = 0; i < cache->numberOfPages; i++) { cache->cacheEntries[i].sector = CACHE_FREE; cache->cacheEntries[i].last_access = 0; diff --git a/source/libfat/fat_cache.h b/source/libfat/fat_cache.h index 5733b98c..6b26de4c 100644 --- a/source/libfat/fat_cache.h +++ b/source/libfat/fat_cache.h @@ -14,13 +14,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -31,7 +31,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef __CACHE_H #define __CACHE_H @@ -44,91 +44,93 @@ 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; /* -Read data from a sector in the cache -If the sector is not in the cache, it will be swapped in -offset is the position to start reading from -size is the amount of data to read -Precondition: offset + size <= BYTES_PER_READ -*/ -bool _FAT_cache_readPartialSector ( CACHE* cache, void* buffer, sec_t sector, unsigned int offset, size_t size ); + Read data from a sector in the cache + If the sector is not in the cache, it will be swapped in + offset is the position to start reading from + size is the amount of data to read + Precondition: offset + size <= BYTES_PER_READ + */ +bool _FAT_cache_readPartialSector(CACHE* cache, void* buffer, sec_t sector, unsigned int offset, size_t size); -bool _FAT_cache_readLittleEndianValue ( CACHE* cache, uint32_t *value, sec_t sector, unsigned int offset, int num_bytes ); +bool _FAT_cache_readLittleEndianValue(CACHE* cache, uint32_t *value, sec_t sector, unsigned int offset, int num_bytes); /* -Write data to a sector in the cache -If the sector is not in the cache, it will be swapped in. -When the sector is swapped out, the data will be written to the disc -offset is the position to start writing to -size is the amount of data to write -Precondition: offset + size <= BYTES_PER_READ -*/ -bool _FAT_cache_writePartialSector ( CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size ); + Write data to a sector in the cache + If the sector is not in the cache, it will be swapped in. + When the sector is swapped out, the data will be written to the disc + offset is the position to start writing to + size is the amount of data to write + Precondition: offset + size <= BYTES_PER_READ + */ +bool _FAT_cache_writePartialSector(CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size); -bool _FAT_cache_writeLittleEndianValue ( CACHE* cache, const uint32_t value, sec_t sector, unsigned int offset, int num_bytes ); +bool _FAT_cache_writeLittleEndianValue(CACHE* cache, const uint32_t value, sec_t sector, unsigned int offset, + int num_bytes); /* -Write data to a sector in the cache, zeroing the sector first -If the sector is not in the cache, it will be swapped in. -When the sector is swapped out, the data will be written to the disc -offset is the position to start writing to -size is the amount of data to write -Precondition: offset + size <= BYTES_PER_READ -*/ -bool _FAT_cache_eraseWritePartialSector ( CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size ); + Write data to a sector in the cache, zeroing the sector first + If the sector is not in the cache, it will be swapped in. + When the sector is swapped out, the data will be written to the disc + offset is the position to start writing to + size is the amount of data to write + Precondition: offset + size <= BYTES_PER_READ + */ +bool _FAT_cache_eraseWritePartialSector(CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, + size_t size); /* -Read several sectors from the cache -*/ -bool _FAT_cache_readSectors ( CACHE* cache, sec_t sector, sec_t numSectors, void* buffer ); + Read several sectors from the cache + */ +bool _FAT_cache_readSectors(CACHE* cache, sec_t sector, sec_t numSectors, void* buffer); /* -Read a full sector from the cache -*/ -static inline bool _FAT_cache_readSector ( CACHE* cache, void* buffer, sec_t sector ) + 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 ) + 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 ); +bool _FAT_cache_writeSectors(CACHE* cache, sec_t sector, sec_t numSectors, const void* buffer); /* -Write any dirty sectors back to disc and clear out the contents of the cache -*/ -bool _FAT_cache_flush ( CACHE* cache ); + Write any dirty sectors back to disc and clear out the contents of the cache + */ +bool _FAT_cache_flush(CACHE* cache); /* -Clear out the contents of the cache without writing any dirty sectors first -*/ -void _FAT_cache_invalidate ( CACHE* cache ); + Clear out the contents of the cache without writing any dirty sectors first + */ +void _FAT_cache_invalidate(CACHE* cache); -CACHE* _FAT_cache_constructor ( unsigned int numberOfPages, unsigned int sectorsPerPage, const DISC_INTERFACE* discInterface, sec_t endOfPartition ); +CACHE* _FAT_cache_constructor(unsigned int numberOfPages, unsigned int sectorsPerPage, + const DISC_INTERFACE* discInterface, sec_t endOfPartition); -void _FAT_cache_destructor ( CACHE* cache ); +void _FAT_cache_destructor(CACHE* cache); #endif // _CACHE_H - diff --git a/source/libfat/fatdir.c b/source/libfat/fatdir.c index dfb5e4ce..ea3972b0 100644 --- a/source/libfat/fatdir.c +++ b/source/libfat/fatdir.c @@ -9,13 +9,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -26,7 +26,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #include #include @@ -44,55 +44,54 @@ #include "filetime.h" #include "lock.h" - -int _FAT_stat_r ( struct _reent *r, const char *path, struct stat *st ) +int _FAT_stat_r(struct _reent *r, const char *path, struct stat *st) { PARTITION* partition = NULL; DIR_ENTRY dirEntry; // Get the partition this file is on - partition = _FAT_partition_getPartitionFromPath ( path ); - if ( partition == NULL ) + 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 ) + if (strchr(path, ':') != NULL) { - path = strchr ( path, ':' ) + 1; + path = strchr(path, ':') + 1; } - if ( strchr ( path, ':' ) != NULL ) + 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 ) ) + if (!_FAT_directory_entryFromPath(partition, &dirEntry, path, NULL)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = ENOENT; return -1; } // Fill in the stat struct - _FAT_directory_entryStat ( partition, &dirEntry, st ); + _FAT_directory_entryStat(partition, &dirEntry, st); - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); return 0; } -int _FAT_link_r ( struct _reent *r, const char *existing, const char *newLink ) +int _FAT_link_r(struct _reent *r, const char *existing, const char *newLink) { r->_errno = ENOTSUP; return -1; } -int _FAT_unlink_r ( struct _reent *r, const char *path ) +int _FAT_unlink_r(struct _reent *r, const char *path) { PARTITION* partition = NULL; DIR_ENTRY dirEntry; @@ -102,66 +101,65 @@ int _FAT_unlink_r ( struct _reent *r, const char *path ) bool errorOccured = false; // Get the partition this directory is on - partition = _FAT_partition_getPartitionFromPath ( path ); - if ( partition == NULL ) + 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 ) + if (partition->readOnly) { r->_errno = EROFS; return -1; } // Move the path pointer to the start of the actual path - if ( strchr ( path, ':' ) != NULL ) + if (strchr(path, ':') != NULL) { - path = strchr ( path, ':' ) + 1; + path = strchr(path, ':') + 1; } - if ( strchr ( path, ':' ) != NULL ) + 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 ) ) + if (!_FAT_directory_entryFromPath(partition, &dirEntry, path, NULL)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = ENOENT; return -1; } - cluster = _FAT_directory_entryGetCluster ( partition, dirEntry.entryData ); - + cluster = _FAT_directory_entryGetCluster(partition, dirEntry.entryData); // If this is a directory, make sure it is empty - if ( _FAT_directory_isDirectory ( &dirEntry ) ) + if (_FAT_directory_isDirectory(&dirEntry)) { - nextEntry = _FAT_directory_getFirstEntry ( partition, &dirContents, cluster ); + nextEntry = _FAT_directory_getFirstEntry(partition, &dirContents, cluster); - while ( nextEntry ) + while (nextEntry) { - if ( !_FAT_directory_isDot ( &dirContents ) ) + 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 ); + _FAT_unlock(&partition->lock); r->_errno = EPERM; return -1; } - nextEntry = _FAT_directory_getNextEntry ( partition, &dirContents ); + nextEntry = _FAT_directory_getNextEntry(partition, &dirContents); } } - if ( _FAT_fat_isValidCluster( partition, cluster ) ) + if (_FAT_fat_isValidCluster(partition, cluster)) { // Remove the cluster chain for this file - if ( !_FAT_fat_clearLinks ( partition, cluster ) ) + if (!_FAT_fat_clearLinks(partition, cluster)) { r->_errno = EIO; errorOccured = true; @@ -169,21 +167,21 @@ int _FAT_unlink_r ( struct _reent *r, const char *path ) } // Remove the directory entry for this file - if ( !_FAT_directory_removeEntry ( partition, &dirEntry ) ) + if (!_FAT_directory_removeEntry(partition, &dirEntry)) { r->_errno = EIO; errorOccured = true; } // Flush any sectors in the disc cache - if ( !_FAT_cache_flush( partition->cache ) ) + if (!_FAT_cache_flush(partition->cache)) { r->_errno = EIO; errorOccured = true; } - _FAT_unlock( &partition->lock ); - if ( errorOccured ) + _FAT_unlock(&partition->lock); + if (errorOccured) { return -1; } @@ -193,48 +191,48 @@ int _FAT_unlink_r ( struct _reent *r, const char *path ) } } -int _FAT_chdir_r ( struct _reent *r, const char *path ) +int _FAT_chdir_r(struct _reent *r, const char *path) { PARTITION* partition = NULL; // Get the partition this directory is on - partition = _FAT_partition_getPartitionFromPath ( path ); - if ( partition == NULL ) + 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 ) + if (strchr(path, ':') != NULL) { - path = strchr ( path, ':' ) + 1; + path = strchr(path, ':') + 1; } - if ( strchr ( path, ':' ) != NULL ) + if (strchr(path, ':') != NULL) { r->_errno = EINVAL; return -1; } - _FAT_lock( &partition->lock ); + _FAT_lock(&partition->lock); // Try changing directory - if ( _FAT_directory_chdir ( partition, path ) ) + if (_FAT_directory_chdir(partition, path)) { // Successful - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); return 0; } else { // Failed - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = ENOTDIR; return -1; } } -int _FAT_rename_r ( struct _reent *r, const char *oldName, const char *newName ) +int _FAT_rename_r(struct _reent *r, const char *oldName, const char *newName) { PARTITION* partition = NULL; DIR_ENTRY oldDirEntry; @@ -243,73 +241,73 @@ int _FAT_rename_r ( struct _reent *r, const char *oldName, const char *newName ) uint32_t dirCluster; // Get the partition this directory is on - partition = _FAT_partition_getPartitionFromPath ( oldName ); - if ( partition == NULL ) + partition = _FAT_partition_getPartitionFromPath(oldName); + if (partition == NULL) { r->_errno = ENODEV; return -1; } - _FAT_lock( &partition->lock ); + _FAT_lock(&partition->lock); // Make sure the same partition is used for the old and new names - if ( partition != _FAT_partition_getPartitionFromPath ( newName ) ) + if (partition != _FAT_partition_getPartitionFromPath(newName)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = EXDEV; return -1; } // Make sure we aren't trying to write to a read-only disc - if ( partition->readOnly ) + if (partition->readOnly) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = EROFS; return -1; } // Move the path pointer to the start of the actual path - if ( strchr ( oldName, ':' ) != NULL ) + if (strchr(oldName, ':') != NULL) { - oldName = strchr ( oldName, ':' ) + 1; + oldName = strchr(oldName, ':') + 1; } - if ( strchr ( oldName, ':' ) != NULL ) + if (strchr(oldName, ':') != NULL) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = EINVAL; return -1; } - if ( strchr ( newName, ':' ) != NULL ) + if (strchr(newName, ':') != NULL) { - newName = strchr ( newName, ':' ) + 1; + newName = strchr(newName, ':') + 1; } - if ( strchr ( newName, ':' ) != NULL ) + if (strchr(newName, ':') != NULL) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = EINVAL; return -1; } // Search for the file on the disc - if ( !_FAT_directory_entryFromPath ( partition, &oldDirEntry, oldName, NULL ) ) + if (!_FAT_directory_entryFromPath(partition, &oldDirEntry, oldName, NULL)) { - _FAT_unlock( &partition->lock ); + _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 ) ) + if (_FAT_directory_entryFromPath(partition, &newDirEntry, newName, NULL)) { - _FAT_unlock( &partition->lock ); + _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 ) + pathEnd = strrchr(newName, DIR_SEPARATOR); + if (pathEnd == NULL) { // No path was specified dirCluster = partition->cwdCluster; @@ -319,53 +317,53 @@ int _FAT_rename_r ( struct _reent *r, const char *oldName, const char *newName ) { // 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 ) ) + if (!_FAT_directory_entryFromPath(partition, &newDirEntry, newName, pathEnd) || !_FAT_directory_isDirectory( + &newDirEntry)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = ENOTDIR; return -1; } - dirCluster = _FAT_directory_entryGetCluster ( partition, newDirEntry.entryData ); + 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 ) ); + memcpy(&newDirEntry, &oldDirEntry, sizeof(DIR_ENTRY)); // Set the new name - strncpy ( newDirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1 ); + strncpy(newDirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1); // Write the new entry - if ( !_FAT_directory_addEntry ( partition, &newDirEntry, dirCluster ) ) + if (!_FAT_directory_addEntry(partition, &newDirEntry, dirCluster)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = ENOSPC; return -1; } // Remove the old entry - if ( !_FAT_directory_removeEntry ( partition, &oldDirEntry ) ) + if (!_FAT_directory_removeEntry(partition, &oldDirEntry)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = EIO; return -1; } // Flush any sectors in the disc cache - if ( !_FAT_cache_flush ( partition->cache ) ) + if (!_FAT_cache_flush(partition->cache)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = EIO; return -1; } - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); return 0; } -int _FAT_mkdir_r ( struct _reent *r, const char *path, int mode ) +int _FAT_mkdir_r(struct _reent *r, const char *path, int mode) { PARTITION* partition = NULL; bool fileExists; @@ -374,48 +372,48 @@ int _FAT_mkdir_r ( struct _reent *r, const char *path, int mode ) uint32_t parentCluster, dirCluster; uint8_t newEntryData[DIR_ENTRY_DATA_SIZE]; - partition = _FAT_partition_getPartitionFromPath ( path ); - if ( partition == NULL ) + 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 ) + if (strchr(path, ':') != NULL) { - path = strchr ( path, ':' ) + 1; + path = strchr(path, ':') + 1; } - if ( strchr ( path, ':' ) != NULL ) + 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 ); + fileExists = _FAT_directory_entryFromPath(partition, &dirEntry, path, NULL); // Make sure it doesn't exist - if ( fileExists ) + if (fileExists) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = EEXIST; return -1; } - if ( partition->readOnly ) + if (partition->readOnly) { // We can't write to a read-only partition - _FAT_unlock( &partition->lock ); + _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 ) + pathEnd = strrchr(path, DIR_SEPARATOR); + if (pathEnd == NULL) { // No path was specified parentCluster = partition->cwdCluster; @@ -425,259 +423,254 @@ int _FAT_mkdir_r ( struct _reent *r, const char *path, int mode ) { // 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 ) ) + if (!_FAT_directory_entryFromPath(partition, &dirEntry, path, pathEnd) + || !_FAT_directory_isDirectory(&dirEntry)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = ENOTDIR; return -1; } - parentCluster = _FAT_directory_entryGetCluster ( partition, dirEntry.entryData ); + 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 ); + 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() ); + 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 ) ) + 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 ); + _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 ); + 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 ) ) + if (!_FAT_directory_addEntry(partition, &dirEntry, parentCluster)) { - _FAT_unlock( &partition->lock ); + _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 ); + 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 ); + 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 ); - + _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; + 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 ); + 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 ); + _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 ) ) + if (!_FAT_cache_flush(partition->cache)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = EIO; return -1; } - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); return 0; } -int _FAT_statvfs_r ( struct _reent *r, const char *path, struct statvfs *buf ) +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 ) + 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_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. + 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. + 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 ); + 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 ) ; + | (partition->readOnly ? ST_RDONLY /* Read only file system */: 0); // Maximum filename length. buf->f_namemax = MAX_FILENAME_LENGTH; - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); return 0; } -DIR_ITER* _FAT_diropen_r( struct _reent *r, DIR_ITER *dirState, const char *path ) +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 ); + DIR_STATE_STRUCT* state = (DIR_STATE_STRUCT*) (dirState->dirStruct); bool fileExists; - state->partition = _FAT_partition_getPartitionFromPath ( path ); - if ( state->partition == 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 ) + if (strchr(path, ':') != NULL) { - path = strchr ( path, ':' ) + 1; + path = strchr(path, ':') + 1; } - if ( strchr ( path, ':' ) != NULL ) + if (strchr(path, ':') != NULL) { r->_errno = EINVAL; return NULL; } - _FAT_lock( &state->partition->lock ); + _FAT_lock(&state->partition->lock); // Get the start cluster of the directory - fileExists = _FAT_directory_entryFromPath ( state->partition, &dirEntry, path, NULL ); + fileExists = _FAT_directory_entryFromPath(state->partition, &dirEntry, path, NULL); - if ( !fileExists ) + if (!fileExists) { - _FAT_unlock( &state->partition->lock ); + _FAT_unlock(&state->partition->lock); r->_errno = ENOENT; return NULL; } // Make sure it is a directory - if ( ! _FAT_directory_isDirectory ( &dirEntry ) ) + if (!_FAT_directory_isDirectory(&dirEntry)) { - _FAT_unlock( &state->partition->lock ); + _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 ); + 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 ); + 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; + _FAT_unlock(&state->partition->lock); + return (DIR_ITER*) state; } -int _FAT_dirreset_r ( struct _reent *r, DIR_ITER *dirState ) +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 ) + if (!state->inUse) { - _FAT_unlock( &state->partition->lock ); + _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 ); + state->validEntry = _FAT_directory_getFirstEntry(state->partition, &(state->currentEntry), state->startCluster); - _FAT_unlock( &state->partition->lock ); + _FAT_unlock(&state->partition->lock); return 0; } -int _FAT_dirnext_r ( struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *filestat ) +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 ) + if (!state->inUse) { - _FAT_unlock( &state->partition->lock ); + _FAT_unlock(&state->partition->lock); r->_errno = EBADF; return -1; } // Make sure there is another file to report on - if ( ! state->validEntry ) + if (!state->validEntry) { - _FAT_unlock( &state->partition->lock ); + _FAT_unlock(&state->partition->lock); r->_errno = ENOENT; return -1; } // Get the filename - strncpy ( filename, state->currentEntry.filename, MAX_FILENAME_LENGTH ); + strncpy(filename, state->currentEntry.filename, MAX_FILENAME_LENGTH); // Get the stats, if requested - if ( filestat != NULL ) + if (filestat != NULL) { - _FAT_directory_entryStat ( state->partition, &( state->currentEntry ), filestat ); + _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 ) ); + state->validEntry = _FAT_directory_getNextEntry(state->partition, &(state->currentEntry)); - _FAT_unlock( &state->partition->lock ); + _FAT_unlock(&state->partition->lock); return 0; } -int _FAT_dirclose_r ( struct _reent *r, DIR_ITER *dirState ) +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 ); + _FAT_lock(&state->partition->lock); state->inUse = false; - _FAT_unlock( &state->partition->lock ); + _FAT_unlock(&state->partition->lock); return 0; } diff --git a/source/libfat/fatdir.h b/source/libfat/fatdir.h index 7f0b7eb1..aff52408 100644 --- a/source/libfat/fatdir.h +++ b/source/libfat/fatdir.h @@ -9,13 +9,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -26,8 +26,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - + */ #ifndef __FATDIR_H #define __FATDIR_H @@ -41,34 +40,33 @@ 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 ); +extern int _FAT_stat_r(struct _reent *r, const char *path, struct stat *st); -extern int _FAT_link_r ( struct _reent *r, const char *existing, const char *newLink ); +extern int _FAT_link_r(struct _reent *r, const char *existing, const char *newLink); -extern int _FAT_unlink_r ( struct _reent *r, const char *name ); +extern int _FAT_unlink_r(struct _reent *r, const char *name); -extern int _FAT_chdir_r ( struct _reent *r, const char *name ); +extern int _FAT_chdir_r(struct _reent *r, const char *name); -extern int _FAT_rename_r ( struct _reent *r, const char *oldName, const char *newName ); +extern int _FAT_rename_r(struct _reent *r, const char *oldName, const char *newName); -extern int _FAT_mkdir_r ( struct _reent *r, const char *path, int mode ); +extern int _FAT_mkdir_r(struct _reent *r, const char *path, int mode); -extern int _FAT_statvfs_r ( struct _reent *r, const char *path, struct statvfs *buf ); +extern int _FAT_statvfs_r(struct _reent *r, const char *path, struct statvfs *buf); /* -Directory iterator functions -*/ -extern DIR_ITER* _FAT_diropen_r( struct _reent *r, DIR_ITER *dirState, const char *path ); -extern int _FAT_dirreset_r ( struct _reent *r, DIR_ITER *dirState ); -extern int _FAT_dirnext_r ( struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *filestat ); -extern int _FAT_dirclose_r ( struct _reent *r, DIR_ITER *dirState ); - + Directory iterator functions + */ +extern DIR_ITER* _FAT_diropen_r(struct _reent *r, DIR_ITER *dirState, const char *path); +extern int _FAT_dirreset_r(struct _reent *r, DIR_ITER *dirState); +extern int _FAT_dirnext_r(struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *filestat); +extern int _FAT_dirclose_r(struct _reent *r, DIR_ITER *dirState); #endif // _FATDIR_H diff --git a/source/libfat/fatfile.c b/source/libfat/fatfile.c index 718a2700..71f4a54d 100644 --- a/source/libfat/fatfile.c +++ b/source/libfat/fatfile.c @@ -9,13 +9,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -28,8 +28,7 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 2009-10-23 oggzee: fixes for cluster aligned file size (write, truncate, seek) -*/ - + */ #include "fatfile.h" @@ -45,49 +44,49 @@ #include "filetime.h" #include "lock.h" -int _FAT_open_r ( struct _reent *r, void *fileStruct, const char *path, int flags, int mode ) +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 ); + FILE_STRUCT* file = (FILE_STRUCT*) fileStruct; + partition = _FAT_partition_getPartitionFromPath(path); - if ( partition == NULL ) + if (partition == NULL) { r->_errno = ENODEV; return -1; } // Move the path pointer to the start of the actual path - if ( strchr ( path, ':' ) != NULL ) + if (strchr(path, ':') != NULL) { - path = strchr ( path, ':' ) + 1; + path = strchr(path, ':') + 1; } - if ( strchr ( path, ':' ) != NULL ) + if (strchr(path, ':') != NULL) { r->_errno = EINVAL; return -1; } // Determine which mode the file is openned for - if ( ( flags & 0x03 ) == O_RDONLY ) + 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 ) + 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 ) + else if ((flags & 0x03) == O_RDWR) { // Open file for read/write access file->read = true; @@ -101,28 +100,28 @@ int _FAT_open_r ( struct _reent *r, void *fileStruct, const char *path, int flag } // Make sure we aren't trying to write to a read-only disc - if ( file->write && partition->readOnly ) + 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 ); + _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 ) + if ((flags & O_CREAT) && (flags & O_EXCL) && fileExists) { - _FAT_unlock( &partition->lock ); + _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 ) ) + if (fileExists && _FAT_directory_isDirectory(&dirEntry)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = EISDIR; return -1; } @@ -131,21 +130,21 @@ int _FAT_open_r ( struct _reent *r, void *fileStruct, const char *path, int flag file->modified = false; // If the file doesn't exist, create it if we're allowed to - if ( !fileExists ) + if (!fileExists) { - if ( flags & O_CREAT ) + if (flags & O_CREAT) { - if ( partition->readOnly ) + if (partition->readOnly) { // We can't write to a read-only partition - _FAT_unlock( &partition->lock ); + _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 ) + pathEnd = strrchr(path, DIR_SEPARATOR); + if (pathEnd == NULL) { // No path was specified dirCluster = partition->cwdCluster; @@ -155,29 +154,29 @@ int _FAT_open_r ( struct _reent *r, void *fileStruct, const char *path, int flag { // 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 ) ) + if (!_FAT_directory_entryFromPath(partition, &dirEntry, path, pathEnd) || !_FAT_directory_isDirectory( + &dirEntry)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = ENOTDIR; return -1; } - dirCluster = _FAT_directory_entryGetCluster ( partition, dirEntry.entryData ); + 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 ); + 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_cTime, _FAT_filetime_getTimeFromRTC()); + u16_to_u8array(dirEntry.entryData, DIR_ENTRY_cDate, _FAT_filetime_getDateFromRTC()); - if ( !_FAT_directory_addEntry ( partition, &dirEntry, dirCluster ) ) + if (!_FAT_directory_addEntry(partition, &dirEntry, dirCluster)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = ENOSPC; return -1; } @@ -188,26 +187,26 @@ int _FAT_open_r ( struct _reent *r, void *fileStruct, const char *path, int flag else { // file doesn't exist, and we aren't creating it - _FAT_unlock( &partition->lock ); + _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; - } - */ + // 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 ) ) + if (file->write && !_FAT_directory_isWritable(&dirEntry)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = EROFS; return -1; } @@ -215,12 +214,12 @@ int _FAT_open_r ( struct _reent *r, void *fileStruct, const char *path, int flag // 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 ) ) + if ((flags & O_TRUNC) && file->write && (file->startCluster != 0)) { - _FAT_fat_clearLinks ( partition, file->startCluster ); + _FAT_fat_clearLinks(partition, file->startCluster); file->startCluster = CLUSTER_FREE; file->filesize = 0; // File is modified since we just cut it all off @@ -228,26 +227,26 @@ int _FAT_open_r ( struct _reent *r, void *fileStruct, const char *path, int flag } // 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->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.sector = 0; file->rwPosition.byte = 0; - if ( flags & O_APPEND ) + 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.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 ) ) + if ((file->filesize > 0) && ((file->filesize % partition->bytesPerCluster) == 0)) { // Set flag to allocate a new cluster file->appendPosition.sector = partition->sectorsPerCluster; @@ -265,7 +264,7 @@ int _FAT_open_r ( struct _reent *r, void *fileStruct, const char *path, int flag // Insert this file into the double-linked list of open files partition->openFileCount += 1; - if ( partition->firstOpenFile ) + if (partition->firstOpenFile) { file->nextOpenFile = partition->firstOpenFile; partition->firstOpenFile->prevOpenFile = file; @@ -277,57 +276,57 @@ int _FAT_open_r ( struct _reent *r, void *fileStruct, const char *path, int flag file->prevOpenFile = NULL; partition->firstOpenFile = file; - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); - return ( int ) file; + return (int) file; } /* -Synchronizes the file data to disc. -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 ) + Synchronizes the file data to disc. + 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]; - if ( !file || !file->inUse ) + if (!file || !file->inUse) { return EBADF; } - if ( file->write && file->modified ) + 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 ); + _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 ); + 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 ); + 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() ); + 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() ); + u16_to_u8array(dirEntryData, DIR_ENTRY_aDate, _FAT_filetime_getDateFromRTC()); // 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 ); + _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 ) ) + if (!_FAT_cache_flush(file->partition->cache)) { return EIO; } @@ -338,24 +337,23 @@ int _FAT_syncToDisc ( FILE_STRUCT* file ) return 0; } - -int _FAT_close_r ( struct _reent *r, int fd ) +int _FAT_close_r(struct _reent *r, int fd) { - FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + FILE_STRUCT* file = (FILE_STRUCT*) fd; int ret = 0; - if ( !file->inUse ) + if (!file->inUse) { r->_errno = EBADF; return -1; } - _FAT_lock( &file->partition->lock ); + _FAT_lock(&file->partition->lock); - if ( file->write ) + if (file->write) { - ret = _FAT_syncToDisc ( file ); - if ( ret != 0 ) + ret = _FAT_syncToDisc(file); + if (ret != 0) { r->_errno = ret; ret = -1; @@ -366,11 +364,11 @@ int _FAT_close_r ( struct _reent *r, int fd ) // Remove this file from the double-linked list of open files file->partition->openFileCount -= 1; - if ( file->nextOpenFile ) + if (file->nextOpenFile) { file->nextOpenFile->prevOpenFile = file->prevOpenFile; } - if ( file->prevOpenFile ) + if (file->prevOpenFile) { file->prevOpenFile->nextOpenFile = file->nextOpenFile; } @@ -379,14 +377,14 @@ int _FAT_close_r ( struct _reent *r, int fd ) file->partition->firstOpenFile = file->nextOpenFile; } - _FAT_unlock( &file->partition->lock ); + _FAT_unlock(&file->partition->lock); return ret; } -ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) +ssize_t _FAT_read_r(struct _reent *r, int fd, char *ptr, size_t len) { - FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + FILE_STRUCT* file = (FILE_STRUCT*) fd; PARTITION* partition; CACHE* cache; FILE_POSITION position; @@ -396,31 +394,31 @@ ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) bool flagNoError = true; // Short circuit cases where len is 0 (or less) - if ( len <= 0 ) + if (len <= 0) { return 0; } // Make sure we can actually read from the file - if ( ( file == NULL ) || !file->inUse || !file->read ) + if ((file == NULL) || !file->inUse || !file->read) { r->_errno = EBADF; return -1; } partition = file->partition; - _FAT_lock( &partition->lock ); + _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 ) + if (file->currentPosition >= file->filesize || file->startCluster == CLUSTER_FREE) { r->_errno = EOVERFLOW; - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); return 0; } // Don't read past end of file - if ( len + file->currentPosition > file->filesize ) + if (len + file->currentPosition > file->filesize) { r->_errno = EOVERFLOW; len = file->filesize - file->currentPosition; @@ -432,21 +430,21 @@ ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) // Align to sector tempVar = BYTES_PER_READ - position.byte; - if ( tempVar > remain ) + if (tempVar > remain) { tempVar = remain; } - if ( ( tempVar < BYTES_PER_READ ) && flagNoError ) + if ((tempVar < BYTES_PER_READ) && flagNoError) { - _FAT_cache_readPartialSector ( cache, ptr, _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, - position.byte, tempVar ); + _FAT_cache_readPartialSector(cache, ptr, _FAT_fat_clusterToSector(partition, position.cluster) + + position.sector, position.byte, tempVar); remain -= tempVar; ptr += tempVar; position.byte += tempVar; - if ( position.byte >= BYTES_PER_READ ) + if (position.byte >= BYTES_PER_READ) { position.byte = 0; position.sector++; @@ -455,7 +453,7 @@ ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) // align to cluster // tempVar is number of sectors to read - if ( remain > ( partition->sectorsPerCluster - position.sector ) * BYTES_PER_READ ) + if (remain > (partition->sectorsPerCluster - position.sector) * BYTES_PER_READ) { tempVar = partition->sectorsPerCluster - position.sector; } @@ -464,10 +462,10 @@ ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) tempVar = remain / BYTES_PER_READ; } - if ( ( tempVar > 0 ) && flagNoError ) + if ((tempVar > 0) && flagNoError) { - if ( ! _FAT_cache_readSectors ( cache, _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, - tempVar, ptr ) ) + if (!_FAT_cache_readSectors(cache, _FAT_fat_clusterToSector(partition, position.cluster) + position.sector, + tempVar, ptr)) { flagNoError = false; r->_errno = EIO; @@ -482,14 +480,14 @@ ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) // 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 ) + if ((position.sector >= partition->sectorsPerCluster) && flagNoError) { - tempNextCluster = _FAT_fat_nextCluster( partition, position.cluster ); - if ( ( remain == 0 ) && ( tempNextCluster == CLUSTER_EOF ) ) + tempNextCluster = _FAT_fat_nextCluster(partition, position.cluster); + if ((remain == 0) && (tempNextCluster == CLUSTER_EOF)) { position.sector = partition->sectorsPerCluster; } - else if ( !_FAT_fat_isValidCluster( partition, tempNextCluster ) ) + else if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { r->_errno = EIO; flagNoError = false; @@ -502,7 +500,7 @@ ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) } // Read in whole clusters, contiguous blocks at a time - while ( ( remain >= partition->bytesPerCluster ) && flagNoError ) + while ((remain >= partition->bytesPerCluster) && flagNoError) { uint32_t chunkEnd; uint32_t nextChunkStart = position.cluster; @@ -511,17 +509,16 @@ ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) do { chunkEnd = nextChunkStart; - nextChunkStart = _FAT_fat_nextCluster ( partition, chunkEnd ); + nextChunkStart = _FAT_fat_nextCluster(partition, chunkEnd); chunkSize += partition->bytesPerCluster; - } - while ( ( nextChunkStart == chunkEnd + 1 ) && + } while ((nextChunkStart == chunkEnd + 1) && #ifdef LIMIT_SECTORS ( 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 ) ) + if (!_FAT_cache_readSectors(cache, _FAT_fat_clusterToSector(partition, position.cluster), chunkSize + / BYTES_PER_READ, ptr)) { flagNoError = false; r->_errno = EIO; @@ -531,12 +528,12 @@ ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) remain -= chunkSize; // Advance to next cluster - if ( ( remain == 0 ) && ( nextChunkStart == CLUSTER_EOF ) ) + if ((remain == 0) && (nextChunkStart == CLUSTER_EOF)) { position.sector = partition->sectorsPerCluster; position.cluster = chunkEnd; } - else if ( !_FAT_fat_isValidCluster( partition, nextChunkStart ) ) + else if (!_FAT_fat_isValidCluster(partition, nextChunkStart)) { r->_errno = EIO; flagNoError = false; @@ -550,10 +547,9 @@ ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) // Read remaining sectors tempVar = remain / BYTES_PER_READ; // Number of sectors left - if ( ( tempVar > 0 ) && flagNoError ) + if ((tempVar > 0) && flagNoError) { - if ( !_FAT_cache_readSectors ( cache, _FAT_fat_clusterToSector ( partition, position.cluster ), - tempVar, ptr ) ) + if (!_FAT_cache_readSectors(cache, _FAT_fat_clusterToSector(partition, position.cluster), tempVar, ptr)) { flagNoError = false; r->_errno = EIO; @@ -568,10 +564,10 @@ ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) // Last remaining sector // Check if anything is left - if ( ( remain > 0 ) && flagNoError ) + if ((remain > 0) && flagNoError) { - _FAT_cache_readPartialSector ( cache, ptr, - _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, 0, remain ); + _FAT_cache_readPartialSector(cache, ptr, _FAT_fat_clusterToSector(partition, position.cluster) + + position.sector, 0, remain); position.byte += remain; remain = 0; } @@ -583,7 +579,7 @@ ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) file->rwPosition = position; file->currentPosition += len; - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); return len; } @@ -591,29 +587,29 @@ ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) // then get next cluster or allocate next cluster // 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 ) +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 ) ) + 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 ) + 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 ) ) + 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 ); + tempNextCluster = _FAT_fat_linkFreeCluster(partition, position->cluster); } - if ( !_FAT_fat_isValidCluster( partition, tempNextCluster ) ) + if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { // Couldn't get a cluster, so abort r->_errno = ENOSPC; @@ -623,37 +619,36 @@ static bool _FAT_check_position_for_next_cluster( struct _reent *r, position->cluster = tempNextCluster; } return true; -err: - if ( flagNoError ) *flagNoError = false; + err: 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 ) + 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}; + 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; + 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.cluster = _FAT_fat_lastCluster(partition, file->startCluster); remain = file->currentPosition - file->filesize; - if ( ( remain > 0 ) && ( file->filesize > 0 ) && ( position.sector == 0 ) && ( position.byte == 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 ) ) + tempNextCluster = _FAT_fat_linkFreeCluster(partition, position.cluster); + if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { // Couldn't get a cluster, so abort r->_errno = ENOSPC; @@ -663,33 +658,32 @@ static bool _FAT_file_extend_r ( struct _reent *r, FILE_STRUCT* file ) position.sector = 0; } - if ( remain + position.byte < BYTES_PER_READ ) + 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 ); + _FAT_cache_writePartialSector(cache, zeroBuffer, _FAT_fat_clusterToSector(partition, position.cluster) + + position.sector, position.byte, remain); position.byte += remain; } else { - if ( position.byte > 0 ) + 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 ); + _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 ++; + position.sector++; } - while ( remain >= BYTES_PER_READ ) + while (remain >= BYTES_PER_READ) { - if ( position.sector >= partition->sectorsPerCluster ) + 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 ) ) + tempNextCluster = _FAT_fat_linkFreeCluster(partition, position.cluster); + if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { // Couldn't get a cluster, so abort r->_errno = ENOSPC; @@ -698,23 +692,23 @@ static bool _FAT_file_extend_r ( struct _reent *r, FILE_STRUCT* file ) 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 ++; + position.sector++; } - if ( !_FAT_check_position_for_next_cluster( r, &position, partition, remain, NULL ) ) + if (!_FAT_check_position_for_next_cluster(r, &position, partition, remain, NULL)) { // error already marked return false; } - if ( remain > 0 ) + if (remain > 0) { - _FAT_cache_writePartialSector ( cache, zeroBuffer, - _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, 0, remain ); + _FAT_cache_writePartialSector(cache, zeroBuffer, _FAT_fat_clusterToSector(partition, position.cluster) + + position.sector, 0, remain); position.byte = remain; } } @@ -724,9 +718,9 @@ static bool _FAT_file_extend_r ( struct _reent *r, FILE_STRUCT* file ) return true; } -ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) +ssize_t _FAT_write_r(struct _reent *r, int fd, const char *ptr, size_t len) { - FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + FILE_STRUCT* file = (FILE_STRUCT*) fd; PARTITION* partition; CACHE* cache; FILE_POSITION position; @@ -737,7 +731,7 @@ ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) bool flagAppending = false; // Make sure we can actually write to the file - if ( ( file == NULL ) || !file->inUse || !file->write ) + if ((file == NULL) || !file->inUse || !file->write) { r->_errno = EBADF; return -1; @@ -745,30 +739,30 @@ ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) partition = file->partition; cache = file->partition->cache; - _FAT_lock( &partition->lock ); + _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 ) + 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 ) + if (len <= 0) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); return 0; } // Get a new cluster for the start of the file if required - if ( file->startCluster == CLUSTER_FREE ) + if (file->startCluster == CLUSTER_FREE) { - tempNextCluster = _FAT_fat_linkFreeCluster ( partition, CLUSTER_FREE ); - if ( !_FAT_fat_isValidCluster( partition, tempNextCluster ) ) + 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 ); + _FAT_unlock(&partition->lock); r->_errno = ENOSPC; return -1; } @@ -780,11 +774,11 @@ ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) file->appendPosition.byte = 0; file->rwPosition.cluster = file->startCluster; - file->rwPosition.sector = 0; + file->rwPosition.sector = 0; file->rwPosition.byte = 0; } - if ( file->append ) + if (file->append) { position = file->appendPosition; flagAppending = true; @@ -792,11 +786,11 @@ ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) else { // If the write pointer is past the end of the file, extend the file to that size - if ( file->currentPosition > file->filesize ) + if (file->currentPosition > file->filesize) { - if ( !_FAT_file_extend_r ( r, file ) ) + if (!_FAT_file_extend_r(r, file)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); return -1; } } @@ -805,44 +799,43 @@ ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) position = file->rwPosition; // If it is writing past the current end of file, set appending flag - if ( len + file->currentPosition > file->filesize ) + 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 ); + _FAT_check_position_for_next_cluster(r, &position, partition, remain, &flagNoError); // Align to sector tempVar = BYTES_PER_READ - position.byte; - if ( tempVar > remain ) + if (tempVar > remain) { tempVar = remain; } - if ( ( tempVar < BYTES_PER_READ ) && flagNoError ) + 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 ); + _FAT_cache_writePartialSector(cache, ptr, _FAT_fat_clusterToSector(partition, position.cluster) + + position.sector, position.byte, tempVar); remain -= tempVar; ptr += tempVar; position.byte += tempVar; - // Move onto next sector - if ( position.byte >= BYTES_PER_READ ) + if (position.byte >= BYTES_PER_READ) { position.byte = 0; - position.sector ++; + position.sector++; } } // Align to cluster // tempVar is number of sectors to write - if ( remain > ( partition->sectorsPerCluster - position.sector ) * BYTES_PER_READ ) + if (remain > (partition->sectorsPerCluster - position.sector) * BYTES_PER_READ) { tempVar = partition->sectorsPerCluster - position.sector; } @@ -851,10 +844,10 @@ ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) tempVar = remain / BYTES_PER_READ; } - if ( ( tempVar > 0 && tempVar < partition->sectorsPerCluster ) && flagNoError ) + if ((tempVar > 0 && tempVar < partition->sectorsPerCluster) && flagNoError) { - if ( !_FAT_cache_writeSectors ( cache, - _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, tempVar, ptr ) ) + if (!_FAT_cache_writeSectors(cache, _FAT_fat_clusterToSector(partition, position.cluster) + position.sector, + tempVar, ptr)) { flagNoError = false; r->_errno = EIO; @@ -868,11 +861,11 @@ ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) } // Write whole clusters - while ( ( remain >= partition->bytesPerCluster ) && flagNoError ) + while ((remain >= partition->bytesPerCluster) && flagNoError) { // allocate next cluster - _FAT_check_position_for_next_cluster( r, &position, partition, remain, &flagNoError ); - if ( !flagNoError ) break; + _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; @@ -880,26 +873,25 @@ ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) FILE_POSITION next_position = position; // group consecutive clusters - while ( flagNoError && + while (flagNoError && #ifdef LIMIT_SECTORS ( chunkSize + partition->bytesPerCluster <= LIMIT_SECTORS * BYTES_PER_READ ) && #endif - ( chunkSize + partition->bytesPerCluster < remain ) ) + (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 + _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 + 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 ) ) + if (!_FAT_cache_writeSectors(cache, _FAT_fat_clusterToSector(partition, position.cluster), chunkSize + / BYTES_PER_READ, ptr)) { flagNoError = false; r->_errno = EIO; @@ -908,7 +900,7 @@ ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) ptr += chunkSize; remain -= chunkSize; - if ( ( chunkEnd != nextChunkStart ) && _FAT_fat_isValidCluster( partition, nextChunkStart ) ) + if ((chunkEnd != nextChunkStart) && _FAT_fat_isValidCluster(partition, nextChunkStart)) { // new cluster is already allocated (because it was not consecutive) position.cluster = nextChunkStart; @@ -923,13 +915,13 @@ ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) } // allocate next cluster if needed - _FAT_check_position_for_next_cluster( r, &position, partition, remain, &flagNoError ); + _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 ((tempVar > 0) && flagNoError) { - if ( !_FAT_cache_writeSectors ( cache, _FAT_fat_clusterToSector ( partition, position.cluster ), tempVar, ptr ) ) + if (!_FAT_cache_writeSectors(cache, _FAT_fat_clusterToSector(partition, position.cluster), tempVar, ptr)) { flagNoError = false; r->_errno = EIO; @@ -943,29 +935,28 @@ ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) } // Last remaining sector - if ( ( remain > 0 ) && flagNoError ) + if ((remain > 0) && flagNoError) { - if ( flagAppending ) + if (flagAppending) { - _FAT_cache_eraseWritePartialSector ( cache, ptr, - _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, 0, remain ); + _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 ); + _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; // Update file information file->modified = true; - if ( file->append ) + if (file->append) { // Appending doesn't affect the read pointer file->appendPosition = position; @@ -976,27 +967,26 @@ ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) // Writing also shifts the read pointer file->rwPosition = position; file->currentPosition += len; - if ( file->filesize < file->currentPosition ) + if (file->filesize < file->currentPosition) { file->filesize = file->currentPosition; } } - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); return len; } - -off_t _FAT_seek_r ( struct _reent *r, int fd, off_t pos, int dir ) +off_t _FAT_seek_r(struct _reent *r, int fd, off_t pos, int dir) { - FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + 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 ) ) + if ((file == NULL) || (file->inUse == false)) { // invalid file r->_errno = EBADF; @@ -1004,56 +994,56 @@ off_t _FAT_seek_r ( struct _reent *r, int fd, off_t pos, int dir ) } partition = file->partition; - _FAT_lock( &partition->lock ); + _FAT_lock(&partition->lock); - switch ( dir ) + switch (dir) { case SEEK_SET: newPosition = pos; break; case SEEK_CUR: - newPosition = ( off_t )file->currentPosition + pos; + newPosition = (off_t) file->currentPosition + pos; break; case SEEK_END: - newPosition = ( off_t )file->filesize + pos; + newPosition = (off_t) file->filesize + pos; break; default: - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = EINVAL; return -1; } - if ( ( pos > 0 ) && ( newPosition < 0 ) ) + if ((pos > 0) && (newPosition < 0)) { - _FAT_unlock( &partition->lock ); + _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 ) ) + if (newPosition < 0 || ((sizeof(newPosition) > 4) && newPosition > (off_t) FILE_MAX_SIZE)) { - _FAT_unlock( &partition->lock ); + _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 ) + 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 ) + if (position >= file->currentPosition) { // start from current cluster int currentCount = file->currentPosition / partition->bytesPerCluster; - if ( file->rwPosition.sector == partition->sectorsPerCluster ) + if (file->rwPosition.sector == partition->sectorsPerCluster) { currentCount--; } @@ -1062,21 +1052,21 @@ off_t _FAT_seek_r ( struct _reent *r, int fd, off_t pos, int dir ) } // Calculate the sector and byte of the current position, // and store them - file->rwPosition.sector = ( position % partition->bytesPerCluster ) / BYTES_PER_READ; + 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 ) ) + 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); } // Check if ran out of clusters and it needs to allocate a new one - if ( clusCount > 0 ) + if (clusCount > 0) { - if ( ( clusCount == 1 ) && ( file->filesize == position ) && ( file->rwPosition.sector == 0 ) ) + if ((clusCount == 1) && (file->filesize == position) && (file->rwPosition.sector == 0)) { // Set flag to allocate a new cluster file->rwPosition.sector = partition->sectorsPerCluster; @@ -1084,7 +1074,7 @@ off_t _FAT_seek_r ( struct _reent *r, int fd, off_t pos, int dir ) } else { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = EINVAL; return -1; } @@ -1096,19 +1086,17 @@ off_t _FAT_seek_r ( struct _reent *r, int fd, off_t pos, int dir ) // Save position file->currentPosition = position; - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); return position; } - - -int _FAT_fstat_r ( struct _reent *r, int fd, struct stat *st ) +int _FAT_fstat_r(struct _reent *r, int fd, struct stat *st) { - FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + FILE_STRUCT* file = (FILE_STRUCT*) fd; PARTITION* partition; DIR_ENTRY fileEntry; - if ( ( file == NULL ) || ( file->inUse == false ) ) + if ((file == NULL) || (file->inUse == false)) { // invalid file r->_errno = EBADF; @@ -1116,59 +1104,59 @@ int _FAT_fstat_r ( struct _reent *r, int fd, struct stat *st ) } partition = file->partition; - _FAT_lock( &partition->lock ); + _FAT_lock(&partition->lock); // Get the file's entry data fileEntry.dataStart = file->dirEntryStart; fileEntry.dataEnd = file->dirEntryEnd; - if ( !_FAT_directory_entryFromPosition ( partition, &fileEntry ) ) + if (!_FAT_directory_entryFromPosition(partition, &fileEntry)) { - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); r->_errno = EIO; return -1; } // Fill in the stat struct - _FAT_directory_entryStat ( partition, &fileEntry, st ); + _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 + 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 ); + _FAT_unlock(&partition->lock); return 0; } -int _FAT_ftruncate_r ( struct _reent *r, int fd, off_t len ) +int _FAT_ftruncate_r(struct _reent *r, int fd, off_t len) { - FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + FILE_STRUCT* file = (FILE_STRUCT*) fd; PARTITION* partition; int ret = 0; - uint32_t newSize = ( uint32_t )len; + uint32_t newSize = (uint32_t) len; - if ( len < 0 ) + 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 ) + 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 ) + if (!file || !file->inUse) { // invalid file r->_errno = EBADF; return -1; } - if ( !file->write ) + if (!file->write) { // Read-only file r->_errno = EINVAL; @@ -1176,28 +1164,28 @@ int _FAT_ftruncate_r ( struct _reent *r, int fd, off_t len ) } partition = file->partition; - _FAT_lock( &partition->lock ); + _FAT_lock(&partition->lock); - if ( newSize > file->filesize ) + 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 ) + if (file->startCluster == CLUSTER_FREE) { - uint32_t tempNextCluster = _FAT_fat_linkFreeCluster ( partition, CLUSTER_FREE ); - if ( !_FAT_fat_isValidCluster( partition, tempNextCluster ) ) + 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 ); + _FAT_unlock(&partition->lock); r->_errno = ENOSPC; return -1; } file->startCluster = tempNextCluster; file->rwPosition.cluster = file->startCluster; - file->rwPosition.sector = 0; + file->rwPosition.sector = 0; file->rwPosition.byte = 0; } // Save the read/write pointer @@ -1206,12 +1194,12 @@ int _FAT_ftruncate_r ( struct _reent *r, int fd, off_t len ) // Set the position to the new size file->currentPosition = newSize; // Extend the file to the new position - if ( !_FAT_file_extend_r ( r, file ) ) + if (!_FAT_file_extend_r(r, file)) { ret = -1; } // Set the append position to the new rwPointer - if ( file->append ) + if (file->append) { file->appendPosition = file->rwPosition; } @@ -1219,13 +1207,13 @@ int _FAT_ftruncate_r ( struct _reent *r, int fd, off_t len ) file->rwPosition = savedPosition; file->currentPosition = savedOffset; } - else if ( newSize < file->filesize ) + else if (newSize < file->filesize) { // Shrinking the file - if ( len == 0 ) + if (len == 0) { // Cutting the file down to nothing, clear all clusters used - _FAT_fat_clearLinks ( partition, file->startCluster ); + _FAT_fat_clearLinks(partition, file->startCluster); file->startCluster = CLUSTER_FREE; file->appendPosition.cluster = CLUSTER_FREE; @@ -1241,21 +1229,21 @@ int _FAT_ftruncate_r ( struct _reent *r, int fd, off_t len ) // 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 ); + chainLength = ((newSize - 1) / partition->bytesPerCluster) + 1; + lastCluster = _FAT_fat_trimChain(partition, file->startCluster, chainLength); - if ( file->append ) + 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 ) + 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.sector = (newSize % partition->bytesPerCluster) / BYTES_PER_READ; } file->appendPosition.cluster = lastCluster; } @@ -1269,38 +1257,38 @@ int _FAT_ftruncate_r ( struct _reent *r, int fd, off_t len ) file->filesize = newSize; file->modified = true; - _FAT_unlock( &partition->lock ); + _FAT_unlock(&partition->lock); return ret; } -int _FAT_fsync_r ( struct _reent *r, int fd ) +int _FAT_fsync_r(struct _reent *r, int fd) { - FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + FILE_STRUCT* file = (FILE_STRUCT*) fd; int ret = 0; - if ( !file->inUse ) + 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 ) + ret = _FAT_syncToDisc(file); + if (ret != 0) { r->_errno = ret; ret = -1; } - _FAT_unlock( &file->partition->lock ); + _FAT_unlock(&file->partition->lock); return ret; } -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) { struct _reent r; FILE_STRUCT file; @@ -1308,16 +1296,16 @@ int _FAT_get_fragments ( const char *path, _frag_append_t append_fragment, void u32 cluster; u32 sector; u32 offset; // in sectors - u32 size; // 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 ); + _FAT_lock(&partition->lock); size = file.filesize / BYTES_PER_READ; cluster = file.startCluster; @@ -1325,30 +1313,28 @@ int _FAT_get_fragments ( const char *path, _frag_append_t append_fragment, void do { - if ( !_FAT_fat_isValidCluster( partition, cluster ) ) + 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 ) ) + 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 ); + cluster = _FAT_fat_nextCluster(partition, cluster); + } while (offset < size); // set size - append_fragment( callback_data, size, 0, 0 ); + append_fragment(callback_data, size, 0, 0); // success ret = 0; -out: - _FAT_unlock( &partition->lock ); - _FAT_close_r( &r, fd ); + 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 537c665b..634c4cfa 100644 --- a/source/libfat/fatfile.h +++ b/source/libfat/fatfile.h @@ -9,13 +9,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -26,8 +26,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - + */ #ifndef _FATFILE_H #define _FATFILE_H @@ -40,68 +39,67 @@ #include "directory.h" #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; -extern int _FAT_open_r ( struct _reent *r, void *fileStruct, const char *path, int flags, int mode ); +extern int _FAT_open_r(struct _reent *r, void *fileStruct, const char *path, int flags, int mode); -extern int _FAT_close_r ( struct _reent *r, int fd ); +extern int _FAT_close_r(struct _reent *r, int fd); -extern ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ); +extern ssize_t _FAT_write_r(struct _reent *r, int fd, const char *ptr, size_t len); -extern ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ); +extern ssize_t _FAT_read_r(struct _reent *r, int fd, char *ptr, size_t len); -extern off_t _FAT_seek_r ( struct _reent *r, int fd, off_t pos, int dir ); +extern off_t _FAT_seek_r(struct _reent *r, int fd, off_t pos, int dir); -extern int _FAT_fstat_r ( struct _reent *r, int fd, struct stat *st ); +extern int _FAT_fstat_r(struct _reent *r, int fd, struct stat *st); -extern int _FAT_stat_r ( struct _reent *r, const char *path, struct stat *st ); +extern int _FAT_stat_r(struct _reent *r, const char *path, struct stat *st); -extern int _FAT_link_r ( struct _reent *r, const char *existing, const char *newLink ); +extern int _FAT_link_r(struct _reent *r, const char *existing, const char *newLink); -extern int _FAT_unlink_r ( struct _reent *r, const char *name ); +extern int _FAT_unlink_r(struct _reent *r, const char *name); -extern int _FAT_chdir_r ( struct _reent *r, const char *name ); +extern int _FAT_chdir_r(struct _reent *r, const char *name); -extern int _FAT_rename_r ( struct _reent *r, const char *oldName, const char *newName ); +extern int _FAT_rename_r(struct _reent *r, const char *oldName, const char *newName); -extern int _FAT_ftruncate_r ( struct _reent *r, int fd, off_t len ); +extern int _FAT_ftruncate_r(struct _reent *r, int fd, off_t len); -extern int _FAT_fsync_r ( struct _reent *r, int fd ); +extern int _FAT_fsync_r(struct _reent *r, int fd); /* -Synchronizes the file data to disc. -Does no locking of its own -- lock the partition before calling. -Returns 0 on success, an error code on failure. -*/ -extern int _FAT_syncToDisc ( FILE_STRUCT* file ); + Synchronizes the file data to disc. + Does no locking of its own -- lock the partition before calling. + Returns 0 on success, an error code on failure. + */ +extern int _FAT_syncToDisc(FILE_STRUCT* file); #endif // _FATFILE_H diff --git a/source/libfat/file_allocation_table.c b/source/libfat/file_allocation_table.c index d2fa769d..5917797e 100644 --- a/source/libfat/file_allocation_table.c +++ b/source/libfat/file_allocation_table.c @@ -8,13 +8,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -25,89 +25,87 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - + */ #include "file_allocation_table.h" #include "partition.h" #include /* -Gets the cluster linked from input cluster -*/ -uint32_t _FAT_fat_nextCluster( PARTITION* partition, uint32_t cluster ) + 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; - if ( cluster == CLUSTER_FREE ) + if (cluster == CLUSTER_FREE) { return CLUSTER_FREE; } - switch ( partition->filesysType ) + 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; + + _FAT_cache_readLittleEndianValue(partition->cache, &nextCluster, sector, offset, sizeof(u8)); + + offset++; + + if (offset >= BYTES_PER_READ) { - 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 ) ); - - offset++; - - 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 ); - - if ( cluster & 0x01 ) - { - nextCluster = nextCluster >> 4; - } - else - { - nextCluster &= 0x0FFF; - } - - if ( nextCluster >= 0x0FF7 ) - { - nextCluster = CLUSTER_EOF; - } - - break; + offset = 0; + sector++; } + nextCluster_h = 0; + + _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 (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; + 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 ) + 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; + 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 ) + if (nextCluster >= 0x0FFFFFF7) { nextCluster = CLUSTER_EOF; } @@ -122,83 +120,83 @@ uint32_t _FAT_fat_nextCluster( PARTITION* partition, uint32_t cluster ) } /* -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 ) + 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; - if ( ( cluster < CLUSTER_FIRST ) || ( cluster > partition->fat.lastCluster /* This will catch CLUSTER_ERROR */ ) ) + if ((cluster < CLUSTER_FIRST) || (cluster > partition->fat.lastCluster /* This will catch CLUSTER_ERROR */)) { return false; } - switch ( partition->filesysType ) + 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; + 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 ) + 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 { - _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 ) + 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; case FS_FAT16: - sector = partition->fat.fatStart + ( ( cluster << 1 ) / BYTES_PER_READ ); - offset = ( cluster % ( BYTES_PER_READ >> 1 ) ) << 1; + 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; case FS_FAT32: - sector = partition->fat.fatStart + ( ( cluster << 2 ) / BYTES_PER_READ ); - offset = ( cluster % ( BYTES_PER_READ >> 2 ) ) << 2; + 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; @@ -211,28 +209,28 @@ static bool _FAT_fat_writeFatEntry ( PARTITION* partition, uint32_t cluster, uin } /*----------------------------------------------------------------- -gets the first available free cluster, sets it -to end of file, links the input cluster to it then returns the -cluster number -If an error occurs, return CLUSTER_ERROR ------------------------------------------------------------------*/ -uint32_t _FAT_fat_linkFreeCluster( PARTITION* partition, uint32_t cluster ) + gets the first available free cluster, sets it + to end of file, links the input cluster to it then returns the + 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; - lastCluster = partition->fat.lastCluster; + lastCluster = partition->fat.lastCluster; - if ( cluster > lastCluster ) + 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 ) ) + curLink = _FAT_fat_nextCluster(partition, cluster); + if ((curLink >= CLUSTER_FIRST) && (curLink <= lastCluster)) { return curLink; // Return the current link - don't allocate a new one } @@ -240,18 +238,18 @@ uint32_t _FAT_fat_linkFreeCluster( PARTITION* partition, uint32_t cluster ) // Get a free cluster firstFree = partition->fat.firstFree; // Start at first valid cluster - if ( firstFree < CLUSTER_FIRST ) + if (firstFree < CLUSTER_FIRST) { firstFree = CLUSTER_FIRST; } // Search until a free cluster is found - while ( _FAT_fat_nextCluster( partition, firstFree ) != CLUSTER_FREE ) + while (_FAT_fat_nextCluster(partition, firstFree) != CLUSTER_FREE) { firstFree++; - if ( firstFree > lastCluster ) + if (firstFree > lastCluster) { - if ( loopedAroundFAT ) + if (loopedAroundFAT) { // If couldn't get a free cluster then return an error partition->fat.firstFree = firstFree; @@ -268,74 +266,70 @@ uint32_t _FAT_fat_linkFreeCluster( PARTITION* partition, uint32_t cluster ) } partition->fat.firstFree = firstFree; - if ( ( cluster >= CLUSTER_FIRST ) && ( cluster < lastCluster ) ) + if ((cluster >= CLUSTER_FIRST) && (cluster < lastCluster)) { // Update the linked from FAT entry - _FAT_fat_writeFatEntry ( partition, cluster, firstFree ); + _FAT_fat_writeFatEntry(partition, cluster, firstFree); } // Create the linked to FAT entry - _FAT_fat_writeFatEntry ( partition, firstFree, CLUSTER_EOF ); + _FAT_fat_writeFatEntry(partition, firstFree, CLUSTER_EOF); return firstFree; } /*----------------------------------------------------------------- -gets the first available free cluster, sets it -to end of file, links the input cluster to it, clears the new -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 ) + gets the first available free cluster, sets it + to end of file, links the input cluster to it, clears the new + 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]; // Link the cluster - newCluster = _FAT_fat_linkFreeCluster( partition, cluster ); + newCluster = _FAT_fat_linkFreeCluster(partition, cluster); - if ( newCluster == CLUSTER_FREE || newCluster == 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++ ) + 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 ); + _FAT_cache_writeSectors(partition->cache, _FAT_fat_clusterToSector(partition, newCluster) + i, 1, emptySector); } return newCluster; } - /*----------------------------------------------------------------- -_FAT_fat_clearLinks -frees any cluster used by a file ------------------------------------------------------------------*/ -bool _FAT_fat_clearLinks ( PARTITION* partition, uint32_t cluster ) + _FAT_fat_clearLinks + frees any cluster used by a file + -----------------------------------------------------------------*/ +bool _FAT_fat_clearLinks(PARTITION* partition, uint32_t cluster) { 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 ) + if (cluster < partition->fat.firstFree) { partition->fat.firstFree = cluster; } - while ( ( cluster != CLUSTER_EOF ) && ( cluster != CLUSTER_FREE ) && ( cluster != CLUSTER_ERROR ) ) + while ((cluster != CLUSTER_EOF) && (cluster != CLUSTER_FREE) && (cluster != CLUSTER_ERROR)) { // Store next cluster before erasing the link - nextCluster = _FAT_fat_nextCluster ( partition, cluster ); + nextCluster = _FAT_fat_nextCluster(partition, cluster); // Erase the link - _FAT_fat_writeFatEntry ( partition, cluster, CLUSTER_FREE ); + _FAT_fat_writeFatEntry(partition, cluster, CLUSTER_FREE); // Move onto next cluster cluster = nextCluster; @@ -345,73 +339,74 @@ bool _FAT_fat_clearLinks ( PARTITION* partition, uint32_t cluster ) } /*----------------------------------------------------------------- -_FAT_fat_trimChain -Drop all clusters past the chainLength. -If chainLength is 0, all clusters are dropped. -If chainLength is 1, the first cluster is kept and the rest are -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 ) + _FAT_fat_trimChain + Drop all clusters past the chainLength. + If chainLength is 0, all clusters are dropped. + If chainLength is 1, the first cluster is kept and the rest are + 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; - if ( chainLength == 0 ) + if (chainLength == 0) { // Drop the entire chain - _FAT_fat_clearLinks ( partition, startCluster ); + _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 ) ) + nextCluster = _FAT_fat_nextCluster(partition, startCluster); + while ((chainLength > 0) && (nextCluster != CLUSTER_FREE) && (nextCluster != CLUSTER_EOF)) { chainLength--; startCluster = nextCluster; - nextCluster = _FAT_fat_nextCluster ( partition, startCluster ); + nextCluster = _FAT_fat_nextCluster(partition, startCluster); } // Drop all clusters after the last in the chain - if ( nextCluster != CLUSTER_FREE && nextCluster != CLUSTER_EOF ) + if (nextCluster != CLUSTER_FREE && nextCluster != CLUSTER_EOF) { - _FAT_fat_clearLinks ( partition, nextCluster ); + _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 ); + _FAT_fat_writeFatEntry(partition, startCluster, CLUSTER_EOF); return startCluster; } } /*----------------------------------------------------------------- -_FAT_fat_lastCluster -Trace the cluster links until the last one is found ------------------------------------------------------------------*/ -uint32_t _FAT_fat_lastCluster ( PARTITION* partition, uint32_t cluster ) + _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 ) ) + while ((_FAT_fat_nextCluster(partition, cluster) != CLUSTER_FREE) && (_FAT_fat_nextCluster(partition, cluster) + != CLUSTER_EOF)) { - cluster = _FAT_fat_nextCluster( partition, cluster ); + cluster = _FAT_fat_nextCluster(partition, cluster); } return cluster; } /*----------------------------------------------------------------- -_FAT_fat_freeClusterCount -Return the number of free clusters available ------------------------------------------------------------------*/ -unsigned int _FAT_fat_freeClusterCount ( PARTITION* partition ) + _FAT_fat_freeClusterCount + Return the number of free clusters available + -----------------------------------------------------------------*/ +unsigned int _FAT_fat_freeClusterCount(PARTITION* partition) { unsigned int count = 0; uint32_t curCluster; - for ( curCluster = CLUSTER_FIRST; curCluster <= partition->fat.lastCluster; curCluster++ ) + for (curCluster = CLUSTER_FIRST; curCluster <= partition->fat.lastCluster; curCluster++) { - if ( _FAT_fat_nextCluster( partition, curCluster ) == CLUSTER_FREE ) + if (_FAT_fat_nextCluster(partition, curCluster) == CLUSTER_FREE) { count++; } diff --git a/source/libfat/file_allocation_table.h b/source/libfat/file_allocation_table.h index 336df819..af37886e 100644 --- a/source/libfat/file_allocation_table.h +++ b/source/libfat/file_allocation_table.h @@ -8,13 +8,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -25,7 +25,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef __FAT_H #define __FAT_H @@ -43,30 +43,28 @@ #define CLUSTERS_PER_FAT12 4085 #define CLUSTERS_PER_FAT16 65525 +uint32_t _FAT_fat_nextCluster(PARTITION* partition, uint32_t cluster); -uint32_t _FAT_fat_nextCluster( PARTITION* partition, uint32_t cluster ); +uint32_t _FAT_fat_linkFreeCluster(PARTITION* partition, uint32_t cluster); +uint32_t _FAT_fat_linkFreeClusterCleared(PARTITION* partition, uint32_t cluster); -uint32_t _FAT_fat_linkFreeCluster( PARTITION* partition, uint32_t cluster ); -uint32_t _FAT_fat_linkFreeClusterCleared ( PARTITION* partition, uint32_t cluster ); +bool _FAT_fat_clearLinks(PARTITION* partition, uint32_t cluster); -bool _FAT_fat_clearLinks ( PARTITION* partition, uint32_t cluster ); +uint32_t _FAT_fat_trimChain(PARTITION* partition, uint32_t startCluster, unsigned int chainLength); -uint32_t _FAT_fat_trimChain ( PARTITION* partition, uint32_t startCluster, unsigned int chainLength ); +uint32_t _FAT_fat_lastCluster(PARTITION* partition, uint32_t cluster); -uint32_t _FAT_fat_lastCluster ( PARTITION* partition, uint32_t cluster ); +unsigned int _FAT_fat_freeClusterCount(PARTITION* partition); -unsigned int _FAT_fat_freeClusterCount ( PARTITION* partition ); - -static inline sec_t _FAT_fat_clusterToSector ( PARTITION* partition, uint32_t cluster ) +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 ) +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 8568c4f1..b991984e 100644 --- a/source/libfat/filetime.c +++ b/source/libfat/filetime.c @@ -7,13 +7,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -24,8 +24,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - + */ #include #include "filetime.h" @@ -40,73 +39,65 @@ #define MAX_DAY 31 #define MIN_DAY 1 -uint16_t _FAT_filetime_getTimeFromRTC ( void ) +uint16_t _FAT_filetime_getTimeFromRTC(void) { #ifdef USE_RTC_TIME struct tm timeParts; time_t epochTime; - if ( time( &epochTime ) == ( time_t ) - 1 ) + if (time(&epochTime) == (time_t) -1) { return 0; } - localtime_r( &epochTime, &timeParts ); + 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; + 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 ) - ); + return (((timeParts.tm_hour & 0x1F) << 11) | ((timeParts.tm_min & 0x3F) << 5) | ((timeParts.tm_sec >> 1) & 0x1F)); #else return 0; #endif } - -uint16_t _FAT_filetime_getDateFromRTC ( void ) +uint16_t _FAT_filetime_getDateFromRTC(void) { #ifdef USE_RTC_TIME struct tm timeParts; time_t epochTime; - if ( time( &epochTime ) == ( time_t ) - 1 ) + if (time(&epochTime) == (time_t) -1) { return 0; } - localtime_r( &epochTime, &timeParts ); + 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; + 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 ) - ); + 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; #endif } -time_t _FAT_filetime_to_time_t ( uint16_t t, uint16_t d ) +time_t _FAT_filetime_to_time_t(uint16_t t, uint16_t d) { struct tm timeParts; timeParts.tm_hour = t >> 11; - timeParts.tm_min = ( t >> 5 ) & 0x3F; - timeParts.tm_sec = ( t & 0x1F ) << 1; + 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_mon = ((d >> 5) & 0x0F) - 1; + timeParts.tm_year = (d >> 9) + 80; timeParts.tm_isdst = 0; - return mktime( &timeParts ); + return mktime(&timeParts); } diff --git a/source/libfat/filetime.h b/source/libfat/filetime.h index a15d75cb..2da5c0eb 100644 --- a/source/libfat/filetime.h +++ b/source/libfat/filetime.h @@ -7,13 +7,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -24,7 +24,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef __FILETIME_H #define __FILETIME_H @@ -32,10 +32,9 @@ #include "common.h" #include -uint16_t _FAT_filetime_getTimeFromRTC ( void ); -uint16_t _FAT_filetime_getDateFromRTC ( void ); - -time_t _FAT_filetime_to_time_t ( uint16_t t, uint16_t d ); +uint16_t _FAT_filetime_getTimeFromRTC(void); +uint16_t _FAT_filetime_getDateFromRTC(void); +time_t _FAT_filetime_to_time_t(uint16_t t, uint16_t d); #endif // _FILETIME_H diff --git a/source/libfat/libfat.c b/source/libfat/libfat.c index cd508d24..7d5c0590 100644 --- a/source/libfat/libfat.c +++ b/source/libfat/libfat.c @@ -1,19 +1,19 @@ /* - libfat.c - Simple functionality for startup, mounting and unmounting of FAT-based devices. + libfat.c + Simple functionality for startup, mounting and unmounting of FAT-based devices. 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: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -24,7 +24,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #include #include @@ -38,178 +38,153 @@ #include "mem_allocate.h" #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 */ +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 */ }; -bool fatMount ( const char* name, const DISC_INTERFACE* interface, sec_t startSector, uint32_t cacheSize, uint32_t SectorsPerPage ) +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; - if ( !interface->startup() ) - return false; + if (!interface->startup()) return false; - if ( !interface->isInserted() ) + if (!interface->isInserted()) { interface->shutdown(); return false; } - devops = _FAT_mem_allocate ( sizeof( devoptab_t ) + strlen( name ) + 1 ); - if ( !devops ) + 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 ); + nameCopy = (char*) (devops + 1); // Initialize the file system - partition = _FAT_partition_constructor ( interface, cacheSize, SectorsPerPage, startSector ); - if ( !partition ) + partition = _FAT_partition_constructor(interface, cacheSize, SectorsPerPage, startSector); + if (!partition) { - _FAT_mem_free ( devops ); + _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 ); + memcpy(devops, &dotab_fat, sizeof(dotab_fat)); + strcpy(nameCopy, name); devops->name = nameCopy; devops->deviceData = partition; - AddDevice ( devops ); + AddDevice(devops); return true; } -bool fatMountSimple ( const char* name, const DISC_INTERFACE* interface ) +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 ) +void fatUnmount(const char* name) { devoptab_t *devops; PARTITION* partition; const DISC_INTERFACE *disc; - devops = ( devoptab_t* )GetDeviceOpTab ( name ); - if ( !devops ) + 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 ) + if (devops->open_r != dotab_fat.open_r) { return; } - if ( RemoveDevice ( name ) == -1 ) + if (RemoveDevice(name) == -1) { return; } - partition = ( PARTITION* )devops->deviceData; + partition = (PARTITION*) devops->deviceData; disc = partition->disc; - _FAT_partition_destructor ( partition ); - _FAT_mem_free ( devops ); + _FAT_partition_destructor(partition); + _FAT_mem_free(devops); disc->shutdown(); } -bool fatInit ( uint32_t cacheSize, bool setAsDefaultDevice ) +bool fatInit(uint32_t cacheSize, bool setAsDefaultDevice) { 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++ ) + 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 ) ) + 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 ) + if (defaultDevice < 0) { defaultDevice = i; } } } - if ( defaultDevice < 0 ) + if (defaultDevice < 0) { // None of our devices mounted return false; } - if ( setAsDefaultDevice ) + if (setAsDefaultDevice) { char filePath[MAXPATHLEN * 2]; - strcpy ( filePath, _FAT_disc_interfaces[defaultDevice].name ); - strcat ( filePath, ":/" ); + 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 ) + 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++ ) + 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 ) ) ) + 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, '/' ); + strcpy(filePath, __system_argv->argv[0]); + lastSlash = strrchr(filePath, '/'); - if ( NULL != lastSlash ) + if (NULL != lastSlash) { - if ( *( lastSlash - 1 ) == ':' ) lastSlash++; + if (*(lastSlash - 1) == ':') lastSlash++; *lastSlash = 0; } } } } #endif - chdir ( filePath ); + chdir(filePath); } return true; } -bool fatInitDefault ( void ) +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 4fc4efdd..49d192ad 100644 --- a/source/libfat/lock.h +++ b/source/libfat/lock.h @@ -6,13 +6,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -24,7 +24,7 @@ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef __LOCK_H #define __LOCK_H @@ -60,28 +60,26 @@ static inline void _FAT_unlock( mutex_t *mutex ) typedef int mutex_t; #endif -static inline void _FAT_lock_init( mutex_t *mutex ) +static inline void _FAT_lock_init(mutex_t *mutex) { return; } -static inline void _FAT_lock_deinit( mutex_t *mutex ) +static inline void _FAT_lock_deinit(mutex_t *mutex) { return; } -static inline void _FAT_lock( mutex_t *mutex ) +static inline void _FAT_lock(mutex_t *mutex) { return; } -static inline void _FAT_unlock( mutex_t *mutex ) +static inline void _FAT_unlock(mutex_t *mutex) { return; } #endif // USE_LWP_LOCK - #endif // _LOCK_H - diff --git a/source/libfat/mem_allocate.h b/source/libfat/mem_allocate.h index a69e13b1..8f9d5240 100644 --- a/source/libfat/mem_allocate.h +++ b/source/libfat/mem_allocate.h @@ -9,13 +9,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -26,27 +26,27 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef __MEM_ALLOCATE_H_ #define __MEM_ALLOCATE_H_ #include -static inline void* _FAT_mem_allocate ( size_t size ) +static inline void* _FAT_mem_allocate(size_t size) { - return malloc ( size ); + return malloc(size); } -static inline void* _FAT_mem_align ( size_t 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 ) +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 f29e9cdd..ef53d413 100644 --- a/source/libfat/partition.c +++ b/source/libfat/partition.c @@ -8,13 +8,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -25,7 +25,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #include "partition.h" #include "bit_ops.h" @@ -41,19 +41,18 @@ sec_t _FAT_startSector; /* -This device name, as known by devkitPro toolchains -*/ + This device name, as known by devkitPro toolchains + */ const char* DEVICE_NAME = "fat"; /* -Data offsets -*/ + Data offsets + */ // BIOS Parameter Block offsets enum BPB { - BPB_jmpBoot = 0x00, - BPB_OEMName = 0x03, + BPB_jmpBoot = 0x00, BPB_OEMName = 0x03, // BIOS Parameter Block BPB_bytesPerSector = 0x0B, BPB_sectorsPerCluster = 0x0D, @@ -96,67 +95,66 @@ enum BPB BPB_bootSig_AA = 0x1FF }; -static const char FAT_SIG[3] = {'F', 'A', 'T'}; +static const char FAT_SIG[3] = { 'F', 'A', 'T' }; - -sec_t FindFirstValidPartition( const DISC_INTERFACE* disc ) +sec_t FindFirstValidPartition(const DISC_INTERFACE* disc) { - uint8_t part_table[16*4]; + 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 ) ) + if (!_FAT_disc_readSectors(disc, 0, 1, sectorBuffer)) { return 0; } - memcpy( part_table, sectorBuffer + 0x1BE, 16*4 ); + memcpy(part_table, sectorBuffer + 0x1BE, 16 * 4); ptr = part_table; - for ( i = 0; i < 4; i++, ptr += 16 ) + for (i = 0; i < 4; i++, ptr += 16) { - sec_t part_lba = u8array_to_u32( ptr, 0x8 ); + 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 ) ) ) + 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 ) + 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 + for (n = 0; n < 8; n++) // max 8 logic partitions { - if ( !_FAT_disc_readSectors ( disc, part_lba + next_lba2, 1, sectorBuffer ) ) return 0; + 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 ) ) ) + 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; + 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 ) ) ) + 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; } @@ -165,62 +163,64 @@ sec_t FindFirstValidPartition( const DISC_INTERFACE* disc ) return 0; } -PARTITION* _FAT_partition_constructor ( const DISC_INTERFACE* disc, uint32_t cacheSize, uint32_t sectorsPerPage, sec_t startSector ) +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}; + uint8_t sectorBuffer[BYTES_PER_READ] = { 0 }; // Read first sector of disc - if ( !_FAT_disc_readSectors ( disc, startSector, 1, sectorBuffer ) ) + 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 ) ) + if ((sectorBuffer[BPB_bootSig_55] != 0x55) || (sectorBuffer[BPB_bootSig_AA] != 0xAA)) { return NULL; } - if ( startSector != 0 ) + 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 ) ) ) + 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 ) ) ) + 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 ) ) + 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 ) ) ) + 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 ) + 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 ) + partition = (PARTITION*) _FAT_mem_allocate(sizeof(PARTITION)); + if (partition == NULL) { return NULL; } @@ -228,77 +228,82 @@ PARTITION* _FAT_partition_constructor ( const DISC_INTERFACE* disc, uint32_t cac _FAT_startSector = startSector; // Init the partition lock - _FAT_lock_init( &partition->lock ); + _FAT_lock_init(&partition->lock); // 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_u16(sectorBuffer, BPB_sectorsPerFAT); + if (partition->fat.sectorsPerFat == 0) { - partition->fat.sectorsPerFat = u8array_to_u32( sectorBuffer, BPB_FAT32_sectorsPerFAT32 ); + 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_u16(sectorBuffer, BPB_numSectorsSmall); + if (partition->numberOfSectors == 0) { - partition->numberOfSectors = u8array_to_u32( sectorBuffer, BPB_numSectors ); + 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->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->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; + 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 ) + if (clusterCount < CLUSTERS_PER_FAT12) { - partition->filesysType = FS_FAT12; // FAT12 volume + partition->filesysType = FS_FAT12; // FAT12 volume } - else if ( clusterCount < CLUSTERS_PER_FAT16 ) + else if (clusterCount < CLUSTERS_PER_FAT16) { - partition->filesysType = FS_FAT16; // FAT16 volume + partition->filesysType = FS_FAT16; // FAT16 volume } else { - partition->filesysType = FS_FAT32; // FAT32 volume + partition->filesysType = FS_FAT32; // FAT32 volume } - if ( partition->filesysType != FS_FAT32 ) + 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 ); + partition->rootDirCluster = u8array_to_u32(sectorBuffer, BPB_FAT32_rootClus); // Check if FAT mirroring is enabled - if ( !( sectorBuffer[BPB_FAT32_extFlags] & 0x80 ) ) + if (!(sectorBuffer[BPB_FAT32_extFlags] & 0x80)) { // Use the active FAT - partition->fat.fatStart = partition->fat.fatStart + ( partition->fat.sectorsPerFat * ( sectorBuffer[BPB_FAT32_extFlags] & 0x0F ) ); + 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 ); + partition->cache = _FAT_cache_constructor(cacheSize, sectorsPerPage, partition->disc, startSector + + partition->numberOfSectors); // 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 ); + partition->readOnly = !(_FAT_disc_features(disc) & FEATURE_MEDIUM_CANWRITE); // There are currently no open files on this partition partition->openFileCount = 0; @@ -307,41 +312,41 @@ PARTITION* _FAT_partition_constructor ( const DISC_INTERFACE* disc, uint32_t cac return partition; } -void _FAT_partition_destructor ( PARTITION* partition ) +void _FAT_partition_destructor(PARTITION* partition) { FILE_STRUCT* nextFile; - _FAT_lock( &partition->lock ); + _FAT_lock(&partition->lock); // Synchronize open files nextFile = partition->firstOpenFile; - while ( nextFile ) + while (nextFile) { - _FAT_syncToDisc ( 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 ); + _FAT_cache_destructor(partition->cache); // Unlock the partition and destroy the lock - _FAT_unlock( &partition->lock ); - _FAT_lock_deinit( &partition->lock ); + _FAT_unlock(&partition->lock); + _FAT_lock_deinit(&partition->lock); // Free memory used by the partition - _FAT_mem_free ( partition ); + _FAT_mem_free(partition); } -PARTITION* _FAT_partition_getPartitionFromPath ( const char* path ) +PARTITION* _FAT_partition_getPartitionFromPath(const char* path) { const devoptab_t *devops; - devops = GetDeviceOpTab ( path ); + devops = GetDeviceOpTab(path); - if ( !devops ) + 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 4417dc0e..90112666 100644 --- a/source/libfat/partition.h +++ b/source/libfat/partition.h @@ -8,13 +8,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -25,7 +25,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef __PARTITION_H #define __PARTITION_H @@ -38,53 +38,57 @@ extern const char* DEVICE_NAME; // Filesystem type -typedef enum {FS_UNKNOWN, FS_FAT12, FS_FAT16, FS_FAT32} FS_TYPE; +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; /* -Mount the supplied device and return a pointer to the struct necessary to use it -*/ -PARTITION* _FAT_partition_constructor ( const DISC_INTERFACE* disc, uint32_t cacheSize, uint32_t SectorsPerPage, sec_t startSector ); + Mount the supplied device and return a pointer to the struct necessary to use it + */ +PARTITION* _FAT_partition_constructor(const DISC_INTERFACE* disc, uint32_t cacheSize, uint32_t SectorsPerPage, + sec_t startSector); /* -Dismount the device and free all structures used. -Will also attempt to synchronise all open files to disc. -*/ -void _FAT_partition_destructor ( PARTITION* partition ); + Dismount the device and free all structures used. + Will also attempt to synchronise all open files to disc. + */ +void _FAT_partition_destructor(PARTITION* partition); /* -Return the partition specified in a path, as taken from the devoptab. -*/ -PARTITION* _FAT_partition_getPartitionFromPath ( const char* path ); + Return the partition specified in a path, as taken from the devoptab. + */ +PARTITION* _FAT_partition_getPartitionFromPath(const char* path); #endif // _PARTITION_H diff --git a/source/libntfs/acls.c b/source/libntfs/acls.c index 76cc6ce5..3cd7a24e 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 @@ -116,82 +116,76 @@ * null SID (S-1-0-0) */ -static const char nullsidbytes[] = { - 1, /* revision */ - 1, /* auth count */ - 0, 0, 0, 0, 0, 0, /* base */ - 0, 0, 0, 0 /* 1st level */ - }; +static const char nullsidbytes[] = { 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; +static const SID *nullsid = (const SID*) nullsidbytes; /* * SID for world (S-1-1-0) */ -static const char worldsidbytes[] = { - 1, /* revision */ - 1, /* auth count */ - 0, 0, 0, 0, 0, 1, /* base */ - 0, 0, 0, 0 /* 1st level */ -} ; +static const char worldsidbytes[] = { 1, /* revision */ +1, /* auth count */ +0, 0, 0, 0, 0, 1, /* base */ +0, 0, 0, 0 /* 1st level */ +}; -const SID *worldsid = (const SID*)worldsidbytes; +const SID *worldsid = (const SID*) worldsidbytes; /* * SID for administrator */ -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 */ +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 */ }; -const SID *adminsid = (const SID*)adminsidbytes; +const SID *adminsid = (const SID*) adminsidbytes; /* * SID for system */ -static const char systemsidbytes[] = { - 1, /* revision */ - 1, /* auth count */ - 0, 0, 0, 0, 0, 5, /* base */ - 18, 0, 0, 0 /* 1st level */ - }; +static const char systemsidbytes[] = { 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; +static const SID *systemsid = (const SID*) systemsidbytes; /* * SID for generic creator-owner * S-1-3-0 */ -static const char ownersidbytes[] = { - 1, /* revision */ - 1, /* auth count */ - 0, 0, 0, 0, 0, 3, /* base */ - 0, 0, 0, 0 /* 1st level */ -} ; +static const char ownersidbytes[] = { 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; +static const SID *ownersid = (const SID*) ownersidbytes; /* * SID for generic creator-group * S-1-3-1 */ -static const char groupsidbytes[] = { - 1, /* revision */ - 1, /* auth count */ - 0, 0, 0, 0, 0, 3, /* base */ - 1, 0, 0, 0 /* 1st level */ -} ; +static const char groupsidbytes[] = { 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; +static const SID *groupsid = (const SID*) groupsidbytes; /* * Determine the size of a SID @@ -199,7 +193,7 @@ static const SID *groupsid = (const SID*)groupsidbytes; int ntfs_sid_size(const SID * sid) { - return (sid->sub_authority_count * 4 + 8); + return (sid->sub_authority_count * 4 + 8); } /* @@ -208,11 +202,10 @@ int ntfs_sid_size(const SID * sid) BOOL ntfs_same_sid(const SID *first, const SID *second) { - int size; + 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)); } /* @@ -222,20 +215,16 @@ BOOL ntfs_same_sid(const SID *first, const SID *second) 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))) + 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)))); } /* @@ -246,10 +235,9 @@ static int is_world_sid(const SID * usid) 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))); + 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))); } /* @@ -259,57 +247,58 @@ BOOL ntfs_is_user_sid(const SID *usid) 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; + 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); } /* @@ -319,9 +308,7 @@ unsigned int ntfs_attr_size(const char *attr) BOOL ntfs_valid_sid(const SID *sid) { - return ((sid->revision == SID_REVISION) - && (sid->sub_authority_count >= 1) - && (sid->sub_authority_count <= 8)); + return ((sid->revision == SID_REVISION) && (sid->sub_authority_count >= 1) && (sid->sub_authority_count <= 8)); } /* @@ -336,14 +323,14 @@ BOOL ntfs_valid_sid(const SID *sid) BOOL ntfs_valid_pattern(const SID *sid) { - int cnt; - u32 auth; - le32 leauth; + 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)); } /* @@ -355,51 +342,51 @@ BOOL ntfs_valid_pattern(const SID *sid) 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; + 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); } /* @@ -407,43 +394,45 @@ static u32 findimplicit(const SID *xsid, const SID *pattern, int parity) * Returns NULL if not found */ -const SID *ntfs_find_usid(const struct MAPPING* usermapping, - uid_t uid, SID *defusid) +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; + 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); } /* @@ -451,43 +440,45 @@ const SID *ntfs_find_usid(const struct MAPPING* usermapping, * Returns 0 (root) if not found */ -const SID *ntfs_find_gsid(const struct MAPPING* groupmapping, - gid_t gid, SID *defgsid) +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; + 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); } /* @@ -497,20 +488,19 @@ const SID *ntfs_find_gsid(const struct MAPPING* groupmapping, uid_t ntfs_find_user(const struct MAPPING* usermapping, const SID *usid) { - uid_t uid; - const struct MAPPING *p; + 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); } /* @@ -520,22 +510,21 @@ uid_t ntfs_find_user(const struct MAPPING* usermapping, const SID *usid) gid_t ntfs_find_group(const struct MAPPING* groupmapping, const SID * gsid) { - gid_t gid; - const struct MAPPING *p; - int gsidsz; + 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); } /* @@ -544,32 +533,31 @@ gid_t ntfs_find_group(const struct MAPPING* groupmapping, const SID * gsid) 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; + 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) - || ((ntfs_sid_size(&pace->sid) + 8) != (int)acesz)) - 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) || ((ntfs_sid_size(&pace->sid) + 8) + != (int) acesz)) ok = FALSE; + offace += acesz; + } + } + return (ok); } /* @@ -583,79 +571,64 @@ static BOOL valid_acl(const ACL *pacl, unsigned int end) 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; + 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)) - && (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+sizeof(ACL) < attrsz))) - && (!offsacl - || ((offsacl >= sizeof(SECURITY_DESCRIPTOR_RELATIVE)) - && (offsacl+sizeof(ACL) < 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_attr_size(securattr) <= attrsz) - && 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)) && (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 + sizeof(ACL) < attrsz))) && (!offsacl || ((offsacl + >= sizeof(SECURITY_DESCRIPTOR_RELATIVE)) && (offsacl + sizeof(ACL) < 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_attr_size(securattr) <= attrsz) && 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); } /* @@ -665,114 +638,109 @@ BOOL ntfs_valid_descr(const char *securattr, unsigned int attrsz) * or zero if nothing is inheritable */ -int ntfs_inherit_acl(const ACL *oldacl, ACL *newacl, - const SID *usid, const SID *gsid, BOOL fordir) +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; + 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; - pnewace->size = cpu_to_le16(acesz); - } - if (ntfs_same_sid(&pnewace->sid, groupsid)) { - memcpy(&pnewace->sid, gsid, gsidsz); - acesz = gsidsz + 8; - pnewace->size = cpu_to_le16(acesz); - } - 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; + pnewace->size = cpu_to_le16(acesz); + } + if (ntfs_same_sid(&pnewace->sid, groupsid)) + { + memcpy(&pnewace->sid, gsid, gsidsz); + acesz = gsidsz + 8; + pnewace->size = cpu_to_le16(acesz); + } + 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 @@ -786,119 +754,123 @@ int ntfs_inherit_acl(const ACL *oldacl, ACL *newacl, 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; + 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); } /* @@ -908,37 +880,39 @@ BOOL ntfs_valid_posix(const struct POSIX_SECURITY *pxdesc) static mode_t posix_header(struct POSIX_SECURITY *pxdesc, mode_t basemode) { - mode_t mode; - u16 tagsset; - struct POSIX_ACE *pace; - int i; + 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); } /* @@ -953,67 +927,77 @@ static mode_t posix_header(struct POSIX_SECURITY *pxdesc, mode_t basemode) 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; + 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); } /* @@ -1025,39 +1009,41 @@ void ntfs_sort_posix(struct POSIX_SECURITY *pxdesc) int ntfs_merge_mode_posix(struct POSIX_SECURITY *pxdesc, mode_t mode) { - int i; - BOOL maskfound; - struct POSIX_ACE *pace; - int todo; + 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); } /* @@ -1068,57 +1054,63 @@ 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) + const struct POSIX_ACL *newacl, int count, BOOL deflt) { - struct POSIX_SECURITY *newpxdesc; - size_t newsize; - int offset; - int oldoffset; - int i; + 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); } /* @@ -1129,184 +1121,205 @@ 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) + 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; + 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) + const struct POSIX_ACE *firstace, + const struct POSIX_ACE *secondace, + int firstcnt, int secondcnt) { - int k; + 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); } /* @@ -1318,481 +1331,534 @@ 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) + 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; + 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; -} ; - - +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; +}; 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) + 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; + 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) + 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; + 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) + 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; + 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); } - /* * Build an ACL composed of several ACE's * returns size of ACL or zero if failed @@ -1806,7 +1872,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 @@ -1879,639 +1945,649 @@ 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) + 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; + 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) +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; + 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 @@ -2522,97 +2598,104 @@ 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) + 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; + 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 */ @@ -2622,85 +2705,77 @@ char *ntfs_build_descr_posix(struct MAPPING* const mapping[], * returns descriptor in allocated memory, must free() after use */ -char *ntfs_build_descr(mode_t mode, - int isdir, const SID * usid, const SID * gsid) +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 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); } /* @@ -2708,95 +2783,86 @@ char *ntfs_build_descr(mode_t mode, * from owner, group and world grants as represented in ACEs */ -static int merge_permissions(BOOL isdir, - le32 owner, le32 group, le32 world, le32 special) +static int merge_permissions(BOOL isdir, 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 @@ -2808,152 +2874,168 @@ 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) + 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; + 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 */ @@ -2963,86 +3045,82 @@ static int norm_std_permissions_posix(struct POSIX_SECURITY *posix_desc, * (standard case : different owner, group and administrator) */ -static int build_std_permissions(const char *securattr, - const SID *usid, const SID *gsid, BOOL isdir) +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 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; - offace = 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; + offace = 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)); } /* @@ -3051,69 +3129,64 @@ static int build_std_permissions(const char *securattr, * and not administrator) */ -static int build_owngrp_permissions(const char *securattr, - const SID *usid, BOOL isdir) +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 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 @@ -3125,106 +3198,116 @@ 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 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 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 */ @@ -3234,84 +3317,82 @@ static int norm_ownadmin_permissions_posix(struct POSIX_SECURITY *posix_desc, * (special case : owner or/and group is administrator) */ - -static int build_ownadmin_permissions(const char *securattr, - const SID *usid, const SID *gsid, BOOL isdir) +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 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; - offace = 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; + offace = 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 @@ -3331,38 +3412,40 @@ static int build_ownadmin_permissions(const char *securattr, 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 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 @@ -3383,39 +3466,39 @@ const SID *ntfs_acl_owner(const char *securattr) * Returns the uid of tenant or zero if none */ - -static uid_t find_tenant(struct MAPPING *const mapping[], - 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 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 */ @@ -3434,440 +3517,527 @@ 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) + 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; + 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 */ @@ -3878,26 +4048,22 @@ struct POSIX_SECURITY *ntfs_build_permissions_posix( * or a negative result (with errno set) if there is a problem */ -int ntfs_build_permissions(const char *securattr, - const SID *usid, const SID *gsid, BOOL isdir) +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 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); } /* @@ -3905,13 +4071,13 @@ int ntfs_build_permissions(const char *securattr, */ static unsigned long atoul(const char *p) -{ /* must be somewhere ! */ - unsigned long v; +{ /* 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); } /* @@ -3922,38 +4088,40 @@ static unsigned long atoul(const char *p) static SID *encodesid(const char *sidstr) { - SID *sid; - int cnt; - BIGSID bigsid; - SID *bsid; - u32 auth; - const char *p; + 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); } /* @@ -3964,25 +4132,24 @@ 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; + 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); } - /* * Get a single mapping item from buffer * @@ -3991,72 +4158,80 @@ static void log_early_error(const char *format, ...) * Returns pointer to item, or NULL when there is no more */ -static struct MAPLIST *getmappingitem(FILEREADER reader, void *fileid, - off_t *poffs, char *buf, int *psrc, s64 *psize) +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; + 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); } /* @@ -4076,34 +4251,35 @@ static struct MAPLIST *getmappingitem(FILEREADER reader, void *fileid, 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; + 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); } /* @@ -4113,36 +4289,35 @@ struct MAPLIST *ntfs_read_mapping(FILEREADER reader, void *fileid) void ntfs_free_mapping(struct MAPPING *mapping[]) { - struct MAPPING *user; - struct MAPPING *group; + 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); + } } - /* * Build the user mapping list * user identification may be given in symbolic or numeric format @@ -4154,62 +4329,61 @@ void ntfs_free_mapping(struct MAPPING *mapping[]) 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 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); } /* @@ -4226,68 +4400,67 @@ struct MAPPING *ntfs_do_user_mapping(struct MAPLIST *firstitem) 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 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 8a83d32d..f9eabbfd 100644 --- a/source/libntfs/acls.h +++ b/source/libntfs/acls.h @@ -56,7 +56,6 @@ #define NTFS_FIND_USER(map,usid) ntfs_find_user(map,usid) #define NTFS_FIND_GROUP(map,gsid) ntfs_find_group(map,gsid) - /* * Matching of ntfs permissions to Linux permissions * these constants are adapted to endianness @@ -64,7 +63,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 \ @@ -75,8 +74,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) @@ -85,19 +84,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) @@ -122,12 +121,13 @@ typedef char BIGSID[40]; * (private to this module) */ -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 +{ + 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); @@ -150,14 +150,11 @@ BOOL ntfs_same_sid(const SID *first, const SID *second); BOOL ntfs_is_user_sid(const SID *usid); - 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); -const SID *ntfs_find_gsid(const struct MAPPING *groupmapping, - gid_t gid, SID *pdefsid); +const SID *ntfs_find_usid(const struct MAPPING *usermapping, uid_t uid, SID *pdefsid); +const SID *ntfs_find_gsid(const struct MAPPING *groupmapping, 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); @@ -168,28 +165,25 @@ 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); -int ntfs_build_permissions(const char *securattr, - const SID *usid, const SID *gsid, BOOL isdir); -char *ntfs_build_descr(mode_t mode, - int isdir, const SID * usid, const SID * gsid); +int ntfs_inherit_acl(const ACL *oldacl, ACL *newacl, const SID *usid, const SID *gsid, BOOL fordir); +int ntfs_build_permissions(const char *securattr, const SID *usid, const SID *gsid, BOOL isdir); +char *ntfs_build_descr(mode_t mode, 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 123c9a91..92f388a2 100644 --- a/source/libntfs/attrib.c +++ b/source/libntfs/attrib.c @@ -66,43 +66,30 @@ #include "efs.h" 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') }; +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') }; -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') }; +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') }; 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; + 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); + 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; + if (na->type == AT_DATA && na->name == AT_UNNAMED) na->ni->flags &= ~flag; } #define GenNAttrIno(func_name, flag) \ @@ -111,8 +98,8 @@ void NAttrSet##func_name(ntfs_attr *na) { NAttrSetFlag (na, flag); } \ void NAttrClear##func_name(ntfs_attr *na){ NAttrClearFlag(na, flag); } GenNAttrIno(Compressed, FILE_ATTR_COMPRESSED) -GenNAttrIno(Encrypted, FILE_ATTR_ENCRYPTED) -GenNAttrIno(Sparse, FILE_ATTR_SPARSE_FILE) +GenNAttrIno(Encrypted, FILE_ATTR_ENCRYPTED) +GenNAttrIno(Sparse, FILE_ATTR_SPARSE_FILE) /** * ntfs_get_attribute_value_length - Find the length of an attribute @@ -124,15 +111,15 @@ GenNAttrIno(Sparse, FILE_ATTR_SPARSE_FILE) */ 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); + 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); } /** @@ -145,165 +132,175 @@ s64 ntfs_get_attribute_value_length(const ATTR_RECORD *a) * * Returns: */ -s64 ntfs_get_attribute_value(const ntfs_volume *vol, - const ATTR_RECORD *a, u8 *b) +s64 ntfs_get_attribute_value(const ntfs_volume *vol, const ATTR_RECORD *a, u8 *b) { - runlist *rl; - s64 total, r; - int i; + 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:... */ @@ -318,17 +315,15 @@ 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) +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; + na->rl = NULL; + na->ni = ni; + na->type = type; + na->name = name; + if (name) + na->name_len = name_len; + else na->name_len = 0; } /** @@ -346,38 +341,31 @@ 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) +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; + 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); + } } /** @@ -395,133 +383,124 @@ void ntfs_attr_init(ntfs_attr *na, const BOOL non_resident, * do not care whether the attribute is named or not set @name to NULL. In * 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 *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; + 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); - - 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; - } + ntfs_log_enter("Entering for inode %lld, attr 0x%x.\n", + (unsigned long long)ni->mft_no, type); - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - goto err_out; + 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 (ntfs_attr_lookup(type, name, name_len, 0, 0, NULL, 0, ctx)) - goto put_err_out; + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) goto 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; + if (ntfs_attr_lookup(type, name, name_len, 0, 0, NULL, 0, ctx)) goto put_err_out; - 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. - * - * Also prevent compression on NTFS version < 3.0 - * or cluster size > 4K or compression is disabled - */ - a->flags &= ~ATTR_COMPRESSION_MASK; - if ((ni->flags & FILE_ATTR_COMPRESSED) - && (ni->vol->major_ver >= 3) - && NVolCompression(ni->vol) - && (ni->vol->cluster_size <= MAX_COMPRESSION_CLUSTER_SIZE)) - 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; - } + a = ctx->attr; - 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; + 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; + } + } -put_err_out: - ntfs_attr_put_search_ctx(ctx); -err_out: - free(newname); - free(na); - na = NULL; - goto out; + __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. + * + * Also prevent compression on NTFS version < 3.0 + * or cluster size > 4K or compression is disabled + */ + a->flags &= ~ATTR_COMPRESSION_MASK; + if ((ni->flags & FILE_ATTR_COMPRESSED) && (ni->vol->major_ver >= 3) && NVolCompression(ni->vol) + && (ni->vol->cluster_size <= MAX_COMPRESSION_CLUSTER_SIZE)) 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); + out: + ntfs_log_leave("\n"); + return na; + + put_err_out: ntfs_attr_put_search_ctx(ctx); + err_out: free(newname); + free(na); + na = NULL; + goto out; } /** @@ -533,15 +512,11 @@ err_out: */ 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); + 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); } /** @@ -555,37 +530,35 @@ void ntfs_attr_close(ntfs_attr *na) */ int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn) { - LCN lcn; - ntfs_attr_search_ctx *ctx; + 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; } /** @@ -602,102 +575,104 @@ int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn) */ 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; + 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); - /* avoid multiple full runlist mappings */ - if (NAttrFullyMapped(na)) { - ret = 0; - goto out; - } - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - goto out; + /* avoid multiple full runlist mappings */ + if (NAttrFullyMapped(na)) + { + ret = 0; + 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) { - NAttrSetFullyMapped(na); - ret = 0; - } -err_out: - ntfs_attr_put_search_ctx(ctx); -out: - ntfs_log_leave("\n"); - return ret; + /* 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) + { + NAttrSetFullyMapped(na); + ret = 0; + } + err_out: ntfs_attr_put_search_ctx(ctx); + out: + ntfs_log_leave("\n"); + return ret; } /** @@ -723,32 +698,30 @@ out: */ LCN ntfs_attr_vcn_to_lcn(ntfs_attr *na, const VCN vcn) { - LCN lcn; - BOOL is_retry = FALSE; + 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); -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; + 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; } /** @@ -773,273 +746,283 @@ retry: */ runlist_element *ntfs_attr_find_vcn(ntfs_attr *na, const VCN vcn) { - runlist_element *rl; - BOOL is_retry = FALSE; + 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); -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; -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; + 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; + 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; } /** * 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; + 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(). */ - - 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; + /* Sanity checking arguments is done in ntfs_attr_pread(). */ - 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); -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; -rl_err_out: - if (total) - return total; - errno = EIO; - return -1; + 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)) + { + 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); + 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; + rl_err_out: if (total) return total; + errno = EIO; + return -1; } /** @@ -1063,243 +1046,244 @@ rl_err_out: */ 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); + s64 ret; - ret = ntfs_attr_pread_i(na, pos, count, b); - - ntfs_log_leave("\n"); - return 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); + + 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; + 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); -err_out: - return ret; + 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; } -static int ntfs_attr_fill_hole(ntfs_attr *na, s64 count, s64 *ofs, - runlist_element **rl, VCN *update_from) +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; + 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 - * compression block, as we may need space to decompress - * existing compressed data. - * So allocate the space common to compression block - * and existing hole. - */ - VCN alloc_vcn; + to_write = min(count, ((*rl)->length << vol->cluster_size_bits) - *ofs); - if ((from_vcn & -na->compression_block_clusters) <= (*rl)->vcn) - alloc_vcn = (*rl)->vcn; - else - alloc_vcn = from_vcn & -na->compression_block_clusters; - need = (alloc_vcn | (na->compression_block_clusters - 1)) - + 1 - alloc_vcn; - if (need > (*rl)->length) { - ntfs_log_error("Cannot allocate %lld clusters" - " within a hole of %lld\n", - (long long)need, - (long long)(*rl)->length); - errno = EIO; - goto err_out; - } - rlc = ntfs_cluster_alloc(vol, alloc_vcn, need, - lcn_seek_from, DATA_ZONE); - } else - rlc = ntfs_cluster_alloc(vol, from_vcn, need, - lcn_seek_from, DATA_ZONE); - if (!rlc) - goto err_out; - if (na->data_flags & (ATTR_COMPRESSION_MASK | ATTR_IS_SPARSE)) - na->compressed_size += need << vol->cluster_size_bits; - - *rl = ntfs_runlists_merge(na->rl, rlc); - /* - * For a compressed attribute, we must be sure there are two - * available entries, so reserve them before it gets too late. - */ - if (*rl && (na->data_flags & ATTR_COMPRESSION_MASK)) { - runlist_element *oldrl = na->rl; - na->rl = *rl; - *rl = ntfs_rl_extend(na,*rl,2); - if (!*rl) na->rl = oldrl; /* restore to original if failed */ - } - 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->unused_runs = 2; - na->rl = *rl; - if ((*update_from == -1) || (from_vcn < *update_from)) - *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; + 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 + * compression block, as we may need space to decompress + * existing compressed data. + * So allocate the space common to compression block + * and existing hole. + */ + VCN alloc_vcn; + + if ((from_vcn & -na->compression_block_clusters) <= (*rl)->vcn) + alloc_vcn = (*rl)->vcn; + else alloc_vcn = from_vcn & -na->compression_block_clusters; + need = (alloc_vcn | (na->compression_block_clusters - 1)) + 1 - alloc_vcn; + if (need > (*rl)->length) + { + ntfs_log_error("Cannot allocate %lld clusters" + " within a hole of %lld\n", + (long long)need, + (long long)(*rl)->length); + errno = EIO; + goto err_out; + } + rlc = ntfs_cluster_alloc(vol, alloc_vcn, need, lcn_seek_from, DATA_ZONE); + } + else rlc = ntfs_cluster_alloc(vol, from_vcn, need, lcn_seek_from, DATA_ZONE); + if (!rlc) goto err_out; + if (na->data_flags & (ATTR_COMPRESSION_MASK | ATTR_IS_SPARSE)) na->compressed_size += need + << vol->cluster_size_bits; + + *rl = ntfs_runlists_merge(na->rl, rlc); + /* + * For a compressed attribute, we must be sure there are two + * available entries, so reserve them before it gets too late. + */ + if (*rl && (na->data_flags & ATTR_COMPRESSION_MASK)) + { + runlist_element *oldrl = na->rl; + na->rl = *rl; + *rl = ntfs_rl_extend(na, *rl, 2); + if (!*rl) na->rl = oldrl; /* restore to original if failed */ + } + 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->unused_runs = 2; + na->rl = *rl; + if ((*update_from == -1) || (from_vcn < *update_from)) *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; } static int stuff_hole(ntfs_attr *na, const s64 pos); @@ -1319,152 +1303,172 @@ static int stuff_hole(ntfs_attr *na, const s64 pos); * -1 if there were an error */ -static int split_compressed_hole(ntfs_attr *na, runlist_element **prl, - s64 pos, s64 count, VCN *update_from) +static int split_compressed_hole(ntfs_attr *na, runlist_element **prl, s64 pos, s64 count, VCN *update_from) { - int compressed_part; - int cluster_size_bits = na->ni->vol->cluster_size_bits; - runlist_element *rl = *prl; + int compressed_part; + int cluster_size_bits = na->ni->vol->cluster_size_bits; + runlist_element *rl = *prl; - compressed_part - = na->compression_block_clusters; - /* reserve entries in runlist if we have to split */ - if (rl->length > na->compression_block_clusters) { - *prl = ntfs_rl_extend(na,*prl,2); - if (!*prl) { - compressed_part = -1; - } else { - rl = *prl; - na->unused_runs = 2; - } - } - if (*prl && (rl->length > na->compression_block_clusters)) { - /* - * Locate the update part relative to beginning of - * current run - */ - int beginwrite = (pos >> cluster_size_bits) - rl->vcn; - s32 endblock = (((pos + count - 1) >> cluster_size_bits) - | (na->compression_block_clusters - 1)) + 1 - rl->vcn; + compressed_part = na->compression_block_clusters; + /* reserve entries in runlist if we have to split */ + if (rl->length > na->compression_block_clusters) + { + *prl = ntfs_rl_extend(na, *prl, 2); + if (!*prl) + { + compressed_part = -1; + } + else + { + rl = *prl; + na->unused_runs = 2; + } + } + if (*prl && (rl->length > na->compression_block_clusters)) + { + /* + * Locate the update part relative to beginning of + * current run + */ + int beginwrite = (pos >> cluster_size_bits) - rl->vcn; + s32 endblock = (((pos + count - 1) >> cluster_size_bits) | (na->compression_block_clusters - 1)) + 1 - rl->vcn; - compressed_part = na->compression_block_clusters - - (rl->length & (na->compression_block_clusters - 1)); - if ((beginwrite + compressed_part) >= na->compression_block_clusters) - compressed_part = na->compression_block_clusters; - /* - * if the run ends beyond end of needed block - * we have to split the run - */ - if (endblock < rl[0].length) { - runlist_element *xrl; - int n; + compressed_part = na->compression_block_clusters - (rl->length & (na->compression_block_clusters - 1)); + if ((beginwrite + compressed_part) >= na->compression_block_clusters) compressed_part + = na->compression_block_clusters; + /* + * if the run ends beyond end of needed block + * we have to split the run + */ + if (endblock < rl[0].length) + { + runlist_element *xrl; + int n; - /* - * we have to split into three parts if the run - * does not end within the first compression block. - * This means the hole begins before the - * compression block. - */ - if (endblock > na->compression_block_clusters) { - if (na->unused_runs < 2) { -ntfs_log_error("No free run, case 1\n"); - } - na->unused_runs -= 2; - xrl = rl; - n = 0; - while (xrl->length) { - xrl++; - n++; - } - do { - xrl[2] = *xrl; - xrl--; - } while (xrl != rl); - rl[1].length = na->compression_block_clusters; - rl[2].length = rl[0].length - endblock; - rl[0].length = endblock - - na->compression_block_clusters; - rl[1].lcn = LCN_HOLE; - rl[2].lcn = LCN_HOLE; - rl[1].vcn = rl[0].vcn + rl[0].length; - rl[2].vcn = rl[1].vcn - + na->compression_block_clusters; - rl = ++(*prl); - } else { - /* - * split into two parts and use the - * first one - */ - if (!na->unused_runs) { -ntfs_log_error("No free run, case 2\n"); - } - na->unused_runs--; - xrl = rl; - n = 0; - while (xrl->length) { - xrl++; - n++; - } - do { - xrl[1] = *xrl; - xrl--; - } while (xrl != rl); - if (beginwrite < endblock) { - /* we will write into the first part of hole */ - rl[1].length = rl[0].length - endblock; - rl[0].length = endblock; - rl[1].vcn = rl[0].vcn + rl[0].length; - rl[1].lcn = LCN_HOLE; - } else { - /* we will write into the second part of hole */ -// impossible ? - rl[1].length = rl[0].length - endblock; - rl[0].length = endblock; - rl[1].vcn = rl[0].vcn + rl[0].length; - rl[1].lcn = LCN_HOLE; - rl = ++(*prl); - } - } - } else { - if (rl[1].length) { - runlist_element *xrl; - int n; + /* + * we have to split into three parts if the run + * does not end within the first compression block. + * This means the hole begins before the + * compression block. + */ + if (endblock > na->compression_block_clusters) + { + if (na->unused_runs < 2) + { + ntfs_log_error("No free run, case 1\n"); + } + na->unused_runs -= 2; + xrl = rl; + n = 0; + while (xrl->length) + { + xrl++; + n++; + } + do + { + xrl[2] = *xrl; + xrl--; + } while (xrl != rl); + rl[1].length = na->compression_block_clusters; + rl[2].length = rl[0].length - endblock; + rl[0].length = endblock - na->compression_block_clusters; + rl[1].lcn = LCN_HOLE; + rl[2].lcn = LCN_HOLE; + rl[1].vcn = rl[0].vcn + rl[0].length; + rl[2].vcn = rl[1].vcn + na->compression_block_clusters; + rl = ++(*prl); + } + else + { + /* + * split into two parts and use the + * first one + */ + if (!na->unused_runs) + { + ntfs_log_error("No free run, case 2\n"); + } + na->unused_runs--; + xrl = rl; + n = 0; + while (xrl->length) + { + xrl++; + n++; + } + do + { + xrl[1] = *xrl; + xrl--; + } while (xrl != rl); + if (beginwrite < endblock) + { + /* we will write into the first part of hole */ + rl[1].length = rl[0].length - endblock; + rl[0].length = endblock; + rl[1].vcn = rl[0].vcn + rl[0].length; + rl[1].lcn = LCN_HOLE; + } + else + { + /* we will write into the second part of hole */ + // impossible ? + rl[1].length = rl[0].length - endblock; + rl[0].length = endblock; + rl[1].vcn = rl[0].vcn + rl[0].length; + rl[1].lcn = LCN_HOLE; + rl = ++(*prl); + } + } + } + else + { + if (rl[1].length) + { + runlist_element *xrl; + int n; - /* - * split into two parts and use the - * last one - */ - if (!na->unused_runs) { -ntfs_log_error("No free run, case 4\n"); - } - na->unused_runs--; - xrl = rl; - n = 0; - while (xrl->length) { - xrl++; - n++; - } - do { - xrl[1] = *xrl; - xrl--; - } while (xrl != rl); - } else { - rl[2].lcn = rl[1].lcn; - rl[2].vcn = rl[1].vcn; - rl[2].length = rl[1].length; - } - rl[1].vcn -= na->compression_block_clusters; - rl[1].lcn = LCN_HOLE; - rl[1].length = na->compression_block_clusters; - rl[0].length -= na->compression_block_clusters; - if (pos >= (rl[1].vcn << cluster_size_bits)) { - rl = ++(*prl); - } - } - if ((*update_from == -1) || ((*prl)->vcn < *update_from)) - *update_from = (*prl)->vcn; - } - return (compressed_part); + /* + * split into two parts and use the + * last one + */ + if (!na->unused_runs) + { + ntfs_log_error("No free run, case 4\n"); + } + na->unused_runs--; + xrl = rl; + n = 0; + while (xrl->length) + { + xrl++; + n++; + } + do + { + xrl[1] = *xrl; + xrl--; + } while (xrl != rl); + } + else + { + rl[2].lcn = rl[1].lcn; + rl[2].vcn = rl[1].vcn; + rl[2].length = rl[1].length; + } + rl[1].vcn -= na->compression_block_clusters; + rl[1].lcn = LCN_HOLE; + rl[1].length = na->compression_block_clusters; + rl[0].length -= na->compression_block_clusters; + if (pos >= (rl[1].vcn << cluster_size_bits)) + { + rl = ++(*prl); + } + } + if ((*update_from == -1) || ((*prl)->vcn < *update_from)) *update_from = (*prl)->vcn; + } + return (compressed_part); } /* @@ -1480,136 +1484,148 @@ ntfs_log_error("No free run, case 4\n"); * -1 if there were an error */ -static int borrow_from_hole(ntfs_attr *na, runlist_element **prl, - s64 pos, s64 count, VCN *update_from, BOOL wasnonresident) +static int borrow_from_hole(ntfs_attr *na, runlist_element **prl, s64 pos, s64 count, VCN *update_from, + BOOL wasnonresident) { - int compressed_part = 0; - int cluster_size_bits = na->ni->vol->cluster_size_bits; - runlist_element *rl = *prl; - s32 endblock; - long long allocated; - runlist_element *zrl; - int irl; - BOOL undecided; - BOOL nothole; + int compressed_part = 0; + int cluster_size_bits = na->ni->vol->cluster_size_bits; + runlist_element *rl = *prl; + s32 endblock; + long long allocated; + runlist_element *zrl; + int irl; + BOOL undecided; + BOOL nothole; - /* check whether the compression block is fully allocated */ - endblock = (((pos + count - 1) >> cluster_size_bits) | (na->compression_block_clusters - 1)) + 1 - rl->vcn; - allocated = 0; - zrl = rl; - irl = 0; - while (zrl->length && (zrl->lcn >= 0) && (allocated < endblock)) { - allocated += zrl->length; - zrl++; - irl++; - } + /* check whether the compression block is fully allocated */ + endblock = (((pos + count - 1) >> cluster_size_bits) | (na->compression_block_clusters - 1)) + 1 - rl->vcn; + allocated = 0; + zrl = rl; + irl = 0; + while (zrl->length && (zrl->lcn >= 0) && (allocated < endblock)) + { + allocated += zrl->length; + zrl++; + irl++; + } - undecided = (allocated < endblock) && (zrl->lcn == LCN_RL_NOT_MAPPED); - nothole = (allocated >= endblock) || (zrl->lcn != LCN_HOLE); + undecided = (allocated < endblock) && (zrl->lcn == LCN_RL_NOT_MAPPED); + nothole = (allocated >= endblock) || (zrl->lcn != LCN_HOLE); - if (undecided || nothole) { - runlist_element *orl = na->rl; - s64 olcn = (*prl)->lcn; - /* - * Map the full runlist (needed to compute the - * compressed size), unless the runlist has not - * yet been created (data just made non-resident) - */ - irl = *prl - na->rl; - if (!NAttrBeingNonResident(na) - && ntfs_attr_map_whole_runlist(na)) { - rl = (runlist_element*)NULL; - } else { - /* - * Mapping the runlist may cause its relocation, - * and relocation may be at the same place with - * relocated contents. - * Have to find the current run again when this - * happens. - */ - if ((na->rl != orl) || ((*prl)->lcn != olcn)) { - zrl = &na->rl[irl]; - while (zrl->length && (zrl->lcn != olcn)) - zrl++; - *prl = zrl; - } - if (!(*prl)->length) { - ntfs_log_error("Mapped run not found," - " inode %lld lcn 0x%llx\n", - (long long)na->ni->mft_no, - (long long)olcn); - rl = (runlist_element*)NULL; - } else { - rl = ntfs_rl_extend(na,*prl,2); - na->unused_runs = 2; - } - } - *prl = rl; - if (rl && undecided) { - allocated = 0; - zrl = rl; - irl = 0; - while (zrl->length && (zrl->lcn >= 0) - && (allocated < endblock)) { - allocated += zrl->length; - zrl++; - irl++; - } - } - } - /* - * compression block not fully allocated and followed - * by a hole : we must allocate in the hole. - */ - if (rl && (allocated < endblock) && (zrl->lcn == LCN_HOLE)) { - s64 xofs; + if (undecided || nothole) + { + runlist_element *orl = na->rl; + s64 olcn = (*prl)->lcn; + /* + * Map the full runlist (needed to compute the + * compressed size), unless the runlist has not + * yet been created (data just made non-resident) + */ + irl = *prl - na->rl; + if (!NAttrBeingNonResident(na) && ntfs_attr_map_whole_runlist(na)) + { + rl = (runlist_element*) NULL; + } + else + { + /* + * Mapping the runlist may cause its relocation, + * and relocation may be at the same place with + * relocated contents. + * Have to find the current run again when this + * happens. + */ + if ((na->rl != orl) || ((*prl)->lcn != olcn)) + { + zrl = &na->rl[irl]; + while (zrl->length && (zrl->lcn != olcn)) + zrl++; + *prl = zrl; + } + if (!(*prl)->length) + { + ntfs_log_error("Mapped run not found," + " inode %lld lcn 0x%llx\n", + (long long)na->ni->mft_no, + (long long)olcn); + rl = (runlist_element*) NULL; + } + else + { + rl = ntfs_rl_extend(na, *prl, 2); + na->unused_runs = 2; + } + } + *prl = rl; + if (rl && undecided) + { + allocated = 0; + zrl = rl; + irl = 0; + while (zrl->length && (zrl->lcn >= 0) && (allocated < endblock)) + { + allocated += zrl->length; + zrl++; + irl++; + } + } + } + /* + * compression block not fully allocated and followed + * by a hole : we must allocate in the hole. + */ + if (rl && (allocated < endblock) && (zrl->lcn == LCN_HOLE)) + { + s64 xofs; - /* - * split the hole if not fully needed - */ - if ((allocated + zrl->length) > endblock) { - runlist_element *xrl; + /* + * split the hole if not fully needed + */ + if ((allocated + zrl->length) > endblock) + { + runlist_element *xrl; - *prl = ntfs_rl_extend(na,*prl,1); - if (*prl) { - /* beware : rl was reallocated */ - rl = *prl; - zrl = &rl[irl]; - na->unused_runs = 0; - xrl = zrl; - while (xrl->length) xrl++; - do { - xrl[1] = *xrl; - } while (xrl-- != zrl); - zrl->length = endblock - allocated; - zrl[1].length -= zrl->length; - zrl[1].vcn = zrl->vcn + zrl->length; - } - } - if (*prl) { - if (wasnonresident) - compressed_part = na->compression_block_clusters - - zrl->length; - xofs = 0; - if (ntfs_attr_fill_hole(na, - zrl->length << cluster_size_bits, - &xofs, &zrl, update_from)) - compressed_part = -1; - else { - /* go back to initial cluster, now reallocated */ - while (zrl->vcn > (pos >> cluster_size_bits)) - zrl--; - *prl = zrl; - } - } - } - if (!*prl) { - ntfs_log_error("No elements to borrow from a hole\n"); - compressed_part = -1; - } else - if ((*update_from == -1) || ((*prl)->vcn < *update_from)) - *update_from = (*prl)->vcn; - return (compressed_part); + *prl = ntfs_rl_extend(na, *prl, 1); + if (*prl) + { + /* beware : rl was reallocated */ + rl = *prl; + zrl = &rl[irl]; + na->unused_runs = 0; + xrl = zrl; + while (xrl->length) + xrl++; + do + { + xrl[1] = *xrl; + } while (xrl-- != zrl); + zrl->length = endblock - allocated; + zrl[1].length -= zrl->length; + zrl[1].vcn = zrl->vcn + zrl->length; + } + } + if (*prl) + { + if (wasnonresident) compressed_part = na->compression_block_clusters - zrl->length; + xofs = 0; + if (ntfs_attr_fill_hole(na, zrl->length << cluster_size_bits, &xofs, &zrl, update_from)) + compressed_part = -1; + else + { + /* go back to initial cluster, now reallocated */ + while (zrl->vcn > (pos >> cluster_size_bits)) + zrl--; + *prl = zrl; + } + } + } + if (!*prl) + { + ntfs_log_error("No elements to borrow from a hole\n"); + compressed_part = -1; + } + else if ((*update_from == -1) || ((*prl)->vcn < *update_from)) *update_from = (*prl)->vcn; + return (compressed_part); } /** @@ -1633,695 +1649,674 @@ static int borrow_from_hole(ntfs_attr *na, runlist_element **prl, */ 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 wasnonresident = FALSE; - BOOL compressed; - BOOL updatemap; + 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 wasnonresident = FALSE; + BOOL compressed; + BOOL updatemap; - 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); - na->unused_runs = 0; /* prepare overflow checks */ - /* - * 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; - /* - * Compression is restricted to data streams and - * only ATTR_IS_COMPRESSED compression mode is supported. - */ - if (compressed - && ((na->type != AT_DATA) - || ((na->data_flags & ATTR_COMPRESSION_MASK) - != ATTR_IS_COMPRESSED))) { - 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 = (pos | (na->compression_block_size - 1)) + 1 - 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; + 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); - 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 (!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); + na->unused_runs = 0; /* prepare overflow checks */ + /* + * 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; + /* + * Compression is restricted to data streams and + * only ATTR_IS_COMPRESSED compression mode is supported. + */ + if (compressed && ((na->type != AT_DATA) || ((na->data_flags & ATTR_COMPRESSION_MASK) != ATTR_IS_COMPRESSED))) + { + errno = EOPNOTSUPP; + goto errno_set; + } - 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,na->rl,2); - if (!na->rl) - goto err_out; - na->unused_runs = 2; - } - /* 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) { - na->data_size = pos + count; - 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; + 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 = (pos | (na->compression_block_size - 1)) + 1 - 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; + + 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, na->rl, 2); + if (!na->rl) goto err_out; + na->unused_runs = 2; + } + /* 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) + { + na->data_size = pos + count; + 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; #if CACHE_NIDATA_SIZE - if (na->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY - ? na->type == AT_INDEX_ROOT && na->name == NTFS_INDEX_I30 - : na->type == AT_DATA && na->name == AT_UNNAMED) { - na->ni->data_size = na->data_size; - if ((compressed || NAttrSparse(na)) - && NAttrNonResident(na)) - na->ni->allocated_size = na->compressed_size; - else - na->ni->allocated_size = na->allocated_size; - set_nino_flag(na->ni,KnownSize); - } + if (na->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY ? na->type == AT_INDEX_ROOT && na->name == NTFS_INDEX_I30 + : na->type == AT_DATA && na->name == AT_UNNAMED) + { + na->ni->data_size = na->data_size; + if ((compressed || NAttrSparse(na)) && NAttrNonResident(na)) + na->ni->allocated_size = na->compressed_size; + else na->ni->allocated_size = na->allocated_size; + set_nino_flag(na->ni,KnownSize); + } #endif - 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; - } - /* - * 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) - /* - * the needed block is in a hole smaller - * than the compression block : we can use - * it fully - */ - compressed_part - = na->compression_block_clusters - - rl->length; - else { - /* - * the needed block is in a hole bigger - * than the compression block : we must - * split the hole and use it partially - */ - compressed_part = split_compressed_hole(na, - &rl, pos, count, &update_from); - } - } else { - if (rl->lcn >= 0) { - /* - * the needed block contains data, make - * sure the full compression block is - * allocated. Borrow from hole if needed - */ - compressed_part = borrow_from_hole(na, - &rl, pos, count, &update_from, - wasnonresident); - } - } + 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; + } + /* + * 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) + /* + * the needed block is in a hole smaller + * than the compression block : we can use + * it fully + */ + compressed_part = na->compression_block_clusters - rl->length; + else + { + /* + * the needed block is in a hole bigger + * than the compression block : we must + * split the hole and use it partially + */ + compressed_part = split_compressed_hole(na, &rl, pos, count, &update_from); + } + } + else + { + if (rl->lcn >= 0) + { + /* + * the needed block contains data, make + * sure the full compression block is + * allocated. Borrow from hole if needed + */ + compressed_part = borrow_from_hole(na, &rl, pos, count, &update_from, wasnonresident); + } + } - if (compressed_part < 0) - goto err_out; + if (compressed_part < 0) goto err_out; - /* just making non-resident, so not yet compressed */ - if (NAttrBeingNonResident(na) - && (compressed_part < na->compression_block_clusters)) - compressed_part = 0; - } - ofs = pos - (rl->vcn << vol->cluster_size_bits); - /* - * 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) { - 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; + /* just making non-resident, so not yet compressed */ + if (NAttrBeingNonResident(na) && (compressed_part < na->compression_block_clusters)) compressed_part = 0; + } + ofs = pos - (rl->vcn << vol->cluster_size_bits); + /* + * 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) + { + 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++; - } - } + 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); -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, cb, compressed_part, - &update_from); - } 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, - &update_from); - } 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. - * For a compressed file, we try to make a partial update - * of the mapping list. This makes a difference only if - * inode extents were needed. - */ - updatemap = (compressed - ? NAttrFullyMapped(na) != 0 : update_from != -1); - if (updatemap) - if (ntfs_attr_update_mapping_pairs(na, - (update_from < 0 ? 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; -err_out: - eo = errno; - if (need_to.undo_initialized_size) { - int err; + /* 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)) + { - 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. */ - updatemap = (compressed - ? NAttrFullyMapped(na) != 0 : update_from != -1); - if (updatemap) - ntfs_attr_update_mapping_pairs(na, 0); - /* 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; + 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, cb, compressed_part, + &update_from); + } + 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, + &update_from); + } + 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. + * For a compressed file, we try to make a partial update + * of the mapping list. This makes a difference only if + * inode extents were needed. + */ + updatemap = (compressed ? NAttrFullyMapped(na) != 0 : update_from != -1); + if (updatemap) if (ntfs_attr_update_mapping_pairs(na, (update_from < 0 ? 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; + err_out: 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. */ + updatemap = (compressed ? NAttrFullyMapped(na) != 0 : update_from != -1); + if (updatemap) ntfs_attr_update_mapping_pairs(na, 0); + /* 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; } int ntfs_attr_pclose(ntfs_attr *na) { - s64 ofs; - int failed; - 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; + s64 ofs; + int failed; + 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); - - if (!na || !na->ni || !na->ni->vol) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - goto errno_set; - } - vol = na->ni->vol; - na->unused_runs = 0; - 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; + ntfs_log_enter("Entering for inode 0x%llx, attr 0x%x.\n", + na->ni->mft_no, na->type); - /* safety check : no recursion on close */ - if (NAttrComprClosing(na)) { - errno = EIO; - ntfs_log_error("Bad ntfs_attr_pclose" - " recursion on inode %lld\n", - (long long)na->ni->mft_no); - goto out; - } - NAttrSetComprClosing(na); - /* - * For a compressed attribute, we must be sure there are two - * available entries, so reserve them before it gets too late. - */ - if (ntfs_attr_map_whole_runlist(na)) - goto err_out; - na->rl = ntfs_rl_extend(na,na->rl,2); - if (!na->rl) - goto err_out; - na->unused_runs = 2; - /* 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) { - runlist_element *xrl; + if (!na || !na->ni || !na->ni->vol) + { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + goto errno_set; + } + vol = na->ni->vol; + na->unused_runs = 0; + 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; - xrl = rl; - do { - xrl++; - } while (xrl->lcn >= 0); - compressed_part = (-xrl->length) - & (na->compression_block_clusters - 1); - } 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; + /* safety check : no recursion on close */ + if (NAttrComprClosing(na)) + { + errno = EIO; + ntfs_log_error("Bad ntfs_attr_pclose" + " recursion on inode %lld\n", + (long long)na->ni->mft_no); + goto out; + } + NAttrSetComprClosing(na); + /* + * For a compressed attribute, we must be sure there are two + * available entries, so reserve them before it gets too late. + */ + if (ntfs_attr_map_whole_runlist(na)) goto err_out; + na->rl = ntfs_rl_extend(na, na->rl, 2); + if (!na->rl) goto err_out; + na->unused_runs = 2; + /* 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) + { + runlist_element *xrl; - ofs = na->initialized_size - (rl->vcn << vol->cluster_size_bits); + xrl = rl; + do + { + xrl++; + } while (xrl->lcn >= 0); + compressed_part = (-xrl->length) & (na->compression_block_clusters - 1); + } + 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; - 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++; - } + ofs = na->initialized_size - (rl->vcn << vol->cluster_size_bits); -retry: - failed = 0; - if (update_from < 0) update_from = 0; - if (!NVolReadOnly(vol)) { - failed = ntfs_compressed_close(na, rl, ofs, &update_from); + 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: failed = 0; + if (update_from < 0) update_from = 0; + if (!NVolReadOnly(vol)) + { + failed = ntfs_compressed_close(na, rl, ofs, &update_from); #if CACHE_NIDATA_SIZE - if (na->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY - ? na->type == AT_INDEX_ROOT && na->name == NTFS_INDEX_I30 - : na->type == AT_DATA && na->name == AT_UNNAMED) { - na->ni->data_size = na->data_size; - na->ni->allocated_size = na->compressed_size; - set_nino_flag(na->ni,KnownSize); - } + if (na->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY ? na->type == AT_INDEX_ROOT && na->name == NTFS_INDEX_I30 + : na->type == AT_DATA && na->name == AT_UNNAMED) + { + na->ni->data_size = na->data_size; + na->ni->allocated_size = na->compressed_size; + set_nino_flag(na->ni,KnownSize); + } #endif - } - if (failed) { - /* If the syscall was interrupted, try again. */ - if (errno == EINTR) - goto retry; - else - goto rl_err_out; - } - if (ctx) - ntfs_attr_put_search_ctx(ctx); - /* Update mapping pairs if needed. */ - if (NAttrFullyMapped(na)) - if (ntfs_attr_update_mapping_pairs(na, 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. - */ -err_out: - eo = errno; - if (ctx) - ntfs_attr_put_search_ctx(ctx); - /* Update mapping pairs if needed. */ - if (NAttrFullyMapped(na)) - ntfs_attr_update_mapping_pairs(na, 0); - errno = eo; -errno_set: - ok = FALSE; - goto out; + } + if (failed) + { + /* If the syscall was interrupted, try again. */ + if (errno == EINTR) + goto retry; + else goto rl_err_out; + } + if (ctx) ntfs_attr_put_search_ctx(ctx); + /* Update mapping pairs if needed. */ + if (NAttrFullyMapped(na)) if (ntfs_attr_update_mapping_pairs(na, 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. + */ + err_out: eo = errno; + if (ctx) ntfs_attr_put_search_ctx(ctx); + /* Update mapping pairs if needed. */ + if (NAttrFullyMapped(na)) ntfs_attr_update_mapping_pairs(na, 0); + errno = eo; + errno_set: ok = FALSE; + goto out; } /** @@ -2353,29 +2348,27 @@ errno_set: * want to return even bad ones to the caller so, e.g. in case of ntfsck, the * 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 ntfs_attr_mst_pread(ntfs_attr *na, const s64 pos, const s64 bk_cnt, const u32 bk_size, void *dst) { - s64 br; - u8 *end; + 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; } /** @@ -2408,49 +2401,47 @@ s64 ntfs_attr_mst_pread(ntfs_attr *na, const s64 pos, const s64 bk_cnt, * simulating an mst read on the written data. This way cache coherency is * achieved. */ -s64 ntfs_attr_mst_pwrite(ntfs_attr *na, const s64 pos, s64 bk_cnt, - const u32 bk_size, void *src) +s64 ntfs_attr_mst_pwrite(ntfs_attr *na, const s64 pos, s64 bk_cnt, const u32 bk_size, void *src) { - s64 written, i; + 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; } /** @@ -2523,151 +2514,157 @@ s64 ntfs_attr_mst_pwrite(ntfs_attr *na, const s64 pos, s64 bk_cnt, * Warning: Never use @val when looking for attribute types which can be * 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) +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; + 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 { - register int rc; - if (name && ((rc = ntfs_names_full_collate(name, - name_len, (ntfschar*)((char*)a + - le16_to_cpu(a->name_offset)), - a->name_length, ic, - upcase, upcase_len)))) { - /* - * If @name collates before a->name, - * there is no matching attribute. - */ - if (rc < 0) { - errno = ENOENT; - return -1; - } - /* If the strings are not equal, continue search. */ - 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; + 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 + { + register int rc; + if (name && ((rc = ntfs_names_full_collate(name, name_len, (ntfschar*) ((char*) a + + le16_to_cpu(a->name_offset)), a->name_length, ic, upcase, upcase_len)))) + { + /* + * If @name collates before a->name, + * there is no matching attribute. + */ + if (rc < 0) + { + errno = ENOENT; + return -1; + } + /* If the strings are not equal, continue search. */ + 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; - } + 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 *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; } /** @@ -2740,328 +2737,295 @@ char *ntfs_attr_name_get(const ntfschar *uname, const int uname_len) * EIO I/O error or corrupt data structures found. * 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) +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; + 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; -find_attr_list_attr: + 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 { - 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 + { + int rc; - if (name && ((rc = ntfs_names_full_collate(name, - name_len, al_name, al_name_len, ic, - vol->upcase, vol->upcase_len)))) { + if (name && ((rc = ntfs_names_full_collate(name, name_len, al_name, al_name_len, ic, vol->upcase, + vol->upcase_len)))) + { - /* - * If @name collates before al_name, - * there is no matching attribute. - */ - if (rc < 0) - goto not_found; - /* If the strings are not equal, continue search. */ - 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. - */ -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; - } -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; -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 @name collates before al_name, + * there is no matching attribute. + */ + if (rc < 0) goto not_found; + /* If the strings are not equal, continue search. */ + 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. + */ + 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; + } + 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; + 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; - 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; + } } /** @@ -3131,37 +3095,32 @@ not_found: * EIO I/O error or corrupt data structures 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) +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; + 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); -out: - ntfs_log_leave("\n"); - return ret; + 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; } /** @@ -3183,15 +3142,16 @@ out: */ 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; + 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; } /** @@ -3202,20 +3162,18 @@ 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) +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; + 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; } /** @@ -3229,21 +3187,21 @@ static void ntfs_attr_init_search_ctx(ntfs_attr_search_ctx *ctx, */ 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; + 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; } /** @@ -3262,17 +3220,17 @@ void ntfs_attr_reinit_search_ctx(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; + 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; } /** @@ -3283,8 +3241,8 @@ ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec) */ void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx) { - // NOTE: save errno if it could change and function stays void! - free(ctx); + // NOTE: save errno if it could change and function stays void! + free(ctx); } /** @@ -3301,30 +3259,28 @@ void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx) * ENOENT - The attribute @type is not specified in $AttrDef. * 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 *ntfs_attr_find_in_attrdef(const ntfs_volume *vol, const ATTR_TYPES type) { - ATTR_DEF *ad; + 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; } /** @@ -3342,45 +3298,45 @@ ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol, * ENOENT - The attribute @type is not specified in $AttrDef. * 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) +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; + 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; } /** @@ -3402,39 +3358,38 @@ 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). */ -static int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPES type, - const ntfschar *name, int name_len) +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; + 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; } /** @@ -3461,16 +3416,16 @@ static int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPE */ 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; + 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; } /** @@ -3489,42 +3444,43 @@ int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPES type) */ int ntfs_make_room_for_attr(MFT_RECORD *m, u8 *pos, u32 size) { - u32 biu; + 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; } /** @@ -3544,118 +3500,124 @@ int ntfs_make_room_for_attr(MFT_RECORD *m, u8 *pos, u32 size) * EEXIST - Attribute of such type and with same name already exists. * 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) +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; + 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 (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY - ? type == AT_INDEX_ROOT && name == NTFS_INDEX_I30 - : type == AT_DATA && name == AT_UNNAMED) { - ni->data_size = size; - ni->allocated_size = (size + 7) & ~7; - set_nino_flag(ni,KnownSize); - } - 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; + /* 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 (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY + ? type == AT_INDEX_ROOT && name == NTFS_INDEX_I30 + : type == AT_DATA && name == AT_UNNAMED) + { + ni->data_size = size; + ni->allocated_size = (size + 7) & ~7; + set_nino_flag(ni,KnownSize); + } + 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; } /** @@ -3676,131 +3638,128 @@ put_err_out: * name already exists. * 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) +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; + 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; -put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + } + 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; } /** @@ -3817,120 +3776,125 @@ put_err_out: */ int ntfs_attr_record_rm(ntfs_attr_search_ctx *ctx) { - ntfs_inode *base_ni, *ni; - ATTR_TYPES type; + ntfs_inode *base_ni, *ni; + ATTR_TYPES type; - 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"); - errno = 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"); + errno = 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; } /** @@ -3959,226 +3923,219 @@ 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) +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; + 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) - && (ni->vol->major_ver >= 3) - && NVolCompression(ni->vol) - && (ni->vol->cluster_size <= MAX_COMPRESSION_CLUSTER_SIZE) - && ((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_attr_record: if ((ni->flags & FILE_ATTR_COMPRESSED) && (ni->vol->major_ver >= 3) && NVolCompression(ni->vol) + && (ni->vol->cluster_size <= MAX_COMPRESSION_CLUSTER_SIZE) && ((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: + /* 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"); -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"); -err_out: - errno = err; - return -1; + 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"); + 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"); + err_out: errno = err; + return -1; } /* * Change an attribute flag */ -int ntfs_attr_set_flags(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, ATTR_FLAGS flags, ATTR_FLAGS mask) +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; + 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); } - /** * ntfs_attr_rm - remove attribute from ntfs inode * @na: opened ntfs attribute to delete @@ -4190,50 +4147,53 @@ int ntfs_attr_set_flags(ntfs_inode *ni, ATTR_TYPES type, */ int ntfs_attr_rm(ntfs_attr *na) { - ntfs_attr_search_ctx *ctx; - int ret = 0; + 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; } /** @@ -4255,52 +4215,53 @@ int ntfs_attr_rm(ntfs_attr *na) */ 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); + u32 old_size, alloc_size, attr_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; - } + old_size = le32_to_cpu(m->bytes_in_use); + alloc_size = le32_to_cpu(m->bytes_allocated); + attr_size = le32_to_cpu(a->length); - 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; + 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; } /** @@ -4317,28 +4278,23 @@ int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size) * ENOSPC - Not enough space in the mft record @m to perform the resize. * 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 ntfs_resident_attr_value_resize(MFT_RECORD *m, ATTR_RECORD *a, const u32 new_size) { - int ret; - - ntfs_log_trace("Entering for new size %u.\n", (unsigned)new_size); + int ret; - /* 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; + 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; } /** @@ -4353,84 +4309,83 @@ int ntfs_resident_attr_value_resize(MFT_RECORD *m, ATTR_RECORD *a, */ int ntfs_attr_record_move_to(ntfs_attr_search_ctx *ctx, ntfs_inode *ni) { - ntfs_attr_search_ctx *nctx; - ATTR_RECORD *a; - int err; + 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; -put_err_out: - ntfs_attr_put_search_ctx(nctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx(nctx); + return 0; + put_err_out: ntfs_attr_put_search_ctx(nctx); + errno = err; + return -1; } /** @@ -4448,75 +4403,75 @@ put_err_out: */ int ntfs_attr_record_move_away(ntfs_attr_search_ctx *ctx, int extra) { - ntfs_inode *base_ni, *ni; - MFT_RECORD *m; - int i; + 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; } /** @@ -4538,180 +4493,177 @@ int ntfs_attr_record_move_away(ntfs_attr_search_ctx *ctx, int extra) * 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. */ -int ntfs_attr_make_non_resident(ntfs_attr *na, - ntfs_attr_search_ctx *ctx) +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; + 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) { - if ((a->flags & ATTR_COMPRESSION_MASK) - == ATTR_IS_COMPRESSED) { - /* must allocate full compression blocks */ - new_allocated_size = ((new_allocated_size - 1) - | ((1L << (STANDARD_COMPRESSION_UNIT - + vol->cluster_size_bits)) - 1)) + 1; - } - /* 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); - NAttrSetBeingNonResident(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) + { + if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) + { + /* must allocate full compression blocks */ + new_allocated_size = ((new_allocated_size - 1) | ((1L << (STANDARD_COMPRESSION_UNIT + + vol->cluster_size_bits)) - 1)) + 1; + } + /* 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); + NAttrSetBeingNonResident(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; + 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; } - static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize); /** @@ -4732,252 +4684,249 @@ 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, - BOOL force_non_resident) +static int ntfs_resident_attr_resize_i(ntfs_attr *na, const s64 newsize, BOOL force_non_resident) { - ntfs_attr_search_ctx *ctx; - ntfs_volume *vol; - ntfs_inode *ni; - int err, ret = STATUS_ERROR; + 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) && !force_non_resident) { - /* 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->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY - ? na->type == AT_INDEX_ROOT && na->name == NTFS_INDEX_I30 - : na->type == AT_DATA && na->name == AT_UNNAMED) { - na->ni->data_size = na->data_size; - if (((na->data_flags & ATTR_COMPRESSION_MASK) - || NAttrSparse(na)) - && NAttrNonResident(na)) - na->ni->allocated_size - = na->compressed_size; - else - na->ni->allocated_size - = na->allocated_size; - set_nino_flag(na->ni,KnownSize); - if (na->type == AT_DATA) - 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) && !force_non_resident) + { + /* 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->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY ? na->type == AT_INDEX_ROOT && na->name == NTFS_INDEX_I30 + : na->type == AT_DATA && na->name == AT_UNNAMED) + { + na->ni->data_size = na->data_size; + if (((na->data_flags & ATTR_COMPRESSION_MASK) || NAttrSparse(na)) && NAttrNonResident(na)) + na->ni->allocated_size = na->compressed_size; + else na->ni->allocated_size = na->allocated_size; + set_nino_flag(na->ni,KnownSize); + if (na->type == AT_DATA) 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); - /* - * do not truncate when forcing non-resident, this - * could cause the attribute to be made resident again, - * so size changes are not allowed. - */ - if (force_non_resident) { - ret = 0; - if (newsize != na->data_size) { - ntfs_log_error("Cannot change size when" - " forcing non-resident\n"); - errno = EIO; - ret = STATUS_ERROR; - } - return (ret); - } - /* 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); + /* + * do not truncate when forcing non-resident, this + * could cause the attribute to be made resident again, + * so size changes are not allowed. + */ + if (force_non_resident) + { + ret = 0; + if (newsize != na->data_size) + { + ntfs_log_error("Cannot change size when" + " forcing non-resident\n"); + errno = EIO; + ret = STATUS_ERROR; + } + return (ret); + } + /* 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; - } - if (((tna->data_flags & ATTR_COMPRESSION_MASK) - == ATTR_IS_COMPRESSED) - && ntfs_attr_pclose(tna)) { - err = errno; - ntfs_attr_close(tna); - goto put_err_out; - } - ntfs_inode_mark_dirty(tna->ni); - ntfs_attr_close(tna); - ntfs_attr_put_search_ctx(ctx); - return ntfs_resident_attr_resize_i(na, newsize, force_non_resident); - } - /* 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_i(na, newsize, force_non_resident); - } + 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; + } + if (((tna->data_flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) && ntfs_attr_pclose(tna)) + { + err = errno; + ntfs_attr_close(tna); + goto put_err_out; + } + ntfs_inode_mark_dirty(tna->ni); + ntfs_attr_close(tna); + ntfs_attr_put_search_ctx(ctx); + return ntfs_resident_attr_resize_i(na, newsize, force_non_resident); + } + /* Check whether error occurred. */ + if (errno != ENOENT) + { + err = errno; + ntfs_log_perror("%s: Attribute lookup failed 1", __FUNCTION__); + goto put_err_out; + } - /* - * Move the attribute to a new mft record, creating an attribute list - * attribute or modifying it if it is already present. - */ + /* + * 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_i(na, newsize, force_non_resident); + } - /* 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; - } + /* + * Move the attribute to a new mft record, creating an attribute list + * attribute or modifying it if it is already present. + */ - /* - * 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; - } + /* 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; + } - /* 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_i(na, newsize, force_non_resident); - } - /* 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; + /* + * 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; + } - ntfs_attr_put_search_ctx(ctx); - /* Try to perform resize once again. */ - return ntfs_resident_attr_resize_i(na, newsize, force_non_resident); + /* 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_i(na, newsize, force_non_resident); + } + /* 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; -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; -put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return ret; + ntfs_attr_put_search_ctx(ctx); + /* Try to perform resize once again. */ + return ntfs_resident_attr_resize_i(na, newsize, force_non_resident); + + 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; + put_err_out: 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, FALSE); - ntfs_log_leave("\n"); - return ret; + int ret; + + ntfs_log_enter("Entering\n"); + ret = ntfs_resident_attr_resize_i(na, newsize, FALSE); + ntfs_log_leave("\n"); + return ret; } /* @@ -4997,15 +4946,16 @@ static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize) int ntfs_attr_force_non_resident(ntfs_attr *na) { - int res; + int res; - res = ntfs_resident_attr_resize_i(na, na->data_size, TRUE); - if (!res && !NAttrNonResident(na)) { - res = -1; - errno = EIO; - ntfs_log_error("Failed to force non-resident\n"); - } - return (res); + res = ntfs_resident_attr_resize_i(na, na->data_size, TRUE); + if (!res && !NAttrNonResident(na)) + { + res = -1; + errno = EIO; + ntfs_log_error("Failed to force non-resident\n"); + } + return (res); } /** @@ -5029,281 +4979,277 @@ int ntfs_attr_force_non_resident(ntfs_attr *na) */ 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_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"); - errno = 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"); + 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; - } + /* 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->vol->major_ver >= 3) - && NVolCompression(na->ni->vol) - && (na->ni->vol->cluster_size <= MAX_COMPRESSION_CLUSTER_SIZE) - && (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->vol->major_ver >= 3) && NVolCompression(na->ni->vol) + && (na->ni->vol->cluster_size <= MAX_COMPRESSION_CLUSTER_SIZE) && (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; } /* * If we are in the first extent, then set/clean sparse bit, * 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) +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_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; + int sparse, ret = 0; - a->allocated_size = cpu_to_sle64(na->allocated_size); + ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x\n", + (unsigned long long)na->ni->mft_no, na->type); - /* Update sparse bit. */ - sparse = ntfs_rl_sparse(na->rl); - if (sparse == -1) { - errno = EIO; - goto error; - } + if (a->lowest_vcn) goto out; - /* 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))) { + a->allocated_size = cpu_to_sle64(na->allocated_size); - 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)); + /* Update sparse bit. */ + sparse = ntfs_rl_sparse(na->rl); + if (sparse == -1) + { + errno = EIO; + goto error; + } - 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); - } + /* 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))) + { - /* 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); + 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; + } - a->mapping_pairs_offset = - cpu_to_le16(le16_to_cpu(a->mapping_pairs_offset) - 8); - } + NAttrSetSparse(na); + a->flags |= ATTR_IS_SPARSE; + a->compression_unit = STANDARD_COMPRESSION_UNIT; /* Windows + set it so, even if attribute is not actually compressed. */ - /* Update compressed size if required. */ - if (sparse || (na->data_flags & ATTR_COMPRESSION_MASK)) { - s64 new_compr_size; + memmove((u8*) a + le16_to_cpu(a->name_offset) + 8, (u8*) a + le16_to_cpu(a->name_offset), a->name_length + * sizeof(ntfschar)); - 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->data_flags & ATTR_COMPRESSION_MASK)) - 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; + 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); + } + + /* 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); + } + + /* 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->data_flags & ATTR_COMPRESSION_MASK)) + 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; } #define NTFS_VCN_DELETE_MARK -2 @@ -5312,328 +5258,321 @@ error: ret = -3; goto out; */ 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; - BOOL first_updated = FALSE; + 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; + BOOL first_updated = FALSE; -retry: - if (!na || !na->rl) { - errno = EINVAL; - ntfs_log_perror("%s: na=%p", __FUNCTION__, na); - return -1; - } + retry: if (!na || !na->rl) + { + 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 (!a->lowest_vcn) - first_updated = TRUE; - /* - * 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 (!a->lowest_vcn) first_updated = TRUE; + /* + * 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; - } - /* - * If the base extent was skipped in the above process, - * we still may have to update the sizes. - */ - if (!first_updated) { - le16 spcomp; + /* + * 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; + } + /* + * If the base extent was skipped in the above process, + * we still may have to update the sizes. + */ + if (!first_updated) + { + le16 spcomp; - ntfs_attr_reinit_search_ctx(ctx); - if (!ntfs_attr_lookup(na->type, na->name, na->name_len, - CASE_SENSITIVE, 0, NULL, 0, ctx)) { - a = ctx->attr; - a->allocated_size = cpu_to_sle64(na->allocated_size); - spcomp = na->data_flags - & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE); - if (spcomp) - a->compressed_size = cpu_to_sle64(na->compressed_size); - if ((na->type == AT_DATA) && (na->name == AT_UNNAMED)) { - na->ni->allocated_size - = (spcomp - ? na->compressed_size - : na->allocated_size); - NInoFileNameSetDirty(na->ni); - } - } else { - ntfs_log_error("Failed to update sizes in base extent\n"); - goto put_err_out; - } - } + ntfs_attr_reinit_search_ctx(ctx); + if (!ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) + { + a = ctx->attr; + a->allocated_size = cpu_to_sle64(na->allocated_size); + spcomp = na->data_flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE); + if (spcomp) a->compressed_size = cpu_to_sle64(na->compressed_size); + if ((na->type == AT_DATA) && (na->name == AT_UNNAMED)) + { + na->ni->allocated_size = (spcomp ? na->compressed_size : na->allocated_size); + NInoFileNameSetDirty(na->ni); + } + } + else + { + ntfs_log_error("Failed to update sizes in base extent\n"); + 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; - } -ok: - ret = 0; -out: - return ret; -put_err_out: - if (ctx) - ntfs_attr_put_search_ctx(ctx); - goto out; + 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; + out: return ret; + put_err_out: if (ctx) ntfs_attr_put_search_ctx(ctx); + goto out; } #undef NTFS_VCN_DELETE_MARK @@ -5664,12 +5603,12 @@ put_err_out: */ 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 ret; + + ntfs_log_enter("Entering\n"); + ret = ntfs_attr_update_mapping_pairs_i(na, from_vcn); + ntfs_log_leave("\n"); + return ret; } /** @@ -5686,141 +5625,147 @@ int ntfs_attr_update_mapping_pairs(ntfs_attr *na, VCN from_vcn) */ 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_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. */ - if (na->data_flags & ATTR_COMPRESSION_MASK) - /* - * For compressed files we must keep full compressions blocks, - * but currently we do not decompress/recompress the last - * block to truncate the data, so we may leave more allocated - * clusters than really needed. - */ - first_free_vcn = (((newsize - 1) - | (na->compression_block_size - 1)) + 1) - >> vol->cluster_size_bits; - else - 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. */ + if (na->data_flags & ATTR_COMPRESSION_MASK) + /* + * For compressed files we must keep full compressions blocks, + * but currently we do not decompress/recompress the last + * block to truncate the data, so we may leave more allocated + * clusters than really needed. + */ + first_free_vcn = (((newsize - 1) | (na->compression_block_size - 1)) + 1) >> vol->cluster_size_bits; + else 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->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { - if (na->type == AT_INDEX_ROOT && na->name == NTFS_INDEX_I30) { - na->ni->data_size = na->data_size; - na->ni->allocated_size = na->allocated_size; - set_nino_flag(na->ni,KnownSize); - } - } else { - 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->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + { + if (na->type == AT_INDEX_ROOT && na->name == NTFS_INDEX_I30) + { + na->ni->data_size = na->data_size; + na->ni->allocated_size = na->allocated_size; + set_nino_flag(na->ni,KnownSize); + } + } + else + { + 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; -put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + /* 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; } /** @@ -5839,215 +5784,224 @@ put_err_out: */ 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; + 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; - - 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; - } + /* + * 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 = 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[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; + } - /* 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; + 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; + } + } - /* 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; - } - } + /* 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; - 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; - } + /* 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; + } + } - 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; - } + 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; + } - /* Update data size. */ - na->data_size = newsize; - ctx->attr->data_size = cpu_to_sle64(newsize); - /* Update data size in the index. */ - if (na->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { - if (na->type == AT_INDEX_ROOT && na->name == NTFS_INDEX_I30) { - na->ni->data_size = na->data_size; - na->ni->allocated_size = na->allocated_size; - set_nino_flag(na->ni,KnownSize); - } - } else { - 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 >> - vol->cluster_size_bits*/)) { - 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; + 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->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + { + if (na->type == AT_INDEX_ROOT && na->name == NTFS_INDEX_I30) + { + na->ni->data_size = na->data_size; + na->ni->allocated_size = na->allocated_size; + set_nino_flag(na->ni,KnownSize); + } + } + else + { + 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 >> + vol->cluster_size_bits*/)) + { + 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; } - 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; + int ret; + + ntfs_log_enter("Entering\n"); + ret = ntfs_non_resident_attr_expand_i(na, newsize); + ntfs_log_leave("\n"); + return ret; } /** @@ -6072,79 +6026,77 @@ static int ntfs_non_resident_attr_expand(ntfs_attr *na, const s64 newsize) */ int ntfs_attr_truncate(ntfs_attr *na, const s64 newsize) { - int ret = STATUS_ERROR; - s64 fullsize; - BOOL compressed; + 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_trace("Cannot truncate encrypted attribute\n"); - 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)) { - 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 know 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 upsizing of compressed files - * unless being able to face the consequences ! - */ - if (compressed && newsize && (newsize > na->data_size)) - 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_trace("Cannot truncate encrypted attribute\n"); + 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)) + { + 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 know 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 upsizing of compressed files + * unless being able to face the consequences ! + */ + if (compressed && newsize && (newsize > na->data_size)) + 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 * @@ -6157,79 +6109,67 @@ out: static int stuff_hole(ntfs_attr *na, const s64 pos) { - s64 size; - s64 begin_size; - s64 end_size; - char *buf; - int ret; + 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); } /** @@ -6251,93 +6191,87 @@ static int stuff_hole(ntfs_attr *na, const s64 pos) * * 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) +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; -out: - ntfs_attr_close(na); -err_exit: - ntfs_log_leave("\n"); - return ret; + 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); + err_exit: + ntfs_log_leave("\n"); + return ret; } - - -int ntfs_attr_exist(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, - u32 name_len) +int ntfs_attr_exist(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, 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_attr_search_ctx *ctx; + int ret; - ntfs_attr_put_search_ctx(ctx); - - return !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_attr_put_search_ctx(ctx); + + return !ret; } -int ntfs_attr_remove(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, - u32 name_len) +int ntfs_attr_remove(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, u32 name_len) { - ntfs_attr *na; - int ret; + 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. */ @@ -6348,54 +6282,51 @@ int ntfs_attr_remove(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, 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; + 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; + u8 *buf, *lut; + s64 br = 0; + s64 total = 0; + s64 nr_free = 0; - lut = ntfs_init_lut256(); - if (!lut) - return -1; - - buf = ntfs_malloc(65536); - if (!buf) - goto out; + lut = ntfs_init_lut256(); + if (!lut) return -1; - 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; + 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); + out: free(lut); + if (!total || br < 0) return -1; + return nr_free; } diff --git a/source/libntfs/attrib.h b/source/libntfs/attrib.h index 43ab7f53..de9085d9 100644 --- a/source/libntfs/attrib.h +++ b/source/libntfs/attrib.h @@ -49,12 +49,10 @@ 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, +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, } ntfs_lcn_special_values; /** @@ -75,31 +73,28 @@ typedef enum { * any modification of the search context, to automagically get the next * 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; +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; }; 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); +extern ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, 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); +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); 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); +extern ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol, const ATTR_TYPES type); /** * ntfs_attrs_walk - syntactic sugar for walking all attributes in an inode @@ -128,8 +123,7 @@ extern ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol, */ 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); + return ntfs_attr_lookup(AT_UNUSED, NULL, 0, CASE_SENSITIVE, 0, NULL, 0, ctx); } /** @@ -174,34 +168,37 @@ static __inline__ int ntfs_attrs_walk(ntfs_attr_search_ctx *ctx) * @state contains NTFS attribute specific flags describing this attribute * 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; - s8 unused_runs; /* pre-reserved entries available */ +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; + s8 unused_runs; /* pre-reserved entries available */ }; /** * enum ntfs_attr_state_bits - bits for the state field in the ntfs_attr * structure */ -typedef enum { - NA_Initialized, /* 1: structure is initialized. */ - NA_NonResident, /* 1: Attribute is not resident. */ - NA_BeingNonResident, /* 1: Attribute is being made not resident. */ - NA_FullyMapped, /* 1: Attribute has been fully mapped */ - NA_ComprClosing, /* 1: Compressed attribute is being closed */ +typedef enum +{ + NA_Initialized, /* 1: structure is initialized. */ + NA_NonResident, /* 1: Attribute is not resident. */ + NA_BeingNonResident, /* 1: Attribute is being made not resident. */ + NA_FullyMapped, /* 1: Attribute has been fully mapped */ + NA_ComprClosing, +/* 1: Compressed attribute is being closed */ } ntfs_attr_state_bits; #define test_nattr_flag(na, flag) test_bit(NA_##flag, (na)->state) @@ -234,8 +231,8 @@ extern void NAttrSet##func_name(ntfs_attr *na); \ extern void NAttrClear##func_name(ntfs_attr *na); GenNAttrIno(Compressed, FILE_ATTR_COMPRESSED) -GenNAttrIno(Encrypted, FILE_ATTR_ENCRYPTED) -GenNAttrIno(Sparse, FILE_ATTR_SPARSE_FILE) +GenNAttrIno(Encrypted, FILE_ATTR_ENCRYPTED) +GenNAttrIno(Sparse, FILE_ATTR_SPARSE_FILE) #undef GenNAttrIno /** @@ -243,54 +240,46 @@ 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 - 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; +typedef union +{ + 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; } 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); +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); - /* 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); +/* 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); extern void ntfs_attr_close(ntfs_attr *na); -extern s64 ntfs_attr_pread(ntfs_attr *na, const s64 pos, s64 count, - void *b); -extern s64 ntfs_attr_pwrite(ntfs_attr *na, const s64 pos, s64 count, - const void *b); +extern s64 ntfs_attr_pread(ntfs_attr *na, const s64 pos, s64 count, void *b); +extern s64 ntfs_attr_pwrite(ntfs_attr *na, const s64 pos, s64 count, 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); +extern void *ntfs_attr_readall(ntfs_inode *ni, const ATTR_TYPES type, 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); -extern s64 ntfs_attr_mst_pwrite(ntfs_attr *na, const s64 pos, - s64 bk_cnt, const u32 bk_size, void *src); +extern s64 ntfs_attr_mst_pread(ntfs_attr *na, const s64 pos, 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); extern int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn); extern int ntfs_attr_map_whole_runlist(ntfs_attr *na); @@ -298,33 +287,26 @@ extern int ntfs_attr_map_whole_runlist(ntfs_attr *na); 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); -extern int ntfs_attr_can_be_resident(const ntfs_volume *vol, - const ATTR_TYPES type); -int ntfs_attr_make_non_resident(ntfs_attr *na, - ntfs_attr_search_ctx *ctx); +extern int ntfs_attr_size_bounds_check(const ntfs_volume *vol, const ATTR_TYPES type, const s64 size); +extern int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPES type); +int ntfs_attr_make_non_resident(ntfs_attr *na, ntfs_attr_search_ctx *ctx); int ntfs_attr_force_non_resident(ntfs_attr *na); 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); -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); +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); +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); 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); -extern int ntfs_attr_set_flags(ntfs_inode *ni, ATTR_TYPES type, - ntfschar *name, u8 name_len, ATTR_FLAGS flags, ATTR_FLAGS mask); +extern int ntfs_attr_add(ntfs_inode *ni, ATTR_TYPES type, 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); 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); +extern int ntfs_resident_attr_value_resize(MFT_RECORD *m, ATTR_RECORD *a, 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); @@ -360,16 +342,13 @@ 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 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); -extern int ntfs_attr_remove(ntfs_inode *ni, const ATTR_TYPES type, - ntfschar *name, u32 name_len); -extern s64 ntfs_attr_get_free_bits(ntfs_attr *na); +extern int ntfs_attr_exist(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, u32 name_len); +extern int ntfs_attr_remove(ntfs_inode *ni, const ATTR_TYPES type, 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 155315ee..5a4a7359 100644 --- a/source/libntfs/attrib_frag.c +++ b/source/libntfs/attrib_frag.c @@ -65,34 +65,36 @@ #define STANDARD_COMPRESSION_UNIT 4 -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' ) - }; +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' ) +}; 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 ( 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; + na->ni->flags |= flag; else - ntfs_log_trace( "Denied setting flag %d for not unnamed data " - "attribute\n", flag ); + 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; + na->ni->flags &= ~flag; } #define GenNAttrIno(func_name, flag) \ @@ -101,8 +103,8 @@ void NAttrSet##func_name(ntfs_attr *na) { NAttrSetFlag (na, flag); } \ void NAttrClear##func_name(ntfs_attr *na){ NAttrClearFlag(na, flag); } GenNAttrIno( Compressed, FILE_ATTR_COMPRESSED ) -GenNAttrIno( Encrypted, FILE_ATTR_ENCRYPTED ) -GenNAttrIno( Sparse, FILE_ATTR_SPARSE_FILE ) +GenNAttrIno( Encrypted, FILE_ATTR_ENCRYPTED ) +GenNAttrIno( Sparse, FILE_ATTR_SPARSE_FILE ) /** * ntfs_get_attribute_value_length - Find the length of an attribute @@ -121,7 +123,7 @@ s64 ntfs_get_attribute_value_length( const ATTR_RECORD *a ) } errno = 0; if ( a->non_resident ) - return sle64_to_cpu( a->data_size ); + return sle64_to_cpu( a->data_size ); return ( s64 )le32_to_cpu( a->value_length ); } @@ -137,7 +139,7 @@ s64 ntfs_get_attribute_value_length( const ATTR_RECORD *a ) * Returns: */ s64 ntfs_get_attribute_value( const ntfs_volume *vol, - const ATTR_RECORD *a, u8 *b ) + const ATTR_RECORD *a, u8 *b ) { runlist *rl; s64 total, r; @@ -158,7 +160,7 @@ s64 ntfs_get_attribute_value( const ntfs_volume *vol, 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 ) ); + "this yet.\n", le16_to_cpu( a->flags ) ); errno = EOPNOTSUPP; return 0; } @@ -247,15 +249,15 @@ s64 ntfs_get_attribute_value( const ntfs_volume *vol, * 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 ); + 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 ); + ntfs_log_perror( ESTR ); else if ( r < rl[i].length << - vol->cluster_size_bits ) + vol->cluster_size_bits ) { ntfs_log_debug( ESTR ": Ran out of input data.\n" ); errno = EIO; @@ -287,13 +289,13 @@ s64 ntfs_get_attribute_value( const ntfs_volume *vol, * 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 ); + 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 ); + ntfs_log_perror( ESTR ); else if ( r < rl[i].length << vol->cluster_size_bits ) { ntfs_log_debug( ESTR ": Ran out of input data.\n" ); @@ -327,16 +329,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 ) + 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; + na->name_len = name_len; else - na->name_len = 0; + na->name_len = 0; } /** @@ -355,23 +357,23 @@ 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 ) + 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 ); + NAttrSetNonResident( na ); if ( data_flags & ATTR_COMPRESSION_MASK ) - NAttrSetCompressed( na ); + NAttrSetCompressed( na ); if ( encrypted ) - NAttrSetEncrypted( na ); + NAttrSetEncrypted( na ); if ( sparse ) - NAttrSetSparse( na ); + NAttrSetSparse( na ); na->allocated_size = allocated_size; na->data_size = data_size; na->initialized_size = initialized_size; @@ -382,9 +384,9 @@ void ntfs_attr_init( ntfs_attr *na, const BOOL non_resident, na->compressed_size = compressed_size; na->compression_block_clusters = 1 << compression_unit; na->compression_block_size = 1 << ( compression_unit + - vol->cluster_size_bits ); + vol->cluster_size_bits ); na->compression_block_size_bits = ffs( - na->compression_block_size ) - 1; + na->compression_block_size ) - 1; } NAttrSetInitialized( na ); } @@ -406,7 +408,7 @@ 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 ) + ntfschar *name, u32 name_len ) { ntfs_attr_search_ctx *ctx; ntfs_attr *na = NULL; @@ -415,7 +417,7 @@ ntfs_attr *ntfs_attr_open( ntfs_inode *ni, const ATTR_TYPES type, BOOL cs; ntfs_log_enter( "Entering for inode %lld, attr 0x%x.\n", - ( unsigned long long )ni->mft_no, type ); + ( unsigned long long )ni->mft_no, type ); if ( !ni || !ni->vol || !ni->mrec ) { @@ -424,21 +426,21 @@ ntfs_attr *ntfs_attr_open( ntfs_inode *ni, const ATTR_TYPES type, } na = ntfs_calloc( sizeof( ntfs_attr ) ); if ( !na ) - goto out; + goto out; if ( name && name != AT_UNNAMED && name != NTFS_INDEX_I30 ) { name = ntfs_ucsndup( name, name_len ); if ( !name ) - goto err_out; + goto err_out; newname = name; } ctx = ntfs_attr_get_search_ctx( ni, NULL ); if ( !ctx ) - goto err_out; + goto err_out; if ( ntfs_attr_lookup( type, name, name_len, 0, 0, NULL, 0, ctx ) ) - goto put_err_out; + goto put_err_out; a = ctx->attr; @@ -447,9 +449,9 @@ ntfs_attr *ntfs_attr_open( ntfs_inode *ni, const ATTR_TYPES type, if ( a->name_length ) { name = ntfs_ucsndup( ( ntfschar* )( ( u8* )a + le16_to_cpu( - a->name_offset ) ), a->name_length ); + a->name_offset ) ), a->name_length ); if ( !name ) - goto put_err_out; + goto put_err_out; newname = name; name_len = a->name_length; } @@ -468,7 +470,7 @@ ntfs_attr *ntfs_attr_open( ntfs_inode *ni, const ATTR_TYPES type, * does not detect or fix them so we need to cope with it, too. */ if ( type == AT_ATTRIBUTE_LIST ) - a->flags = 0; + a->flags = 0; if ( ( type == AT_DATA ) && !a->initialized_size ) { @@ -482,19 +484,19 @@ ntfs_attr *ntfs_attr_open( ntfs_inode *ni, const ATTR_TYPES type, */ a->flags &= ~ATTR_COMPRESSION_MASK; if ( na->ni->flags & FILE_ATTR_COMPRESSED ) - a->flags |= ATTR_IS_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 ) ) ) ) + ( ( !( 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 ); + "(0x%x <> 0x%x)", ( unsigned long long )ni->mft_no, + a->flags, na->ni->flags ); goto put_err_out; } @@ -505,35 +507,35 @@ ntfs_attr *ntfs_attr_open( ntfs_inode *ni, const ATTR_TYPES type, { errno = EIO; ntfs_log_perror( "Compressed inode %lld attr 0x%x has " - "no compression unit", - ( unsigned long long )ni->mft_no, type ); + "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 ); + 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 ); + 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: + out: ntfs_log_leave( "\n" ); return na; -put_err_out: + put_err_out: ntfs_attr_put_search_ctx( ctx ); -err_out: + err_out: free( newname ); free( na ); na = NULL; @@ -550,13 +552,13 @@ err_out: void ntfs_attr_close( ntfs_attr *na ) { if ( !na ) - return; + return; if ( NAttrNonResident( na ) && na->rl ) - free( 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->name ); free( na ); } @@ -575,25 +577,25 @@ int ntfs_attr_map_runlist( ntfs_attr *na, VCN vcn ) 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 ); + ( 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; + return 0; ctx = ntfs_attr_get_search_ctx( na->ni, NULL ); if ( !ctx ) - return -1; + 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 ) ) + vcn, NULL, 0, ctx ) ) { runlist_element *rl; /* Decode the runlist. */ rl = ntfs_mapping_pairs_decompress( na->ni->vol, ctx->attr, - na->rl ); + na->rl ); if ( rl ) { na->rl = rl; @@ -627,11 +629,11 @@ int ntfs_attr_map_whole_runlist( ntfs_attr *na ) int ret = -1; ntfs_log_enter( "Entering for inode %llu, attr 0x%x.\n", - ( unsigned long long )na->ni->mft_no, na->type ); + ( unsigned long long )na->ni->mft_no, na->type ); ctx = ntfs_attr_get_search_ctx( na->ni, NULL ); if ( !ctx ) - goto out; + goto out; /* Map all attribute extents one by one. */ next_vcn = last_vcn = highest_vcn = 0; @@ -642,11 +644,11 @@ int ntfs_attr_map_whole_runlist( ntfs_attr *na ) int not_mapped = 0; if ( ntfs_rl_vcn_to_lcn( na->rl, next_vcn ) == LCN_RL_NOT_MAPPED ) - not_mapped = 1; + not_mapped = 1; if ( ntfs_attr_lookup( na->type, na->name, na->name_len, - CASE_SENSITIVE, next_vcn, NULL, 0, ctx ) ) - break; + CASE_SENSITIVE, next_vcn, NULL, 0, ctx ) ) + break; a = ctx->attr; @@ -654,9 +656,9 @@ int ntfs_attr_map_whole_runlist( ntfs_attr *na ) { /* Decode the runlist. */ rl = ntfs_mapping_pairs_decompress( na->ni->vol, - a, na->rl ); + a, na->rl ); if ( !rl ) - goto err_out; + goto err_out; na->rl = rl; } @@ -667,13 +669,13 @@ int ntfs_attr_map_whole_runlist( ntfs_attr *na ) { errno = EIO; ntfs_log_perror( "First extent of inode %llu " - "attribute has non-zero lowest_vcn", - ( unsigned long long )na->ni->mft_no ); + "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; + vol->cluster_size_bits; } /* Get the lowest vcn for the next extent. */ @@ -692,7 +694,7 @@ int ntfs_attr_map_whole_runlist( ntfs_attr *na ) { errno = EIO; ntfs_log_perror( "Inode %llu has corrupt attribute list", - ( unsigned long long )na->ni->mft_no ); + ( unsigned long long )na->ni->mft_no ); goto err_out; } } @@ -705,16 +707,16 @@ int ntfs_attr_map_whole_runlist( ntfs_attr *na ) { 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 ); + "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: + ret = 0; + err_out: ntfs_attr_put_search_ctx( ctx ); -out: + out: ntfs_log_leave( "\n" ); return ret; } @@ -746,15 +748,15 @@ LCN ntfs_attr_vcn_to_lcn( ntfs_attr *na, const VCN vcn ) BOOL is_retry = FALSE; if ( !na || !NAttrNonResident( na ) || vcn < 0 ) - return ( LCN )LCN_EINVAL; + 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 ); -retry: + 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; + return lcn; if ( !is_retry && !ntfs_attr_map_runlist( na, vcn ) ) { is_retry = TRUE; @@ -766,7 +768,7 @@ retry: * successfully, something is really badly wrong... */ if ( !is_retry || lcn == ( LCN )LCN_RL_NOT_MAPPED ) - return ( LCN )LCN_EIO; + return ( LCN )LCN_EIO; /* lcn contains the appropriate error code. */ return lcn; } @@ -803,20 +805,20 @@ runlist_element *ntfs_attr_find_vcn( ntfs_attr *na, const VCN 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: + ( unsigned long long )na->ni->mft_no, na->type, + ( long long )vcn ); + retry: rl = na->rl; if ( !rl ) - goto map_rl; + goto map_rl; if ( vcn < rl[0].vcn ) - goto map_rl; + goto map_rl; while ( rl->length ) { if ( vcn < rl[1].vcn ) { if ( rl->lcn >= ( LCN )LCN_HOLE ) - return rl; + return rl; break; } rl++; @@ -824,19 +826,19 @@ retry: switch ( rl->lcn ) { case ( LCN )LCN_RL_NOT_MAPPED: - goto map_rl; + goto map_rl; case ( LCN )LCN_ENOENT: - errno = ENOENT; - break; + errno = ENOENT; + break; case ( LCN )LCN_EINVAL: - errno = EINVAL; - break; + errno = EINVAL; + break; default: - errno = EIO; - break; + errno = EIO; + break; } return NULL; -map_rl: + map_rl: /* The @vcn is in an unmapped region, map the runlist and retry. */ if ( !is_retry && !ntfs_attr_map_runlist( na, vcn ) ) { @@ -850,18 +852,17 @@ map_rl: * in our code paths. */ if ( is_retry || errno == EINVAL || errno == ENOENT ) - errno = EIO; + errno = EIO; return NULL; } - #endif /** * 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 ) +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; @@ -871,20 +872,20 @@ static s64 ntfs_attr_getfragments_i( ntfs_attr *na, const s64 pos, s64 count, u6 /* 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) && 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; - } - */ + 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 @@ -892,15 +893,14 @@ static s64 ntfs_attr_getfragments_i( ntfs_attr *na, const s64 pos, s64 count, u6 * However, allow if mounted with efs_raw option */ vol = na->ni->vol; - if ( !vol->efs_raw && NAttrEncrypted( na ) && NAttrNonResident( na ) ) + if (!vol->efs_raw && NAttrEncrypted(na) && NAttrNonResident( na )) { errno = EACCES; //return -1; return -32; } - if ( !count ) - return 0; + if (!count) return 0; /* * Truncate reads beyond end of attribute, * but round to next 512 byte boundary for encrypted @@ -908,60 +908,57 @@ static s64 ntfs_attr_getfragments_i( ntfs_attr *na, const s64 pos, s64 count, u6 */ 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->ni->vol->efs_raw && (na->data_flags & ATTR_IS_ENCRYPTED) && NAttrNonResident( na )) { - if ( na->data_size != na->initialized_size ) + 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; + max_init = max_read = ((na->data_size + 511) & ~511) + 2; } - if ( pos + count > max_read ) + if (pos + count > max_read) { - if ( pos >= max_read ) - return 0; + 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 ) ) + if (!NAttrNonResident( na )) { return -34; // No resident files /* - ntfs_attr_search_ctx *ctx; - char *val; + 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; - */ + 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 + count > max_init) { - if ( pos >= max_init ) + if (pos >= max_init) { //memset(b, 0, count); return count; @@ -976,41 +973,39 @@ static s64 ntfs_attr_getfragments_i( ntfs_attr *na, const s64 pos, s64 count, u6 * 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 ) ) + 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++; - } - */ + 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 ) + 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 ) + if (errno == ENOENT) { errno = EIO; ntfs_log_perror( "%s: Failed to find VCN #1", __FUNCTION__ ); @@ -1023,43 +1018,43 @@ static s64 ntfs_attr_getfragments_i( ntfs_attr *na, const s64 pos, s64 count, u6 * 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 ) + ofs = pos - (rl->vcn << vol->cluster_size_bits); + for (; count; rl++, ofs = 0) { - if ( rl->lcn == LCN_RL_NOT_MAPPED ) + if (rl->lcn == LCN_RL_NOT_MAPPED) { - rl = ntfs_attr_find_vcn( na, rl->vcn ); - if ( !rl ) + rl = ntfs_attr_find_vcn(na, rl->vcn); + if (!rl) { - if ( errno == ENOENT ) + if (errno == ENOENT) { errno = EIO; ntfs_log_perror( "%s: Failed to find VCN #2", - __FUNCTION__ ); + __FUNCTION__ ); } goto rl_err_out; } /* Needed for case when runs merged. */ - ofs = pos + total - ( rl->vcn << vol->cluster_size_bits ); + ofs = pos + total - (rl->vcn << vol->cluster_size_bits); } - if ( !rl->length ) + 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) 0) { - if ( rl->lcn != ( LCN )LCN_HOLE ) + if (rl->lcn != (LCN) LCN_HOLE) { ntfs_log_perror( "%s: Bad run (%lld)", - __FUNCTION__, - ( long long )rl->lcn ); + __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 ); + vol->cluster_size_bits ) - ofs ); //memset(b, 0, to_read); /* Update progress counters. */ total += to_read; @@ -1069,58 +1064,51 @@ static s64 ntfs_attr_getfragments_i( ntfs_attr *na, const s64 pos, s64 count, u6 } /* It is a real lcn, read it into @dst. */ to_read = min( count, ( rl->length << vol->cluster_size_bits ) - - ofs ); -retry: + 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 ); + " %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 = 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 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 ) + ret = append_fragment(callback_data, off_sec, sector, count_sec); + if (ret) { - if ( ret < 0 ) return ret; + if (ret < 0) return ret; return -50; } /* If everything ok, update progress counters and continue. */ - if ( br > 0 ) + if (br > 0) { total += br; count -= br; b = b + br; } - if ( br == to_read ) - continue; + 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; + 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; + rl_err_out: if (total) return total; errno = EIO; //return -1; return -39; } - /** * ntfs_attr_pread - read from an attribute specified by an ntfs_attr structure * @na: ntfs attribute to read from @@ -1140,29 +1128,28 @@ rl_err_out: * to the return code of ntfs_pread(), or to EINVAL in case of invalid * 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 ntfs_attr_getfragments(ntfs_attr *na, const s64 pos, s64 count, u64 offset, _ntfs_frag_append_t append_fragment, + void *callback_data) { s64 ret; - if ( !na || !na->ni || !na->ni->vol || !callback_data || pos < 0 || count < 0 ) + 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 ); + __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; @@ -1180,7 +1167,7 @@ static int ntfs_attr_fill_zero( ntfs_attr *na, s64 pos, s64 count ) int ret = -1; ntfs_log_trace( "pos %lld, count %lld\n", ( long long )pos, - ( long long )count ); + ( long long )count ); if ( !na || pos < 0 || count < 0 ) { @@ -1190,7 +1177,7 @@ static int ntfs_attr_fill_zero( ntfs_attr *na, s64 pos, s64 count ) buf = ntfs_calloc( NTFS_BUF_SIZE ); if ( !buf ) - goto err_out; + goto err_out; rli = na->rl; ofsi = 0; @@ -1198,7 +1185,7 @@ static int ntfs_attr_fill_zero( ntfs_attr *na, s64 pos, s64 count ) while ( pos < end ) { while ( rli->length && ( ofsi + ( rli->length << - vol->cluster_size_bits ) <= pos ) ) + vol->cluster_size_bits ) <= pos ) ) { ofsi += ( rli->length << vol->cluster_size_bits ); rli++; @@ -1214,14 +1201,14 @@ static int ntfs_attr_fill_zero( ntfs_attr *na, s64 pos, s64 count ) } ret = 0; -err_free: + err_free: free( buf ); -err_out: + err_out: return ret; } static int ntfs_attr_fill_hole( ntfs_attr *na, s64 count, s64 *ofs, - runlist_element **rl, VCN *update_from ) + runlist_element **rl, VCN *update_from ) { s64 to_write; s64 need; @@ -1237,19 +1224,19 @@ static int ntfs_attr_fill_hole( ntfs_attr *na, s64 count, s64 *ofs, 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 ); + "%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; + 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 ); + "Please report to %s.\n", NTFS_DEV_LIST ); errno = EIO; goto err_out; } @@ -1268,9 +1255,9 @@ static int ntfs_attr_fill_hole( ntfs_attr *na, s64 count, s64 *ofs, * be updated */ if ( na->data_flags & ATTR_COMPRESSION_MASK ) - lcn_seek_from = rlc->lcn + rlc->length; + lcn_seek_from = rlc->lcn + rlc->length; else - lcn_seek_from = rlc->lcn + ( from_vcn - rlc->vcn ); + lcn_seek_from = rlc->lcn + ( from_vcn - rlc->vcn ); break; } } @@ -1285,14 +1272,14 @@ static int ntfs_attr_fill_hole( ntfs_attr *na, s64 count, s64 *ofs, { lcn_seek_from = rlc->lcn - ( rlc->vcn - from_vcn ); if ( lcn_seek_from < -1 ) - lcn_seek_from = -1; + lcn_seek_from = -1; break; } } } need = ( ( *ofs + to_write - 1 ) >> vol->cluster_size_bits ) - + 1 + ( *rl )->vcn - from_vcn; + + 1 + ( *rl )->vcn - from_vcn; if ( ( na->data_flags & ATTR_COMPRESSION_MASK ) && ( need < na->compression_block_clusters ) ) { @@ -1301,13 +1288,13 @@ static int ntfs_attr_fill_hole( ntfs_attr *na, s64 count, s64 *ofs, * We may need space to decompress existing compressed data. */ rlc = ntfs_cluster_alloc( vol, ( *rl )->vcn, ( *rl )->length, - lcn_seek_from, DATA_ZONE ); + lcn_seek_from, DATA_ZONE ); } else - rlc = ntfs_cluster_alloc( vol, from_vcn, need, - lcn_seek_from, DATA_ZONE ); + rlc = ntfs_cluster_alloc( vol, from_vcn, need, + lcn_seek_from, DATA_ZONE ); if ( !rlc ) - goto err_out; + goto err_out; *rl = ntfs_runlists_merge( na->rl, rlc ); /* @@ -1315,7 +1302,7 @@ static int ntfs_attr_fill_hole( ntfs_attr *na, s64 count, s64 *ofs, * available entry, so reserve it before it gets too late. */ if ( *rl && ( na->data_flags & ATTR_COMPRESSION_MASK ) ) - *rl = ntfs_rl_extend( *rl, 1 ); + *rl = ntfs_rl_extend( *rl, 1 ); if ( !*rl ) { eo = errno; @@ -1323,14 +1310,14 @@ static int ntfs_attr_fill_hole( ntfs_attr *na, s64 count, s64 *ofs, if ( ntfs_cluster_free_from_rl( vol, rlc ) ) { ntfs_log_perror( "Failed to free hot clusters. " - "Please run chkdsk /f" ); + "Please run chkdsk /f" ); } errno = eo; goto err_out; } na->rl = *rl; if ( *update_from == -1 ) - *update_from = from_vcn; + *update_from = from_vcn; *rl = ntfs_attr_find_vcn( na, cur_vcn ); if ( !*rl ) { @@ -1339,18 +1326,18 @@ static int ntfs_attr_fill_hole( ntfs_attr *na, s64 count, s64 *ofs, * 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 ); + "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 )++; + ( *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 ); + "Please report to the %s.\n", NTFS_DEV_LIST ); errno = EIO; goto err_out; } @@ -1358,8 +1345,8 @@ static int ntfs_attr_fill_hole( ntfs_attr *na, s64 count, s64 *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; + *ofs ) ) + goto err_out; } if ( ( *rl )->vcn < cur_vcn ) { @@ -1378,7 +1365,7 @@ static int ntfs_attr_fill_hole( ntfs_attr *na, s64 count, s64 *ofs, } ret = 0; -err_out: + err_out: return ret; } @@ -1417,16 +1404,17 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) int compressed_part; struct { - unsigned int undo_initialized_size : 1; - unsigned int undo_data_size : 1; - } need_to = { 0, 0 }; + 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 ); + "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 ) { @@ -1436,7 +1424,7 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) } vol = na->ni->vol; compressed = ( na->data_flags & ATTR_COMPRESSION_MASK ) - != const_cpu_to_le16( 0 ); + != const_cpu_to_le16( 0 ); /* * Encrypted attributes are only supported in raw mode. We return * access denied, which is what Windows NT4 does, too. @@ -1456,11 +1444,11 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) && ( na->type == AT_DATA ) && ( pos > na->initialized_size ) && stuff_hole( na, pos ) ) - goto errno_set; + 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 ); + && !pos && ( count == na->initialized_size ); /* * Writing to compressed files is currently restricted * to appending data. However we have to accept @@ -1468,13 +1456,13 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) * 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 ) ) ) ) ) + || ( ( 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; @@ -1482,7 +1470,7 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) } if ( !count ) - goto out; + 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. */ @@ -1496,7 +1484,7 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) } /* resizing may change the compression mode */ compressed = ( na->data_flags & ATTR_COMPRESSION_MASK ) - != const_cpu_to_le16( 0 ); + != const_cpu_to_le16( 0 ); need_to.undo_data_size = 1; } /* @@ -1511,7 +1499,7 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) { fullcount = na->data_size - pos; if ( count > fullcount ) - count = fullcount; + count = fullcount; } old_initialized_size = na->initialized_size; /* If it is a resident attribute, write the data to the mft record. */ @@ -1521,9 +1509,9 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) ctx = ntfs_attr_get_search_ctx( na->ni, NULL ); if ( !ctx ) - goto err_out; + goto err_out; if ( ntfs_attr_lookup( na->type, na->name, na->name_len, 0, - 0, NULL, 0, ctx ) ) + 0, NULL, 0, ctx ) ) { ntfs_log_perror( "%s: lookup failed", __FUNCTION__ ); goto err_out; @@ -1539,7 +1527,7 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) } memcpy( val + pos, b, count ); if ( ntfs_mft_record_write( vol, ctx->ntfs_ino->mft_no, - ctx->mrec ) ) + ctx->mrec ) ) { /* * NOTE: We are in a bad state at this moment. We have @@ -1560,7 +1548,7 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) if ( pos + count > na->initialized_size ) { if ( ntfs_attr_map_whole_runlist( na ) ) - goto err_out; + goto err_out; /* * For a compressed attribute, we must be sure there is an * available entry, and, when reopening a compressed file, @@ -1571,37 +1559,37 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) { na->rl = ntfs_rl_extend( na->rl, 2 ); if ( !na->rl ) - goto err_out; + goto err_out; } /* Set initialized_size to @pos + @count. */ ctx = ntfs_attr_get_search_ctx( na->ni, NULL ); if ( !ctx ) - goto err_out; + goto err_out; if ( ntfs_attr_lookup( na->type, na->name, na->name_len, 0, - 0, NULL, 0, ctx ) ) - goto err_out; + 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; + 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; + ctx->attr->data_size = ctx->attr->initialized_size; if ( ntfs_mft_record_write( vol, ctx->ntfs_ino->mft_no, - ctx->mrec ) ) + 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 ); + cpu_to_sle64( old_initialized_size ); ntfs_mft_record_write( vol, ctx->ntfs_ino->mft_no, - ctx->mrec ); + ctx->mrec ); goto err_out; } na->initialized_size = pos + count; @@ -1654,9 +1642,9 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) && wasnonresident ) { if ( rl->length < na->compression_block_clusters ) - compressed_part - = na->compression_block_clusters - - rl->length; + compressed_part + = na->compression_block_clusters + - rl->length; else { compressed_part @@ -1681,17 +1669,17 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) s64 xofs; if ( wasnonresident ) - compressed_part = na->compression_block_clusters - - rl[1].length; + 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; + rl->length << vol->cluster_size_bits, + &xofs, &rl, &update_from ) ) + goto err_out; /* the fist allocated cluster was not merged */ if ( !xofs ) - rl--; + rl--; } } /* @@ -1710,7 +1698,7 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) { errno = EIO; ntfs_log_perror( "%s: Failed to find VCN" - " #4", __FUNCTION__ ); + " #4", __FUNCTION__ ); } goto rl_err_out; } @@ -1731,13 +1719,13 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) { errno = EIO; ntfs_log_perror( "%s: Unexpected LCN (%lld)", - __FUNCTION__, - ( long long )rl->lcn ); + __FUNCTION__, + ( long long )rl->lcn ); goto rl_err_out; } if ( ntfs_attr_fill_hole( na, fullcount, &ofs, &rl, - &update_from ) ) - goto err_out; + &update_from ) ) + goto err_out; } if ( compressed ) { @@ -1751,10 +1739,10 @@ s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) /* It is a real lcn, write it to the volume. */ to_write = min( count, ( rl->length << vol->cluster_size_bits ) - ofs ); -retry: + 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 ); + "%lld.\n", ( long long )to_write, ( long long )rl->vcn, + ( long long )rl->lcn, ( long long )ofs ); if ( !NVolReadOnly( vol ) ) { @@ -1774,7 +1762,7 @@ retry: * data is generally first written uncompressed. */ if ( rounding && ( ( wend == na->initialized_size ) || - ( wend < ( hole_end << vol->cluster_size_bits ) ) ) ) + ( wend < ( hole_end << vol->cluster_size_bits ) ) ) ) { char *cb; @@ -1783,7 +1771,7 @@ retry: cb = ntfs_malloc( rounding ); if ( !cb ) - goto err_out; + goto err_out; memcpy( cb, b, to_write ); memset( cb + to_write, 0, rounding - to_write ); @@ -1791,15 +1779,15 @@ retry: if ( compressed ) { written = ntfs_compressed_pwrite( na, - rl, wpos, ofs, to_write, - rounding, b, compressed_part ); + rl, wpos, ofs, to_write, + rounding, b, compressed_part ); } else { written = ntfs_pwrite( vol->dev, wpos, - rounding, cb ); + rounding, cb ); if ( written == rounding ) - written = to_write; + written = to_write; } free( cb ); @@ -1809,16 +1797,16 @@ retry: if ( compressed ) { written = ntfs_compressed_pwrite( na, - rl, wpos, ofs, to_write, - to_write, b, compressed_part ); + rl, wpos, ofs, to_write, + to_write, b, compressed_part ); } else - written = ntfs_pwrite( vol->dev, wpos, - to_write, b ); + written = ntfs_pwrite( vol->dev, wpos, + to_write, b ); } } else - written = to_write; + written = to_write; /* If everything ok, update progress counters and continue. */ if ( written > 0 ) { @@ -1832,39 +1820,39 @@ retry: /* Partial write cannot be dealt with, stop there */ /* If the syscall was interrupted, try again. */ if ( written == ( s64 ) - 1 && errno == EINTR ) - goto retry; + goto retry; if ( !written ) - errno = EIO; + errno = EIO; goto rl_err_out; } compressed_part = 0; } -done: + done: if ( ctx ) - ntfs_attr_put_search_ctx( 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: + 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: + rl_err_out: eo = errno; if ( total ) { if ( need_to.undo_initialized_size ) { if ( pos + total > na->initialized_size ) - goto done; + goto done; /* * TODO: Need to try to change initialized_size. If it * succeeds goto done, otherwise goto err_out. (AIA) @@ -1874,7 +1862,7 @@ rl_err_out: goto done; } errno = eo; -err_out: + err_out: eo = errno; if ( need_to.undo_initialized_size ) { @@ -1885,22 +1873,22 @@ err_out: { ctx = ntfs_attr_get_search_ctx( na->ni, NULL ); if ( !ctx ) - err = 1; + err = 1; } else - ntfs_attr_reinit_search_ctx( ctx ); + ntfs_attr_reinit_search_ctx( ctx ); if ( !err ) { err = ntfs_attr_lookup( na->type, na->name, - na->name_len, 0, 0, NULL, 0, ctx ); + 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 ); + old_initialized_size ); err = ntfs_mft_record_write( vol, - ctx->ntfs_ino->mft_no, - ctx->mrec ); + ctx->ntfs_ino->mft_no, + ctx->mrec ); } } if ( err ) @@ -1911,20 +1899,20 @@ err_out: * data or at least zeroes. (AIA) */ ntfs_log_error( "Eeek! Failed to recover from error. " - "Leaving metadata in inconsistent " - "state! Run chkdsk!\n" ); + "Leaving metadata in inconsistent " + "state! Run chkdsk!\n" ); } } if ( ctx ) - ntfs_attr_put_search_ctx( 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*/ ); + 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" ); + ntfs_log_perror( "Failed to restore data_size" ); errno = eo; -errno_set: + errno_set: total = -1; goto out; } @@ -1943,7 +1931,7 @@ int ntfs_attr_pclose( ntfs_attr *na ) BOOL compressed; ntfs_log_enter( "Entering for inode 0x%llx, attr 0x%x.\n", - na->ni->mft_no, na->type ); + na->ni->mft_no, na->type ); if ( !na || !na->ni || !na->ni->vol ) { @@ -1953,7 +1941,7 @@ int ntfs_attr_pclose( ntfs_attr *na ) } vol = na->ni->vol; compressed = ( na->data_flags & ATTR_COMPRESSION_MASK ) - != const_cpu_to_le16( 0 ); + != const_cpu_to_le16( 0 ); /* * Encrypted non-resident attributes are not supported. We return * access denied, which is what Windows NT4 does, too. @@ -1966,17 +1954,17 @@ int ntfs_attr_pclose( ntfs_attr *na ) /* If this is not a compressed attribute get out */ /* same if it is resident */ if ( !compressed || !NAttrNonResident( na ) ) - goto out; + 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; + goto err_out; na->rl = ntfs_rl_extend( na->rl, 1 ); if ( !na->rl ) - goto err_out; + 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 ) @@ -2000,21 +1988,21 @@ int ntfs_attr_pclose( ntfs_attr *na ) */ compressed_part = 0; if ( ( rl->lcn >= 0 ) && ( rl[1].lcn == ( LCN )LCN_HOLE ) ) - compressed_part - = na->compression_block_clusters - rl[1].length; + 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; + compressed_part + = na->compression_block_clusters + - rl->length; else - compressed_part - = na->compression_block_clusters; + compressed_part + = na->compression_block_clusters; } /* done, if the last block set was compressed */ if ( compressed_part ) - goto out; + goto out; ofs = na->initialized_size - ( rl->vcn << vol->cluster_size_bits ); @@ -2027,7 +2015,7 @@ int ntfs_attr_pclose( ntfs_attr *na ) { errno = EIO; ntfs_log_perror( "%s: Failed to find VCN" - " #6", __FUNCTION__ ); + " #6", __FUNCTION__ ); } goto rl_err_out; } @@ -2047,13 +2035,13 @@ int ntfs_attr_pclose( ntfs_attr *na ) { errno = EIO; ntfs_log_perror( "%s: Unexpected LCN (%lld)", - __FUNCTION__, - ( long long )rl->lcn ); + __FUNCTION__, + ( long long )rl->lcn ); goto rl_err_out; } if ( ntfs_attr_fill_hole( na, ( s64 )0, &ofs, &rl, &update_from ) ) - goto err_out; + goto err_out; } while ( rl->length && ( ofs >= ( rl->length << vol->cluster_size_bits ) ) ) @@ -2062,27 +2050,27 @@ int ntfs_attr_pclose( ntfs_attr *na ) rl++; } -retry: + retry: if ( !NVolReadOnly( vol ) ) { written = ntfs_compressed_close( na, rl, ofs ); /* If everything ok, update progress counters and continue. */ if ( !written ) - goto done; + goto done; } /* If the syscall was interrupted, try again. */ if ( written == ( s64 ) - 1 && errno == EINTR ) - goto retry; + goto retry; if ( !written ) - errno = EIO; + errno = EIO; goto rl_err_out; -done: + done: if ( ctx ) - ntfs_attr_put_search_ctx( ctx ); + ntfs_attr_put_search_ctx( ctx ); /* Update mapping pairs if needed. */ - if ( ntfs_attr_update_mapping_pairs( na, 0 /*update_from*/ ) ) + if ( ntfs_attr_update_mapping_pairs( na, 0 /*update_from*/) ) { /* * FIXME: trying to recover by goto rl_err_out; @@ -2091,24 +2079,24 @@ done: ok = FALSE; goto out; } -out: + out: ntfs_log_leave( "\n" ); return ( !ok ); -rl_err_out: + 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. */ -err_out: + err_out: eo = errno; if ( ctx ) - ntfs_attr_put_search_ctx( ctx ); + ntfs_attr_put_search_ctx( ctx ); /* Update mapping pairs if needed. */ - ntfs_attr_update_mapping_pairs( na, 0 /*update_from*/ ); + ntfs_attr_update_mapping_pairs( na, 0 /*update_from*/); errno = eo; -errno_set: + errno_set: ok = FALSE; goto out; } @@ -2143,14 +2131,14 @@ 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 ) + 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 ); + ( unsigned long long )na->ni->mft_no, na->type, + ( long long )pos ); if ( bk_cnt < 0 || bk_size % NTFS_BLOCK_SIZE ) { errno = EINVAL; @@ -2159,11 +2147,11 @@ s64 ntfs_attr_mst_pread( ntfs_attr *na, const s64 pos, const s64 bk_cnt, } br = ntfs_attr_pread( na, pos, bk_cnt * bk_size, dst ); if ( br <= 0 ) - return br; + 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 ); + ntfs_mst_post_read_fixup( ( NTFS_RECORD* )dst, bk_size ); /* Finally, return the number of blocks read. */ return br; } @@ -2199,33 +2187,33 @@ 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 ) + 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 ); + ( 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; + 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 ); + ( ( 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; + return err; bk_cnt = i; break; } @@ -2235,14 +2223,14 @@ s64 ntfs_attr_mst_pwrite( ntfs_attr *na, const s64 pos, s64 bk_cnt, if ( written <= 0 ) { ntfs_log_perror( "%s: written=%lld", __FUNCTION__, - ( long long )written ); + ( 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 ) ); + ntfs_mst_post_write_fixup( ( NTFS_RECORD* )( ( u8* )src + i * + bk_size ) ); if ( written <= 0 ) - return written; + return written; /* Finally, return the number of complete blocks written. */ return written / bk_size; } @@ -2318,8 +2306,8 @@ 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 ) + 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; @@ -2356,28 +2344,28 @@ static int ntfs_attr_find( const ATTR_TYPES type, const ntfschar *name, 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 ) ) ) + 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; + break; ctx->attr = a; if ( ( ( type != AT_UNUSED ) && ( le32_to_cpu( a->type ) > - le32_to_cpu( type ) ) ) || + le32_to_cpu( type ) ) ) || ( a->type == AT_END ) ) { errno = ENOENT; return -1; } if ( !a->length ) - break; + break; /* If this is an enumeration return this attribute. */ if ( type == AT_UNUSED ) - return 0; + return 0; if ( a->type != type ) - continue; + continue; /* * If @name is AT_UNNAMED we want an unnamed attribute. * If @name is present, compare the two names. @@ -2393,16 +2381,16 @@ static int ntfs_attr_find( const ATTR_TYPES type, const ntfschar *name, } } 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 ) ) + ( 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 ); + ( 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. @@ -2414,19 +2402,19 @@ static int ntfs_attr_find( const ATTR_TYPES type, const ntfschar *name, } /* If the strings are not equal, continue search. */ if ( rc ) - continue; + 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 ); + ( 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; + continue; } /* * The names match or @name not present and attribute is @@ -2434,15 +2422,15 @@ static int ntfs_attr_find( const ATTR_TYPES type, const ntfschar *name, * and are done. */ if ( !val ) - return 0; + 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 ) ) ); + min( val_len, + le32_to_cpu( a->value_length ) ) ); /* * If @val collates before the current attribute's * value, there is no matching attribute. @@ -2452,7 +2440,7 @@ static int ntfs_attr_find( const ATTR_TYPES type, const ntfschar *name, register u32 avl; avl = le32_to_cpu( a->value_length ); if ( val_len == avl ) - return 0; + return 0; if ( val_len < avl ) { errno = ENOENT; @@ -2468,7 +2456,7 @@ static int ntfs_attr_find( const ATTR_TYPES type, const ntfschar *name, } errno = EIO; ntfs_log_perror( "%s: Corrupt inode (%lld)", __FUNCTION__, - ctx->ntfs_ino ? ( long long )ctx->ntfs_ino->mft_no : -1 ); + ctx->ntfs_ino ? ( long long )ctx->ntfs_ino->mft_no : -1 ); return -1; } @@ -2494,7 +2482,7 @@ char *ntfs_attr_name_get( const ntfschar *uname, const int uname_len ) } else if ( name_len > 0 ) - return name; + return name; ntfs_attr_name_free( &name ); return NULL; @@ -2571,9 +2559,9 @@ 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 ) + 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; @@ -2587,7 +2575,7 @@ static int ntfs_external_attr_find( ATTR_TYPES type, const ntfschar *name, 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 ); + ( unsigned long long )ni->mft_no, type ); if ( !base_ni ) { /* First call happens with the base mft record. */ @@ -2595,9 +2583,9 @@ static int ntfs_external_attr_find( ATTR_TYPES type, const ntfschar *name, ctx->base_mrec = ctx->mrec; } if ( ni == base_ni ) - ctx->base_attr = ctx->attr; + ctx->base_attr = ctx->attr; if ( type == AT_END ) - goto not_found; + goto not_found; vol = base_ni->vol; al_start = base_ni->attr_list; al_end = al_start + base_ni->attr_list_size; @@ -2622,12 +2610,12 @@ static int ntfs_external_attr_find( ATTR_TYPES type, const ntfschar *name, if ( ( type == AT_UNUSED ) && is_first_search && le32_to_cpu( al_entry->type ) > le32_to_cpu( AT_ATTRIBUTE_LIST ) ) - goto find_attr_list_attr; + goto find_attr_list_attr; } else { al_entry = ( ATTR_LIST_ENTRY* )( ( char* )ctx->al_entry + - le16_to_cpu( ctx->al_entry->length ) ); + 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 @@ -2640,7 +2628,7 @@ static int ntfs_external_attr_find( ATTR_TYPES type, const ntfschar *name, le32_to_cpu( AT_ATTRIBUTE_LIST ) ) { int rc; -find_attr_list_attr: + find_attr_list_attr: /* Check for bogus calls. */ if ( name || name_len || val || val_len || lowest_vcn ) @@ -2656,11 +2644,11 @@ find_attr_list_attr: ctx->is_first = TRUE; /* Sanity checks are performed elsewhere. */ ctx->attr = ( ATTR_RECORD* )( ( u8* )ctx->mrec + - le16_to_cpu( ctx->mrec->attrs_offset ) ); + 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 ); + IGNORE_CASE, NULL, 0, ctx ); /* * Setup the search context so the correct @@ -2671,11 +2659,11 @@ find_attr_list_attr: /* Got it. Done. */ if ( !rc ) - return 0; + return 0; /* Error! If other than not found return it. */ if ( errno != ENOENT ) - return rc; + return rc; /* Not found?!? Absurd! */ errno = EIO; @@ -2683,29 +2671,29 @@ find_attr_list_attr: return -1; } } - for ( ;; al_entry = next_al_entry ) + 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. */ + 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; + goto not_found; if ( !al_entry->length ) - break; + break; if ( ( u8* )al_entry + 6 > al_end || ( u8* )al_entry + le16_to_cpu( al_entry->length ) > al_end ) - break; + break; next_al_entry = ( ATTR_LIST_ENTRY* )( ( u8* )al_entry + - le16_to_cpu( al_entry->length ) ); + le16_to_cpu( al_entry->length ) ); if ( type != AT_UNUSED ) { if ( le32_to_cpu( al_entry->type ) > le32_to_cpu( type ) ) - goto not_found; + goto not_found; if ( type != al_entry->type ) - continue; + continue; } al_name_len = al_entry->name_length; al_name = ( ntfschar* )( ( u8* )al_entry + al_entry->name_offset ); @@ -2714,7 +2702,7 @@ find_attr_list_attr: * attribute list entry. */ if ( type == AT_UNUSED ) - goto is_enumeration; + goto is_enumeration; /* * If @name is AT_UNNAMED we want an unnamed attribute. * If @name is present, compare the two names. @@ -2723,26 +2711,26 @@ find_attr_list_attr: if ( name == AT_UNNAMED ) { if ( al_name_len ) - goto not_found; + goto not_found; } else if ( name && !ntfs_names_are_equal( al_name, al_name_len, - name, name_len, ic, vol->upcase, - vol->upcase_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 ); + 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; + goto not_found; /* If the strings are not equal, continue search. */ if ( rc ) - continue; + continue; /* * FIXME: Reverse engineering showed 0, IGNORE_CASE but * that is inconsistent with ntfs_attr_find(). The @@ -2752,12 +2740,12 @@ find_attr_list_attr: * on... (AIA) */ rc = ntfs_names_collate( name, name_len, al_name, - al_name_len, 1, CASE_SENSITIVE, - vol->upcase, vol->upcase_len ); + al_name_len, 1, CASE_SENSITIVE, + vol->upcase, vol->upcase_len ); if ( rc == -1 ) - goto not_found; + goto not_found; if ( rc ) - continue; + continue; } /* * The names match or @name not present and attribute is @@ -2765,34 +2753,34 @@ find_attr_list_attr: * 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 && + 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 && + 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 && + 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: + 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 ) ) + ni->mrec->sequence_number ) ) { ntfs_log_error( "Found stale mft reference in " - "attribute list!\n" ); + "attribute list!\n" ); break; } } - else /* Mft references do not match. */ + else /* Mft references do not match. */ { /* Do we want the base record back? */ if ( MREF_LE( al_entry->mft_reference ) == @@ -2805,15 +2793,15 @@ is_enumeration: { /* We want an extent record. */ ni = ntfs_extent_inode_open( base_ni, - al_entry->mft_reference ); + al_entry->mft_reference ); if ( !ni ) - break; + break; ctx->ntfs_ino = ni; ctx->mrec = ni->mrec; } } a = ctx->attr = ( ATTR_RECORD* )( ( char* )ctx->mrec + - le16_to_cpu( ctx->mrec->attrs_offset ) ); + 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 @@ -2831,29 +2819,29 @@ is_enumeration: * Use a manual loop so we can still use break and continue * with the same meanings as above. */ -do_next_attr_loop: + do_next_attr_loop: if ( ( char* )a < ( char* )ctx->mrec || ( char* )a > ( char* )ctx->mrec + le32_to_cpu( ctx->mrec->bytes_allocated ) ) - break; + break; if ( a->type == AT_END ) - continue; + continue; if ( !a->length ) - break; + break; if ( al_entry->instance != a->instance ) - goto do_next_attr; + 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; + 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; + 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 @@ -2861,13 +2849,13 @@ do_next_attr_loop: * 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 ) ) ) + 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: + 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; @@ -2881,7 +2869,7 @@ do_next_attr: errno = EIO; ntfs_log_perror( "Inode is corrupt (%lld)", ( long long )base_ni->mft_no ); return -1; -not_found: + 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 @@ -2891,7 +2879,7 @@ not_found: { ntfs_attr_reinit_search_ctx( ctx ); return ntfs_attr_find( AT_END, name, name_len, ic, val, val_len, - ctx ); + ctx ); } /* * The attribute wasn't found. Before we return, we want to ensure @@ -2908,7 +2896,7 @@ not_found: */ ctx->mrec = ctx->base_mrec; ctx->attr = ( ATTR_RECORD* )( ( u8* )ctx->mrec + - le16_to_cpu( ctx->mrec->attrs_offset ) ); + le16_to_cpu( ctx->mrec->attrs_offset ) ); ctx->is_first = TRUE; ctx->ntfs_ino = ctx->base_ntfs_ino; ctx->base_ntfs_ino = NULL; @@ -2927,7 +2915,7 @@ not_found: do { ret = ntfs_attr_find( type, name, name_len, ic, val, - val_len, ctx ); + val_len, ctx ); } while ( !ret ); return ret; @@ -3002,9 +2990,9 @@ 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 ) + 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; @@ -3013,8 +3001,8 @@ int ntfs_attr_lookup( const ATTR_TYPES type, const ntfschar *name, 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 ) ) ) + ( !ctx->ntfs_ino || !( vol = ctx->ntfs_ino->vol ) || + !vol->upcase || !vol->upcase_len ) ) ) { errno = EINVAL; ntfs_log_perror( "%s", __FUNCTION__ ); @@ -3022,15 +3010,15 @@ int ntfs_attr_lookup( const ATTR_TYPES type, const ntfschar *name, } if ( ctx->base_ntfs_ino ) - base_ni = ctx->base_ntfs_ino; + base_ni = ctx->base_ntfs_ino; else - base_ni = ctx->ntfs_ino; + 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 ); + 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: + ret = ntfs_external_attr_find( type, name, name_len, ic, + lowest_vcn, val, val_len, ctx ); + out: ntfs_log_leave( "\n" ); return ret; } @@ -3057,7 +3045,7 @@ 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; + return -1; if ( ctx->attr->type == AT_END ) { errno = ENOSPC; @@ -3076,10 +3064,10 @@ 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 ) + ntfs_inode *ni, MFT_RECORD *mrec ) { if ( !mrec ) - mrec = ni->mrec; + mrec = ni->mrec; ctx->mrec = mrec; /* Sanity checks are performed elsewhere. */ ctx->attr = ( ATTR_RECORD* )( ( u8* )mrec + le16_to_cpu( mrec->attrs_offset ) ); @@ -3108,7 +3096,7 @@ void ntfs_attr_reinit_search_ctx( ntfs_attr_search_ctx *ctx ) ctx->is_first = TRUE; /* Sanity checks are performed elsewhere. */ ctx->attr = ( ATTR_RECORD* )( ( u8* )ctx->mrec + - le16_to_cpu( ctx->mrec->attrs_offset ) ); + 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. @@ -3146,7 +3134,7 @@ ntfs_attr_search_ctx *ntfs_attr_get_search_ctx( ntfs_inode *ni, MFT_RECORD *mrec } ctx = ntfs_malloc( sizeof( ntfs_attr_search_ctx ) ); if ( ctx ) - ntfs_attr_init_search_ctx( ctx, ni, mrec ); + ntfs_attr_init_search_ctx( ctx, ni, mrec ); return ctx; } @@ -3177,7 +3165,7 @@ 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 ) + const ATTR_TYPES type ) { ATTR_DEF *ad; @@ -3192,10 +3180,10 @@ ATTR_DEF *ntfs_attr_find_in_attrdef( const ntfs_volume *vol, { /* We haven't found it yet, carry on searching. */ if ( le32_to_cpu( ad->type ) < le32_to_cpu( type ) ) - continue; + continue; /* We found the attribute; return it. */ if ( ad->type == type ) - return ad; + return ad; /* We have gone too far already. No point in continuing. */ break; } @@ -3220,7 +3208,7 @@ 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 ) + const s64 size ) { ATTR_DEF *ad; s64 min_size, max_size; @@ -3229,7 +3217,7 @@ int ntfs_attr_size_bounds_check( const ntfs_volume *vol, const ATTR_TYPES type, { errno = EINVAL; ntfs_log_perror( "%s: size=%lld", __FUNCTION__, - ( long long )size ); + ( long long )size ); return -1; } @@ -3246,7 +3234,7 @@ int ntfs_attr_size_bounds_check( const ntfs_volume *vol, const ATTR_TYPES type, ad = ntfs_attr_find_in_attrdef( vol, type ); if ( !ad ) - return -1; + return -1; min_size = sle64_to_cpu( ad->min_size ); max_size = sle64_to_cpu( ad->max_size ); @@ -3256,8 +3244,8 @@ int ntfs_attr_size_bounds_check( const ntfs_volume *vol, const ATTR_TYPES type, { 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 ); + "%lld,%lld,%lld)", type, ( long long )min_size, + ( long long )size, ( long long )max_size ); return -1; } return 0; @@ -3285,7 +3273,7 @@ int ntfs_attr_can_be_non_resident( const ntfs_volume *vol, const ATTR_TYPES type /* Find the attribute definition record in $AttrDef. */ ad = ntfs_attr_find_in_attrdef( vol, type ); if ( !ad ) - return -1; + return -1; /* Check the flags and return the result. */ if ( ad->flags & ATTR_DEF_RESIDENT ) { @@ -3326,7 +3314,7 @@ int ntfs_attr_can_be_resident( const ntfs_volume *vol, const ATTR_TYPES type ) return -1; } if ( type != AT_INDEX_ALLOCATION ) - return 0; + return 0; ntfs_log_trace( "Attribute can't be resident\n" ); errno = EPERM; @@ -3352,7 +3340,7 @@ 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 ); + ( int )( pos - ( u8* )m ), ( unsigned ) size ); /* Make size 8-byte alignment. */ size = ( size + 7 ) & ~7; @@ -3372,7 +3360,7 @@ int ntfs_make_room_for_attr( MFT_RECORD *m, u8 *pos, u32 size ) } /* Nothing to do. */ if ( !size ) - return 0; + return 0; biu = le32_to_cpu( m->bytes_in_use ); /* Do we have enough space? */ @@ -3408,8 +3396,8 @@ 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 ) + ntfschar *name, u8 name_len, u8 *val, u32 size, + ATTR_FLAGS data_flags ) { ntfs_attr_search_ctx *ctx; u32 length; @@ -3419,7 +3407,7 @@ int ntfs_resident_attr_record_add( ntfs_inode *ni, ATTR_TYPES type, 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 ); + ( long long ) ni->mft_no, ( unsigned ) type, ( unsigned ) data_flags ); if ( !ni || ( !name && name_len ) ) { @@ -3430,23 +3418,23 @@ int ntfs_resident_attr_record_add( ntfs_inode *ni, ATTR_TYPES type, if ( ntfs_attr_can_be_resident( ni->vol, type ) ) { if ( errno == EPERM ) - ntfs_log_trace( "Attribute can't be resident.\n" ); + ntfs_log_trace( "Attribute can't be resident.\n" ); else - ntfs_log_trace( "ntfs_attr_can_be_resident failed.\n" ); + 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; + 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 ) ) + ctx ) ) { err = EEXIST; ntfs_log_trace( "Attribute already present.\n" ); @@ -3462,8 +3450,8 @@ int ntfs_resident_attr_record_add( ntfs_inode *ni, ATTR_TYPES type, /* Make room for attribute. */ length = offsetof( ATTR_RECORD, resident_end ) + - ( ( name_len * sizeof( ntfschar ) + 7 ) & ~7 ) + - ( ( size + 7 ) & ~7 ); + ( ( name_len * sizeof( ntfschar ) + 7 ) & ~7 ) + + ( ( size + 7 ) & ~7 ); if ( ntfs_make_room_for_attr( ctx->mrec, ( u8* ) ctx->attr, length ) ) { err = errno; @@ -3478,29 +3466,29 @@ int ntfs_resident_attr_record_add( ntfs_inode *ni, ATTR_TYPES type, 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 ) ); + ? 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 ); + memcpy( ( u8* )a + le16_to_cpu( a->value_offset ), val, size ); else - memset( ( u8* )a + le16_to_cpu( a->value_offset ), 0, size ); + memset( ( u8* )a + le16_to_cpu( a->value_offset ), 0, size ); if ( type == AT_FILE_NAME ) - a->resident_flags = RESIDENT_ATTR_IS_INDEXED; + a->resident_flags = RESIDENT_ATTR_IS_INDEXED; else - a->resident_flags = 0; + a->resident_flags = 0; if ( name_len ) - memcpy( ( u8* )a + le16_to_cpu( a->name_offset ), - name, sizeof( ntfschar ) * 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 ); + cpu_to_le16( ( le16_to_cpu( m->next_attr_instance ) + 1 ) & 0xffff ); if ( ni->nr_extents == -1 ) - base_ni = ni->base_ni; + base_ni = ni->base_ni; else - base_ni = ni; + base_ni = ni; if ( type != AT_ATTRIBUTE_LIST && NInoAttrList( base_ni ) ) { if ( ntfs_attrlist_entry_add( ni, a ) ) @@ -3508,7 +3496,7 @@ int ntfs_resident_attr_record_add( ntfs_inode *ni, ATTR_TYPES type, err = errno; ntfs_attr_record_resize( m, a, 0 ); ntfs_log_trace( "Failed add attribute entry to " - "ATTRIBUTE_LIST.\n" ); + "ATTRIBUTE_LIST.\n" ); goto put_err_out; } } @@ -3520,7 +3508,7 @@ int ntfs_resident_attr_record_add( ntfs_inode *ni, ATTR_TYPES type, ntfs_inode_mark_dirty( ni ); ntfs_attr_put_search_ctx( ctx ); return offset; -put_err_out: + put_err_out: ntfs_attr_put_search_ctx( ctx ); errno = err; return -1; @@ -3545,8 +3533,8 @@ 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 ) + ntfschar *name, u8 name_len, VCN lowest_vcn, int dataruns_size, + ATTR_FLAGS flags ) { ntfs_attr_search_ctx *ctx; u32 length; @@ -3556,9 +3544,9 @@ int ntfs_non_resident_attr_record_add( ntfs_inode *ni, ATTR_TYPES type, 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 ); + "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 ) ) { @@ -3569,23 +3557,23 @@ int ntfs_non_resident_attr_record_add( ntfs_inode *ni, ATTR_TYPES type, if ( ntfs_attr_can_be_non_resident( ni->vol, type ) ) { if ( errno == EPERM ) - ntfs_log_perror( "Attribute can't be non resident" ); + ntfs_log_perror( "Attribute can't be non resident" ); else - ntfs_log_perror( "ntfs_attr_can_be_non_resident failed" ); + 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; + 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 ) ) + ctx ) ) { err = EEXIST; ntfs_log_perror( "Attribute 0x%x already present", type ); @@ -3603,9 +3591,9 @@ int ntfs_non_resident_attr_record_add( ntfs_inode *ni, ATTR_TYPES type, /* 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 ); + 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; @@ -3619,14 +3607,14 @@ int ntfs_non_resident_attr_record_add( ntfs_inode *ni, ATTR_TYPES type, 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 ) ); + ( ( 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; + ? STANDARD_COMPRESSION_UNIT : 0; /* If @lowest_vcn == 0, than setup empty attribute. */ if ( !lowest_vcn ) { @@ -3638,14 +3626,14 @@ int ntfs_non_resident_attr_record_add( ntfs_inode *ni, ATTR_TYPES type, *( ( 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 ); + 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 ); + cpu_to_le16( ( le16_to_cpu( m->next_attr_instance ) + 1 ) & 0xffff ); if ( ni->nr_extents == -1 ) - base_ni = ni->base_ni; + base_ni = ni->base_ni; else - base_ni = ni; + base_ni = ni; if ( type != AT_ATTRIBUTE_LIST && NInoAttrList( base_ni ) ) { if ( ntfs_attrlist_entry_add( ni, a ) ) @@ -3664,7 +3652,7 @@ int ntfs_non_resident_attr_record_add( ntfs_inode *ni, ATTR_TYPES type, */ ntfs_attr_reinit_search_ctx( ctx ); if ( ntfs_attr_lookup( type, name, name_len, CASE_SENSITIVE, - lowest_vcn, NULL, 0, ctx ) ) + lowest_vcn, NULL, 0, ctx ) ) { ntfs_log_perror( "%s: attribute lookup failed", __FUNCTION__ ); ntfs_attr_put_search_ctx( ctx ); @@ -3674,7 +3662,7 @@ int ntfs_non_resident_attr_record_add( ntfs_inode *ni, ATTR_TYPES type, offset = ( u8* )ctx->attr - ( u8* )ctx->mrec; ntfs_attr_put_search_ctx( ctx ); return offset; -put_err_out: + put_err_out: ntfs_attr_put_search_ctx( ctx ); errno = err; return -1; @@ -3705,24 +3693,24 @@ int ntfs_attr_record_rm( ntfs_attr_search_ctx *ctx ) } 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 ) ); + ( 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; + base_ni = ctx->base_ntfs_ino; else - base_ni = ctx->ntfs_ino; + 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" ); + "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" ); + if ( ntfs_attrlist_entry_add( ni, ctx->attr ) ) + ntfs_log_trace( "Rollback failed. Leaving inconstant " + "metadata.\n" ); err = EIO; return -1; } @@ -3737,7 +3725,7 @@ int ntfs_attr_record_rm( ntfs_attr_search_ctx *ctx ) if ( ntfs_attrlist_entry_rm( ctx ) ) { ntfs_log_trace( "Couldn't delete record from " - "$ATTRIBUTE_LIST.\n" ); + "$ATTRIBUTE_LIST.\n" ); return -1; } } @@ -3746,7 +3734,7 @@ int ntfs_attr_record_rm( ntfs_attr_search_ctx *ctx ) if ( type == AT_ATTRIBUTE_LIST ) { if ( NInoAttrList( base_ni ) && base_ni->attr_list ) - free( base_ni->attr_list ); + free( base_ni->attr_list ); base_ni->attr_list = NULL; NInoClearAttrList( base_ni ); NInoAttrListClearDirty( base_ni ); @@ -3765,18 +3753,18 @@ int ntfs_attr_record_rm( ntfs_attr_search_ctx *ctx ) } /* Remove done if we freed base inode. */ if ( ni == base_ni ) - return 0; + return 0; } if ( type == AT_ATTRIBUTE_LIST || !NInoAttrList( base_ni ) ) - return 0; + 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 ) ) + 0, NULL, 0, ctx ) ) { /* * FIXME: Should we succeed here? Definitely something @@ -3784,7 +3772,7 @@ int ntfs_attr_record_rm( ntfs_attr_search_ctx *ctx ) * that we have got attribute list. */ ntfs_log_trace( "Couldn't find attribute list. Succeed " - "anyway.\n" ); + "anyway.\n" ); return 0; } /* Deallocate clusters. */ @@ -3793,18 +3781,18 @@ int ntfs_attr_record_rm( ntfs_attr_search_ctx *ctx ) runlist *al_rl; al_rl = ntfs_mapping_pairs_decompress( base_ni->vol, - ctx->attr, NULL ); + ctx->attr, NULL ); if ( !al_rl ) { ntfs_log_trace( "Couldn't decompress attribute list " - "runlist. Succeed anyway.\n" ); + "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" ); + "Couldn't free clusters from " + "attribute list runlist.\n" ); } free( al_rl ); } @@ -3817,7 +3805,7 @@ int ntfs_attr_record_rm( ntfs_attr_search_ctx *ctx ) * but without extents. */ ntfs_log_trace( "Couldn't remove attribute list. Succeed " - "anyway.\n" ); + "anyway.\n" ); return 0; } } @@ -3851,7 +3839,7 @@ 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 ) + ntfschar *name, u8 name_len, u8 *val, s64 size ) { u32 attr_rec_size; int err, i, offset; @@ -3865,21 +3853,21 @@ int ntfs_attr_add( ntfs_inode *ni, ATTR_TYPES type, { errno = EINVAL; ntfs_log_perror( "%s: ni=%p size=%lld", __FUNCTION__, ni, - ( long long )size ); + ( 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 ); + ( long long )ni->mft_no, type, ( long long )size ); if ( ni->nr_extents == -1 ) - ni = ni->base_ni; + 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; + errno = EIO; return -1; } @@ -3897,7 +3885,7 @@ int ntfs_attr_add( ntfs_inode *ni, ATTR_TYPES type, { errno = EINVAL; ntfs_log_perror( "val is mandatory for always resident " - "attributes" ); + "attributes" ); return -1; } if ( size > ni->vol->mft_record_size ) @@ -3908,7 +3896,7 @@ int ntfs_attr_add( ntfs_inode *ni, ATTR_TYPES type, } } else - can_be_non_resident = TRUE; + can_be_non_resident = TRUE; /* * Determine resident or not will be new attribute. We add 8 to size in @@ -3930,12 +3918,12 @@ int ntfs_attr_add( ntfs_inode *ni, ATTR_TYPES type, } /* Calculate attribute record size. */ if ( is_resident ) - attr_rec_size = offsetof( ATTR_RECORD, resident_end ) + - ( ( name_len * sizeof( ntfschar ) + 7 ) & ~7 ) + - ( ( size + 7 ) & ~7 ); + 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; + 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 @@ -3961,7 +3949,7 @@ int ntfs_attr_add( ntfs_inode *ni, ATTR_TYPES type, 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; + goto add_attr_record; } /* There is no extent that contain enough space for new attribute. */ @@ -3985,22 +3973,22 @@ int ntfs_attr_add( ntfs_inode *ni, ATTR_TYPES type, goto err_out; } -add_attr_record: + 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; + || ( ( type == AT_INDEX_ROOT ) && ( name == NTFS_INDEX_I30 ) ) ) ) + data_flags = ATTR_IS_COMPRESSED; else - data_flags = const_cpu_to_le16( 0 ); + 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 ); + name_len, val, size, data_flags ); if ( offset < 0 ) { if ( errno == ENOSPC && can_be_non_resident ) - goto add_non_resident; + goto add_non_resident; err = errno; ntfs_log_perror( "Failed to add resident attribute" ); goto free_err_out; @@ -4008,10 +3996,10 @@ add_attr_record: return 0; } -add_non_resident: + add_non_resident: /* Add non resident attribute. */ offset = ntfs_non_resident_attr_record_add( attr_ni, type, name, - name_len, 0, 8, data_flags ); + name_len, 0, 8, data_flags ); if ( offset < 0 ) { err = errno; @@ -4021,7 +4009,7 @@ add_non_resident: /* If @size == 0, we are done. */ if ( !size ) - return 0; + return 0; /* Open new attribute and resize it. */ na = ntfs_attr_open( ni, type, name, name_len ); @@ -4038,25 +4026,25 @@ add_non_resident: 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_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: + 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" ); -free_err_out: + ( 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" ); -err_out: + if ( ntfs_mft_record_free( attr_ni->vol, attr_ni ) ) + ntfs_log_perror( "Failed to free MFT record" ); + err_out: errno = err; return -1; } @@ -4066,7 +4054,7 @@ err_out: */ 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 ) { ntfs_attr_search_ctx *ctx; int res; @@ -4077,11 +4065,11 @@ int ntfs_attr_set_flags( ntfs_inode *ni, ATTR_TYPES type, if ( ctx ) { if ( !ntfs_attr_lookup( type, name, name_len, - CASE_SENSITIVE, 0, NULL, 0, ctx ) ) + CASE_SENSITIVE, 0, NULL, 0, ctx ) ) { /* do the requested change (all small endian le16) */ ctx->attr->flags = ( ctx->attr->flags & ~mask ) - | ( flags & mask ); + | ( flags & mask ); NInoSetDirty( ni ); res = 0; } @@ -4090,7 +4078,6 @@ int ntfs_attr_set_flags( ntfs_inode *ni, ATTR_TYPES type, return ( res ); } - /** * ntfs_attr_rm - remove attribute from ntfs inode * @na: opened ntfs attribute to delete @@ -4113,17 +4100,17 @@ int ntfs_attr_rm( ntfs_attr *na ) } ntfs_log_trace( "Entering for inode 0x%llx, attr 0x%x.\n", - ( long long ) na->ni->mft_no, na->type ); + ( long long ) na->ni->mft_no, na->type ); /* Free cluster allocation. */ if ( NAttrNonResident( na ) ) { if ( ntfs_attr_map_whole_runlist( na ) ) - return -1; + 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" ); + "inconstant metadata.\n" ); ret = -1; } } @@ -4131,14 +4118,14 @@ int ntfs_attr_rm( ntfs_attr *na ) /* Search for attribute extents and remove them all. */ ctx = ntfs_attr_get_search_ctx( na->ni, NULL ); if ( !ctx ) - return -1; + return -1; while ( !ntfs_attr_lookup( na->type, na->name, na->name_len, - CASE_SENSITIVE, 0, NULL, 0, ctx ) ) + CASE_SENSITIVE, 0, NULL, 0, ctx ) ) { if ( ntfs_attr_record_rm( ctx ) ) { ntfs_log_trace( "Failed to remove attribute extent. Leaving " - "inconstant metadata.\n" ); + "inconstant metadata.\n" ); ret = -1; } ntfs_attr_reinit_search_ctx( ctx ); @@ -4147,7 +4134,7 @@ int ntfs_attr_rm( ntfs_attr *na ) if ( errno != ENOENT ) { ntfs_log_trace( "Attribute lookup failed. Probably leaving inconstant " - "metadata.\n" ); + "metadata.\n" ); ret = -1; } @@ -4175,13 +4162,13 @@ 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 ); + old_size = le32_to_cpu( m->bytes_in_use ); alloc_size = le32_to_cpu( m->bytes_allocated ); - attr_size = le32_to_cpu( a->length ); + 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 ); + ( 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; @@ -4197,7 +4184,7 @@ int ntfs_attr_record_resize( MFT_RECORD *m, ATTR_RECORD *a, u32 new_size ) { errno = ENOSPC; ntfs_log_trace( "Not enough space in the MFT record " - "(%u > %u)\n", new_muse, alloc_size ); + "(%u > %u)\n", new_muse, alloc_size ); return -1; } @@ -4206,20 +4193,20 @@ int ntfs_attr_record_resize( MFT_RECORD *m, ATTR_RECORD *a, u32 new_size ) { errno = ENOSPC; ntfs_log_trace( "Too big INDEX_ROOT (%u > %u)\n", - new_muse, alloc_size ); + 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 ); + 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 ); + a->length = cpu_to_le32( new_size ); } return 0; } @@ -4239,7 +4226,7 @@ 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 ) + const u32 new_size ) { int ret; @@ -4247,16 +4234,16 @@ int ntfs_resident_attr_value_resize( MFT_RECORD *m, ATTR_RECORD *a, /* 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; + 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 ) ); + 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; @@ -4286,18 +4273,18 @@ int ntfs_attr_record_move_to( ntfs_attr_search_ctx *ctx, ntfs_inode *ni ) } 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 ); + "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; + return 0; if ( !ctx->al_entry ) { ntfs_log_trace( "Inode should contain attribute list to use this " - "function.\n" ); + "function.\n" ); errno = EINVAL; return -1; } @@ -4306,7 +4293,7 @@ int ntfs_attr_record_move_to( ntfs_attr_search_ctx *ctx, ntfs_inode *ni ) a = ctx->attr; nctx = ntfs_attr_get_search_ctx( ni, NULL ); if ( !nctx ) - return -1; + return -1; /* * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for @@ -4314,11 +4301,11 @@ int ntfs_attr_record_move_to( ntfs_attr_search_ctx *ctx, ntfs_inode *ni ) * 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 ) ) + 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" ); + "present in this MFT record.\n" ); err = EEXIST; goto put_err_out; } @@ -4331,7 +4318,7 @@ int ntfs_attr_record_move_to( ntfs_attr_search_ctx *ctx, ntfs_inode *ni ) /* Make space and move attribute. */ if ( ntfs_make_room_for_attr( ni->mrec, ( u8* ) nctx->attr, - le32_to_cpu( a->length ) ) ) + le32_to_cpu( a->length ) ) ) { err = errno; ntfs_log_trace( "Couldn't make space for attribute.\n" ); @@ -4340,20 +4327,20 @@ int ntfs_attr_record_move_to( ntfs_attr_search_ctx *ctx, ntfs_inode *ni ) 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 ); + ( 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 ) ); + 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; -put_err_out: + put_err_out: ntfs_attr_put_search_ctx( nctx ); errno = err; return -1; @@ -4382,31 +4369,31 @@ int ntfs_attr_record_move_away( ntfs_attr_search_ctx *ctx, int extra ) { errno = EINVAL; ntfs_log_perror( "%s: ctx=%p ctx->attr=%p extra=%d", __FUNCTION__, - ctx, ctx ? ctx->attr : NULL, extra ); + 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 ); + ( 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; + base_ni = ctx->base_ntfs_ino; else - base_ni = ctx->ntfs_ino; + 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 ); + ( 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 ); + ( unsigned long long )base_ni->mft_no ); return -1; } @@ -4417,12 +4404,12 @@ int ntfs_attr_record_move_away( ntfs_attr_search_ctx *ctx, int extra ) m = ni->mrec; if ( ctx->ntfs_ino->mft_no == ni->mft_no ) - continue; + continue; if ( le32_to_cpu( m->bytes_allocated ) - le32_to_cpu( m->bytes_in_use ) < le32_to_cpu( ctx->attr->length ) + extra ) - continue; + continue; /* * ntfs_attr_record_move_to can fail if extent with other lowest @@ -4430,7 +4417,7 @@ int ntfs_attr_record_move_away( ntfs_attr_search_ctx *ctx, int extra ) * do not return error. */ if ( !ntfs_attr_record_move_to( ctx, ni ) ) - return 0; + return 0; } /* @@ -4471,7 +4458,7 @@ 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 ) + ntfs_attr_search_ctx *ctx ) { s64 new_allocated_size, bw; ntfs_volume *vol = na->ni->vol; @@ -4486,28 +4473,28 @@ int ntfs_attr_make_non_resident( ntfs_attr *na, if ( NAttrNonResident( na ) ) { ntfs_log_trace( "Eeek! Trying to make non-resident attribute " - "non-resident. Aborting...\n" ); + "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; + return -1; new_allocated_size = ( le32_to_cpu( a->value_length ) + vol->cluster_size - - 1 ) & ~( vol->cluster_size - 1 ); + - 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 ); + vol->cluster_size_bits, -1, DATA_ZONE ); if ( !rl ) - return -1; + return -1; } else - rl = NULL; + rl = NULL; /* * Setup the in-memory attribute structure to be non-resident so that * we can use ntfs_attr_pwrite(). @@ -4534,15 +4521,15 @@ int ntfs_attr_make_non_resident( ntfs_attr *na, { /* 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 ) ); + ( 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 ); + "(bw = %lli, errno = %i). " + "Aborting...\n", ( long long )bw, err ); if ( bw >= 0 ) - err = EIO; + err = EIO; goto cluster_free_err_out; } } @@ -4552,14 +4539,14 @@ int ntfs_attr_make_non_resident( ntfs_attr *na, { err = errno; ntfs_log_debug( "Eeek! Failed to get size for mapping pairs array. " - "Aborting...\n" ); + "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; + name_ofs = ( sizeof( ATTR_REC ) + 7 ) & ~7; else - name_ofs = ( sizeof( ATTR_REC ) - sizeof( a->compressed_size ) + 7 ) & ~7; + 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 @@ -4583,14 +4570,14 @@ int ntfs_attr_make_non_resident( ntfs_attr *na, /* 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 ) ); + 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 ); + vol->cluster_size_bits ); a->mapping_pairs_offset = cpu_to_le16( mp_ofs ); @@ -4622,23 +4609,23 @@ int ntfs_attr_make_non_resident( ntfs_attr *na, /* 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 ) + 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 ); + "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; -cluster_free_err_out: + 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" ); + 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; @@ -4647,7 +4634,6 @@ cluster_free_err_out: return -1; } - static int ntfs_resident_attr_resize( ntfs_attr *na, const s64 newsize ); /** @@ -4674,15 +4660,15 @@ static int ntfs_resident_attr_resize_i( ntfs_attr *na, const s64 newsize ) 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 ); + ( 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; + return -1; if ( ntfs_attr_lookup( na->type, na->name, na->name_len, 0, 0, NULL, 0, - ctx ) ) + ctx ) ) { err = errno; ntfs_log_perror( "ntfs_attr_lookup failed" ); @@ -4697,7 +4683,7 @@ static int ntfs_resident_attr_resize_i( ntfs_attr *na, const s64 newsize ) { err = errno; if ( err == ENOENT ) - err = EIO; + err = EIO; ntfs_log_perror( "%s: bounds check failed", __FUNCTION__ ); goto put_err_out; } @@ -4710,14 +4696,14 @@ static int ntfs_resident_attr_resize_i( ntfs_attr *na, const s64 newsize ) { /* Perform the resize of the attribute record. */ if ( !( ret = ntfs_resident_attr_value_resize( ctx->mrec, ctx->attr, - newsize ) ) ) + 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; + na->compressed_size = na->allocated_size; if ( na->type == AT_DATA && na->name == AT_UNNAMED ) { na->ni->data_size = na->data_size; @@ -4759,19 +4745,19 @@ static int ntfs_resident_attr_resize_i( ntfs_attr *na, const s64 newsize ) a = ctx->attr; if ( a->non_resident ) - continue; + 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; + 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 ); + le16_to_cpu( a->name_offset ) ), a->name_length ); if ( !tna ) { err = errno; @@ -4804,7 +4790,7 @@ static int ntfs_resident_attr_resize_i( ntfs_attr *na, const s64 newsize ) { ntfs_attr_put_search_ctx( ctx ); if ( ntfs_inode_free_space( na->ni, offsetof( ATTR_RECORD, - non_resident_end ) + 8 ) ) + non_resident_end ) + 8 ) ) { ntfs_log_perror( "Could not free space in MFT record" ); return -1; @@ -4820,7 +4806,7 @@ static int ntfs_resident_attr_resize_i( ntfs_attr *na, const s64 newsize ) /* 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 ) ) + 0, NULL, 0, ctx ) ) { ntfs_log_perror( "%s: Attribute lookup failed 2", __FUNCTION__ ); err = errno; @@ -4843,14 +4829,14 @@ static int ntfs_resident_attr_resize_i( ntfs_attr *na, const s64 newsize ) /* Add attribute list if not present. */ if ( na->ni->nr_extents == -1 ) - ni = na->ni->base_ni; + ni = na->ni->base_ni; else - ni = na->ni; + ni = na->ni; if ( !NInoAttrList( ni ) ) { ntfs_attr_put_search_ctx( ctx ); if ( ntfs_inode_add_attrlist( ni ) ) - return -1; + return -1; return ntfs_resident_attr_resize( na, newsize ); } /* Allocate new mft record. */ @@ -4870,13 +4856,13 @@ static int ntfs_resident_attr_resize_i( ntfs_attr *na, const s64 newsize ) } /* Update ntfs attribute. */ if ( na->ni->nr_extents == -1 ) - na->ni = ni; + na->ni = ni; ntfs_attr_put_search_ctx( ctx ); /* Try to perform resize once again. */ return ntfs_resident_attr_resize( na, newsize ); -resize_done: + resize_done: /* * Set the inode (and its base inode if it exists) dirty so it is * written out later. @@ -4884,7 +4870,7 @@ resize_done: ntfs_inode_mark_dirty( ctx->ntfs_ino ); ntfs_attr_put_search_ctx( ctx ); return 0; -put_err_out: + put_err_out: ntfs_attr_put_search_ctx( ctx ); errno = err; return ret; @@ -4933,7 +4919,7 @@ static int ntfs_attr_make_resident( ntfs_attr *na, ntfs_attr_search_ctx *ctx ) if ( sle64_to_cpu( a->lowest_vcn ) ) { ntfs_log_trace( "Eeek! Should be called for the first extent of the " - "attribute. Aborting...\n" ); + "attribute. Aborting...\n" ); err = EINVAL; return -1; } @@ -4942,7 +4928,7 @@ static int ntfs_attr_make_resident( ntfs_attr *na, ntfs_attr_search_ctx *ctx ) if ( !NAttrNonResident( na ) ) { ntfs_log_trace( "Eeek! Trying to make resident attribute resident. " - "Aborting...\n" ); + "Aborting...\n" ); errno = EINVAL; return -1; } @@ -4956,12 +4942,12 @@ static int ntfs_attr_make_resident( ntfs_attr *na, ntfs_attr_search_ctx *ctx ) /* Check that the attribute is allowed to be resident. */ if ( ntfs_attr_can_be_resident( vol, na->type ) ) - return -1; + return -1; if ( na->data_flags & ATTR_IS_ENCRYPTED ) { ntfs_log_trace( "Making encrypted streams resident is not " - "implemented yet.\n" ); + "implemented yet.\n" ); errno = EOPNOTSUPP; return -1; } @@ -4982,13 +4968,13 @@ static int ntfs_attr_make_resident( ntfs_attr *na, ntfs_attr_search_ctx *ctx ) /* Read and cache the whole runlist if not already done. */ if ( ntfs_attr_map_whole_runlist( na ) ) - return -1; + 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_length * sizeof( ntfschar ) ); } a->name_offset = cpu_to_le16( name_ofs ); @@ -5000,8 +4986,8 @@ static int ntfs_attr_make_resident( ntfs_attr *na, ntfs_attr_search_ctx *ctx ) * 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 ); + "Please report to the %s. Aborting...\n", + NTFS_DEV_LIST ); errno = EIO; return -1; } @@ -5028,33 +5014,33 @@ static int ntfs_attr_make_resident( ntfs_attr *na, ntfs_attr_search_ctx *ctx ) * for which we do need to set this flag. (AIA) */ if ( a->type == AT_FILE_NAME ) - a->resident_flags = RESIDENT_ATTR_IS_INDEXED; + a->resident_flags = RESIDENT_ATTR_IS_INDEXED; else - a->resident_flags = 0; + 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; + 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 ); + ( u8* )a + val_ofs ); if ( bytes_read != na->initialized_size ) { if ( bytes_read < 0 ) - err = errno; + err = errno; ntfs_log_trace( "Eeek! Failed to read attribute data. Leaving " - "inconstant metadata. Run chkdsk. " - "Aborting...\n" ); + "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 ); + memset( ( u8* )a + val_ofs + na->initialized_size, 0, + na->data_size - na->initialized_size ); /* * Deallocate clusters from the runlist. @@ -5068,7 +5054,7 @@ static int ntfs_attr_make_resident( ntfs_attr *na, ntfs_attr_search_ctx *ctx ) err = errno; ntfs_log_perror( "Eeek! Failed to release allocated clusters" ); ntfs_log_trace( "Ignoring error and leaving behind wasted " - "clusters.\n" ); + "clusters.\n" ); } /* Throw away the now unused runlist. */ @@ -5091,15 +5077,15 @@ 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 ) + 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 ); + ( unsigned long long )na->ni->mft_no, na->type ); if ( a->lowest_vcn ) - goto out; + goto out; a->allocated_size = cpu_to_sle64( na->allocated_size ); @@ -5120,16 +5106,16 @@ static int ntfs_attr_update_meta( ATTR_RECORD *a, ntfs_attr *na, MFT_RECORD *m, * free space in the current mft record. */ if ( ( le32_to_cpu( a->length ) - - le16_to_cpu( a->mapping_pairs_offset ) == 8 ) + le16_to_cpu( a->mapping_pairs_offset ) == 8 ) && !( le32_to_cpu( m->bytes_allocated ) - - le32_to_cpu( m->bytes_in_use ) ) ) + 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 leave; goto retry; } if ( ntfs_attr_record_move_away( ctx, 8 ) ) @@ -5141,7 +5127,7 @@ static int ntfs_attr_update_meta( ATTR_RECORD *a, ntfs_attr *na, MFT_RECORD *m, goto retry; } if ( !( le32_to_cpu( a->length ) - le16_to_cpu( - a->mapping_pairs_offset ) ) ) + a->mapping_pairs_offset ) ) ) { errno = EIO; ntfs_log_perror( "Mapping pairs space is 0" ); @@ -5150,17 +5136,17 @@ static int ntfs_attr_update_meta( ATTR_RECORD *a, ntfs_attr *na, MFT_RECORD *m, NAttrSetSparse( na ); a->flags |= ATTR_IS_SPARSE; - a->compression_unit = STANDARD_COMPRESSION_UNIT; /* Windows + 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 ) ); + ( 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 ); + cpu_to_le16( le16_to_cpu( a->mapping_pairs_offset ) + 8 ); } /* Attribute no longer sparse. */ @@ -5173,14 +5159,14 @@ static int ntfs_attr_update_meta( ATTR_RECORD *a, ntfs_attr *na, MFT_RECORD *m, 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 ) ); + ( 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->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 ); + cpu_to_le16( le16_to_cpu( a->mapping_pairs_offset ) - 8 ); } /* Update compressed size if required. */ @@ -5190,7 +5176,7 @@ static int ntfs_attr_update_meta( ATTR_RECORD *a, ntfs_attr *na, MFT_RECORD *m, new_compr_size = ntfs_rl_get_compressed_size( na->ni->vol, na->rl ); if ( new_compr_size == -1 ) - goto error; + goto error; na->compressed_size = new_compr_size; a->compressed_size = cpu_to_sle64( new_compr_size ); @@ -5202,16 +5188,16 @@ static int ntfs_attr_update_meta( ATTR_RECORD *a, ntfs_attr *na, MFT_RECORD *m, if ( na->type == AT_DATA && na->name == AT_UNNAMED ) { if ( sparse ) - na->ni->allocated_size = na->compressed_size; + na->ni->allocated_size = na->compressed_size; else - na->ni->allocated_size = na->allocated_size; + na->ni->allocated_size = na->allocated_size; NInoFileNameSetDirty( na->ni ); } -out: + out: return ret; -leave: ret = -1; goto out; /* return -1 */ -retry: ret = -2; goto out; -error: ret = -3; goto out; + leave: ret = -1; goto out; /* return -1 */ + retry: ret = -2; goto out; + error: ret = -3; goto out; } #define NTFS_VCN_DELETE_MARK -2 @@ -5229,7 +5215,7 @@ static int ntfs_attr_update_mapping_pairs_i( ntfs_attr *na, VCN from_vcn ) int err, mp_size, cur_max_mp_size, exp_max_mp_size, ret = -1; BOOL finished_build; -retry: + retry: if ( !na || !na->rl || from_vcn ) { errno = EINVAL; @@ -5238,7 +5224,7 @@ retry: } ntfs_log_trace( "Entering for inode %llu, attr 0x%x\n", - ( unsigned long long )na->ni->mft_no, na->type ); + ( unsigned long long )na->ni->mft_no, na->type ); if ( !NAttrNonResident( na ) ) { @@ -5248,20 +5234,20 @@ retry: } if ( na->ni->nr_extents == -1 ) - base_ni = na->ni->base_ni; + base_ni = na->ni->base_ni; else - base_ni = na->ni; + base_ni = na->ni; ctx = ntfs_attr_get_search_ctx( base_ni, NULL ); if ( !ctx ) - return -1; + 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 ) ) + CASE_SENSITIVE, from_vcn, NULL, 0, ctx ) ) { a = ctx->attr; m = ctx->mrec; @@ -5291,7 +5277,7 @@ retry: } if ( first_lcn == LCN_ENOENT || first_lcn == LCN_RL_NOT_MAPPED ) - finished_build = TRUE; + finished_build = TRUE; } /* @@ -5303,8 +5289,8 @@ retry: 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 ); + "%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; @@ -5322,17 +5308,17 @@ retry: * 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 ); + 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; + 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 ); + stop_vcn, exp_max_mp_size ); if ( mp_size <= 0 ) { ntfs_log_perror( "%s: get MP size failed", __FUNCTION__ ); @@ -5350,11 +5336,11 @@ retry: { ntfs_attr_put_search_ctx( ctx ); if ( ntfs_inode_free_space( na->ni, mp_size - - cur_max_mp_size ) ) + cur_max_mp_size ) ) { ntfs_log_perror( "Attribute list is too " - "big. Defragment the " - "volume\n" ); + "big. Defragment the " + "volume\n" ); return -1; } goto retry; @@ -5384,8 +5370,8 @@ retry: 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 ) ) + le16_to_cpu( a->mapping_pairs_offset ) + + mp_size ) ) { errno = EIO; ntfs_log_perror( "Failed to resize attribute" ); @@ -5397,7 +5383,7 @@ retry: 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 ) ) && + NInoAttrList( ctx->ntfs_ino ) ) && ctx->attr->type != AT_ATTRIBUTE_LIST ) { ctx->al_entry->lowest_vcn = cpu_to_sle64( stop_vcn ); @@ -5409,13 +5395,13 @@ retry: * 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; + a->mapping_pairs_offset ), mp_size, na->rl, + stop_vcn, &stop_rl ) ) + finished_build = TRUE; if ( stop_rl ) - stop_vcn = stop_rl->vcn; + stop_vcn = stop_rl->vcn; else - stop_vcn = 0; + stop_vcn = 0; if ( !finished_build && errno != ENOSPC ) { ntfs_log_perror( "Failed to build mapping pairs" ); @@ -5436,11 +5422,11 @@ retry: 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 ) ) + CASE_SENSITIVE, 0, NULL, 0, ctx ) ) { if ( sle64_to_cpu( ctx->attr->highest_vcn ) != NTFS_VCN_DELETE_MARK ) - continue; + continue; /* Remove unused attribute record. */ if ( ntfs_attr_record_rm( ctx ) ) { @@ -5466,7 +5452,7 @@ retry: { /* Calculate size of rest mapping pairs. */ mp_size = ntfs_get_size_for_mapping_pairs( na->ni->vol, - na->rl, stop_vcn, INT_MAX ); + na->rl, stop_vcn, INT_MAX ); if ( mp_size <= 0 ) { ntfs_log_perror( "%s: get mp size failed", __FUNCTION__ ); @@ -5485,14 +5471,14 @@ retry: * 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 ) + 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 ); + 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; + 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, @@ -5502,25 +5488,25 @@ retry: 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" ); + 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 ); + le16_to_cpu( a->mapping_pairs_offset ), mp_size, na->rl, + stop_vcn, &stop_rl ); if ( stop_rl ) - stop_vcn = stop_rl->vcn; + stop_vcn = stop_rl->vcn; else - stop_vcn = 0; + 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" ); + ntfs_log_perror( "Couldn't free MFT record" ); errno = err; goto put_err_out; } @@ -5528,15 +5514,15 @@ retry: ntfs_inode_mark_dirty( ni ); /* All mapping pairs has been written. */ if ( !err ) - break; + break; } -ok: + ok: ret = 0; -out: + out: return ret; -put_err_out: + put_err_out: if ( ctx ) - ntfs_attr_put_search_ctx( ctx ); + ntfs_attr_put_search_ctx( ctx ); goto out; } #undef NTFS_VCN_DELETE_MARK @@ -5597,7 +5583,7 @@ static int ntfs_non_resident_attr_shrink( ntfs_attr *na, const s64 newsize ) 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 ); + na->ni->mft_no, na->type, ( long long )newsize ); vol = na->ni->vol; @@ -5610,16 +5596,16 @@ static int ntfs_non_resident_attr_shrink( ntfs_attr *na, const s64 newsize ) if ( errno == ERANGE ) { ntfs_log_trace( "Eeek! Size bounds check failed. " - "Aborting...\n" ); + "Aborting...\n" ); } else if ( errno == ENOENT ) - errno = EIO; + errno = EIO; return -1; } /* The first cluster outside the new allocation. */ first_free_vcn = ( newsize + vol->cluster_size - 1 ) >> - vol->cluster_size_bits; + vol->cluster_size_bits; /* * Compare the new allocation with the old one and only deallocate * clusters if there is a change. @@ -5629,16 +5615,16 @@ static int ntfs_non_resident_attr_shrink( ntfs_attr *na, const s64 newsize ) if ( ntfs_attr_map_whole_runlist( na ) ) { ntfs_log_trace( "Eeek! ntfs_attr_map_whole_runlist " - "failed.\n" ); + "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 ); + -1 ); if ( nr_freed_clusters < 0 ) { ntfs_log_trace( "Eeek! Freeing of clusters failed. " - "Aborting...\n" ); + "Aborting...\n" ); return -1; } @@ -5658,11 +5644,11 @@ static int ntfs_non_resident_attr_shrink( ntfs_attr *na, const s64 newsize ) /* 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*/ ) ) + 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" ); + "Leaving inconstant metadata. " + "Run chkdsk.\n" ); return -1; } } @@ -5670,16 +5656,16 @@ static int ntfs_non_resident_attr_shrink( ntfs_attr *na, const s64 newsize ) /* Get the first attribute record. */ ctx = ntfs_attr_get_search_ctx( na->ni, NULL ); if ( !ctx ) - return -1; + return -1; if ( ntfs_attr_lookup( na->type, na->name, na->name_len, CASE_SENSITIVE, - 0, NULL, 0, ctx ) ) + 0, NULL, 0, ctx ) ) { err = errno; if ( err == ENOENT ) - err = EIO; + err = EIO; ntfs_log_trace( "Eeek! Lookup of first attribute extent failed. " - "Leaving inconstant metadata.\n" ); + "Leaving inconstant metadata.\n" ); goto put_err_out; } @@ -5705,8 +5691,8 @@ static int ntfs_non_resident_attr_shrink( ntfs_attr *na, const s64 newsize ) { /* If couldn't make resident, just continue. */ if ( errno != EPERM ) - ntfs_log_error( "Failed to make attribute " - "resident. Leaving as is...\n" ); + ntfs_log_error( "Failed to make attribute " + "resident. Leaving as is...\n" ); } } @@ -5715,7 +5701,7 @@ static int ntfs_non_resident_attr_shrink( ntfs_attr *na, const s64 newsize ) /* Done! */ ntfs_attr_put_search_ctx( ctx ); return 0; -put_err_out: + put_err_out: ntfs_attr_put_search_ctx( ctx ); errno = err; return -1; @@ -5746,8 +5732,8 @@ static int ntfs_non_resident_attr_expand_i( ntfs_attr *na, const s64 newsize ) 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 ); + ( unsigned long long )na->ni->mft_no, na->type, + ( long long )newsize, ( long long )na->data_size ); vol = na->ni->vol; @@ -5758,7 +5744,7 @@ static int ntfs_non_resident_attr_expand_i( ntfs_attr *na, const s64 newsize ) if ( ntfs_attr_size_bounds_check( vol, na->type, newsize ) < 0 ) { if ( errno == ENOENT ) - errno = EIO; + errno = EIO; ntfs_log_perror( "%s: bounds check failed", __FUNCTION__ ); return -1; } @@ -5767,7 +5753,7 @@ static int ntfs_non_resident_attr_expand_i( ntfs_attr *na, const s64 newsize ) 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; + vol->cluster_size_bits; /* * Compare the new allocation with the old one and only allocate * clusters if there is a change. @@ -5788,13 +5774,13 @@ static int ntfs_non_resident_attr_expand_i( ntfs_attr *na, const s64 newsize ) { rl = ntfs_malloc( 0x1000 ); if ( !rl ) - return -1; + return -1; rl[0].vcn = ( na->allocated_size >> - vol->cluster_size_bits ); + vol->cluster_size_bits ); rl[0].lcn = LCN_HOLE; rl[0].length = first_free_vcn - - ( na->allocated_size >> vol->cluster_size_bits ); + ( na->allocated_size >> vol->cluster_size_bits ); rl[1].vcn = first_free_vcn; rl[1].lcn = LCN_ENOENT; rl[1].length = 0; @@ -5813,32 +5799,32 @@ static int ntfs_non_resident_attr_expand_i( ntfs_attr *na, const s64 newsize ) { /* 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--; + rl--; /* * Only set lcn_seek_from it the LCN is valid. */ if ( rl->lcn >= 0 ) - lcn_seek_from = rl->lcn + rl->length; + 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 ); + 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 ) ); + "(%lld)", + ( long long )first_free_vcn - + ( ( long long )na->allocated_size >> + vol->cluster_size_bits ) ); return -1; } } @@ -5861,7 +5847,7 @@ static int ntfs_non_resident_attr_expand_i( ntfs_attr *na, const s64 newsize ) 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*/ ) ) + vol->cluster_size_bits*/) ) { err = errno; ntfs_log_perror( "Mapping pairs update failed" ); @@ -5879,23 +5865,23 @@ static int ntfs_non_resident_attr_expand_i( ntfs_attr *na, const s64 newsize ) return -1; } else - goto rollback; + goto rollback; } if ( ntfs_attr_lookup( na->type, na->name, na->name_len, CASE_SENSITIVE, - 0, NULL, 0, ctx ) ) + 0, NULL, 0, ctx ) ) { err = errno; ntfs_log_perror( "Lookup of first attribute extent failed" ); if ( err == ENOENT ) - err = EIO; + err = EIO; if ( na->allocated_size != org_alloc_size ) { ntfs_attr_put_search_ctx( ctx ); goto rollback; } else - goto put_err_out; + goto put_err_out; } /* Update data size. */ @@ -5912,17 +5898,17 @@ static int ntfs_non_resident_attr_expand_i( ntfs_attr *na, const s64 newsize ) /* Done! */ ntfs_attr_put_search_ctx( ctx ); return 0; -rollback: + rollback: /* Free allocated clusters. */ if ( ntfs_cluster_free( vol, na, org_alloc_size >> - vol->cluster_size_bits, -1 ) < 0 ) + 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 ) ) + vol->cluster_size_bits ) ) { /* * Failed to truncate the runlist, so just throw it away, it @@ -5938,20 +5924,19 @@ rollback: na->allocated_size = org_alloc_size; /* Restore mapping pairs. */ if ( ntfs_attr_update_mapping_pairs( na, 0 /*na->allocated_size >> - vol->cluster_size_bits*/ ) ) + vol->cluster_size_bits*/) ) { ntfs_log_perror( "Failed to restore old mapping pairs" ); } } errno = err; return -1; -put_err_out: + put_err_out: 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; @@ -5997,8 +5982,8 @@ int ntfs_attr_truncate( ntfs_attr *na, const s64 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 ); + ( unsigned long long )na->ni->mft_no, na->type, + ( long long )newsize ); if ( na->data_size == newsize ) { @@ -6024,11 +6009,11 @@ int ntfs_attr_truncate( ntfs_attr *na, const s64 newsize ) * (important case : $INDEX_ROOT:$I30) */ compressed = ( na->data_flags & ATTR_COMPRESSION_MASK ) - != const_cpu_to_le16( 0 ); + != const_cpu_to_le16( 0 ); if ( compressed && NAttrNonResident( na ) && ( ( ( na->data_flags & ATTR_COMPRESSION_MASK ) != ATTR_IS_COMPRESSED ) - || ( newsize && ( newsize < na->data_size ) ) ) ) + || ( newsize && ( newsize < na->data_size ) ) ) ) { errno = EOPNOTSUPP; ntfs_log_perror( "Failed to truncate compressed attribute" ); @@ -6048,18 +6033,18 @@ int ntfs_attr_truncate( ntfs_attr *na, const s64 newsize ) * unless being able to face the consequences ! */ if ( compressed && newsize ) - fullsize = ( na->initialized_size - | ( na->compression_block_size - 1 ) ) + 1; + fullsize = ( na->initialized_size + | ( na->compression_block_size - 1 ) ) + 1; else - fullsize = newsize; + fullsize = newsize; if ( fullsize > na->data_size ) - ret = ntfs_non_resident_attr_expand( na, fullsize ); + ret = ntfs_non_resident_attr_expand( na, fullsize ); else - ret = ntfs_non_resident_attr_shrink( na, fullsize ); + ret = ntfs_non_resident_attr_shrink( na, fullsize ); } else - ret = ntfs_resident_attr_resize( na, newsize ); -out: + ret = ntfs_resident_attr_resize( na, newsize ); + out: ntfs_log_leave( "Return status %d\n", ret ); return ret; } @@ -6093,7 +6078,7 @@ static int stuff_hole( ntfs_attr *na, const s64 pos ) { ret = ntfs_resident_attr_resize( na, pos ); if ( !ret && !NAttrNonResident( na ) ) - na->initialized_size = na->data_size = pos; + na->initialized_size = na->data_size = pos; } if ( !ret && NAttrNonResident( na ) ) { @@ -6102,8 +6087,8 @@ static int stuff_hole( ntfs_attr *na, const s64 pos ) & ~( na->compression_block_size - 1 ) ) { begin_size = ( ( na->initialized_size - 1 ) - | ( na->compression_block_size - 1 ) ) - + 1 - na->initialized_size; + | ( 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 ); } @@ -6114,45 +6099,45 @@ static int stuff_hole( ntfs_attr *na, const s64 pos ) end_size = 0; } if ( size ) - buf = ( char* )ntfs_malloc( size ); + buf = ( char* )ntfs_malloc( size ); else - buf = ( char* )NULL; + 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; + 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; + pos - end_size ) ) + ret = -1; else - na->initialized_size - = na->data_size = pos - end_size; + 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; + na->initialized_size, end_size, buf ) + != end_size ) ) + ret = -1; if ( buf ) - free( buf ); + free( buf ); } else - ret = -1; + 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 ); + "target %lld reached %lld\n", + ( long long )pos, ( long long )na->initialized_size ); errno = EIO; ret = -1; } @@ -6179,7 +6164,7 @@ static int stuff_hole( ntfs_attr *na, const s64 pos ) * 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 ) + ntfschar *name, u32 name_len, s64 *data_size ) { ntfs_attr *na; void *data, *ret = NULL; @@ -6195,7 +6180,7 @@ void *ntfs_attr_readall( ntfs_inode *ni, const ATTR_TYPES type, } data = ntfs_malloc( na->data_size ); if ( !data ) - goto out; + goto out; size = ntfs_attr_pread( na, 0, na->data_size, data ); if ( size != na->data_size ) @@ -6206,18 +6191,16 @@ void *ntfs_attr_readall( ntfs_inode *ni, const ATTR_TYPES type, } ret = data; if ( data_size ) - *data_size = size; -out: + *data_size = size; + out: ntfs_attr_close( na ); -err_exit: + err_exit: ntfs_log_leave( "\n" ); return ret; } - - int ntfs_attr_exist( ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, - u32 name_len ) + u32 name_len ) { ntfs_attr_search_ctx *ctx; int ret; @@ -6226,10 +6209,10 @@ int ntfs_attr_exist( ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, ctx = ntfs_attr_get_search_ctx( ni, NULL ); if ( !ctx ) - return 0; + return 0; ret = ntfs_attr_lookup( type, name, name_len, CASE_SENSITIVE, 0, NULL, 0, - ctx ); + ctx ); ntfs_attr_put_search_ctx( ctx ); @@ -6237,7 +6220,7 @@ int ntfs_attr_exist( ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, } int ntfs_attr_remove( ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, - u32 name_len ) + u32 name_len ) { ntfs_attr *na; int ret; @@ -6258,15 +6241,15 @@ int ntfs_attr_remove( ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, if ( type != AT_DATA ) { ntfs_log_perror( "Failed to open attribute 0x%02x of inode " - "0x%llx", type, ( unsigned long long )ni->mft_no ); + "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_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; @@ -6285,53 +6268,53 @@ static u8 *ntfs_init_lut256( void ) lut = ntfs_malloc( 256 ); if ( lut ) - for ( i = 0; i < 256; i++ ) - *( lut + i ) = 8 - BITCOUNT( i ); + 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 br = 0; + s64 total = 0; s64 nr_free = 0; lut = ntfs_init_lut256(); if ( !lut ) - return -1; + return -1; buf = ntfs_malloc( 65536 ); if ( !buf ) - goto out; + goto out; while ( 1 ) { u32 *p; br = ntfs_attr_pread( na, total, 65536, buf ); if ( br <= 0 ) - break; + break; total += br; p = ( u32 * )buf + br / 4 - 1; - for ( ; ( u8 * )p >= buf; p-- ) + for (; ( u8 * )p >= buf; p-- ) { - nr_free += lut[ *p & 255] + - lut[( *p >> 8 ) & 255] + - lut[( *p >> 16 ) & 255] + - lut[( *p >> 24 ) ]; + 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 )]; + 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: + out: free( lut ); if ( !total || br < 0 ) - return -1; + return -1; return nr_free; } diff --git a/source/libntfs/attrlist.c b/source/libntfs/attrlist.c index 9c62f316..a062237d 100644 --- a/source/libntfs/attrlist.c +++ b/source/libntfs/attrlist.c @@ -60,36 +60,39 @@ */ int ntfs_attrlist_need(ntfs_inode *ni) { - ATTR_LIST_ENTRY *ale; + 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; } /** @@ -106,131 +109,130 @@ int ntfs_attrlist_need(ntfs_inode *ni) */ 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; + 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; -err_out: - if (na) - ntfs_attr_close(na); - free(new_al); - errno = err; - return -1; + /* 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; } /** @@ -243,72 +245,72 @@ err_out: */ 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; + 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; -err_out: - if (na) - ntfs_attr_close(na); - free(new_al); - errno = err; - return -1; + /* 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; } diff --git a/source/libntfs/attrlist.h b/source/libntfs/attrlist.h index 2952e48b..62f10f9a 100644 --- a/source/libntfs/attrlist.h +++ b/source/libntfs/attrlist.h @@ -42,10 +42,9 @@ extern int ntfs_attrlist_entry_rm(ntfs_attr_search_ctx *ctx); */ static __inline__ void ntfs_attrlist_mark_dirty(ntfs_inode *ni) { - if (ni->nr_extents == -1) - NInoAttrListSetDirty(ni->base_ni); - else - NInoAttrListSetDirty(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 762be0b3..89d2b5af 100644 --- a/source/libntfs/bit_ops.h +++ b/source/libntfs/bit_ops.h @@ -3,17 +3,17 @@ 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: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -24,7 +24,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef _BIT_OPS_H #define _BIT_OPS_H @@ -32,26 +32,30 @@ #include /*----------------------------------------------------------------- -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)); + 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)); } -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)); +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)); } -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); +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); } -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); +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); } #endif // _BIT_OPS_H diff --git a/source/libntfs/bitmap.c b/source/libntfs/bitmap.c index 65162a29..c3350fb1 100644 --- a/source/libntfs/bitmap.c +++ b/source/libntfs/bitmap.c @@ -55,12 +55,10 @@ */ 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)); + if (!bitmap || new_value > 1) return; + if (!new_value) + bitmap[bit >> 3] &= ~(1 << (bit & 7)); + else bitmap[bit >> 3] |= (1 << (bit & 7)); } /** @@ -73,9 +71,8 @@ void ntfs_bit_set(u8 *bitmap, const u64 bit, const u8 new_value) */ char ntfs_bit_get(const u8 *bitmap, const u64 bit) { - if (!bitmap) - return -1; - return (bitmap[bit >> 3] >> (bit & 7)) & 1; + if (!bitmap) return -1; + return (bitmap[bit >> 3] >> (bit & 7)) & 1; } /** @@ -89,15 +86,13 @@ char ntfs_bit_get(const u8 *bitmap, const u64 bit) */ char ntfs_bit_get_and_set(u8 *bitmap, const u64 bit, const u8 new_value) { - register u8 old_bit, shift; + 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; } /** @@ -112,146 +107,147 @@ 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) +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 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; - - /* Depending on @value, zero or set all bits in the allocated buffer. */ - memset(buf, value ? 0xff : 0, bufsize); + buf = ntfs_malloc(bufsize); + if (!buf) return -1; - /* 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; - } + /* Depending on @value, zero or set all bits in the allocated buffer. */ + memset(buf, value ? 0xff : 0, bufsize); - /* 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; + /* 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; + } - /* 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; - } - } + /* 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; - /* 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; - } + /* 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; + } + } - /* 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; + /* 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; + } - 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; + /* 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; } /** @@ -267,13 +263,13 @@ free_err_out: */ 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 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; } /** @@ -289,12 +285,12 @@ int ntfs_bitmap_set_run(ntfs_attr *na, s64 start_bit, s64 count) */ 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 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 10b5f6c5..9314c130 100644 --- a/source/libntfs/bitmap.h +++ b/source/libntfs/bitmap.h @@ -39,8 +39,8 @@ extern void ntfs_bit_set(u8 *bitmap, const u64 bit, const u8 new_value); extern char ntfs_bit_get(const u8 *bitmap, const u64 bit); extern char ntfs_bit_get_and_set(u8 *bitmap, const u64 bit, const u8 new_value); -extern int ntfs_bitmap_set_run(ntfs_attr *na, s64 start_bit, s64 count); -extern int ntfs_bitmap_clear_run(ntfs_attr *na, s64 start_bit, s64 count); +extern int ntfs_bitmap_set_run(ntfs_attr *na, s64 start_bit, s64 count); +extern int ntfs_bitmap_clear_run(ntfs_attr *na, s64 start_bit, s64 count); /** * ntfs_bitmap_set_bit - set a bit in a bitmap @@ -53,7 +53,7 @@ extern int ntfs_bitmap_clear_run(ntfs_attr *na, s64 start_bit, s64 count); */ static __inline__ int ntfs_bitmap_set_bit(ntfs_attr *na, s64 bit) { - return ntfs_bitmap_set_run(na, bit, 1); + return ntfs_bitmap_set_run(na, bit, 1); } /** @@ -67,7 +67,7 @@ static __inline__ int ntfs_bitmap_set_bit(ntfs_attr *na, s64 bit) */ static __inline__ int ntfs_bitmap_clear_bit(ntfs_attr *na, s64 bit) { - return ntfs_bitmap_clear_run(na, bit, 1); + return ntfs_bitmap_clear_run(na, bit, 1); } /* @@ -78,7 +78,7 @@ static __inline__ int ntfs_bitmap_clear_bit(ntfs_attr *na, s64 bit) */ static __inline__ u32 ntfs_rol32(u32 word, unsigned int shift) { - return (word << shift) | (word >> (32 - shift)); + return (word << shift) | (word >> (32 - shift)); } /* @@ -89,7 +89,7 @@ static __inline__ u32 ntfs_rol32(u32 word, unsigned int shift) */ static __inline__ u32 ntfs_ror32(u32 word, unsigned int shift) { - return (word >> shift) | (word << (32 - 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 e9bea370..f1ea39c0 100644 --- a/source/libntfs/bootsect.c +++ b/source/libntfs/bootsect.c @@ -59,104 +59,122 @@ */ BOOL ntfs_boot_sector_is_ntfs(NTFS_BOOT_SECTOR *b) { - u32 i; - BOOL ret = FALSE; + 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; -not_ntfs: - return ret; + ret = TRUE; + not_ntfs: 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"; +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"; /** * ntfs_boot_sector_parse - setup an ntfs volume from an ntfs boot sector @@ -170,116 +188,116 @@ static const char *last_sector_error = */ int ntfs_boot_sector_parse(ntfs_volume *vol, const NTFS_BOOT_SECTOR *bs) { - s64 sectors; - u8 sectors_per_cluster; - s8 c; + 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; - } - - 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->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->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; + 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; } diff --git a/source/libntfs/cache.c b/source/libntfs/cache.c index dd147672..f7c5b667 100644 --- a/source/libntfs/cache.c +++ b/source/libntfs/cache.c @@ -60,81 +60,92 @@ * Do not call when a record has been modified (with no key change) */ -static void inserthashindex(struct CACHE_HEADER *cache, - struct CACHED_GENERIC *current) +static void inserthashindex(struct CACHE_HEADER *cache, struct CACHED_GENERIC *current) { - int h; - struct HASH_ENTRY *link; - struct HASH_ENTRY *first; + int h; + struct HASH_ENTRY *link; + struct HASH_ENTRY *first; - if (cache->dohash) { - h = cache->dohash(current); - if ((h >= 0) && (h < cache->max_hash)) { - /* get a free link and insert at top of hash list */ - link = cache->free_hash; - if (link) { - cache->free_hash = link->next; - first = cache->first_hash[h]; - if (first) - link->next = first; - else - link->next = NULL; - link->entry = current; - cache->first_hash[h] = link; - } else { - ntfs_log_error("No more hash entries," - " cache %s hashing dropped\n", - cache->name); - cache->dohash = (cache_hash)NULL; - } - } else { - ntfs_log_error("Illegal hash value," - " cache %s hashing dropped\n", - cache->name); - cache->dohash = (cache_hash)NULL; - } - } + if (cache->dohash) + { + h = cache->dohash(current); + if ((h >= 0) && (h < cache->max_hash)) + { + /* get a free link and insert at top of hash list */ + link = cache->free_hash; + if (link) + { + cache->free_hash = link->next; + first = cache->first_hash[h]; + if (first) + link->next = first; + else link->next = NULL; + link->entry = current; + cache->first_hash[h] = link; + } + else + { + ntfs_log_error("No more hash entries," + " cache %s hashing dropped\n", + cache->name); + cache->dohash = (cache_hash) NULL; + } + } + else + { + ntfs_log_error("Illegal hash value," + " cache %s hashing dropped\n", + cache->name); + cache->dohash = (cache_hash) NULL; + } + } } /* * Drop a hash index when a record is about to be deleted */ -static void drophashindex(struct CACHE_HEADER *cache, - const struct CACHED_GENERIC *current, int hash) +static void drophashindex(struct CACHE_HEADER *cache, const struct CACHED_GENERIC *current, int hash) { - struct HASH_ENTRY *link; - struct HASH_ENTRY *previous; + struct HASH_ENTRY *link; + struct HASH_ENTRY *previous; - if (cache->dohash) { - if ((hash >= 0) && (hash < cache->max_hash)) { - /* find the link and unlink */ - link = cache->first_hash[hash]; - previous = (struct HASH_ENTRY*)NULL; - while (link && (link->entry != current)) { - previous = link; - link = link->next; - } - if (link) { - if (previous) - previous->next = link->next; - else - cache->first_hash[hash] = link->next; - link->next = cache->free_hash; - cache->free_hash = link; - } else { - ntfs_log_error("Bad hash list," - " cache %s hashing dropped\n", - cache->name); - cache->dohash = (cache_hash)NULL; - } - } else { - ntfs_log_error("Illegal hash value," - " cache %s hashing dropped\n", - cache->name); - cache->dohash = (cache_hash)NULL; - } - } + if (cache->dohash) + { + if ((hash >= 0) && (hash < cache->max_hash)) + { + /* find the link and unlink */ + link = cache->first_hash[hash]; + previous = (struct HASH_ENTRY*) NULL; + while (link && (link->entry != current)) + { + previous = link; + link = link->next; + } + if (link) + { + if (previous) + previous->next = link->next; + else cache->first_hash[hash] = link->next; + link->next = cache->free_hash; + cache->free_hash = link; + } + else + { + ntfs_log_error("Bad hash list," + " cache %s hashing dropped\n", + cache->name); + cache->dohash = (cache_hash) NULL; + } + } + else + { + ntfs_log_error("Illegal hash value," + " cache %s hashing dropped\n", + cache->name); + cache->dohash = (cache_hash) NULL; + } + } } /* @@ -144,64 +155,64 @@ static void drophashindex(struct CACHE_HEADER *cache, * The returned entry may be modified, but not freed */ -struct CACHED_GENERIC *ntfs_fetch_cache(struct CACHE_HEADER *cache, - const struct CACHED_GENERIC *wanted, cache_compare compare) +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; - struct HASH_ENTRY *link; - int h; + struct CACHED_GENERIC *current; + struct CACHED_GENERIC *previous; + struct HASH_ENTRY *link; + int h; - current = (struct CACHED_GENERIC*)NULL; - if (cache) { - if (cache->dohash) { - /* - * When possible, use the hash table to - * locate the entry if present - */ - h = cache->dohash(wanted); - link = cache->first_hash[h]; - while (link && compare(link->entry, wanted)) - link = link->next; - if (link) - current = link->entry; - } - if (!cache->dohash) { - /* - * Search sequentially in LRU list if no hash table - * or if hashing has just failed - */ - current = cache->most_recent_entry; - while (current - && compare(current, wanted)) { - current = current->next; - } - } - if (current) { - previous = current->previous; - cache->hits++; - if (previous) { - /* - * found and not at head of list, unlink from current - * position and relink as head of list - */ - previous->next = current->next; - if (current->next) - current->next->previous - = current->previous; - else - cache->oldest_entry - = current->previous; - current->next = cache->most_recent_entry; - current->previous - = (struct CACHED_GENERIC*)NULL; - cache->most_recent_entry->previous = current; - cache->most_recent_entry = current; - } - } - cache->reads++; - } - return (current); + current = (struct CACHED_GENERIC*) NULL; + if (cache) + { + if (cache->dohash) + { + /* + * When possible, use the hash table to + * locate the entry if present + */ + h = cache->dohash(wanted); + link = cache->first_hash[h]; + while (link && compare(link->entry, wanted)) + link = link->next; + if (link) current = link->entry; + } + if (!cache->dohash) + { + /* + * Search sequentially in LRU list if no hash table + * or if hashing has just failed + */ + current = cache->most_recent_entry; + while (current && compare(current, wanted)) + { + current = current->next; + } + } + if (current) + { + previous = current->previous; + cache->hits++; + if (previous) + { + /* + * found and not at head of list, unlink from current + * position and relink as head of list + */ + previous->next = current->next; + if (current->next) + current->next->previous = current->previous; + else cache->oldest_entry = current->previous; + current->next = cache->most_recent_entry; + current->previous = (struct CACHED_GENERIC*) NULL; + cache->most_recent_entry->previous = current; + cache->most_recent_entry = current; + } + } + cache->reads++; + } + return (current); } /* @@ -209,121 +220,125 @@ struct CACHED_GENERIC *ntfs_fetch_cache(struct CACHE_HEADER *cache, * returns the cache entry or NULL if not possible */ -struct CACHED_GENERIC *ntfs_enter_cache(struct CACHE_HEADER *cache, - const struct CACHED_GENERIC *item, - cache_compare compare) +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 *before; - struct HASH_ENTRY *link; - int h; + struct CACHED_GENERIC *current; + struct CACHED_GENERIC *before; + struct HASH_ENTRY *link; + int h; - current = (struct CACHED_GENERIC*)NULL; - if (cache) { - if (cache->dohash) { - /* - * When possible, use the hash table to - * find out whether the entry if present - */ - h = cache->dohash(item); - link = cache->first_hash[h]; - while (link && compare(link->entry, item)) - link = link->next; - if (link) { - current = link->entry; - } - } - if (!cache->dohash) { - /* - * 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; - while (current - && compare(current, item)) { - current = current->next; - } - } + current = (struct CACHED_GENERIC*) NULL; + if (cache) + { + if (cache->dohash) + { + /* + * When possible, use the hash table to + * find out whether the entry if present + */ + h = cache->dohash(item); + link = cache->first_hash[h]; + while (link && compare(link->entry, item)) + link = link->next; + if (link) + { + current = link->entry; + } + } + if (!cache->dohash) + { + /* + * 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; + while (current && compare(current, item)) + { + 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; - if (!cache->oldest_entry) - cache->oldest_entry = current; - } else { - /* reusing the oldest entry */ - current = cache->oldest_entry; - before = current->previous; - before->next = (struct CACHED_GENERIC*)NULL; - if (cache->dohash) - drophashindex(cache,current, - cache->dohash(current)); - if (cache->dofree) - cache->dofree(current); - cache->oldest_entry = 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; - current->previous = (struct CACHED_GENERIC*)NULL; - if (cache->most_recent_entry) - cache->most_recent_entry->previous = current; - 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; - } - if (cache->dohash && current) - inserthashindex(cache,current); - } - 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; + if (!cache->oldest_entry) cache->oldest_entry = current; + } + else + { + /* reusing the oldest entry */ + current = cache->oldest_entry; + before = current->previous; + before->next = (struct CACHED_GENERIC*) NULL; + if (cache->dohash) drophashindex(cache, current, cache->dohash(current)); + if (cache->dofree) cache->dofree(current); + cache->oldest_entry = 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; + current->previous = (struct CACHED_GENERIC*) NULL; + if (cache->most_recent_entry) cache->most_recent_entry->previous = current; + 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; + } + if (cache->dohash && current) inserthashindex(cache, current); + } + cache->writes++; + } + return (current); } /* @@ -332,32 +347,26 @@ struct CACHED_GENERIC *ntfs_enter_cache(struct CACHE_HEADER *cache, * A specific function may be called for entry deletion */ -static void do_invalidate(struct CACHE_HEADER *cache, - struct CACHED_GENERIC *current, int flags) +static void do_invalidate(struct CACHE_HEADER *cache, struct CACHED_GENERIC *current, int flags) { - struct CACHED_GENERIC *previous; - - previous = current->previous; - if ((flags & CACHE_FREE) && cache->dofree) - cache->dofree(current); - /* - * Relink into free list - */ - if (current->next) - current->next->previous = current->previous; - else - cache->oldest_entry = current->previous; - 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; - } + struct CACHED_GENERIC *previous; + previous = current->previous; + if ((flags & CACHE_FREE) && cache->dofree) cache->dofree(current); + /* + * Relink into free list + */ + if (current->next) + current->next->previous = current->previous; + else cache->oldest_entry = current->previous; + 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; +} /* * Invalidate entries in cache @@ -371,80 +380,85 @@ static void do_invalidate(struct CACHE_HEADER *cache, * supposed to be found. */ -int ntfs_invalidate_cache(struct CACHE_HEADER *cache, - const struct CACHED_GENERIC *item, cache_compare compare, - int flags) +int ntfs_invalidate_cache(struct CACHE_HEADER *cache, const struct CACHED_GENERIC *item, cache_compare compare, + int flags) { - struct CACHED_GENERIC *current; - struct CACHED_GENERIC *previous; - struct CACHED_GENERIC *next; - struct HASH_ENTRY *link; - int count; - int h; + struct CACHED_GENERIC *current; + struct CACHED_GENERIC *previous; + struct CACHED_GENERIC *next; + struct HASH_ENTRY *link; + int count; + int h; - current = (struct CACHED_GENERIC*)NULL; - count = 0; - if (cache) { - if (!(flags & CACHE_NOHASH) && cache->dohash) { - /* - * When possible, use the hash table to - * find out whether the entry if present - */ - h = cache->dohash(item); - link = cache->first_hash[h]; - while (link) { - if (compare(link->entry, item)) - link = link->next; - else { - current = link->entry; - link = link->next; - if (current) { - drophashindex(cache,current,h); - do_invalidate(cache, - current,flags); - count++; - } - } - } - } - if ((flags & CACHE_NOHASH) || !cache->dohash) { - /* - * Search sequentially in LRU list - */ - current = cache->most_recent_entry; - previous = (struct CACHED_GENERIC*)NULL; - while (current) { - if (!compare(current, item)) { - next = current->next; - if (cache->dohash) - drophashindex(cache,current, - cache->dohash(current)); - do_invalidate(cache,current,flags); - current = next; - count++; - } else { - previous = current; - current = current->next; - } - } - } - } - return (count); + current = (struct CACHED_GENERIC*) NULL; + count = 0; + if (cache) + { + if (!(flags & CACHE_NOHASH) && cache->dohash) + { + /* + * When possible, use the hash table to + * find out whether the entry if present + */ + h = cache->dohash(item); + link = cache->first_hash[h]; + while (link) + { + if (compare(link->entry, item)) + link = link->next; + else + { + current = link->entry; + link = link->next; + if (current) + { + drophashindex(cache, current, h); + do_invalidate(cache, current, flags); + count++; + } + } + } + } + if ((flags & CACHE_NOHASH) || !cache->dohash) + { + /* + * Search sequentially in LRU list + */ + current = cache->most_recent_entry; + previous = (struct CACHED_GENERIC*) NULL; + while (current) + { + if (!compare(current, item)) + { + next = current->next; + if (cache->dohash) drophashindex(cache, current, cache->dohash(current)); + do_invalidate(cache, current, flags); + current = next; + count++; + } + else + { + previous = current; + current = current->next; + } + } + } + } + return (count); } -int ntfs_remove_cache(struct CACHE_HEADER *cache, - struct CACHED_GENERIC *item, int flags) +int ntfs_remove_cache(struct CACHE_HEADER *cache, struct CACHED_GENERIC *item, int flags) { - int count; + int count; - count = 0; - if (cache) { - if (cache->dohash) - drophashindex(cache,item,cache->dohash(item)); - do_invalidate(cache,item,flags); - count++; - } - return (count); + count = 0; + if (cache) + { + if (cache->dohash) drophashindex(cache, item, cache->dohash(item)); + do_invalidate(cache, item, flags); + count++; + } + return (count); } /* @@ -453,17 +467,17 @@ int ntfs_remove_cache(struct CACHE_HEADER *cache, static void ntfs_free_cache(struct CACHE_HEADER *cache) { - struct CACHED_GENERIC *entry; + struct CACHED_GENERIC *entry; - if (cache) { - for (entry=cache->most_recent_entry; entry; entry=entry->next) { - if (cache->dofree) - cache->dofree(entry); - if (entry->variable) - free(entry->variable); - } - free(cache); - } + if (cache) + { + for (entry = cache->most_recent_entry; entry; entry = entry->next) + { + if (cache->dofree) cache->dofree(entry); + if (entry->variable) free(entry->variable); + } + free(cache); + } } /* @@ -472,82 +486,87 @@ static void ntfs_free_cache(struct CACHE_HEADER *cache) * Returns the cache header, or NULL if the cache could not be created */ -static struct CACHE_HEADER *ntfs_create_cache(const char *name, - cache_free dofree, cache_hash dohash, - int full_item_size, - int item_count, int max_hash) +static struct CACHE_HEADER *ntfs_create_cache(const char *name, cache_free dofree, cache_hash dohash, + int full_item_size, int item_count, int max_hash) { - struct CACHE_HEADER *cache; - struct CACHED_GENERIC *pc; - struct CACHED_GENERIC *qc; - struct HASH_ENTRY *ph; - struct HASH_ENTRY *qh; - struct HASH_ENTRY **px; - size_t size; - int i; + struct CACHE_HEADER *cache; + struct CACHED_GENERIC *pc; + struct CACHED_GENERIC *qc; + struct HASH_ENTRY *ph; + struct HASH_ENTRY *qh; + struct HASH_ENTRY **px; + size_t size; + int i; - size = sizeof(struct CACHE_HEADER) + item_count*full_item_size; - if (max_hash) - size += item_count*sizeof(struct HASH_ENTRY) - + max_hash*sizeof(struct HASH_ENTRY*); - cache = (struct CACHE_HEADER*)ntfs_malloc(size); - if (cache) { - /* header */ - cache->name = name; - cache->dofree = dofree; - if (dohash && max_hash) { - cache->dohash = dohash; - cache->max_hash = max_hash; - } else { - cache->dohash = (cache_hash)NULL; - cache->max_hash = 0; - } - cache->fixed_size = full_item_size - sizeof(struct CACHED_GENERIC); - cache->reads = 0; - cache->writes = 0; - cache->hits = 0; - /* chain the data entries, and mark an invalid entry */ - cache->most_recent_entry = (struct CACHED_GENERIC*)NULL; - cache->oldest_entry = (struct CACHED_GENERIC*)NULL; - cache->free_entry = &cache->entry[0]; - pc = &cache->entry[0]; - for (i=0; i<(item_count - 1); i++) { - qc = (struct CACHED_GENERIC*)((char*)pc - + full_item_size); - pc->next = qc; - pc->variable = (void*)NULL; - pc->varsize = 0; - pc = qc; - } - /* special for the last entry */ - pc->next = (struct CACHED_GENERIC*)NULL; - pc->variable = (void*)NULL; - pc->varsize = 0; + size = sizeof(struct CACHE_HEADER) + item_count * full_item_size; + if (max_hash) size += item_count * sizeof(struct HASH_ENTRY) + max_hash * sizeof(struct HASH_ENTRY*); + cache = (struct CACHE_HEADER*) ntfs_malloc(size); + if (cache) + { + /* header */ + cache->name = name; + cache->dofree = dofree; + if (dohash && max_hash) + { + cache->dohash = dohash; + cache->max_hash = max_hash; + } + else + { + cache->dohash = (cache_hash) NULL; + cache->max_hash = 0; + } + cache->fixed_size = full_item_size - sizeof(struct CACHED_GENERIC); + cache->reads = 0; + cache->writes = 0; + cache->hits = 0; + /* chain the data entries, and mark an invalid entry */ + cache->most_recent_entry = (struct CACHED_GENERIC*) NULL; + cache->oldest_entry = (struct CACHED_GENERIC*) NULL; + cache->free_entry = &cache->entry[0]; + pc = &cache->entry[0]; + for (i = 0; i < (item_count - 1); i++) + { + qc = (struct CACHED_GENERIC*) ((char*) pc + full_item_size); + pc->next = qc; + pc->variable = (void*) NULL; + pc->varsize = 0; + pc = qc; + } + /* special for the last entry */ + pc->next = (struct CACHED_GENERIC*) NULL; + pc->variable = (void*) NULL; + pc->varsize = 0; - if (max_hash) { - /* chain the hash entries */ - ph = (struct HASH_ENTRY*)(((char*)pc) + full_item_size); - cache->free_hash = ph; - for (i=0; i<(item_count - 1); i++) { - qh = &ph[1]; - ph->next = qh; - ph = qh; - } - /* special for the last entry */ - if (item_count) { - ph->next = (struct HASH_ENTRY*)NULL; - } - /* create and initialize the hash indexes */ - px = (struct HASH_ENTRY**)&ph[1]; - cache->first_hash = px; - for (i=0; ifree_hash = (struct HASH_ENTRY*)NULL; - cache->first_hash = (struct HASH_ENTRY**)NULL; - } - } - return (cache); + if (max_hash) + { + /* chain the hash entries */ + ph = (struct HASH_ENTRY*) (((char*) pc) + full_item_size); + cache->free_hash = ph; + for (i = 0; i < (item_count - 1); i++) + { + qh = &ph[1]; + ph->next = qh; + ph = qh; + } + /* special for the last entry */ + if (item_count) + { + ph->next = (struct HASH_ENTRY*) NULL; + } + /* create and initialize the hash indexes */ + px = (struct HASH_ENTRY**) &ph[1]; + cache->first_hash = px; + for (i = 0; i < max_hash; i++) + px[i] = (struct HASH_ENTRY*) NULL; + } + else + { + cache->free_hash = (struct HASH_ENTRY*) NULL; + cache->first_hash = (struct HASH_ENTRY**) NULL; + } + } + return (cache); } /* @@ -560,30 +579,25 @@ static struct CACHE_HEADER *ntfs_create_cache(const char *name, void ntfs_create_lru_caches(ntfs_volume *vol) { #if CACHE_INODE_SIZE - /* inode cache */ - vol->xinode_cache = ntfs_create_cache("inode",(cache_free)NULL, - ntfs_dir_inode_hash, sizeof(struct CACHED_INODE), - CACHE_INODE_SIZE, 2*CACHE_INODE_SIZE); + /* inode cache */ + vol->xinode_cache = ntfs_create_cache("inode", (cache_free) NULL, ntfs_dir_inode_hash, sizeof(struct CACHED_INODE), + CACHE_INODE_SIZE, 2 * CACHE_INODE_SIZE); #endif #if CACHE_NIDATA_SIZE - /* idata cache */ - vol->nidata_cache = ntfs_create_cache("nidata", - ntfs_inode_nidata_free, ntfs_inode_nidata_hash, - sizeof(struct CACHED_NIDATA), - CACHE_NIDATA_SIZE, 2*CACHE_NIDATA_SIZE); + /* idata cache */ + vol->nidata_cache = ntfs_create_cache("nidata", ntfs_inode_nidata_free, ntfs_inode_nidata_hash, + sizeof(struct CACHED_NIDATA), CACHE_NIDATA_SIZE, 2 * CACHE_NIDATA_SIZE); #endif #if CACHE_LOOKUP_SIZE - /* lookup cache */ - vol->lookup_cache = ntfs_create_cache("lookup", - (cache_free)NULL, ntfs_dir_lookup_hash, - sizeof(struct CACHED_LOOKUP), - CACHE_LOOKUP_SIZE, 2*CACHE_LOOKUP_SIZE); + /* lookup cache */ + vol->lookup_cache = ntfs_create_cache("lookup", (cache_free) NULL, ntfs_dir_lookup_hash, + sizeof(struct CACHED_LOOKUP), CACHE_LOOKUP_SIZE, 2 * CACHE_LOOKUP_SIZE); #endif - vol->securid_cache = ntfs_create_cache("securid",(cache_free)NULL, - (cache_hash)NULL,sizeof(struct CACHED_SECURID), CACHE_SECURID_SIZE, 0); + vol->securid_cache = ntfs_create_cache("securid", (cache_free) NULL, (cache_hash) NULL, + sizeof(struct CACHED_SECURID), CACHE_SECURID_SIZE, 0); #if CACHE_LEGACY_SIZE - vol->legacy_cache = ntfs_create_cache("legacy",(cache_free)NULL, - (cache_hash)NULL, sizeof(struct CACHED_PERMISSIONS_LEGACY), CACHE_LEGACY_SIZE, 0); + vol->legacy_cache = ntfs_create_cache("legacy", (cache_free) NULL, (cache_hash) NULL, + sizeof(struct CACHED_PERMISSIONS_LEGACY), CACHE_LEGACY_SIZE, 0); #endif } @@ -594,16 +608,16 @@ void ntfs_create_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 #if CACHE_NIDATA_SIZE - ntfs_free_cache(vol->nidata_cache); + ntfs_free_cache(vol->nidata_cache); #endif #if CACHE_LOOKUP_SIZE - ntfs_free_cache(vol->lookup_cache); + ntfs_free_cache(vol->lookup_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/cache.h b/source/libntfs/cache.h index 67e4f9da..7f88cabd 100644 --- a/source/libntfs/cache.h +++ b/source/libntfs/cache.h @@ -24,93 +24,95 @@ #include "volume.h" -struct CACHED_GENERIC { - struct CACHED_GENERIC *next; - struct CACHED_GENERIC *previous; - void *variable; - size_t varsize; - union { - /* force alignment for pointers and u64 */ - u64 u64align; - void *ptralign; - } fixed[0]; -} ; +struct CACHED_GENERIC +{ + struct CACHED_GENERIC *next; + struct CACHED_GENERIC *previous; + void *variable; + size_t varsize; + union + { + /* force alignment for pointers and u64 */ + u64 u64align; + void *ptralign; + } fixed[0]; +}; -struct CACHED_INODE { - struct CACHED_INODE *next; - struct CACHED_INODE *previous; - const char *pathname; - size_t varsize; - /* above fields must match "struct CACHED_GENERIC" */ - u64 inum; -} ; +struct CACHED_INODE +{ + struct CACHED_INODE *next; + struct CACHED_INODE *previous; + const char *pathname; + size_t varsize; + /* above fields must match "struct CACHED_GENERIC" */ + u64 inum; +}; -struct CACHED_NIDATA { - struct CACHED_NIDATA *next; - struct CACHED_NIDATA *previous; - const char *pathname; /* not used */ - size_t varsize; /* not used */ - /* above fields must match "struct CACHED_GENERIC" */ - u64 inum; - ntfs_inode *ni; -} ; +struct CACHED_NIDATA +{ + struct CACHED_NIDATA *next; + struct CACHED_NIDATA *previous; + const char *pathname; /* not used */ + size_t varsize; /* not used */ + /* above fields must match "struct CACHED_GENERIC" */ + u64 inum; + ntfs_inode *ni; +}; -struct CACHED_LOOKUP { - struct CACHED_LOOKUP *next; - struct CACHED_LOOKUP *previous; - const char *name; - size_t namesize; - /* above fields must match "struct CACHED_GENERIC" */ - u64 parent; - u64 inum; -} ; +struct CACHED_LOOKUP +{ + struct CACHED_LOOKUP *next; + struct CACHED_LOOKUP *previous; + const char *name; + size_t namesize; + /* above fields must match "struct CACHED_GENERIC" */ + u64 parent; + u64 inum; +}; -enum { - CACHE_FREE = 1, - CACHE_NOHASH = 2 -} ; +enum +{ + CACHE_FREE = 1, CACHE_NOHASH = 2 +}; -typedef int (*cache_compare)(const struct CACHED_GENERIC *cached, - const struct CACHED_GENERIC *item); +typedef int (*cache_compare)(const struct CACHED_GENERIC *cached, const struct CACHED_GENERIC *item); typedef void (*cache_free)(const struct CACHED_GENERIC *cached); typedef int (*cache_hash)(const struct CACHED_GENERIC *cached); -struct HASH_ENTRY { - struct HASH_ENTRY *next; - struct CACHED_GENERIC *entry; -} ; +struct HASH_ENTRY +{ + struct HASH_ENTRY *next; + struct CACHED_GENERIC *entry; +}; -struct CACHE_HEADER { - const char *name; - struct CACHED_GENERIC *most_recent_entry; - struct CACHED_GENERIC *oldest_entry; - struct CACHED_GENERIC *free_entry; - struct HASH_ENTRY *free_hash; - struct HASH_ENTRY **first_hash; - cache_free dofree; - cache_hash dohash; - unsigned long reads; - unsigned long writes; - unsigned long hits; - int fixed_size; - int max_hash; - struct CACHED_GENERIC entry[0]; -} ; +struct CACHE_HEADER +{ + const char *name; + struct CACHED_GENERIC *most_recent_entry; + struct CACHED_GENERIC *oldest_entry; + struct CACHED_GENERIC *free_entry; + struct HASH_ENTRY *free_hash; + struct HASH_ENTRY **first_hash; + cache_free dofree; + cache_hash dohash; + unsigned long reads; + unsigned long writes; + unsigned long hits; + int fixed_size; + int max_hash; + 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); -struct CACHED_GENERIC *ntfs_enter_cache(struct CACHE_HEADER *cache, - const struct CACHED_GENERIC *item, - cache_compare compare); -int ntfs_invalidate_cache(struct CACHE_HEADER *cache, - const struct CACHED_GENERIC *item, - cache_compare compare, int flags); -int ntfs_remove_cache(struct CACHE_HEADER *cache, - struct CACHED_GENERIC *item, int flags); +struct CACHED_GENERIC *ntfs_fetch_cache(struct CACHE_HEADER *cache, 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); +int ntfs_invalidate_cache(struct CACHE_HEADER *cache, const struct CACHED_GENERIC *item, cache_compare compare, + int flags); +int ntfs_remove_cache(struct CACHE_HEADER *cache, struct CACHED_GENERIC *item, int flags); void ntfs_create_lru_caches(ntfs_volume *vol); void ntfs_free_lru_caches(ntfs_volume *vol); diff --git a/source/libntfs/cache2.c b/source/libntfs/cache2.c index 872f1a57..06a4f10a 100644 --- a/source/libntfs/cache2.c +++ b/source/libntfs/cache2.c @@ -16,13 +16,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -33,7 +33,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #include #include @@ -45,330 +45,384 @@ #define CACHE_FREE UINT_MAX -NTFS_CACHE* _NTFS_cache_constructor (unsigned int numberOfPages, unsigned int sectorsPerPage, const DISC_INTERFACE* discInterface, sec_t endOfPartition, sec_t sectorSize) { - NTFS_CACHE* cache; - unsigned int i; - NTFS_CACHE_ENTRY* cacheEntries; +NTFS_CACHE* _NTFS_cache_constructor(unsigned int numberOfPages, unsigned int sectorsPerPage, + const DISC_INTERFACE* discInterface, sec_t endOfPartition, sec_t sectorSize) +{ + 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->sectorSize = sectorSize; + cache->disc = discInterface; + cache->endOfPartition = endOfPartition; + cache->numberOfPages = numberOfPages; + cache->sectorsPerPage = sectorsPerPage; + cache->sectorSize = sectorSize; + 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 * cache->sectorSize); + } - 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 * cache->sectorSize ); - } + cache->cacheEntries = cacheEntries; - cache->cacheEntries = cacheEntries; - - return cache; + return cache; } -void _NTFS_cache_destructor (NTFS_CACHE* cache) { - unsigned int i; +void _NTFS_cache_destructor(NTFS_CACHE* cache) +{ + 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 u32 accessCounter = 0; -static u32 accessTime(){ - accessCounter++; - return accessCounter; -} - -static NTFS_CACHE_ENTRY* _NTFS_cache_getPage(NTFS_CACHE *cache,sec_t sector) +static u32 accessTime() { - 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; - - 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(!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(); - - return &(cacheEntries[oldUsed]); + accessCounter++; + return accessCounter; } -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; - - 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]; - } - } - } - - return entry; -} - -bool _NTFS_cache_readSectors(NTFS_CACHE *cache,sec_t sector,sec_t numSectors,void *buffer) +static NTFS_CACHE_ENTRY* _NTFS_cache_getPage(NTFS_CACHE *cache, sec_t sector) { - sec_t sec; - sec_t secs_to_read; - NTFS_CACHE_ENTRY *entry; - uint8_t *dest = buffer; + unsigned int i; + NTFS_CACHE_ENTRY* cacheEntries = cache->cacheEntries; + unsigned int numberOfPages = cache->numberOfPages; + unsigned int sectorsPerPage = cache->sectorsPerPage; - while(numSectors>0) { - entry = _NTFS_cache_getPage(cache,sector); - if(entry==NULL) return false; + bool foundFree = false; + unsigned int oldUsed = 0; + unsigned int oldAccess = UINT_MAX; - sec = sector - entry->sector; - secs_to_read = entry->count - sec; - if(secs_to_read>numSectors) secs_to_read = numSectors; + for (i = 0; i < numberOfPages; i++) + { + if (sector >= cacheEntries[i].sector && sector < (cacheEntries[i].sector + cacheEntries[i].count)) + { + cacheEntries[i].last_access = accessTime(); + return &(cacheEntries[i]); + } - memcpy(dest,entry->cache + (sec*cache->sectorSize),(secs_to_read*cache->sectorSize)); + if (foundFree == false && (cacheEntries[i].sector == CACHE_FREE || cacheEntries[i].last_access < oldAccess)) + { + if (cacheEntries[i].sector == CACHE_FREE) foundFree = true; + oldUsed = i; + oldAccess = cacheEntries[i].last_access; + } + } - dest += (secs_to_read*cache->sectorSize); - sector += secs_to_read; - numSectors -= secs_to_read; - } + 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; - return true; + 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(); + + 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; + + for (i = 0; i < numberOfPages; i++) + { + if (cacheEntries[i].sector != CACHE_FREE) + { + bool intersect; + if (sector > 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]; + } + } + } + + 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; + + 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; + + memcpy(dest, entry->cache + (sec * cache->sectorSize), (secs_to_read * cache->sectorSize)); + + dest += (secs_to_read * cache->sectorSize); + sector += secs_to_read; + numSectors -= secs_to_read; + } + + return true; } /* -Reads some data from a cache page, determined by the sector number -*/ + 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) +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; + sec_t sec; + NTFS_CACHE_ENTRY *entry; - if (offset + size > cache->sectorSize) return false; + if (offset + size > cache->sectorSize) 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*cache->sectorSize) + offset),size); + sec = sector - entry->sector; + memcpy(buffer, entry->cache + ((sec * cache->sectorSize) + 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; +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; - 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. -*/ + 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) +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; + sec_t sec; + NTFS_CACHE_ENTRY *entry; - if (offset + size > cache->sectorSize) return false; + if (offset + size > cache->sectorSize) 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*cache->sectorSize) + offset),buffer,size); + sec = sector - entry->sector; + memcpy(entry->cache + ((sec * cache->sectorSize) + 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}; +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 }; - 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 -*/ + 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) +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; + sec_t sec; + NTFS_CACHE_ENTRY *entry; - if (offset + size > cache->sectorSize) return false; + if (offset + size > cache->sectorSize) 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*cache->sectorSize),0,cache->sectorSize); - memcpy(entry->cache + ((sec*cache->sectorSize) + offset),buffer,size); + sec = sector - entry->sector; + memset(entry->cache + (sec * cache->sectorSize), 0, cache->sectorSize); + memcpy(entry->cache + ((sec * cache->sectorSize) + 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) +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; + sec_t sec; + sec_t secs_to_write; + NTFS_CACHE_ENTRY* entry; + const uint8_t *src = buffer; - while(numSectors>0) - { - entry = _NTFS_cache_findPage(cache,sector,numSectors); + while (numSectors > 0) + { + 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*cache->sectorSize); - sector += secs_to_write; - numSectors -= secs_to_write; - } + cache->disc->writeSectors(sector, secs_to_write, src); + src += (secs_to_write * cache->sectorSize); + 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*cache->sectorSize),src,(secs_to_write*cache->sectorSize)); + memcpy(entry->cache + (sec * cache->sectorSize), src, (secs_to_write * cache->sectorSize)); - src += (secs_to_write*cache->sectorSize); - sector += secs_to_write; - numSectors -= secs_to_write; + src += (secs_to_write * cache->sectorSize); + 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; + 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; - 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) - return; +void _NTFS_cache_invalidate(NTFS_CACHE* cache) +{ + 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/cache2.h b/source/libntfs/cache2.h index 21daca7c..bb315606 100644 --- a/source/libntfs/cache2.h +++ b/source/libntfs/cache2.h @@ -15,13 +15,13 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -32,7 +32,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ #ifndef _CACHE2_H #define _CACHE2_H @@ -46,90 +46,92 @@ #include #include -typedef struct { - sec_t sector; - unsigned int count; - u64 last_access; - bool dirty; - u8* cache; +typedef struct +{ + 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; - sec_t sectorSize; - NTFS_CACHE_ENTRY* cacheEntries; +typedef struct +{ + const DISC_INTERFACE* disc; + sec_t endOfPartition; + unsigned int numberOfPages; + unsigned int sectorsPerPage; + sec_t sectorSize; + NTFS_CACHE_ENTRY* cacheEntries; } NTFS_CACHE; /* -Read data from a sector in the NTFS_CACHE -If the sector is not in the NTFS_CACHE, it will be swapped in -offset is the position to start reading from -size is the amount of data to read -Precondition: offset + size <= BYTES_PER_READ -*/ + Read data from a sector in the NTFS_CACHE + If the sector is not in the NTFS_CACHE, it will be swapped in + offset is the position to start reading from + size is the amount of data to read + Precondition: offset + size <= BYTES_PER_READ + */ //bool _NTFS_cache_readPartialSector (NTFS_CACHE* NTFS_CACHE, void* buffer, sec_t sector, unsigned int offset, size_t size); //bool _NTFS_cache_readLittleEndianValue (NTFS_CACHE* NTFS_CACHE, uint32_t *value, sec_t sector, unsigned int offset, int num_bytes); /* -Write data to a sector in the NTFS_CACHE -If the sector is not in the NTFS_CACHE, it will be swapped in. -When the sector is swapped out, the data will be written to the disc -offset is the position to start writing to -size is the amount of data to write -Precondition: offset + size <= BYTES_PER_READ -*/ + Write data to a sector in the NTFS_CACHE + If the sector is not in the NTFS_CACHE, it will be swapped in. + When the sector is swapped out, the data will be written to the disc + offset is the position to start writing to + size is the amount of data to write + Precondition: offset + size <= BYTES_PER_READ + */ //bool _NTFS_cache_writePartialSector (NTFS_CACHE* NTFS_CACHE, const void* buffer, sec_t sector, unsigned int offset, size_t size); //bool _NTFS_cache_writeLittleEndianValue (NTFS_CACHE* NTFS_CACHE, const uint32_t value, sec_t sector, unsigned int offset, int num_bytes); /* -Write data to a sector in the NTFS_CACHE, zeroing the sector first -If the sector is not in the NTFS_CACHE, it will be swapped in. -When the sector is swapped out, the data will be written to the disc -offset is the position to start writing to -size is the amount of data to write -Precondition: offset + size <= BYTES_PER_READ -*/ + Write data to a sector in the NTFS_CACHE, zeroing the sector first + If the sector is not in the NTFS_CACHE, it will be swapped in. + When the sector is swapped out, the data will be written to the disc + offset is the position to start writing to + size is the amount of data to write + Precondition: offset + size <= BYTES_PER_READ + */ //bool _NTFS_cache_eraseWritePartialSector (NTFS_CACHE* NTFS_CACHE, const void* buffer, sec_t sector, unsigned int offset, size_t size); /* -Read several sectors from the NTFS_CACHE -*/ -bool _NTFS_cache_readSectors (NTFS_CACHE* NTFS_CACHE, sec_t sector, sec_t numSectors, void* buffer); + Read several sectors from the NTFS_CACHE + */ +bool _NTFS_cache_readSectors(NTFS_CACHE* NTFS_CACHE, sec_t sector, sec_t numSectors, void* buffer); /* -Read a full sector from the NTFS_CACHE -*/ + Read a full sector from the NTFS_CACHE + */ //static inline bool _NTFS_cache_readSector (NTFS_CACHE* NTFS_CACHE, void* buffer, sec_t sector) { // return _NTFS_cache_readPartialSector (NTFS_CACHE, buffer, sector, 0, BYTES_PER_READ); //} /* -Write a full sector to the NTFS_CACHE -*/ + Write a full sector to the NTFS_CACHE + */ //static inline bool _NTFS_cache_writeSector (NTFS_CACHE* NTFS_CACHE, const void* buffer, sec_t sector) { // return _NTFS_cache_writePartialSector (NTFS_CACHE, buffer, sector, 0, BYTES_PER_READ); //} -bool _NTFS_cache_writeSectors (NTFS_CACHE* NTFS_CACHE, sec_t sector, sec_t numSectors, const void* buffer); +bool _NTFS_cache_writeSectors(NTFS_CACHE* NTFS_CACHE, sec_t sector, sec_t numSectors, const void* buffer); /* -Write any dirty sectors back to disc and clear out the contents of the NTFS_CACHE -*/ -bool _NTFS_cache_flush (NTFS_CACHE* NTFS_CACHE); + Write any dirty sectors back to disc and clear out the contents of the NTFS_CACHE + */ +bool _NTFS_cache_flush(NTFS_CACHE* NTFS_CACHE); /* -Clear out the contents of the NTFS_CACHE without writing any dirty sectors first -*/ -void _NTFS_cache_invalidate (NTFS_CACHE* NTFS_CACHE); + Clear out the contents of the NTFS_CACHE without writing any dirty sectors first + */ +void _NTFS_cache_invalidate(NTFS_CACHE* NTFS_CACHE); -NTFS_CACHE* _NTFS_cache_constructor (unsigned int numberOfPages, unsigned int sectorsPerPage, const DISC_INTERFACE* discInterface, sec_t endOfPartition, sec_t sectorSize); +NTFS_CACHE* _NTFS_cache_constructor(unsigned int numberOfPages, unsigned int sectorsPerPage, + const DISC_INTERFACE* discInterface, sec_t endOfPartition, sec_t sectorSize); -void _NTFS_cache_destructor (NTFS_CACHE* NTFS_CACHE); +void _NTFS_cache_destructor(NTFS_CACHE* NTFS_CACHE); #endif // _CACHE_H - diff --git a/source/libntfs/collate.c b/source/libntfs/collate.c index 5f7a015a..a44c671a 100644 --- a/source/libntfs/collate.c +++ b/source/libntfs/collate.c @@ -52,22 +52,21 @@ * * 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) +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; + 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; } /** @@ -82,30 +81,30 @@ 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) +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; + 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; } /** @@ -114,39 +113,40 @@ static int ntfs_collate_ntofs_ulong(ntfs_volume *vol __attribute__((unused)), * Returns: -1, 0 or 1 depending of how the arrays compare */ -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) +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; + 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; } /** @@ -162,45 +162,47 @@ 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) +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 le32 *p1, *p2; + int rc; + u32 d1, d2; + const le32 *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 le32*)data1; - p2 = (const le32*)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 le32*) data1; + p2 = (const le32*) 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; } /** @@ -215,25 +217,21 @@ 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))) +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))) { - const FILE_NAME_ATTR *file_name_attr1; - const FILE_NAME_ATTR *file_name_attr2; - int rc; + const FILE_NAME_ATTR *file_name_attr1; + const FILE_NAME_ATTR *file_name_attr2; + int rc; - ntfs_log_trace("Entering.\n"); - file_name_attr1 = (const FILE_NAME_ATTR*)data1; - file_name_attr2 = (const FILE_NAME_ATTR*)data2; - rc = ntfs_names_full_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, - CASE_SENSITIVE, vol->upcase, vol->upcase_len); - ntfs_log_trace("Done, returning %i.\n", rc); - return rc; + ntfs_log_trace("Entering.\n"); + file_name_attr1 = (const FILE_NAME_ATTR*) data1; + file_name_attr2 = (const FILE_NAME_ATTR*) data2; + rc = ntfs_names_full_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, CASE_SENSITIVE, vol->upcase, + vol->upcase_len); + ntfs_log_trace("Done, returning %i.\n", rc); + return rc; } /* @@ -244,28 +242,29 @@ static int ntfs_collate_file_name(ntfs_volume *vol, COLLATE ntfs_get_collate_function(COLLATION_RULES cr) { - COLLATE collate; + COLLATE collate; - switch (cr) { - case COLLATION_BINARY : - collate = ntfs_collate_binary; - break; - case COLLATION_FILE_NAME : - collate = ntfs_collate_file_name; - break; - case COLLATION_NTOFS_SECURITY_HASH : - collate = ntfs_collate_ntofs_security_hash; - break; - case COLLATION_NTOFS_ULONG : - collate = ntfs_collate_ntofs_ulong; - break; - case COLLATION_NTOFS_ULONGS : - collate = ntfs_collate_ntofs_ulongs; - break; - default : - errno = EOPNOTSUPP; - collate = (COLLATE)NULL; - break; - } - return (collate); + switch (cr) + { + case COLLATION_BINARY: + collate = ntfs_collate_binary; + break; + case COLLATION_FILE_NAME: + collate = ntfs_collate_file_name; + break; + case COLLATION_NTOFS_SECURITY_HASH: + collate = ntfs_collate_ntofs_security_hash; + break; + case COLLATION_NTOFS_ULONG: + collate = ntfs_collate_ntofs_ulong; + break; + case COLLATION_NTOFS_ULONGS: + collate = ntfs_collate_ntofs_ulongs; + break; + default: + errno = EOPNOTSUPP; + collate = (COLLATE) NULL; + break; + } + return (collate); } diff --git a/source/libntfs/compat.c b/source/libntfs/compat.c index 63114a48..d241cf8a 100644 --- a/source/libntfs/compat.c +++ b/source/libntfs/compat.c @@ -37,31 +37,35 @@ */ int ffs(int x) { - int r = 1; + 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,32 +124,32 @@ static const char rcsid[] = "$Id: compat.c,v 1.1.1.1.2.1 2008-08-16 15:17:44 jpa #include #endif -int daemon(int nochdir, int noclose) { - int fd; +int daemon(int nochdir, int noclose) +{ + 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 @@ -218,29 +222,31 @@ static const char rcsid[] = "$Id: compat.c,v 1.1.1.1.2.1 2008-08-16 15:17:44 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 *strsep(char **stringp, const char *delim) +{ + 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 */ } /* diff --git a/source/libntfs/compress.c b/source/libntfs/compress.c index fbd30ba9..816c7e53 100644 --- a/source/libntfs/compress.c +++ b/source/libntfs/compress.c @@ -65,31 +65,29 @@ /** * 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, +typedef enum +{ + /* 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]; -} ; +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]; +}; /* * Initialize the match tree @@ -97,12 +95,12 @@ struct COMPRESS_CONTEXT { static void ntfs_init_compress_tree(struct COMPRESS_CONTEXT *pctx) { - int i; + 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,88 +108,95 @@ static void ntfs_init_compress_tree(struct COMPRESS_CONTEXT *pctx) * further similar strings */ -static void ntfs_new_node (struct COMPRESS_CONTEXT *pctx, - unsigned int r) +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 long mxi; - unsigned int mxl; + unsigned int pp; + BOOL less; + BOOL done; + const unsigned char *key; + int c; + unsigned long 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 long 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 long i; + register const unsigned char *p1, *p2; - i = 1; - mxi = NTFS_SB_SIZE - r; - if (mxi < 2) - less = FALSE; - else { - p1 = key; - p2 = &pctx->inbuf[pp]; - /* this loop has a significant impact on performances */ - 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; - /* remove pp */ - pctx->dad[pp] = NIL; - 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; + mxi = NTFS_SB_SIZE - r; + if (mxi < 2) + less = FALSE; + else + { + p1 = key; + p2 = &pctx->inbuf[pp]; + /* this loop has a significant impact on performances */ + 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; + /* remove pp */ + pctx->dad[pp] = NIL; + 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); } /* @@ -202,50 +207,51 @@ 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) +static unsigned int ntfs_nextmatch(struct COMPRESS_CONTEXT *pctx, unsigned int rr, int dd) { - unsigned int bestlen = 0; + 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); -bug : - return (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); + bug: return (0); } /* @@ -255,93 +261,98 @@ bug : * or zero if there was an error */ -static unsigned int ntfs_compress_block(const char *inbuf, - unsigned int size, char *outbuf) +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; + 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 */ -bug : - return (0); + 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); } /** @@ -359,173 +370,169 @@ 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) +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. */ + /* + * 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); -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; -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; + 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; + 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; - 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; -return_overflow: - errno = EOVERFLOW; - ntfs_log_perror("Failed to decompress file"); - return -1; + /* 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; } /** @@ -543,42 +550,38 @@ 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) +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; + /* + * 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; } /** @@ -604,259 +607,263 @@ restart: */ 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 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; -do_next_cb: - nr_cbs--; - cb_pos = cb; - vcn = start_vcn; - start_vcn += 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; - /* 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) { - if (!br) { - ntfs_log_error("Failed to read an" - " uncompressed cluster," - " inode %lld offs 0x%llx\n", - (long long)na->ni->mft_no, - (long long)ofs); - errno = EIO; - } - 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; + /* Need a temporary buffer for each loaded compression block. */ + cb = (u8*) ntfs_malloc(cb_size); + if (!cb) return -1; - /* - * 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) { - if (!br) { - ntfs_log_error("Failed to read a" - " compressed cluster, " - " inode %lld offs 0x%llx\n", - (long long)na->ni->mft_no, - (long long)(vcn << vol->cluster_size_bits)); - errno = EIO; - } - 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; + /* 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; + + /* 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) + { + if (!br) + { + ntfs_log_error("Failed to read an" + " uncompressed cluster," + " inode %lld offs 0x%llx\n", + (long long)na->ni->mft_no, + (long long)ofs); + errno = EIO; + } + 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) + { + if (!br) + { + ntfs_log_error("Failed to read a" + " compressed cluster, " + " inode %lld offs 0x%llx\n", + (long long)na->ni->mft_no, + (long long)(vcn << vol->cluster_size_bits)); + errno = EIO; + } + 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; } /* @@ -865,40 +872,41 @@ do_next_cb: * Returns the amount of data read */ -static u32 read_clusters(ntfs_volume *vol, const runlist_element *rl, - s64 offs, u32 to_read, char *inbuf) +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; + 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); } /* @@ -907,42 +915,42 @@ static u32 read_clusters(ntfs_volume *vol, const runlist_element *rl, * Returns the amount of data written */ -static s32 write_clusters(ntfs_volume *vol, const runlist_element *rl, - s64 offs, s32 to_write, const char *outbuf) +static s32 write_clusters(ntfs_volume *vol, const runlist_element *rl, s64 offs, s32 to_write, const char *outbuf) { - s32 count; - s32 put, xput; - s64 xpos; - BOOL first; - const char *xoutbuf; - const runlist_element *xrl; + s32 count; + s32 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); } - /* * Compress and write a set of blocks * @@ -952,96 +960,94 @@ static s32 write_clusters(ntfs_volume *vol, const runlist_element *rl, * or -2 if there were an irrecoverable error (errno set) */ -static s32 ntfs_comp_set(ntfs_attr *na, runlist_element *rl, - s64 offs, u32 insz, const char *inbuf) +static s32 ntfs_comp_set(ntfs_attr *na, runlist_element *rl, s64 offs, u32 insz, const char *inbuf) { - ntfs_volume *vol; - char *outbuf; - char *pbuf; - u32 compsz; - s32 written; - s32 rounded; - unsigned int clsz; - u32 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 } ; + ntfs_volume *vol; + char *outbuf; + char *pbuf; + u32 compsz; + s32 written; + s32 rounded; + unsigned int clsz; + u32 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) { - /* - * TODO : 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); + 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 < insz) && !fail; p += NTFS_SB_SIZE) + { + if ((p + NTFS_SB_SIZE) < insz) + bsz = NTFS_SB_SIZE; + else bsz = insz - p; + pbuf = &outbuf[compsz]; + sz = ntfs_compress_block(&inbuf[p], bsz, pbuf); + /* fail if all the clusters (or more) are needed */ + if (!sz || ((compsz + sz + clsz + 2) > 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) + { + /* + * TODO : 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); } /* @@ -1051,40 +1057,42 @@ static s32 ntfs_comp_set(ntfs_attr *na, runlist_element *rl, * errno is set if the runlist is not valid */ -static BOOL valid_compressed_run(ntfs_attr *na, runlist_element *rl, - BOOL fullcheck, const char *text) +static BOOL valid_compressed_run(ntfs_attr *na, runlist_element *rl, BOOL fullcheck, const char *text) { - runlist_element *xrl; - const char *err; - BOOL ok = TRUE; + runlist_element *xrl; + const char *err; + BOOL ok = TRUE; - xrl = rl; - while (xrl->vcn & (na->compression_block_clusters - 1)) - xrl--; - err = (const char*)NULL; - while (xrl->length) { - if ((xrl->vcn + xrl->length) != xrl[1].vcn) - err = "Runs not adjacent"; - if (xrl->lcn == LCN_HOLE) { - if ((xrl->vcn + xrl->length) - & (na->compression_block_clusters - 1)) { - err = "Invalid hole"; - } - if (fullcheck && (xrl[1].lcn == LCN_HOLE)) { - err = "Adjacent holes"; - } - } - if (err) { - ntfs_log_error("%s at %s index %ld inode %lld\n", - err, text, (long)(xrl - na->rl), - (long long)na->ni->mft_no); - errno = EIO; - ok = FALSE; - err = (const char*)NULL; - } - xrl++; - } - return (ok); + xrl = rl; + while (xrl->vcn & (na->compression_block_clusters - 1)) + xrl--; + err = (const char*) NULL; + while (xrl->length) + { + if ((xrl->vcn + xrl->length) != xrl[1].vcn) err = "Runs not adjacent"; + if (xrl->lcn == LCN_HOLE) + { + if ((xrl->vcn + xrl->length) & (na->compression_block_clusters - 1)) + { + err = "Invalid hole"; + } + if (fullcheck && (xrl[1].lcn == LCN_HOLE)) + { + err = "Adjacent holes"; + } + } + if (err) + { + ntfs_log_error("%s at %s index %ld inode %lld\n", + err, text, (long)(xrl - na->rl), + (long long)na->ni->mft_no); + errno = EIO; + ok = FALSE; + err = (const char*) NULL; + } + xrl++; + } + return (ok); } /* @@ -1115,206 +1123,229 @@ static BOOL valid_compressed_run(ntfs_attr *na, runlist_element *rl, * */ -static int ntfs_compress_overwr_free(ntfs_attr *na, runlist_element *rl, - s32 usedcnt, s32 freecnt, VCN *update_from) +static int ntfs_compress_overwr_free(ntfs_attr *na, runlist_element *rl, s32 usedcnt, s32 freecnt, VCN *update_from) { - BOOL beginhole; - BOOL mergeholes; - s32 oldlength; - s32 freelength; - s64 freelcn; - s64 freevcn; - runlist_element *freerl; - ntfs_volume *vol; - s32 carry; - int res; + BOOL beginhole; + BOOL mergeholes; + s32 oldlength; + s32 freelength; + s64 freelcn; + s64 freevcn; + runlist_element *freerl; + ntfs_volume *vol; + s32 carry; + int res; - vol = na->ni->vol; - res = 0; - freelcn = rl->lcn + usedcnt; - freevcn = rl->vcn + usedcnt; - freelength = rl->length - usedcnt; - beginhole = !usedcnt && !rl->vcn; - /* can merge with hole before ? */ - mergeholes = !usedcnt - && rl[0].vcn - && (rl[-1].lcn == LCN_HOLE); - /* truncate current run, carry to subsequent hole */ - carry = freelength; - oldlength = rl->length; - if (mergeholes) { - /* merging with a hole before */ - freerl = rl; - } else { - rl->length -= freelength; /* warning : can be zero */ - freerl = ++rl; - } - if (!mergeholes && (usedcnt || beginhole)) { - s32 freed; - runlist_element *frl; - runlist_element *erl; - int holes = 0; - BOOL threeparts; + vol = na->ni->vol; + res = 0; + freelcn = rl->lcn + usedcnt; + freevcn = rl->vcn + usedcnt; + freelength = rl->length - usedcnt; + beginhole = !usedcnt && !rl->vcn; + /* can merge with hole before ? */ + mergeholes = !usedcnt && rl[0].vcn && (rl[-1].lcn == LCN_HOLE); + /* truncate current run, carry to subsequent hole */ + carry = freelength; + oldlength = rl->length; + if (mergeholes) + { + /* merging with a hole before */ + freerl = rl; + } + else + { + rl->length -= freelength; /* warning : can be zero */ + freerl = ++rl; + } + if (!mergeholes && (usedcnt || beginhole)) + { + s32 freed; + runlist_element *frl; + runlist_element *erl; + int holes = 0; + BOOL threeparts; - /* free the unneeded clusters from initial run, then freerl */ - threeparts = (freelength > freecnt); - freed = 0; - frl = freerl; - if (freelength) { - res = ntfs_cluster_free_basic(vol,freelcn, - (threeparts ? freecnt : freelength)); - if (!res) - freed += (threeparts ? freecnt : freelength); - if (!usedcnt) { - holes++; - freerl--; - freerl->length += (threeparts - ? freecnt : freelength); - if (freerl->vcn < *update_from) - *update_from = freerl->vcn; - } - } - while (!res && frl->length && (freed < freecnt)) { - if (frl->length <= (freecnt - freed)) { - res = ntfs_cluster_free_basic(vol, frl->lcn, - frl->length); - if (!res) { - freed += frl->length; - frl->lcn = LCN_HOLE; - frl->length += carry; - carry = 0; - holes++; - } - } else { - res = ntfs_cluster_free_basic(vol, frl->lcn, - freecnt - freed); - if (!res) { - frl->lcn += freecnt - freed; - frl->vcn += freecnt - freed; - frl->length -= freecnt - freed; - freed = freecnt; - } - } - frl++; - } - na->compressed_size -= freed << vol->cluster_size_bits; - switch (holes) { - case 0 : - /* there are no hole, must insert one */ - /* space for hole has been prereserved */ - if (freerl->lcn == LCN_HOLE) { - if (threeparts) { - erl = freerl; - while (erl->length) - erl++; - do { - erl[2] = *erl; - } while (erl-- != freerl); + /* free the unneeded clusters from initial run, then freerl */ + threeparts = (freelength > freecnt); + freed = 0; + frl = freerl; + if (freelength) + { + res = ntfs_cluster_free_basic(vol, freelcn, (threeparts ? freecnt : freelength)); + if (!res) freed += (threeparts ? freecnt : freelength); + if (!usedcnt) + { + holes++; + freerl--; + freerl->length += (threeparts ? freecnt : freelength); + if (freerl->vcn < *update_from) *update_from = freerl->vcn; + } + } + while (!res && frl->length && (freed < freecnt)) + { + if (frl->length <= (freecnt - freed)) + { + res = ntfs_cluster_free_basic(vol, frl->lcn, frl->length); + if (!res) + { + freed += frl->length; + frl->lcn = LCN_HOLE; + frl->length += carry; + carry = 0; + holes++; + } + } + else + { + res = ntfs_cluster_free_basic(vol, frl->lcn, freecnt - freed); + if (!res) + { + frl->lcn += freecnt - freed; + frl->vcn += freecnt - freed; + frl->length -= freecnt - freed; + freed = freecnt; + } + } + frl++; + } + na->compressed_size -= freed << vol->cluster_size_bits; + switch (holes) + { + case 0: + /* there are no hole, must insert one */ + /* space for hole has been prereserved */ + if (freerl->lcn == LCN_HOLE) + { + if (threeparts) + { + erl = freerl; + while (erl->length) + erl++; + do + { + erl[2] = *erl; + } while (erl-- != freerl); - freerl[1].length = freelength - freecnt; - freerl->length = freecnt; - freerl[1].lcn = freelcn + freecnt; - freerl[1].vcn = freevcn + freecnt; - freerl[2].lcn = LCN_HOLE; - freerl[2].vcn = freerl[1].vcn - + freerl[1].length; - freerl->vcn = freevcn; - } else { - freerl->vcn = freevcn; - freerl->length += freelength; - } - } else { - erl = freerl; - while (erl->length) - erl++; - if (threeparts) { - do { - erl[2] = *erl; - } while (erl-- != freerl); - freerl[1].lcn = freelcn + freecnt; - freerl[1].vcn = freevcn + freecnt; - freerl[1].length = oldlength - usedcnt - freecnt; - } else { - do { - erl[1] = *erl; - } while (erl-- != freerl); - } - freerl->lcn = LCN_HOLE; - freerl->vcn = freevcn; - freerl->length = freecnt; - } - break; - case 1 : - /* there is a single hole, may have to merge */ - freerl->vcn = freevcn; - if (freerl[1].lcn == LCN_HOLE) { - freerl->length += freerl[1].length; - erl = freerl; - do { - erl++; - *erl = erl[1]; - } while (erl->length); - } - break; - default : - /* there were several holes, must merge them */ - freerl->lcn = LCN_HOLE; - freerl->vcn = freevcn; - freerl->length = freecnt; - if (freerl[holes].lcn == LCN_HOLE) { - freerl->length += freerl[holes].length; - holes++; - } - erl = freerl; - do { - erl++; - *erl = erl[holes - 1]; - } while (erl->length); - break; - } - } else { - s32 freed; - runlist_element *frl; - runlist_element *xrl; + freerl[1].length = freelength - freecnt; + freerl->length = freecnt; + freerl[1].lcn = freelcn + freecnt; + freerl[1].vcn = freevcn + freecnt; + freerl[2].lcn = LCN_HOLE; + freerl[2].vcn = freerl[1].vcn + freerl[1].length; + freerl->vcn = freevcn; + } + else + { + freerl->vcn = freevcn; + freerl->length += freelength; + } + } + else + { + erl = freerl; + while (erl->length) + erl++; + if (threeparts) + { + do + { + erl[2] = *erl; + } while (erl-- != freerl); + freerl[1].lcn = freelcn + freecnt; + freerl[1].vcn = freevcn + freecnt; + freerl[1].length = oldlength - usedcnt - freecnt; + } + else + { + do + { + erl[1] = *erl; + } while (erl-- != freerl); + } + freerl->lcn = LCN_HOLE; + freerl->vcn = freevcn; + freerl->length = freecnt; + } + break; + case 1: + /* there is a single hole, may have to merge */ + freerl->vcn = freevcn; + if (freerl[1].lcn == LCN_HOLE) + { + freerl->length += freerl[1].length; + erl = freerl; + do + { + erl++; + *erl = erl[1]; + } while (erl->length); + } + break; + default: + /* there were several holes, must merge them */ + freerl->lcn = LCN_HOLE; + freerl->vcn = freevcn; + freerl->length = freecnt; + if (freerl[holes].lcn == LCN_HOLE) + { + freerl->length += freerl[holes].length; + holes++; + } + erl = freerl; + do + { + erl++; + *erl = erl[holes - 1]; + } while (erl->length); + break; + } + } + else + { + s32 freed; + runlist_element *frl; + runlist_element *xrl; - freed = 0; - frl = freerl--; - if (freerl->vcn < *update_from) - *update_from = freerl->vcn; - while (!res && frl->length && (freed < freecnt)) { - if (frl->length <= (freecnt - freed)) { - freerl->length += frl->length; - freed += frl->length; - res = ntfs_cluster_free_basic(vol, frl->lcn, - frl->length); - frl++; - } else { - freerl->length += freecnt - freed; - res = ntfs_cluster_free_basic(vol, frl->lcn, - freecnt - freed); - frl->lcn += freecnt - freed; - frl->vcn += freecnt - freed; - frl->length -= freecnt - freed; - freed = freecnt; - } - } - /* remove unneded runlist entries */ - xrl = freerl; - /* group with next run if also a hole */ - if (frl->length && (frl->lcn == LCN_HOLE)) { - xrl->length += frl->length; - frl++; - } - while (frl->length) { - *++xrl = *frl++; - } - *++xrl = *frl; /* terminator */ - na->compressed_size -= freed << vol->cluster_size_bits; - } - return (res); + freed = 0; + frl = freerl--; + if (freerl->vcn < *update_from) *update_from = freerl->vcn; + while (!res && frl->length && (freed < freecnt)) + { + if (frl->length <= (freecnt - freed)) + { + freerl->length += frl->length; + freed += frl->length; + res = ntfs_cluster_free_basic(vol, frl->lcn, frl->length); + frl++; + } + else + { + freerl->length += freecnt - freed; + res = ntfs_cluster_free_basic(vol, frl->lcn, freecnt - freed); + frl->lcn += freecnt - freed; + frl->vcn += freecnt - freed; + frl->length -= freecnt - freed; + freed = freecnt; + } + } + /* remove unneded runlist entries */ + xrl = freerl; + /* group with next run if also a hole */ + if (frl->length && (frl->lcn == LCN_HOLE)) + { + xrl->length += frl->length; + frl++; + } + while (frl->length) + { + *++xrl = *frl++; + } + *++xrl = *frl; /* terminator */ + na->compressed_size -= freed << vol->cluster_size_bits; + } + return (res); } - /* * Free unneeded clusters after compression * @@ -1326,136 +1357,141 @@ static int ntfs_compress_overwr_free(ntfs_attr *na, runlist_element *rl, * Returns zero unless some error occurred (described by errno) */ -static int ntfs_compress_free(ntfs_attr *na, runlist_element *rl, - s64 used, s64 reserved, BOOL appending, - VCN *update_from) +static int ntfs_compress_free(ntfs_attr *na, runlist_element *rl, s64 used, s64 reserved, BOOL appending, + VCN *update_from) { - s32 freecnt; - s32 usedcnt; - int res; - s64 freelcn; - s64 freevcn; - s32 freelength; - BOOL mergeholes; - BOOL beginhole; - ntfs_volume *vol; - runlist_element *freerl; + s32 freecnt; + s32 usedcnt; + int res; + s64 freelcn; + s64 freevcn; + s32 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; - if (rl->vcn < *update_from) - *update_from = rl->vcn; - /* skip entries fully used, if any */ - while (rl->length && (rl->length < usedcnt)) { - usedcnt -= rl->length; /* must be > 0 */ - 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. - */ - /* get the free part in initial run */ - freelcn = rl->lcn + usedcnt; - freevcn = rl->vcn + usedcnt; - /* new count of allocated clusters */ - if (!((freevcn + freecnt) - & (na->compression_block_clusters - 1))) { - if (!appending) - res = ntfs_compress_overwr_free(na,rl, - usedcnt,freecnt,update_from); - else { - freelength = rl->length - usedcnt; - beginhole = !usedcnt && !rl->vcn; - mergeholes = !usedcnt - && rl[0].vcn - && (rl[-1].lcn == LCN_HOLE); - if (mergeholes) { - s32 carry; + res = -1; /* default return */ + vol = na->ni->vol; + freecnt = (reserved - used) >> vol->cluster_size_bits; + usedcnt = (reserved >> vol->cluster_size_bits) - freecnt; + if (rl->vcn < *update_from) *update_from = rl->vcn; + /* skip entries fully used, if any */ + while (rl->length && (rl->length < usedcnt)) + { + usedcnt -= rl->length; /* must be > 0 */ + 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. + */ + /* get the free part in initial run */ + freelcn = rl->lcn + usedcnt; + freevcn = rl->vcn + usedcnt; + /* new count of allocated clusters */ + if (!((freevcn + freecnt) & (na->compression_block_clusters - 1))) + { + if (!appending) + res = ntfs_compress_overwr_free(na, rl, usedcnt, freecnt, update_from); + else + { + freelength = rl->length - usedcnt; + beginhole = !usedcnt && !rl->vcn; + mergeholes = !usedcnt && rl[0].vcn && (rl[-1].lcn == LCN_HOLE); + if (mergeholes) + { + s32 carry; - /* shorten the runs which have free space */ - carry = freecnt; - freerl = rl; - while (freerl->length < carry) { - carry -= freerl->length; - freerl++; - } - freerl->length = carry; - freerl = rl; - } else { - rl->length = usedcnt; /* can be zero ? */ - 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; - } else { - /* why is this different from the begin hole case ? */ - if ((freelength > 0) - && !mergeholes - && !usedcnt) { - freerl--; - freerl->length = freelength; - if (freerl->vcn < *update_from) - *update_from - = freerl->vcn; - } - } - /* free the hole */ - res = ntfs_cluster_free_from_rl(vol,freerl); - if (!res) { - na->compressed_size -= freecnt - << vol->cluster_size_bits; - 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; - } - if (freerl->vcn < *update_from) - *update_from = freerl->vcn; - /* 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); + /* shorten the runs which have free space */ + carry = freecnt; + freerl = rl; + while (freerl->length < carry) + { + carry -= freerl->length; + freerl++; + } + freerl->length = carry; + freerl = rl; + } + else + { + rl->length = usedcnt; /* can be zero ? */ + 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; + } + else + { + /* why is this different from the begin hole case ? */ + if ((freelength > 0) && !mergeholes && !usedcnt) + { + freerl--; + freerl->length = freelength; + if (freerl->vcn < *update_from) *update_from = freerl->vcn; + } + } + /* free the hole */ + res = ntfs_cluster_free_from_rl(vol, freerl); + if (!res) + { + na->compressed_size -= freecnt << vol->cluster_size_bits; + 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; + } + if (freerl->vcn < *update_from) *update_from = freerl->vcn; + /* 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); } /* @@ -1463,40 +1499,40 @@ static int ntfs_compress_free(ntfs_attr *na, runlist_element *rl, * Do nothing if something fails */ -static int ntfs_read_append(ntfs_attr *na, const runlist_element *rl, - s64 offs, u32 compsz, s32 pos, BOOL appending, - char *outbuf, s64 to_write, const void *b) +static int ntfs_read_append(ntfs_attr *na, const runlist_element *rl, s64 offs, u32 compsz, s32 pos, BOOL appending, + char *outbuf, s64 to_write, const void *b) { - int fail = 1; - char *compbuf; - u32 decompsz; - u32 got; + 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 */ - if (appending) - decompsz = ((pos - 1) | (NTFS_SB_SIZE - 1)) + 1; - else - decompsz = na->compression_block_size; - 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 */ + if (appending) + decompsz = ((pos - 1) | (NTFS_SB_SIZE - 1)) + 1; + else decompsz = na->compression_block_size; + 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); } /* @@ -1507,34 +1543,29 @@ static int ntfs_read_append(ntfs_attr *na, const runlist_element *rl, * or -1 if there were an irrecoverable error (errno set) */ -static int ntfs_flush(ntfs_attr *na, runlist_element *rl, s64 offs, - const char *outbuf, s32 count, BOOL compress, - BOOL appending, VCN *update_from) +static int ntfs_flush(ntfs_attr *na, runlist_element *rl, s64 offs, const char *outbuf, s32 count, BOOL compress, + BOOL appending, VCN *update_from) { - int rounded; - int written; - int clsz; + 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, appending, - update_from)) - written = -1; - } else - written = 0; - 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, appending, + update_from)) written = -1; + } + else written = 0; + 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); } /* @@ -1549,193 +1580,190 @@ static int ntfs_flush(ntfs_attr *na, runlist_element *rl, s64 offs, * to be allocated before the function is called again. */ -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, - VCN *update_from) +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, VCN *update_from) { - ntfs_volume *vol; - runlist_element *brl; /* entry containing the beginning of block */ - int compression_length; - s64 written; - s64 to_read; - s64 to_flush; - s64 roffs; - s64 got; - s64 start_vcn; - s64 nextblock; - s64 endwrite; - u32 compsz; - char *inbuf; - char *outbuf; - BOOL fail; - BOOL done; - BOOL compress; - BOOL appending; + ntfs_volume *vol; + runlist_element *brl; /* entry containing the beginning of block */ + int compression_length; + s64 written; + s64 to_read; + s64 to_flush; + s64 roffs; + s64 got; + s64 start_vcn; + s64 nextblock; + s64 endwrite; + u32 compsz; + char *inbuf; + char *outbuf; + BOOL fail; + BOOL done; + BOOL compress; + BOOL appending; - if (!valid_compressed_run(na,wrl,FALSE,"begin compressed write")) { - return (-1); - } - if ((*update_from < 0) - || (compressed_part < 0) - || (compressed_part > (int)na->compression_block_clusters)) { - ntfs_log_error("Bad update vcn or compressed_part %d for compressed write\n", - compressed_part); - errno = EIO; - return (-1); - } - /* make sure there are two unused entries in runlist */ - if (na->unused_runs < 2) { - ntfs_log_error("No unused runs for compressed write\n"); - errno = EIO; - return (-1); - } - if (wrl->vcn < *update_from) - *update_from = wrl->vcn; - written = -1; /* 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; - /* determine whether we are appending to file */ - endwrite = offs + to_write + (wrl->vcn << vol->cluster_size_bits); - appending = endwrite >= na->initialized_size; - if (endwrite >= 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; - if (start_vcn < *update_from) - *update_from = start_vcn; - 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; - outbuf = (char*)ntfs_malloc(na->compression_block_size); - if (outbuf) { - if (appending) { - to_read = offs - roffs; - to_flush = to_read + to_write; - } else { - to_read = na->data_size - - (brl->vcn << vol->cluster_size_bits); - if (to_read > na->compression_block_size) - to_read = na->compression_block_size; - to_flush = to_read; - } - if (!ntfs_read_append(na, brl, roffs, compsz, - (s32)(offs - roffs), appending, - outbuf, to_write, b)) { - written = ntfs_flush(na, brl, roffs, - outbuf, to_flush, compress, appending, - update_from); - 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, - appending, update_from)) { - 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; - } - } - } - if ((written >= 0) - && !valid_compressed_run(na,wrl,TRUE,"end compressed write")) - written = -1; - return (written); + if (!valid_compressed_run(na, wrl, FALSE, "begin compressed write")) + { + return (-1); + } + if ((*update_from < 0) || (compressed_part < 0) || (compressed_part > (int) na->compression_block_clusters)) + { + ntfs_log_error("Bad update vcn or compressed_part %d for compressed write\n", + compressed_part); + errno = EIO; + return (-1); + } + /* make sure there are two unused entries in runlist */ + if (na->unused_runs < 2) + { + ntfs_log_error("No unused runs for compressed write\n"); + errno = EIO; + return (-1); + } + if (wrl->vcn < *update_from) *update_from = wrl->vcn; + written = -1; /* 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; + /* determine whether we are appending to file */ + endwrite = offs + to_write + (wrl->vcn << vol->cluster_size_bits); + appending = endwrite >= na->initialized_size; + if (endwrite >= 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; + if (start_vcn < *update_from) *update_from = start_vcn; + 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; + outbuf = (char*) ntfs_malloc(na->compression_block_size); + if (outbuf) + { + if (appending) + { + to_read = offs - roffs; + to_flush = to_read + to_write; + } + else + { + to_read = na->data_size - (brl->vcn << vol->cluster_size_bits); + if (to_read > na->compression_block_size) to_read = na->compression_block_size; + to_flush = to_read; + } + if (!ntfs_read_append(na, brl, roffs, compsz, (s32) (offs - roffs), appending, outbuf, to_write, b)) + { + written = ntfs_flush(na, brl, roffs, outbuf, to_flush, compress, appending, update_from); + 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, appending, + update_from)) + { + 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; + } + } + } + if ((written >= 0) && !valid_compressed_run(na, wrl, TRUE, "end compressed write")) written = -1; + return (written); } /* @@ -1746,86 +1774,84 @@ 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, - VCN *update_from) +int ntfs_compressed_close(ntfs_attr *na, runlist_element *wrl, s64 offs, VCN *update_from) { - 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; + 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; - if (na->unused_runs < 2) { - ntfs_log_error("No unused runs for compressed close\n"); - errno = EIO; - return (-1); - } - if (*update_from < 0) { - ntfs_log_error("Bad update vcn for compressed close\n"); - errno = EIO; - return (-1); - } - if (wrl->vcn < *update_from) - *update_from = wrl->vcn; - 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; - if (start_vcn < *update_from) - *update_from = start_vcn; - 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, - TRUE, update_from)) { - done = TRUE; - } else - /* if compression failed, leave uncompressed */ - if (written == -1) - done = TRUE; - } - } else - done = TRUE; - free(inbuf); - } - } - if (done && !valid_compressed_run(na,wrl,TRUE,"end compressed close")) - done = FALSE; - return (!done); + if (na->unused_runs < 2) + { + ntfs_log_error("No unused runs for compressed close\n"); + errno = EIO; + return (-1); + } + if (*update_from < 0) + { + ntfs_log_error("Bad update vcn for compressed close\n"); + errno = EIO; + return (-1); + } + if (wrl->vcn < *update_from) *update_from = wrl->vcn; + 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; + if (start_vcn < *update_from) *update_from = start_vcn; + 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, TRUE, + update_from)) + { + done = TRUE; + } + else + /* if compression failed, leave uncompressed */ + if (written == -1) done = TRUE; + } + } + else done = TRUE; + free(inbuf); + } + } + if (done && !valid_compressed_run(na, wrl, TRUE, "end compressed close")) done = FALSE; + return (!done); } diff --git a/source/libntfs/compress.h b/source/libntfs/compress.h index c2569321..a197ab52 100644 --- a/source/libntfs/compress.h +++ b/source/libntfs/compress.h @@ -26,16 +26,12 @@ #include "types.h" #include "attrib.h" -extern s64 ntfs_compressed_attr_pread(ntfs_attr *na, s64 pos, s64 count, - void *b); +extern s64 ntfs_compressed_attr_pread(ntfs_attr *na, s64 pos, s64 count, 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, - VCN *update_from); +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, VCN *update_from); -extern int ntfs_compressed_close(ntfs_attr *na, runlist_element *brl, - s64 offs, VCN *update_from); +extern int ntfs_compressed_close(ntfs_attr *na, runlist_element *brl, s64 offs, VCN *update_from); #endif /* defined _NTFS_COMPRESS_H */ diff --git a/source/libntfs/config.h b/source/libntfs/config.h index ba0168e1..77e26077 100644 --- a/source/libntfs/config.h +++ b/source/libntfs/config.h @@ -133,7 +133,7 @@ #undef HAVE_SETXATTR /* Define to 1 if `stat' has the bug that it succeeds when given the - zero-length file name argument. */ + zero-length file name argument. */ #define HAVE_STAT_EMPTY_STRING_BUG 1 /* Define to 1 if you have the header file. */ @@ -203,7 +203,7 @@ #undef HAVE_STRUCT_STAT_ST_RDEV /* Define to 1 if your `struct stat' has `st_blocks'. Deprecated, use - `HAVE_STRUCT_STAT_ST_BLOCKS' instead. */ + `HAVE_STRUCT_STAT_ST_BLOCKS' instead. */ #undef HAVE_ST_BLOCKS /* Define to 1 if you have the `sysconf' function. */ @@ -279,7 +279,7 @@ #undef IGNORE_MTAB /* Define to 1 if `lstat' dereferences a symlink specified with a trailing - slash. */ + slash. */ #undef LSTAT_FOLLOWS_SLASHED_SYMLINK /* Define to 1 if your C compiler doesn't accept -c and -o together. */ @@ -340,11 +340,11 @@ #undef WINDOWS /* Define to 1 if your processor stores words with the most significant byte - first (like Motorola and SPARC, unlike Intel and VAX). */ + first (like Motorola and SPARC, unlike Intel and VAX). */ #define WORDS_BIGENDIAN 1 /* Define to 1 if your processor stores words with the least significant byte - first (like Intel and VAX, unlike Motorola and SPARC). */ + first (like Intel and VAX, unlike Motorola and SPARC). */ #undef WORDS_LITTLEENDIAN /* Number of bits in a file offset, on hosts where this is settable. */ @@ -362,7 +362,7 @@ #undef _REENTRANT /* Define to `__inline__' or `__inline' if that's what the C compiler - calls it, or to nothing if 'inline' is not supported under any name. */ + calls it, or to nothing if 'inline' is not supported under any name. */ #ifndef __cplusplus #define inline __inline__ #endif diff --git a/source/libntfs/debug.c b/source/libntfs/debug.c index f1934833..35b9c0d0 100644 --- a/source/libntfs/debug.c +++ b/source/libntfs/debug.c @@ -44,35 +44,40 @@ */ 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 " }; + 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/debug.h b/source/libntfs/debug.h index cf39b625..085da9fa 100644 --- a/source/libntfs/debug.h +++ b/source/libntfs/debug.h @@ -33,7 +33,9 @@ struct _runlist_element; #ifdef DEBUG extern void ntfs_debug_runlist_dump(const struct _runlist_element *rl); #else -static __inline__ void ntfs_debug_runlist_dump(const struct _runlist_element *rl __attribute__((unused))) {} +static __inline__ void ntfs_debug_runlist_dump(const struct _runlist_element *rl __attribute__((unused))) +{ +} #endif #define NTFS_BUG(msg) \ diff --git a/source/libntfs/device.c b/source/libntfs/device.c index c77d8f95..25a9234e 100644 --- a/source/libntfs/device.c +++ b/source/libntfs/device.c @@ -103,29 +103,32 @@ * On success return a pointer to the allocated ntfs device structure and on * 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 *ntfs_device_alloc(const char *name, const long state, struct ntfs_device_operations *dops, + void *priv_data) { - struct ntfs_device *dev; + 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; } /** @@ -141,17 +144,19 @@ struct ntfs_device *ntfs_device_alloc(const char *name, const long state, */ 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; + if (!dev) + { + errno = EINVAL; + return -1; + } + if (NDevOpen(dev)) + { + errno = EBUSY; + return -1; + } + free(dev->d_name); + free(dev); + return 0; } /** @@ -175,33 +180,32 @@ int ntfs_device_free(struct ntfs_device *dev) */ s64 ntfs_pread(struct ntfs_device *dev, const s64 pos, s64 count, void *b) { - s64 br, total; - struct ntfs_device_operations *dops; + s64 br, total; + struct ntfs_device_operations *dops; - 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; + ntfs_log_trace("pos %lld, count %lld\n",(long long)pos,(long long)count); - 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; + 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; } /** @@ -223,46 +227,43 @@ s64 ntfs_pread(struct ntfs_device *dev, const s64 pos, s64 count, void *b) * appropriately to the return code of either seek, write, or set * to EINVAL in case of invalid arguments. */ -s64 ntfs_pwrite(struct ntfs_device *dev, const s64 pos, s64 count, - const void *b) +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; + 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; - } - - dops = dev->d_ops; + if (!b || count < 0 || pos < 0) + { + errno = EINVAL; + goto out; + } + if (!count) return 0; + if (NDevReadOnly(dev)) + { + errno = EROFS; + goto out; + } - 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; + 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; } /** @@ -294,31 +295,29 @@ out: * sector transfer error. This should be detected by the caller by checking for * the magic being "BAAD". */ -s64 ntfs_mst_pread(struct ntfs_device *dev, const s64 pos, s64 count, - const u32 bksize, void *b) +s64 ntfs_mst_pread(struct ntfs_device *dev, const s64 pos, s64 count, const u32 bksize, void *b) { - s64 br, i; + 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; } /** @@ -351,40 +350,38 @@ s64 ntfs_mst_pread(struct ntfs_device *dev, const s64 pos, s64 count, * simulating an mst read on the written data. This way cache coherency is * achieved. */ -s64 ntfs_mst_pwrite(struct ntfs_device *dev, const s64 pos, s64 count, - const u32 bksize, void *b) +s64 ntfs_mst_pwrite(struct ntfs_device *dev, const s64 pos, s64 count, const u32 bksize, void *b) { - s64 written, i; + 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; } /** @@ -398,29 +395,30 @@ s64 ntfs_mst_pwrite(struct ntfs_device *dev, const s64 pos, s64 count, * volume @vol into buffer @b. Return number of clusters read or -1 on error, * with errno set to the error code. */ -s64 ntfs_cluster_read(const ntfs_volume *vol, const s64 lcn, const s64 count, - void *b) +s64 ntfs_cluster_read(const ntfs_volume *vol, const s64 lcn, const s64 count, void *b) { - s64 br; + 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; } /** @@ -434,32 +432,32 @@ s64 ntfs_cluster_read(const ntfs_volume *vol, const s64 lcn, const s64 count, * buffer @b to volume @vol. Return the number of clusters written or -1 on * 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 ntfs_cluster_write(const ntfs_volume *vol, const s64 lcn, const s64 count, const void *b) { - s64 bw; + 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; } /** @@ -474,12 +472,10 @@ s64 ntfs_cluster_write(const ntfs_volume *vol, const s64 lcn, */ static int ntfs_device_offset_valid(struct ntfs_device *dev, s64 ofs) { - char ch; + 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; } /** @@ -496,61 +492,65 @@ static int ntfs_device_offset_valid(struct ntfs_device *dev, s64 ofs) */ s64 ntfs_device_size_get(struct ntfs_device *dev, int block_size) { - s64 high, low; + 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; } /** @@ -567,23 +567,25 @@ s64 ntfs_device_size_get(struct ntfs_device *dev, int block_size) */ s64 ntfs_device_partition_start_sector_get(struct ntfs_device *dev) { - if (!dev) { - errno = EINVAL; - return -1; - } + 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; } /** @@ -600,24 +602,26 @@ s64 ntfs_device_partition_start_sector_get(struct ntfs_device *dev) */ int ntfs_device_heads_get(struct ntfs_device *dev) { - if (!dev) { - errno = EINVAL; - return -1; - } + 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; } /** @@ -634,24 +638,26 @@ int ntfs_device_heads_get(struct ntfs_device *dev) */ int ntfs_device_sectors_per_track_get(struct ntfs_device *dev) { - if (!dev) { - errno = EINVAL; - return -1; - } + 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; } /** @@ -668,24 +674,26 @@ int ntfs_device_sectors_per_track_get(struct ntfs_device *dev) */ int ntfs_device_sector_size_get(struct ntfs_device *dev) { - if (!dev) { - errno = EINVAL; - return -1; - } + 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; } /** @@ -701,30 +709,30 @@ int ntfs_device_sector_size_get(struct ntfs_device *dev) * EOPNOTSUPP System does not support BLKBSZSET ioctl * 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))) +int ntfs_device_block_size_set(struct ntfs_device *dev, int block_size __attribute__((unused))) { - if (!dev) { - errno = EINVAL; - return -1; - } + 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 a19d29c4..3dc50cbe 100644 --- a/source/libntfs/device.h +++ b/source/libntfs/device.h @@ -36,11 +36,13 @@ * * 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. */ +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. */ } ntfs_device_state_bits; #define test_ndev_flag(nd, flag) test_bit(ND_##flag, (nd)->d_state) @@ -69,12 +71,13 @@ typedef enum { * The ntfs device structure defining all operations needed to access the low * 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 - device operations. */ +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 + device operations. */ }; struct stat; @@ -85,38 +88,32 @@ struct stat; * The ntfs device operations defining all operations that can be performed on * 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); +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); }; -extern struct ntfs_device *ntfs_device_alloc(const char *name, const long state, - struct ntfs_device_operations *dops, void *priv_data); +extern struct ntfs_device *ntfs_device_alloc(const char *name, const long state, 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); -extern s64 ntfs_pwrite(struct ntfs_device *dev, const s64 pos, s64 count, - const void *b); +extern s64 ntfs_pread(struct ntfs_device *dev, const s64 pos, s64 count, void *b); +extern s64 ntfs_pwrite(struct ntfs_device *dev, const s64 pos, s64 count, const void *b); -extern s64 ntfs_mst_pread(struct ntfs_device *dev, const s64 pos, s64 count, - const u32 bksize, void *b); -extern s64 ntfs_mst_pwrite(struct ntfs_device *dev, const s64 pos, s64 count, - const u32 bksize, void *b); +extern s64 ntfs_mst_pread(struct ntfs_device *dev, const s64 pos, s64 count, const u32 bksize, void *b); +extern s64 ntfs_mst_pwrite(struct ntfs_device *dev, const s64 pos, s64 count, const u32 bksize, void *b); -extern s64 ntfs_cluster_read(const ntfs_volume *vol, const s64 lcn, - const s64 count, void *b); -extern s64 ntfs_cluster_write(const ntfs_volume *vol, const s64 lcn, - const s64 count, const void *b); +extern s64 ntfs_cluster_read(const ntfs_volume *vol, const s64 lcn, const s64 count, void *b); +extern s64 ntfs_cluster_write(const ntfs_volume *vol, const s64 lcn, 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 fad4d85f..de0136fe 100644 --- a/source/libntfs/device_io.h +++ b/source/libntfs/device_io.h @@ -45,11 +45,12 @@ /** * struct hd_geometry - */ -struct hd_geometry { - unsigned char heads; - unsigned char sectors; - unsigned short cylinders; - unsigned long start; +struct hd_geometry +{ + unsigned char heads; + unsigned char sectors; + unsigned short cylinders; + unsigned long start; }; #endif #ifndef BLKGETSIZE @@ -70,7 +71,6 @@ struct hd_geometry { #endif /* __CYGWIN32__ */ - /* Forward declaration. */ struct ntfs_device_operations; diff --git a/source/libntfs/dir.c b/source/libntfs/dir.c index 2372f3f8..4b2d165c 100644 --- a/source/libntfs/dir.c +++ b/source/libntfs/dir.c @@ -70,21 +70,15 @@ * The little endian Unicode strings "$I30", "$SII", "$SDH", "$O" * 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') }; -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') }; -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') }; -ntfschar NTFS_INDEX_O[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('O'), - const_cpu_to_le16('\0') }; -ntfschar NTFS_INDEX_Q[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('Q'), - const_cpu_to_le16('\0') }; -ntfschar NTFS_INDEX_R[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('R'), - const_cpu_to_le16('\0') }; +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') }; +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') }; +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') }; +ntfschar NTFS_INDEX_O[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('O'), const_cpu_to_le16('\0') }; +ntfschar NTFS_INDEX_Q[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('Q'), const_cpu_to_le16('\0') }; +ntfschar NTFS_INDEX_R[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('R'), const_cpu_to_le16('\0') }; #if CACHE_INODE_SIZE @@ -96,30 +90,27 @@ ntfschar NTFS_INDEX_R[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('R'), int ntfs_dir_inode_hash(const struct CACHED_GENERIC *cached) { - const char *path; - const unsigned char *name; + const char *path; + const unsigned char *name; - path = (const char*)cached->variable; - if (!path) { - ntfs_log_error("Bad inode cache entry\n"); - return (-1); - } - name = (const unsigned char*)strrchr(path,'/'); - if (!name) - name = (const unsigned char*)path; - return (((name[0] << 1) + name[1] + strlen((const char*)name)) - % (2*CACHE_INODE_SIZE)); + path = (const char*) cached->variable; + if (!path) + { + ntfs_log_error("Bad inode cache entry\n"); + return (-1); + } + name = (const unsigned char*) strrchr(path, '/'); + if (!name) name = (const unsigned char*) path; + return (((name[0] << 1) + name[1] + strlen((const char*) name)) % (2 * CACHE_INODE_SIZE)); } /* * Pathname comparing for entering/fetching from cache */ -static int inode_cache_compare(const struct CACHED_GENERIC *cached, - const struct CACHED_GENERIC *wanted) +static int inode_cache_compare(const struct CACHED_GENERIC *cached, const struct CACHED_GENERIC *wanted) { - return (!cached->variable - || strcmp(cached->variable, wanted->variable)); + return (!cached->variable || strcmp(cached->variable, wanted->variable)); } /* @@ -133,27 +124,23 @@ static int inode_cache_compare(const struct CACHED_GENERIC *cached, * Only use associated with a CACHE_NOHASH flag */ -static int inode_cache_inv_compare(const struct CACHED_GENERIC *cached, - const struct CACHED_GENERIC *wanted) +static int inode_cache_inv_compare(const struct CACHED_GENERIC *cached, const struct CACHED_GENERIC *wanted) { - int len; - BOOL different; - const struct CACHED_INODE *w; - const struct CACHED_INODE *c; + int len; + BOOL different; + const struct CACHED_INODE *w; + const struct CACHED_INODE *c; - w = (const struct CACHED_INODE*)wanted; - c = (const struct CACHED_INODE*)cached; - if (w->pathname) { - len = strlen(w->pathname); - different = !cached->variable - || ((w->inum != MREF(c->inum)) - && (strncmp(c->pathname, w->pathname, len) - || ((c->pathname[len] != '\0') - && (c->pathname[len] != '/')))); - } else - different = !c->pathname - || (w->inum != MREF(c->inum)); - return (different); + w = (const struct CACHED_INODE*) wanted; + c = (const struct CACHED_INODE*) cached; + if (w->pathname) + { + len = strlen(w->pathname); + different = !cached->variable || ((w->inum != MREF(c->inum)) && (strncmp(c->pathname, w->pathname, len) + || ((c->pathname[len] != '\0') && (c->pathname[len] != '/')))); + } + else different = !c->pathname || (w->inum != MREF(c->inum)); + return (different); } #endif @@ -164,15 +151,12 @@ static int inode_cache_inv_compare(const struct CACHED_GENERIC *cached, * File name comparing for entering/fetching from lookup cache */ -static int lookup_cache_compare(const struct CACHED_GENERIC *cached, - const struct CACHED_GENERIC *wanted) +static int lookup_cache_compare(const struct CACHED_GENERIC *cached, const struct CACHED_GENERIC *wanted) { - const struct CACHED_LOOKUP *c = (const struct CACHED_LOOKUP*) cached; - const struct CACHED_LOOKUP *w = (const struct CACHED_LOOKUP*) wanted; - return (!c->name - || (c->parent != w->parent) - || (c->namesize != w->namesize) - || memcmp(c->name, w->name, c->namesize)); + const struct CACHED_LOOKUP *c = (const struct CACHED_LOOKUP*) cached; + const struct CACHED_LOOKUP *w = (const struct CACHED_LOOKUP*) wanted; + return (!c->name || (c->parent != w->parent) || (c->namesize != w->namesize) || memcmp(c->name, w->name, + c->namesize)); } /* @@ -183,14 +167,11 @@ static int lookup_cache_compare(const struct CACHED_GENERIC *cached, * Only use associated with a CACHE_NOHASH flag */ -static int lookup_cache_inv_compare(const struct CACHED_GENERIC *cached, - const struct CACHED_GENERIC *wanted) +static int lookup_cache_inv_compare(const struct CACHED_GENERIC *cached, const struct CACHED_GENERIC *wanted) { - const struct CACHED_LOOKUP *c = (const struct CACHED_LOOKUP*) cached; - const struct CACHED_LOOKUP *w = (const struct CACHED_LOOKUP*) wanted; - return (!c->name - || (c->parent != w->parent) - || (MREF(c->inum) != MREF(w->inum))); + const struct CACHED_LOOKUP *c = (const struct CACHED_LOOKUP*) cached; + const struct CACHED_LOOKUP *w = (const struct CACHED_LOOKUP*) wanted; + return (!c->name || (c->parent != w->parent) || (MREF(c->inum) != MREF(w->inum))); } /* @@ -201,18 +182,19 @@ static int lookup_cache_inv_compare(const struct CACHED_GENERIC *cached, int ntfs_dir_lookup_hash(const struct CACHED_GENERIC *cached) { - const unsigned char *name; - int count; - unsigned int val; + const unsigned char *name; + int count; + unsigned int val; - name = (const unsigned char*)cached->variable; - count = cached->varsize; - if (!name || !count) { - ntfs_log_error("Bad lookup cache entry\n"); - return (-1); - } - val = (name[0] << 2) + (name[1] << 1) + name[count - 1] + count; - return (val % (2*CACHE_LOOKUP_SIZE)); + name = (const unsigned char*) cached->variable; + count = cached->varsize; + if (!name || !count) + { + ntfs_log_error("Bad lookup cache entry\n"); + return (-1); + } + val = (name[0] << 2) + (name[1] << 1) + name[count - 1] + count; + return (val % (2 * CACHE_LOOKUP_SIZE)); } #endif @@ -242,295 +224,287 @@ int ntfs_dir_lookup_hash(const struct CACHED_GENERIC *cached) * If the volume is mounted with the case sensitive flag set, then we only * allow exact matches. */ -u64 ntfs_inode_lookup_by_name(ntfs_inode *dir_ni, - const ntfschar *uname, const int uname_len) +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; - IGNORE_CASE_BOOL case_sensitivity; - u8 *index_end; - ntfs_attr *ia_na; - int eo, rc; - u32 index_block_size, index_vcn_size; - u8 index_vcn_size_bits; + 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; + IGNORE_CASE_BOOL case_sensitivity; + 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; - } - case_sensitivity = (NVolCaseSensitive(vol) ? CASE_SENSITIVE : IGNORE_CASE); - /* 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_full_collate(uname, uname_len, - (ntfschar*)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length, - case_sensitivity, 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; - /* - * 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. */ + /* 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; + } + case_sensitivity = (NVolCaseSensitive(vol) ? CASE_SENSITIVE : IGNORE_CASE); + /* 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; - /* 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; - } + 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_full_collate(uname, uname_len, (ntfschar*) &ie->key.file_name.file_name, + ie->key.file_name.file_name_length, case_sensitivity, 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; + /* + * 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. */ - /* 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; - } + /* 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; + } - /* 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; - } + /* 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; + } - /* Get the starting vcn of the index_block holding the child node. */ - vcn = sle64_to_cpup((u8*)ie + le16_to_cpu(ie->length) - 8); + /* 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; + } -descend_into_child_node: + /* Get the starting vcn of the index_block holding the child node. */ + vcn = sle64_to_cpup((u8*)ie + le16_to_cpu(ie->length) - 8); - /* 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; - } + descend_into_child_node: - 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; - } + /* 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; + } - /* 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_full_collate(uname, uname_len, - (ntfschar*)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length, - case_sensitivity, 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; - 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_put_err_out: - 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; + 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_full_collate(uname, uname_len, (ntfschar*) &ie->key.file_name.file_name, + ie->key.file_name.file_name_length, case_sensitivity, 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; + 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_put_err_out: 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; } /* @@ -544,72 +518,73 @@ close_err_out: u64 ntfs_inode_lookup_by_mbsname(ntfs_inode *dir_ni, const char *name) { - int uname_len; - ntfschar *uname = (ntfschar*)NULL; - u64 inum; - char *cached_name; - const char *const_name; + int uname_len; + ntfschar *uname = (ntfschar*) NULL; + u64 inum; + char *cached_name; + const char *const_name; - if (!NVolCaseSensitive(dir_ni->vol)) { - cached_name = ntfs_uppercase_mbs(name, - dir_ni->vol->upcase, dir_ni->vol->upcase_len); - const_name = cached_name; - } else { - cached_name = (char*)NULL; - const_name = name; - } - if (const_name) { + if (!NVolCaseSensitive(dir_ni->vol)) + { + cached_name = ntfs_uppercase_mbs(name, dir_ni->vol->upcase, dir_ni->vol->upcase_len); + const_name = cached_name; + } + else + { + cached_name = (char*) NULL; + const_name = name; + } + if (const_name) + { #if CACHE_LOOKUP_SIZE - /* - * fetch inode from cache - */ + /* + * fetch inode from cache + */ - if (dir_ni->vol->lookup_cache) { - struct CACHED_LOOKUP item; - struct CACHED_LOOKUP *cached; + if (dir_ni->vol->lookup_cache) + { + struct CACHED_LOOKUP item; + struct CACHED_LOOKUP *cached; - item.name = const_name; - item.namesize = strlen(const_name) + 1; - item.parent = dir_ni->mft_no; - cached = (struct CACHED_LOOKUP*)ntfs_fetch_cache( - dir_ni->vol->lookup_cache, - GENERIC(&item), lookup_cache_compare); - if (cached) { - inum = cached->inum; - if (inum == (u64)-1) - errno = ENOENT; - } else { - /* Generate unicode name. */ - uname_len = ntfs_mbstoucs(name, &uname); - if (uname_len >= 0) { - inum = ntfs_inode_lookup_by_name(dir_ni, - uname, uname_len); - item.inum = inum; - /* enter into cache, even if not found */ - ntfs_enter_cache(dir_ni->vol->lookup_cache, - GENERIC(&item), - lookup_cache_compare); - free(uname); - } else - inum = (s64)-1; - } - } else + item.name = const_name; + item.namesize = strlen(const_name) + 1; + item.parent = dir_ni->mft_no; + cached = (struct CACHED_LOOKUP*) ntfs_fetch_cache(dir_ni->vol->lookup_cache, GENERIC(&item), + lookup_cache_compare); + if (cached) + { + inum = cached->inum; + if (inum == (u64) -1) errno = ENOENT; + } + else + { + /* Generate unicode name. */ + uname_len = ntfs_mbstoucs(name, &uname); + if (uname_len >= 0) + { + inum = ntfs_inode_lookup_by_name(dir_ni, uname, uname_len); + item.inum = inum; + /* enter into cache, even if not found */ + ntfs_enter_cache(dir_ni->vol->lookup_cache, GENERIC(&item), lookup_cache_compare); + free(uname); + } + else inum = (s64) -1; + } + } + else #endif - { - /* Generate unicode name. */ - uname_len = ntfs_mbstoucs(cached_name, &uname); - if (uname_len >= 0) - inum = ntfs_inode_lookup_by_name(dir_ni, - uname, uname_len); - else - inum = (s64)-1; - } - if (cached_name) - free(cached_name); - } else - inum = (s64)-1; - return (inum); + { + /* Generate unicode name. */ + uname_len = ntfs_mbstoucs(cached_name, &uname); + if (uname_len >= 0) + inum = ntfs_inode_lookup_by_name(dir_ni, uname, uname_len); + else inum = (s64) -1; + } + if (cached_name) free(cached_name); + } + else inum = (s64) -1; + return (inum); } /* @@ -621,32 +596,33 @@ u64 ntfs_inode_lookup_by_mbsname(ntfs_inode *dir_ni, const char *name) void ntfs_inode_update_mbsname(ntfs_inode *dir_ni, const char *name, u64 inum) { #if CACHE_LOOKUP_SIZE - struct CACHED_LOOKUP item; - struct CACHED_LOOKUP *cached; - char *cached_name; + struct CACHED_LOOKUP item; + struct CACHED_LOOKUP *cached; + char *cached_name; - if (dir_ni->vol->lookup_cache) { - if (!NVolCaseSensitive(dir_ni->vol)) { - cached_name = ntfs_uppercase_mbs(name, - dir_ni->vol->upcase, dir_ni->vol->upcase_len); - item.name = cached_name; - } else { - cached_name = (char*)NULL; - item.name = name; - } - if (item.name) { - item.namesize = strlen(item.name) + 1; - item.parent = dir_ni->mft_no; - item.inum = inum; - cached = (struct CACHED_LOOKUP*)ntfs_enter_cache( - dir_ni->vol->lookup_cache, - GENERIC(&item), lookup_cache_compare); - if (cached) - cached->inum = inum; - if (cached_name) - free(cached_name); - } - } + if (dir_ni->vol->lookup_cache) + { + if (!NVolCaseSensitive(dir_ni->vol)) + { + cached_name = ntfs_uppercase_mbs(name, dir_ni->vol->upcase, dir_ni->vol->upcase_len); + item.name = cached_name; + } + else + { + cached_name = (char*) NULL; + item.name = name; + } + if (item.name) + { + item.namesize = strlen(item.name) + 1; + item.parent = dir_ni->mft_no; + item.inum = inum; + cached = (struct CACHED_LOOKUP*) ntfs_enter_cache(dir_ni->vol->lookup_cache, GENERIC(&item), + lookup_cache_compare); + if (cached) cached->inum = inum; + if (cached_name) free(cached_name); + } + } #endif } @@ -663,210 +639,221 @@ void ntfs_inode_update_mbsname(ntfs_inode *dir_ni, const char *name, u64 inum) * Return: inode Success, the pathname was valid * 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) +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; + 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; - } - - ntfs_log_trace("path: '%s'\n", pathname); - - ascii = strdup(pathname); - if (!ascii) { - ntfs_log_error("Out of memory.\n"); - err = ENOMEM; - goto out; - } + if (!vol || !pathname) + { + errno = EINVAL; + return NULL; + } - 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); -#endif - 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; - } -#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; - } - } + ntfs_log_trace("path: '%s'\n", pathname); - while (p && *p) { - /* Find the end of the first token. */ - q = strchr(p, PATH_SEP); - if (q != NULL) { - *q = '\0'; - } + 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++; #if CACHE_INODE_SIZE - /* - * fetch inode for partial path from cache - */ - cached = (struct CACHED_INODE*)NULL; - if (!parent) { - 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; - } - } - /* - * if not in cache, translate, search, then - * insert into cache if found - */ - if (!cached) { - 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; - } - inum = ntfs_inode_lookup_by_name(ni, unicode, len); - if (!parent && (inum != (u64) -1)) { - item.inum = inum; - ntfs_enter_cache(vol->xinode_cache, - GENERIC(&item), - inode_cache_compare); - } - } + 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 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; + } +#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; + } + } + + while (p && *p) + { + /* Find the end of the first token. */ + q = strchr(p, PATH_SEP); + if (q != NULL) + { + *q = '\0'; + } +#if CACHE_INODE_SIZE + /* + * fetch inode for partial path from cache + */ + cached = (struct CACHED_INODE*) NULL; + if (!parent) + { + 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; + } + } + /* + * if not in cache, translate, search, then + * insert into cache if found + */ + if (!cached) + { + 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; + } + inum = ntfs_inode_lookup_by_name(ni, unicode, len); + if (!parent && (inum != (u64) -1)) + { + item.inum = inum; + ntfs_enter_cache(vol->xinode_cache, GENERIC(&item), inode_cache_compare); + } + } #else - 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; - } - inum = ntfs_inode_lookup_by_name(ni, unicode, len); + 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; + } + 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; - } - - free(unicode); - unicode = NULL; + 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; + } - if (q) *q++ = PATH_SEP; /* JPA */ - p = q; - while (p && *p && *p == PATH_SEP) - p++; - } + free(unicode); + unicode = NULL; - result = ni; - ni = NULL; -close: - if (ni && (ni != parent)) - if (ntfs_inode_close(ni) && !err) - err = errno; -out: - free(ascii); - free(unicode); - if (err) - errno = err; - return result; + if (q) *q++ = PATH_SEP; /* JPA */ + p = q; + while (p && *p && *p == PATH_SEP) + p++; + } + + result = ni; + ni = NULL; + close: if (ni && (ni != parent)) if (ntfs_inode_close(ni) && !err) err = errno; + out: 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') }; +static const ntfschar dotdot[3] = { const_cpu_to_le16('.'), 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; +typedef union +{ + INDEX_ROOT *ir; + INDEX_ALLOCATION *ia; } index_union __attribute__((__transparent_union__)); /** * enum INDEX_TYPE - * More helpers for ntfs_readdir(). */ -typedef enum { - INDEX_TYPE_ROOT, /* index root */ - INDEX_TYPE_ALLOCATION, /* index allocation */ +typedef enum +{ + INDEX_TYPE_ROOT, /* index root */ + INDEX_TYPE_ALLOCATION, +/* index allocation */ } INDEX_TYPE; /** @@ -883,67 +870,57 @@ typedef enum { * Pass information specifying the current directory entry @ie to the @filldir * 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) +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; - BOOL metadata; - ntfschar *loname; - int res; - MFT_REF mref; + FILE_NAME_ATTR *fn = &ie->key.file_name; + unsigned dt_type; + BOOL metadata; + ntfschar *loname; + int res; + MFT_REF mref; - 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; + ntfs_log_trace("Entering.\n"); - /* return metadata files and hidden files if requested */ - mref = le64_to_cpu(ie->indexed_file); - metadata = (MREF(mref) != FILE_root) && (MREF(mref) < FILE_first_user); - if ((!metadata && (NVolShowHidFiles(dir_ni->vol) - || !(fn->file_attributes & FILE_ATTR_HIDDEN))) - || (NVolShowSysFiles(dir_ni->vol) && (NVolShowHidFiles(dir_ni->vol) - || metadata))) { - if (NVolCaseSensitive(dir_ni->vol)) { - res = filldir(dirent, fn->file_name, - fn->file_name_length, - fn->file_name_type, *pos, - mref, dt_type); - } else { - loname = (ntfschar*)ntfs_malloc(2*fn->file_name_length); - if (loname) { - memcpy(loname, fn->file_name, - 2*fn->file_name_length); - ntfs_name_locase(loname, fn->file_name_length, - dir_ni->vol->locase, - dir_ni->vol->upcase_len); - res = filldir(dirent, loname, - fn->file_name_length, - fn->file_name_type, *pos, - mref, dt_type); - free(loname); - } else - res = -1; - } - } else - res = 0; - return (res); + /* 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 metadata files and hidden files if requested */ + mref = le64_to_cpu(ie->indexed_file); + metadata = (MREF(mref) != FILE_root) && (MREF(mref) < FILE_first_user); + if ((!metadata && (NVolShowHidFiles(dir_ni->vol) || !(fn->file_attributes & FILE_ATTR_HIDDEN))) + || (NVolShowSysFiles(dir_ni->vol) && (NVolShowHidFiles(dir_ni->vol) || metadata))) + { + if (NVolCaseSensitive(dir_ni->vol)) + { + res = filldir(dirent, fn->file_name, fn->file_name_length, fn->file_name_type, *pos, mref, dt_type); + } + else + { + loname = (ntfschar*) ntfs_malloc(2 * fn->file_name_length); + if (loname) + { + memcpy(loname, fn->file_name, 2 * fn->file_name_length); + ntfs_name_locase(loname, fn->file_name_length, dir_ni->vol->locase, dir_ni->vol->upcase_len); + res = filldir(dirent, loname, fn->file_name_length, fn->file_name_type, *pos, mref, dt_type); + free(loname); + } + else res = -1; + } + } + else res = 0; + return (res); } /** @@ -966,49 +943,48 @@ static int ntfs_filldir(ntfs_inode *dir_ni, s64 *pos, u8 ivcn_bits, */ 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; + MFT_REF mref; + ntfs_attr_search_ctx *ctx; + FILE_NAME_ATTR *fn; + int eo; - ntfs_log_trace("Entering.\n"); - - if (!ni) { - errno = EINVAL; - return ERR_MREF(-1); - } + ntfs_log_trace("Entering.\n"); - 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; -err_out: - eo = errno; - ntfs_attr_put_search_ctx(ctx); - errno = eo; - 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; + io_err_out: errno = EIO; + err_out: eo = errno; + ntfs_attr_put_search_ctx(ctx); + errno = eo; + return ERR_MREF(-1); } /** @@ -1027,347 +1003,324 @@ err_out: * Note: Index blocks are parsed in ascending vcn order, from which follows * that the directory entries are not returned sorted. */ -int ntfs_readdir(ntfs_inode *dir_ni, s64 *pos, - void *dirent, ntfs_filldir_t filldir) +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; + 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"); - - if (!dir_ni || !pos || !filldir) { - errno = EINVAL; - return -1; - } + ntfs_log_trace("Entering.\n"); - if (!(dir_ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) { - errno = ENOTDIR; - return -1; - } + if (!dir_ni || !pos || !filldir) + { + errno = EINVAL; + return -1; + } - vol = dir_ni->vol; + if (!(dir_ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) + { + errno = ENOTDIR; + return -1; + } - ntfs_log_trace("Entering for inode %lld, *pos 0x%llx.\n", - (unsigned long long)dir_ni->mft_no, (long long)*pos); + vol = dir_ni->vol; - /* 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; + ntfs_log_trace("Entering for inode %lld, *pos 0x%llx.\n", + (unsigned long long)dir_ni->mft_no, (long long)*pos); - rc = 0; + /* 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; - /* Are we at end of dir yet? */ - if (*pos >= i_size + vol->mft_record_size) - goto done; + rc = 0; - /* 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; + /* Are we at end of dir yet? */ + if (*pos >= i_size + vol->mft_record_size) goto done; - 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; - } + /* 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; - rc = filldir(dirent, dotdot, 2, FILE_NAME_POSIX, *pos, - parent_mref, NTFS_DT_DIR); - if (rc) - goto err_out; - ++*pos; - } + 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; + } - ctx = ntfs_attr_get_search_ctx(dir_ni, NULL); - if (!ctx) - goto err_out; + rc = filldir(dirent, dotdot, 2, FILE_NAME_POSIX, *pos, parent_mref, NTFS_DT_DIR); + if (rc) goto err_out; + ++*pos; + } - /* 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)); + ctx = ntfs_attr_get_search_ctx(dir_ni, NULL); + if (!ctx) goto err_out; - /* 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; - } + /* 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)); - /* 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; - } + /* 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; + } - 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; + /* 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; + } - /* If there is no index allocation attribute we are finished. */ - if (!ia_na) - goto EOD; + 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; - /* Advance *pos to the beginning of the index allocation. */ - *pos = vol->mft_record_size; + if (!le16_to_cpu(ie->length)) goto dir_err_out; -skip_index_root: + /* 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 (!ia_na) - goto done; + /* If there is no index allocation attribute we are finished. */ + if (!ia_na) goto EOD; - /* Allocate a buffer for the current index block. */ - ia = ntfs_malloc(index_block_size); - if (!ia) - goto err_out; + /* Advance *pos to the beginning of the index allocation. */ + *pos = vol->mft_record_size; - 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; - } + skip_index_root: - /* Get the offset into the index allocation attribute. */ - ia_pos = *pos - vol->mft_record_size; + if (!ia_na) goto done; - 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; - } + /* Allocate a buffer for the current index block. */ + ia = ntfs_malloc(index_block_size); + if (!ia) 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; + 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; + } - 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; - } + /* Get the offset into the index allocation attribute. */ + ia_pos = *pos - vol->mft_record_size; - 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 = 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; + } - ntfs_log_debug("Handling index block 0x%llx.\n", (long long)bmp_pos); + bmp_buf_size = min(bmp_na->data_size - (bmp_pos >> 3), 4096); + bmp = ntfs_malloc(bmp_buf_size); + if (!bmp) 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; - } + 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; + } - 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; -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; -dir_err_out: - 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; + 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; + } + } + + 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; + } + + 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; + 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; + dir_err_out: 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; } - /** * __ntfs_create - create object on ntfs volume * @dir_ni: ntfs inode for directory in which create new object @@ -1400,359 +1353,376 @@ err_out: * Return opened ntfs inode that describes created object on success or NULL * 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) +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; + 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"); - - /* 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; + 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; #if CACHE_NIDATA_SIZE - ntfs_inode_invalidate(dir_ni->vol, ni->mft_no); + ntfs_inode_invalidate(dir_ni->vol, ni->mft_no); #endif - /* - * 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 = ni->creation_time; - si->last_data_change_time = ni->last_data_change_time; - si->last_mft_change_time = ni->last_mft_change_time; - si->last_access_time = 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; - } - ni->flags |= FILE_ATTR_ARCHIVE; - if (NVolHideDotFiles(dir_ni->vol) - && (name_len > 1) - && (name[0] == const_cpu_to_le16('.')) - && (name[1] != const_cpu_to_le16('.'))) - ni->flags |= FILE_ATTR_HIDDEN; - /* - * Set compression flag according to parent directory - * unless NTFS version < 3.0 or cluster size > 4K - * or compression has been disabled - */ - if ((dir_ni->flags & FILE_ATTR_COMPRESSED) - && (dir_ni->vol->major_ver >= 3) - && NVolCompression(dir_ni->vol) - && (dir_ni->vol->cluster_size <= MAX_COMPRESSION_CLUSTER_SIZE) - && (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 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 = ni->creation_time; + si->last_data_change_time = ni->last_data_change_time; + si->last_mft_change_time = ni->last_mft_change_time; + si->last_access_time = 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; + } + ni->flags |= FILE_ATTR_ARCHIVE; + if (NVolHideDotFiles(dir_ni->vol) + && (name_len > 1) + && (name[0] == const_cpu_to_le16('.')) + && (name[1] != const_cpu_to_le16('.'))) + ni->flags |= FILE_ATTR_HIDDEN; + /* + * Set compression flag according to parent directory + * unless NTFS version < 3.0 or cluster size > 4K + * or compression has been disabled + */ + if ((dir_ni->flags & FILE_ATTR_COMPRESSED) + && (dir_ni->vol->major_ver >= 3) + && NVolCompression(dir_ni->vol) + && (dir_ni->vol->cluster_size <= MAX_COMPRESSION_CLUSTER_SIZE) + && (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; + } - if (!securid) { - if (ntfs_sd_add_everyone(ni)) { - err = errno; - goto err_out; - } - } - rollback_sd = 1; + 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; + 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; + /* 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->file_attributes |= FILE_ATTR_ARCHIVE; - fn->file_attributes |= ni->flags & FILE_ATTR_HIDDEN; - fn->creation_time = ni->creation_time; - fn->last_data_change_time = ni->last_data_change_time; - fn->last_mft_change_time = ni->last_mft_change_time; - fn->last_access_time = ni->last_access_time; - if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) - fn->data_size = fn->allocated_size = const_cpu_to_le64(0); - else { - 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"); + 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->file_attributes |= FILE_ATTR_ARCHIVE; + fn->file_attributes |= ni->flags & FILE_ATTR_HIDDEN; + fn->creation_time = ni->creation_time; + fn->last_data_change_time = ni->last_data_change_time; + fn->last_mft_change_time = ni->last_mft_change_time; + fn->last_access_time = ni->last_access_time; + if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + fn->data_size = fn->allocated_size = const_cpu_to_le64(0); + else + { + 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"); - 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; } /** * Some wrappers around __ntfs_create() ... */ -ntfs_inode *ntfs_create(ntfs_inode *dir_ni, le32 securid, ntfschar *name, - u8 name_len, mode_t type) +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); + 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) +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); + 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) +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); + 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; - - if (!(ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) - return 0; + ntfs_attr *na; + int ret = 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; + 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; } 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; + 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; } /** @@ -1767,269 +1737,269 @@ 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) +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_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_NIDATA_SIZE - int i; + int i; #endif #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 #if CACHE_LOOKUP_SIZE - struct CACHED_LOOKUP lkitem; + struct CACHED_LOOKUP lkitem; #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; -search: - while (!ntfs_attr_lookup(AT_FILE_NAME, AT_UNNAMED, 0, CASE_SENSITIVE, - 0, NULL, 0, actx)) { - char *s; - BOOL case_sensitive = IGNORE_CASE; + ntfs_log_trace("Entering.\n"); - 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 (!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; + + 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_LOOKUP_SIZE - /* invalidate entry in lookup cache */ - lkitem.name = (const char*)NULL; - lkitem.namesize = 0; - lkitem.inum = ni->mft_no; - lkitem.parent = dir_ni->mft_no; - ntfs_invalidate_cache(vol->lookup_cache, GENERIC(&lkitem), - lookup_cache_inv_compare, CACHE_NOHASH); + /* invalidate entry in lookup cache */ + lkitem.name = (const char*) NULL; + lkitem.namesize = 0; + lkitem.inum = ni->mft_no; + lkitem.parent = dir_ni->mft_no; + ntfs_invalidate_cache(vol->lookup_cache, GENERIC(&lkitem), lookup_cache_inv_compare, CACHE_NOHASH); #endif #if CACHE_INODE_SIZE - inum = ni->mft_no; - 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.varsize = strlen(p); - } else { - item.pathname = (const char*)NULL; - item.varsize = 0; - } - item.inum = inum; - count = ntfs_invalidate_cache(vol->xinode_cache, GENERIC(&item), - inode_cache_inv_compare, CACHE_NOHASH); - if (pathname && !count) - ntfs_log_error("Could not delete inode cache entry for %s\n", - pathname); + inum = ni->mft_no; + 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.varsize = strlen(p); + } + else + { + item.pathname = (const char*) NULL; + item.varsize = 0; + } + item.inum = inum; + count = ntfs_invalidate_cache(vol->xinode_cache, GENERIC(&item), inode_cache_inv_compare, CACHE_NOHASH); + if (pathname && !count) ntfs_log_error("Could not delete inode cache entry for %s\n", + pathname); #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; - } - if (ntfs_delete_object_id_index(ni)) { - /* - * Failed to remove the object id index : proceed anyway - * This is not a critical error. - */ - 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; + } + if (ntfs_delete_object_id_index(ni)) + { + /* + * Failed to remove the object id index : proceed anyway + * This is not a critical error. + */ + 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. */ + 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. */ #if CACHE_NIDATA_SIZE - /* - * Disconnect extents before deleting them, so they are - * not wrongly moved to cache through the chainings - */ - for (i=ni->nr_extents-1; i>=0; i--) { - ni->extent_nis[i]->base_ni = (ntfs_inode*)NULL; - ni->extent_nis[i]->nr_extents = 0; - if (ntfs_mft_record_free(ni->vol, ni->extent_nis[i])) { - err = errno; - ntfs_log_error("Failed to free extent MFT record. " - "Leaving inconsistent metadata.\n"); - } - } - free(ni->extent_nis); - ni->nr_extents = 0; - ni->extent_nis = (ntfs_inode**)NULL; + /* + * Disconnect extents before deleting them, so they are + * not wrongly moved to cache through the chainings + */ + for (i = ni->nr_extents - 1; i >= 0; i--) + { + ni->extent_nis[i]->base_ni = (ntfs_inode*) NULL; + ni->extent_nis[i]->nr_extents = 0; + if (ntfs_mft_record_free(ni->vol, ni->extent_nis[i])) + { + err = errno; + ntfs_log_error("Failed to free extent MFT record. " + "Leaving inconsistent metadata.\n"); + } + } + free(ni->extent_nis); + ni->nr_extents = 0; + ni->extent_nis = (ntfs_inode**) NULL; #else - 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"); - } + 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"); + } #endif - 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 (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; + 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 (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; } /** @@ -2047,86 +2017,88 @@ 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) +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; + 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->data_size = fn->allocated_size = const_cpu_to_le64(0); - } else { - fn->allocated_size = cpu_to_sle64(ni->allocated_size); - fn->data_size = cpu_to_sle64(ni->data_size); - } - fn->creation_time = ni->creation_time; - fn->last_data_change_time = ni->last_data_change_time; - fn->last_mft_change_time = ni->last_mft_change_time; - fn->last_access_time = 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"); -err_out: - free(fn); - errno = err; - return -1; + 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->data_size = fn->allocated_size = const_cpu_to_le64(0); + } + else + { + fn->allocated_size = cpu_to_sle64(ni->allocated_size); + fn->data_size = cpu_to_sle64(ni->data_size); + } + fn->creation_time = ni->creation_time; + fn->last_data_change_time = ni->last_data_change_time; + fn->last_mft_change_time = ni->last_mft_change_time; + fn->last_access_time = 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"); + err_out: 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)); + return (ntfs_link_i(ni, dir_ni, name, name_len, FILE_NAME_POSIX)); } /* @@ -2142,30 +2114,30 @@ int ntfs_link(ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, u8 name_len) ntfs_inode *ntfs_dir_parent_inode(ntfs_inode *ni) { - ntfs_inode *dir_ni = (ntfs_inode*)NULL; - u64 inum; - FILE_NAME_ATTR *fn; - ntfs_attr_search_ctx *ctx; + ntfs_inode *dir_ni = (ntfs_inode*) NULL; + u64 inum; + FILE_NAME_ATTR *fn; + ntfs_attr_search_ctx *ctx; - if (ni->mft_no != FILE_root) { - /* find the name in the attributes */ - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - return ((ntfs_inode*)NULL); + if (ni->mft_no != FILE_root) + { + /* find the name in the attributes */ + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) return ((ntfs_inode*) NULL); - if (!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)); - inum = le64_to_cpu(fn->parent_directory); - if (inum != (u64)-1) { - dir_ni = ntfs_inode_open(ni->vol, MREF(inum)); - } - } - ntfs_attr_put_search_ctx(ctx); - } - return (dir_ni); + if (!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)); + inum = le64_to_cpu(fn->parent_directory); + if (inum != (u64) -1) + { + dir_ni = ntfs_inode_open(ni->vol, MREF(inum)); + } + } + ntfs_attr_put_search_ctx(ctx); + } + return (dir_ni); } #ifdef HAVE_SETXATTR @@ -2182,39 +2154,40 @@ ntfs_inode *ntfs_dir_parent_inode(ntfs_inode *ni) 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; + 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); } - /* * Get a long name for a file in designated directory * @@ -2225,98 +2198,108 @@ static int get_dos_name(ntfs_inode *ni, u64 dnum, ntfschar *dosname) static int get_long_name(ntfs_inode *ni, u64 dnum, ntfschar *longname) { - size_t outsize = 0; - FILE_NAME_ATTR *fn; - ntfs_attr_search_ctx *ctx; + 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; - /* first search for WIN32 or DOS+WIN32 names */ - 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)); + /* first search for WIN32 or DOS+WIN32 names */ + 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_WIN32) - && (MREF_LE(fn->parent_directory) == dnum)) { - /* - * Found a WIN32 or WIN32+DOS name for the entry - * copy name - */ - outsize = fn->file_name_length; - memcpy(longname,fn->file_name,outsize*sizeof(ntfschar)); - } - } - /* if not found search for POSIX names */ - if (!outsize) { - ntfs_attr_reinit_search_ctx(ctx); - 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_WIN32) + && (MREF_LE(fn->parent_directory) == dnum)) + { + /* + * Found a WIN32 or WIN32+DOS name for the entry + * copy name + */ + outsize = fn->file_name_length; + memcpy(longname,fn->file_name,outsize*sizeof(ntfschar)); + } + } + /* if not found search for POSIX names */ + if (!outsize) + { + ntfs_attr_reinit_search_ctx(ctx); + 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_POSIX) - && (MREF_LE(fn->parent_directory) == dnum)) { - /* - * Found a POSIX name for the entry - * copy name - */ - outsize = fn->file_name_length; - memcpy(longname,fn->file_name,outsize*sizeof(ntfschar)); - } - } - } - ntfs_attr_put_search_ctx(ctx); - return (outsize); + if ((fn->file_name_type == FILE_NAME_POSIX) + && (MREF_LE(fn->parent_directory) == dnum)) + { + /* + * Found a POSIX name for the entry + * copy name + */ + outsize = fn->file_name_length; + memcpy(longname,fn->file_name,outsize*sizeof(ntfschar)); + } + } + } + ntfs_attr_put_search_ctx(ctx); + return (outsize); } - /* * Get the ntfs DOS name into an extended attribute */ int ntfs_get_ntfs_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni, - char *value, size_t size) + char *value, size_t size) { - int outsize = 0; - char *outname = (char*)NULL; - u64 dnum; - int doslen; - ntfschar dosname[MAX_DOS_NAME_LENGTH]; + int outsize = 0; + char *outname = (char*)NULL; + u64 dnum; + int doslen; + ntfschar dosname[MAX_DOS_NAME_LENGTH]; - dnum = dir_ni->mft_no; - 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; - } - return (outsize); + dnum = dir_ni->mft_no; + 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; + } + return (outsize); } /* @@ -2327,51 +2310,57 @@ int ntfs_get_ntfs_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni, */ static int set_namespace(ntfs_inode *ni, ntfs_inode *dir_ni, - ntfschar *name, int len, - FILE_NAME_TYPE_FLAGS nametype) + 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; + 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); } /* @@ -2401,96 +2390,109 @@ static int set_namespace(ntfs_inode *ni, ntfs_inode *dir_ni, */ static int set_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni, - ntfschar *shortname, int shortlen, - ntfschar *longname, int longlen, - ntfschar *deletename, int deletelen, BOOL existed) + 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; + 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_update_times(ni, NTFS_UPDATE_CTIME); - ntfs_inode_update_times(dir_ni, NTFS_UPDATE_MCTIME); - if (ntfs_inode_close_in_dir(ni,dir_ni) && !res) - res = -1; - if (ntfs_inode_close(dir_ni) && !res) - res = -1; - } - } 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 */ -// is it ok to not provide the path ? - if (!ntfs_delete(vol, (char*)NULL, 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; - if (ntfs_inode_close_in_dir(ni, - dir_ni) - && !res) - res = -1; - } - if (ntfs_inode_close(dir_ni) && !res) - res = -1; - } - } - } else { - ntfs_inode_close_in_dir(ni,dir_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_update_times(ni, NTFS_UPDATE_CTIME); + ntfs_inode_update_times(dir_ni, NTFS_UPDATE_MCTIME); + if (ntfs_inode_close_in_dir(ni,dir_ni) && !res) + res = -1; + if (ntfs_inode_close(dir_ni) && !res) + res = -1; + } + } + 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 */ + // is it ok to not provide the path ? + if (!ntfs_delete(vol, (char*)NULL, 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; + if (ntfs_inode_close_in_dir(ni, + dir_ni) + && !res) + res = -1; + } + if (ntfs_inode_close(dir_ni) && !res) + res = -1; + } + } + } + else + { + ntfs_inode_close_in_dir(ni,dir_ni); + ntfs_inode_close(dir_ni); + } + } + return (res); } - /* * Set the ntfs DOS name into an extended attribute * @@ -2502,83 +2504,99 @@ static int set_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni, */ int ntfs_set_ntfs_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni, - const char *value, size_t size, int flags) + const char *value, size_t size, int flags) { - 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[NTFS_MAX_NAME_LEN]; + 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[NTFS_MAX_NAME_LEN]; - 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_in_dir(ni,dir_ni); - ntfs_inode_close(dir_ni); - res = -errno; - return res; - } - dnum = dir_ni->mft_no; - longlen = get_long_name(ni, dnum, longname); - if (longlen > 0) { - oldlen = get_dos_name(ni, dnum, oldname); - if ((oldlen >= 0) - && !ntfs_forbidden_chars(longname, longlen)) { - 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, - 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, - shortname, shortlen, - longname, longlen, - longname, longlen, FALSE); - closed = TRUE; - } - } - } else - res = -1; - } else { - res = -1; - errno = ENOENT; - } - free(shortname); - if (!closed) { - ntfs_inode_close_in_dir(ni,dir_ni); - ntfs_inode_close(dir_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_in_dir(ni,dir_ni); + ntfs_inode_close(dir_ni); + res = -errno; + return res; + } + dnum = dir_ni->mft_no; + longlen = get_long_name(ni, dnum, longname); + if (longlen > 0) + { + oldlen = get_dos_name(ni, dnum, oldname); + if ((oldlen >= 0) + && !ntfs_forbidden_chars(longname, longlen)) + { + 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, + 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, + shortname, shortlen, + longname, longlen, + longname, longlen, FALSE); + closed = TRUE; + } + } + } + else + res = -1; + } + else + { + res = -1; + errno = ENOENT; + } + free(shortname); + if (!closed) + { + ntfs_inode_close_in_dir(ni,dir_ni); + ntfs_inode_close(dir_ni); + } + return (res ? -1 : 0); } /* @@ -2587,74 +2605,83 @@ int ntfs_set_ntfs_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni, int ntfs_remove_ntfs_dos_name(ntfs_inode *ni, ntfs_inode *dir_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[NTFS_MAX_NAME_LEN]; + 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[NTFS_MAX_NAME_LEN]; - res = -1; - vol = ni->vol; - dnum = dir_ni->mft_no; - longlen = get_long_name(ni, dnum, longname); - if (longlen > 0) { - 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 inode %lld to Posix\n", - (long long)ni->mft_no); - } - break; - default : - /* name was Posix or not found : error */ - errno = ENOENT; - break; - } - } - } else { - errno = ENOENT; - res = -1; - } - if (!deleted) { - ntfs_inode_close_in_dir(ni,dir_ni); - ntfs_inode_close(dir_ni); - } - return (res); + res = -1; + vol = ni->vol; + dnum = dir_ni->mft_no; + longlen = get_long_name(ni, dnum, longname); + if (longlen > 0) + { + 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 inode %lld to Posix\n", + (long long)ni->mft_no); + } + break; + default : + /* name was Posix or not found : error */ + errno = ENOENT; + break; + } + } + } + else + { + errno = ENOENT; + res = -1; + } + if (!deleted) + { + ntfs_inode_close_in_dir(ni,dir_ni); + ntfs_inode_close(dir_ni); + } + return (res); } #endif diff --git a/source/libntfs/dir.h b/source/libntfs/dir.h index 56e76fe7..2eb65fb4 100644 --- a/source/libntfs/dir.h +++ b/source/libntfs/dir.h @@ -59,27 +59,21 @@ extern ntfschar NTFS_INDEX_O[3]; 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); +extern u64 ntfs_inode_lookup_by_name(ntfs_inode *dir_ni, const ntfschar *uname, const int uname_len); extern u64 ntfs_inode_lookup_by_mbsname(ntfs_inode *dir_ni, const char *name); -extern void ntfs_inode_update_mbsname(ntfs_inode *dir_ni, const char *name, - u64 inum); +extern void ntfs_inode_update_mbsname(ntfs_inode *dir_ni, const char *name, u64 inum); -extern ntfs_inode *ntfs_pathname_to_inode(ntfs_volume *vol, ntfs_inode *parent, - const char *pathname); -extern ntfs_inode *ntfs_create(ntfs_inode *dir_ni, le32 securid, - 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); -extern ntfs_inode *ntfs_create_symlink(ntfs_inode *dir_ni, le32 securid, - ntfschar *name, u8 name_len, ntfschar *target, int target_len); +extern ntfs_inode *ntfs_pathname_to_inode(ntfs_volume *vol, ntfs_inode *parent, const char *pathname); +extern ntfs_inode *ntfs_create(ntfs_inode *dir_ni, le32 securid, 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); +extern ntfs_inode *ntfs_create_symlink(ntfs_inode *dir_ni, le32 securid, 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); +extern int ntfs_delete(ntfs_volume *vol, const char *path, 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); +extern int ntfs_link(ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, u8 name_len); /* * File types (adapted from include ) @@ -100,19 +94,15 @@ extern int ntfs_link(ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, * This allows the caller to read directories into their application or * 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); +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); -extern int ntfs_readdir(ntfs_inode *dir_ni, s64 *pos, - void *dirent, ntfs_filldir_t filldir); +extern int ntfs_readdir(ntfs_inode *dir_ni, s64 *pos, void *dirent, ntfs_filldir_t filldir); ntfs_inode *ntfs_dir_parent_inode(ntfs_inode *ni); -int ntfs_get_ntfs_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni, - char *value, size_t size); -int ntfs_set_ntfs_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni, - const char *value, size_t size, int flags); +int ntfs_get_ntfs_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni, char *value, size_t size); +int ntfs_set_ntfs_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni, const char *value, size_t size, int flags); int ntfs_remove_ntfs_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni); #if CACHE_INODE_SIZE diff --git a/source/libntfs/efs.c b/source/libntfs/efs.c index 6ccec20a..d72cf002 100644 --- a/source/libntfs/efs.c +++ b/source/libntfs/efs.c @@ -60,14 +60,14 @@ #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) -} ; - +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) +}; /* * Get the ntfs EFS info into an extended attribute @@ -75,49 +75,63 @@ static ntfschar logged_utility_stream_name[] = { int ntfs_get_efs_info(ntfs_inode *ni, char *value, size_t size) { - EFS_ATTR_HEADER *efs_info; - s64 attr_size = 0; + 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_error("Bad efs_info for inode %lld\n", - (long long)ni->mft_no); - } else { - ntfs_log_error("Could not get efsinfo" - " for inode %lld\n", - (long long)ni->mft_no); - } - errno = EIO; - attr_size = 0; - } - } else { - errno = ENODATA; - ntfs_log_trace("Inode %lld is not encrypted\n", - (long long)ni->mft_no); - } - } - 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_error("Bad efs_info for inode %lld\n", + (long long)ni->mft_no); + } + else + { + ntfs_log_error("Could not get efsinfo" + " for inode %lld\n", + (long long)ni->mft_no); + } + errno = EIO; + attr_size = 0; + } + } + else + { + errno = ENODATA; + ntfs_log_trace("Inode %lld is not encrypted\n", + (long long)ni->mft_no); + } + } + return (attr_size ? (int)attr_size : -errno); } /* @@ -135,76 +149,89 @@ int ntfs_get_efs_info(ntfs_inode *ni, char *value, size_t size) static int fixup_loop(ntfs_inode *ni) { - ntfs_attr_search_ctx *ctx; - ntfs_attr *na; - ATTR_RECORD *a; - BOOL restart; - BOOL first; - int cnt; - int maxcnt; - int res = 0; + ntfs_attr_search_ctx *ctx; + ntfs_attr *na; + ATTR_RECORD *a; + BOOL restart; + BOOL first; + int cnt; + int maxcnt; + int res = 0; - maxcnt = 0; - do { - restart = FALSE; - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) { - ntfs_log_error("Failed to get ctx for efs\n"); - res = -1; - } - cnt = 0; - while (!restart && !res - && !ntfs_attr_lookup(AT_DATA, NULL, 0, - CASE_SENSITIVE, 0, NULL, 0, ctx)) { - cnt++; - a = ctx->attr; - 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"); - res = -1; - } - if (na && !(ctx->attr->flags & ATTR_IS_ENCRYPTED)) { - if (!NAttrNonResident(na) - && ntfs_attr_make_non_resident(na, ctx)) { - /* - * ntfs_attr_make_non_resident fails if there - * is not enough space in the MFT record. - * When this happens, force making non-resident - * so that some other attribute is expelled. - */ - if (ntfs_attr_force_non_resident(na)) { - res = -1; - } else { - /* make sure there is some progress */ - if (cnt <= maxcnt) { - errno = EIO; - ntfs_log_error("Multiple failure" - " making non resident\n"); - res = -1; - } else { - ntfs_attr_put_search_ctx(ctx); - ctx = (ntfs_attr_search_ctx*)NULL; - restart = TRUE; - maxcnt = cnt; - } - } - } - if (!restart && !res - && ntfs_efs_fixup_attribute(ctx, na)) { - ntfs_log_error("Error in efs fixup of AT_DATA Attribute\n"); - res = -1; - } - } - if (na) - ntfs_attr_close(na); - } - first = FALSE; - } while (restart && !res); - if (ctx) - ntfs_attr_put_search_ctx(ctx); - return (res); + maxcnt = 0; + do + { + restart = FALSE; + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + { + ntfs_log_error("Failed to get ctx for efs\n"); + res = -1; + } + cnt = 0; + while (!restart && !res + && !ntfs_attr_lookup(AT_DATA, NULL, 0, + CASE_SENSITIVE, 0, NULL, 0, ctx)) + { + cnt++; + a = ctx->attr; + 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"); + res = -1; + } + if (na && !(ctx->attr->flags & ATTR_IS_ENCRYPTED)) + { + if (!NAttrNonResident(na) + && ntfs_attr_make_non_resident(na, ctx)) + { + /* + * ntfs_attr_make_non_resident fails if there + * is not enough space in the MFT record. + * When this happens, force making non-resident + * so that some other attribute is expelled. + */ + if (ntfs_attr_force_non_resident(na)) + { + res = -1; + } + else + { + /* make sure there is some progress */ + if (cnt <= maxcnt) + { + errno = EIO; + ntfs_log_error("Multiple failure" + " making non resident\n"); + res = -1; + } + else + { + ntfs_attr_put_search_ctx(ctx); + ctx = (ntfs_attr_search_ctx*)NULL; + restart = TRUE; + maxcnt = cnt; + } + } + } + if (!restart && !res + && ntfs_efs_fixup_attribute(ctx, na)) + { + ntfs_log_error("Error in efs fixup of AT_DATA Attribute\n"); + res = -1; + } + } + if (na) + ntfs_attr_close(na); + } + first = FALSE; + }while (restart && !res); + if (ctx) + ntfs_attr_put_search_ctx(ctx); + return (res); } /* @@ -214,100 +241,121 @@ static int fixup_loop(ntfs_inode *ni) */ int ntfs_set_efs_info(ntfs_inode *ni, const char *value, size_t size, - int flags) - -{ - int res; - int written; - ntfs_attr *na; - const EFS_ATTR_HEADER *info_header; + int flags) - res = 0; - if (ni && value && size) { - if (ni->flags & (FILE_ATTR_ENCRYPTED | FILE_ATTR_COMPRESSED)) { - if (ni->flags & FILE_ATTR_ENCRYPTED) { - ntfs_log_trace("Inode %lld already encrypted\n", - (long long)ni->mft_no); - 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("Inode %lld cannot be encrypted and compressed\n", - (long long)ni->mft_no); - 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 */ - - if (fixup_loop(ni)) - return -1; - } - ni->flags |= FILE_ATTR_ENCRYPTED; - NInoSetDirty(ni); - NInoFileNameSetDirty(ni); - } - } else { - errno = EINVAL; - res = -1; - } - return (res ? -1 : 0); +{ + int res; + int written; + ntfs_attr *na; + const EFS_ATTR_HEADER *info_header; + + res = 0; + if (ni && value && size) + { + if (ni->flags & (FILE_ATTR_ENCRYPTED | FILE_ATTR_COMPRESSED)) + { + if (ni->flags & FILE_ATTR_ENCRYPTED) + { + ntfs_log_trace("Inode %lld already encrypted\n", + (long long)ni->mft_no); + 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("Inode %lld cannot be encrypted and compressed\n", + (long long)ni->mft_no); + 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 */ + + if (fixup_loop(ni)) + return -1; + } + ni->flags |= FILE_ATTR_ENCRYPTED; + NInoSetDirty(ni); + NInoFileNameSetDirty(ni); + } + } + else + { + errno = EINVAL; + res = -1; + } + return (res ? -1 : 0); } /* @@ -321,119 +369,138 @@ int ntfs_set_efs_info(ntfs_inode *ni, const char *value, size_t size, * -1 if failed (errno tells why) */ -int ntfs_efs_fixup_attribute(ntfs_attr_search_ctx *ctx, ntfs_attr *na) +int ntfs_efs_fixup_attribute(ntfs_attr_search_ctx *ctx, ntfs_attr *na) { - u64 newsize; - u64 oldsize; - le16 appended_bytes; - u16 padding_length; - ntfs_inode *ni; - BOOL close_ctx = FALSE; + u64 newsize; + u64 oldsize; + le16 appended_bytes; + u16 padding_length; + ntfs_inode *ni; + BOOL close_ctx = FALSE; - if (!na) { - ntfs_log_error("no 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; - } - } else { - if (!NAttrNonResident(na)) { - ntfs_log_error("Cannot make non resident" - " when a context has been allocated\n"); - goto err_out; - } - } + if (!na) + { + ntfs_log_error("no 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; + } + } + else + { + if (!NAttrNonResident(na)) + { + ntfs_log_error("Cannot make non resident" + " when a context has been allocated\n"); + goto err_out; + } + } - /* no extra bytes are added to void attributes */ - oldsize = na->data_size; - if (oldsize) { - /* make sure size is valid for a raw encrypted stream */ - if ((oldsize & 511) != 2) { - ntfs_log_error("Bad raw encrypted stream\n"); - goto err_out; - } - /* read padding length from last two bytes of attribute */ - if (ntfs_attr_pread(na, oldsize - 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)oldsize); - goto err_out; - } - newsize = oldsize - padding_length - 2; - /* - * truncate attribute to possibly free clusters allocated - * for the last two bytes, but do not truncate to new size - * to avoid losing useful data - */ - if (ntfs_attr_truncate(na, oldsize - 2)) { - ntfs_log_error("Error truncating attribute\n"); - goto err_out; - } - } else - newsize = 0; + /* no extra bytes are added to void attributes */ + oldsize = na->data_size; + if (oldsize) + { + /* make sure size is valid for a raw encrypted stream */ + if ((oldsize & 511) != 2) + { + ntfs_log_error("Bad raw encrypted stream\n"); + goto err_out; + } + /* read padding length from last two bytes of attribute */ + if (ntfs_attr_pread(na, oldsize - 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)oldsize); + goto err_out; + } + newsize = oldsize - padding_length - 2; + /* + * truncate attribute to possibly free clusters allocated + * for the last two bytes, but do not truncate to new size + * to avoid losing useful data + */ + if (ntfs_attr_truncate(na, oldsize - 2)) + { + ntfs_log_error("Error truncating attribute\n"); + goto err_out; + } + } + else + newsize = 0; - /* - * Encrypted AT_DATA Attributes MUST be non-resident - * This has to be done after the attribute is resized, as - * resizing down to zero may cause the attribute to be made - * resident. - */ - if (!NAttrNonResident(na) - && ntfs_attr_make_non_resident(na, ctx)) { - if (!close_ctx - || ntfs_attr_force_non_resident(na)) { - ntfs_log_error("Error making DATA attribute non-resident\n"); - goto err_out; - } else { - /* - * must reinitialize context after forcing - * non-resident. We need a context for updating - * the state, and at this point, we are sure - * the context is not used elsewhere. - */ - ntfs_attr_reinit_search_ctx(ctx); - 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; - } - } - } - ni = na->ni; - if (!na->name_len) { - ni->data_size = newsize; - ni->allocated_size = na->allocated_size; - } - NInoSetDirty(ni); - NInoFileNameSetDirty(ni); + /* + * Encrypted AT_DATA Attributes MUST be non-resident + * This has to be done after the attribute is resized, as + * resizing down to zero may cause the attribute to be made + * resident. + */ + if (!NAttrNonResident(na) + && ntfs_attr_make_non_resident(na, ctx)) + { + if (!close_ctx + || ntfs_attr_force_non_resident(na)) + { + ntfs_log_error("Error making DATA attribute non-resident\n"); + goto err_out; + } + else + { + /* + * must reinitialize context after forcing + * non-resident. We need a context for updating + * the state, and at this point, we are sure + * the context is not used elsewhere. + */ + ntfs_attr_reinit_search_ctx(ctx); + 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; + } + } + } + ni = na->ni; + if (!na->name_len) + { + ni->data_size = newsize; + ni->allocated_size = na->allocated_size; + } + NInoSetDirty(ni); + NInoFileNameSetDirty(ni); - 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_ctx && ctx) - ntfs_attr_put_search_ctx(ctx); - return (-1); + 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_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 6eada067..46328c2b 100644 --- a/source/libntfs/efs.h +++ b/source/libntfs/efs.h @@ -23,8 +23,7 @@ int ntfs_get_efs_info(ntfs_inode *ni, char *value, size_t size); -int ntfs_set_efs_info(ntfs_inode *ni, - const char *value, size_t size, int flags); +int ntfs_set_efs_info(ntfs_inode *ni, const char *value, size_t size, int flags); int ntfs_efs_fixup_attribute(ntfs_attr_search_ctx *ctx, ntfs_attr *na); #endif /* EFS_H */ diff --git a/source/libntfs/gekko_io.c b/source/libntfs/gekko_io.c index 48ca90d4..601b433d 100644 --- a/source/libntfs/gekko_io.c +++ b/source/libntfs/gekko_io.c @@ -69,7 +69,8 @@ static s64 ntfs_device_gekko_io_readbytes(struct ntfs_device *dev, s64 offset, s64 count, void *buf); static bool ntfs_device_gekko_io_readsectors(struct ntfs_device *dev, sec_t sector, sec_t numSectors, void* buffer); static s64 ntfs_device_gekko_io_writebytes(struct ntfs_device *dev, s64 offset, s64 count, const void *buf); -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); /** * @@ -80,32 +81,37 @@ static int ntfs_device_gekko_io_open(struct ntfs_device *dev, int flags) // Get the device driver descriptor gekko_fd *fd = DEV_FD(dev); - if (!fd) { + if (!fd) + { errno = EBADF; return -1; } // Get the device interface const DISC_INTERFACE* interface = fd->interface; - if (!interface) { + if (!interface) + { errno = ENODEV; return -1; } // Start the device interface and ensure that it is inserted - if (!interface->startup()) { + if (!interface->startup()) + { ntfs_log_perror("device failed to start\n"); errno = EIO; return -1; } - if (!interface->isInserted()) { + if (!interface->isInserted()) + { ntfs_log_perror("device media is not inserted\n"); errno = EIO; return -1; } // Check that the device isn't already open (used by another volume?) - if (NDevOpen(dev)) { + if (NDevOpen(dev)) + { ntfs_log_perror("device is busy (already open)\n"); errno = EBUSY; return -1; @@ -113,12 +119,16 @@ static int ntfs_device_gekko_io_open(struct ntfs_device *dev, int flags) // Check that there is a valid NTFS boot sector at the start of the device NTFS_BOOT_SECTOR boot; - if (interface->readSectors(fd->startSector, 1, &boot)) { - if (!ntfs_boot_sector_is_ntfs(&boot)) { + if (interface->readSectors(fd->startSector, 1, &boot)) + { + if (!ntfs_boot_sector_is_ntfs(&boot)) + { errno = EINVALPART; return -1; } - } else { + } + else + { ntfs_log_perror("read failure @ sector %d\n", fd->startSector); errno = EIO; return -1; @@ -133,12 +143,14 @@ static int ntfs_device_gekko_io_open(struct ntfs_device *dev, int flags) fd->ino = le64_to_cpu(boot.volume_serial_number); // Mark the device as read-only (if required) - if (flags & O_RDONLY) { + if (flags & O_RDONLY) + { NDevSetReadOnly(dev); } // Create the cache - fd->cache = _NTFS_cache_constructor(fd->cachePageCount, fd->cachePageSize, interface, fd->startSector + fd->sectorCount, fd->sectorSize); + fd->cache = _NTFS_cache_constructor(fd->cachePageCount, fd->cachePageSize, interface, fd->startSector + + fd->sectorCount, fd->sectorSize); // Mark the device as open NDevSetBlock(dev); @@ -156,13 +168,15 @@ static int ntfs_device_gekko_io_close(struct ntfs_device *dev) // Get the device driver descriptor gekko_fd *fd = DEV_FD(dev); - if (!fd) { + if (!fd) + { errno = EBADF; return -1; } // Check that the device is actually open - if (!NDevOpen(dev)) { + if (!NDevOpen(dev)) + { ntfs_log_perror("device is not open\n"); errno = EIO; return -1; @@ -173,7 +187,8 @@ static int ntfs_device_gekko_io_close(struct ntfs_device *dev) NDevClearBlock(dev); // Flush the device (if dirty and not read-only) - if (NDevDirty(dev) && !NDevReadOnly(dev)) { + if (NDevDirty(dev) && !NDevReadOnly(dev)) + { ntfs_log_debug("device is dirty, will now sync\n"); // ...? @@ -184,16 +199,17 @@ static int ntfs_device_gekko_io_close(struct ntfs_device *dev) } // Flush and destroy the cache (if required) - if (fd->cache) { + if (fd->cache) + { _NTFS_cache_flush(fd->cache); _NTFS_cache_destructor(fd->cache); } // Shutdown the device interface /*const DISC_INTERFACE* interface = fd->interface; - if (interface) { - interface->shutdown(); - }*/ + if (interface) { + interface->shutdown(); + }*/ // Free the device driver private data ntfs_free(dev->d_private); @@ -211,16 +227,24 @@ static s64 ntfs_device_gekko_io_seek(struct ntfs_device *dev, s64 offset, int wh // Get the device driver descriptor gekko_fd *fd = DEV_FD(dev); - if (!fd) { + if (!fd) + { errno = EBADF; return -1; } // 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; @@ -267,26 +291,27 @@ static s64 ntfs_device_gekko_io_readbytes(struct ntfs_device *dev, s64 offset, s // Get the device driver descriptor gekko_fd *fd = DEV_FD(dev); - if (!fd) { + if (!fd) + { errno = EBADF; return -1; } // Get the device interface const DISC_INTERFACE* interface = fd->interface; - if (!interface) { + if (!interface) + { errno = ENODEV; return -1; } - if(offset < 0) + if (offset < 0) { errno = EROFS; return -1; } - if(!count) - return 0; + if (!count) return 0; sec_t sec_start = (sec_t) fd->startSector; sec_t sec_count = 1; @@ -294,33 +319,38 @@ static s64 ntfs_device_gekko_io_readbytes(struct ntfs_device *dev, s64 offset, s u8 *buffer = NULL; // Determine the range of sectors required for this read - if (offset > 0) { + if (offset > 0) + { sec_start += (sec_t) floor((f64) offset / (f64) fd->sectorSize); } - if (buffer_offset+count > fd->sectorSize) { - sec_count = (sec_t) ceil((f64) (buffer_offset+count) / (f64) fd->sectorSize); + if (buffer_offset + count > fd->sectorSize) + { + sec_count = (sec_t) ceil((f64) (buffer_offset + count) / (f64) fd->sectorSize); } // If this read happens to be on the sector boundaries then do the read straight into the destination buffer - if((buffer_offset == 0) && (count % fd->sectorSize == 0)) { + if ((buffer_offset == 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); - if (!ntfs_device_gekko_io_readsectors(dev, sec_start, sec_count, buf)) { + if (!ntfs_device_gekko_io_readsectors(dev, sec_start, sec_count, buf)) + { ntfs_log_perror("direct read failure @ sector %d (%d sector(s) long)\n", sec_start, sec_count); errno = EIO; return -1; } - // Else read into a buffer and copy over only what was requested + // 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); - if (!buffer) { + buffer = (u8*) ntfs_alloc(sec_count * fd->sectorSize); + if (!buffer) + { errno = ENOMEM; return -1; } @@ -328,7 +358,8 @@ static s64 ntfs_device_gekko_io_readbytes(struct ntfs_device *dev, s64 offset, s // Read from the device ntfs_log_trace("buffered read from sector %d (%d sector(s) long)\n", sec_start, sec_count); ntfs_log_trace("count: %d sec_count:%d fd->sectorSize: %d )\n", (u32)count, (u32)sec_count,(u32)fd->sectorSize); - if (!ntfs_device_gekko_io_readsectors(dev, sec_start, sec_count, buffer)) { + if (!ntfs_device_gekko_io_readsectors(dev, sec_start, sec_count, buffer)) + { ntfs_log_perror("buffered read failure @ sector %d (%d sector(s) long)\n", sec_start, sec_count); ntfs_free(buffer); errno = EIO; @@ -353,31 +384,34 @@ static s64 ntfs_device_gekko_io_writebytes(struct ntfs_device *dev, s64 offset, // Get the device driver descriptor gekko_fd *fd = DEV_FD(dev); - if (!fd) { + if (!fd) + { errno = EBADF; return -1; } // Get the device interface const DISC_INTERFACE* interface = fd->interface; - if (!interface) { + if (!interface) + { errno = ENODEV; return -1; } // Check that the device can be written to - if (NDevReadOnly(dev)) { + if (NDevReadOnly(dev)) + { errno = EROFS; return -1; } - if(count < 0 || offset < 0) { + if (count < 0 || offset < 0) + { errno = EROFS; return -1; } - if(count == 0) - return 0; + if (count == 0) return 0; sec_t sec_start = (sec_t) fd->startSector; sec_t sec_count = 1; @@ -385,48 +419,55 @@ static s64 ntfs_device_gekko_io_writebytes(struct ntfs_device *dev, s64 offset, u8 *buffer = NULL; // Determine the range of sectors required for this write - if (offset > 0) { + if (offset > 0) + { sec_start += (sec_t) floor((f64) offset / (f64) fd->sectorSize); } - if ((buffer_offset+count) > fd->sectorSize) { - sec_count = (sec_t) ceil((f64) (buffer_offset+count) / (f64) fd->sectorSize); + if ((buffer_offset + count) > fd->sectorSize) + { + sec_count = (sec_t) ceil((f64) (buffer_offset + count) / (f64) fd->sectorSize); } // If this write happens to be on the sector boundaries then do the write straight to disc - if((buffer_offset == 0) && (count % fd->sectorSize == 0)) + if ((buffer_offset == 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); - if (!ntfs_device_gekko_io_writesectors(dev, sec_start, sec_count, buf)) { + if (!ntfs_device_gekko_io_writesectors(dev, sec_start, sec_count, buf)) + { ntfs_log_perror("direct write failure @ sector %d (%d sector(s) long)\n", sec_start, sec_count); errno = EIO; 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 buffer = (u8 *) ntfs_alloc(sec_count * fd->sectorSize); - if (!buffer) { + if (!buffer) + { errno = ENOMEM; return -1; } // 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(buffer_offset != 0) + if (buffer_offset != 0) { - if (!ntfs_device_gekko_io_readsectors(dev, sec_start, 1, buffer)) { + if (!ntfs_device_gekko_io_readsectors(dev, sec_start, 1, buffer)) + { ntfs_log_perror("read failure @ sector %d\n", sec_start); ntfs_free(buffer); errno = EIO; return -1; } } - if((buffer_offset+count) % fd->sectorSize != 0) + if ((buffer_offset + count) % fd->sectorSize != 0) { - if (!ntfs_device_gekko_io_readsectors(dev, sec_start + sec_count - 1, 1, buffer + ((sec_count-1) * fd->sectorSize))) { + 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 - 1); ntfs_free(buffer); errno = EIO; @@ -439,7 +480,8 @@ static s64 ntfs_device_gekko_io_writebytes(struct ntfs_device *dev, s64 offset, // Write to the device ntfs_log_trace("buffered write to sector %d (%d sector(s) long)\n", sec_start, sec_count); - if (!ntfs_device_gekko_io_writesectors(dev, sec_start, sec_count, buffer)) { + if (!ntfs_device_gekko_io_writesectors(dev, sec_start, sec_count, buffer)) + { ntfs_log_perror("buffered write failure @ sector %d\n", sec_start); ntfs_free(buffer); errno = EIO; @@ -460,24 +502,26 @@ static bool ntfs_device_gekko_io_readsectors(struct ntfs_device *dev, sec_t sect { // Get the device driver descriptor gekko_fd *fd = DEV_FD(dev); - if (!fd) { + if (!fd) + { errno = EBADF; return false; } // Read the sectors from disc (or cache, if enabled) if (fd->cache) return _NTFS_cache_readSectors(fd->cache, sector, numSectors, buffer); - else - return fd->interface->readSectors(sector, numSectors, buffer); + else return fd->interface->readSectors(sector, numSectors, buffer); 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) { + if (!fd) + { errno = EBADF; return false; } @@ -485,8 +529,7 @@ static bool ntfs_device_gekko_io_writesectors(struct ntfs_device *dev, sec_t sec // Write the sectors to disc (or cache, if enabled) if (fd->cache) return _NTFS_cache_writeSectors(fd->cache, sector, numSectors, buffer); - else - return fd->interface->writeSectors(sector, numSectors, buffer); + else return fd->interface->writeSectors(sector, numSectors, buffer); return false; } @@ -496,11 +539,12 @@ 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); + gekko_fd *fd = DEV_FD(dev); ntfs_log_trace("dev %p\n", dev); // Check that the device can be written to - if (NDevReadOnly(dev)) { + if (NDevReadOnly(dev)) + { errno = EROFS; return -1; } @@ -509,8 +553,10 @@ static int ntfs_device_gekko_io_sync(struct ntfs_device *dev) NDevClearDirty(dev); // Flush any sectors in the disc cache (if required) - if (fd->cache) { - if (!_NTFS_cache_flush(fd->cache)) { + if (fd->cache) + { + if (!_NTFS_cache_flush(fd->cache)) + { errno = EIO; return -1; } @@ -528,19 +574,18 @@ static int ntfs_device_gekko_io_stat(struct ntfs_device *dev, struct stat *buf) // Get the device driver descriptor gekko_fd *fd = DEV_FD(dev); - if (!fd) { + if (!fd) + { errno = EBADF; return -1; } // Short circuit cases were we don't actually have to do anything - if (!buf) - return 0; + if (!buf) return 0; // Build the device mode - mode_t mode = (S_IFBLK) | - (S_IRUSR | S_IRGRP | S_IROTH) | - ((!NDevReadOnly(dev)) ? (S_IWUSR | S_IWGRP | S_IWOTH) : 0); + mode_t mode = (S_IFBLK) | (S_IRUSR | S_IRGRP | S_IROTH) + | ((!NDevReadOnly(dev)) ? (S_IWUSR | S_IWGRP | S_IWOTH) : 0); // Zero out the stat buffer memset(buf, 0, sizeof(struct stat)); @@ -565,33 +610,38 @@ static int ntfs_device_gekko_io_ioctl(struct ntfs_device *dev, int request, void // Get the device driver descriptor gekko_fd *fd = DEV_FD(dev); - if (!fd) { + if (!fd) + { errno = EBADF; return -1; } // Figure out which i/o control was requested - switch (request) { + 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; @@ -599,27 +649,30 @@ 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; fd->sectorSize = sectorSize; return 0; } - #endif +#endif // Unimplemented ioctrl - default: { + default: + { ntfs_log_perror("Unimplemented ioctrl %i\n", request); errno = EOPNOTSUPP; return -1; @@ -633,15 +686,8 @@ static int ntfs_device_gekko_io_ioctl(struct ntfs_device *dev, int request, void /** * Device operations for working with gekko style devices and files. */ -struct ntfs_device_operations ntfs_device_gekko_io_ops = { - .open = ntfs_device_gekko_io_open, - .close = ntfs_device_gekko_io_close, - .seek = ntfs_device_gekko_io_seek, - .read = ntfs_device_gekko_io_read, - .write = ntfs_device_gekko_io_write, - .pread = ntfs_device_gekko_io_pread, - .pwrite = ntfs_device_gekko_io_pwrite, - .sync = ntfs_device_gekko_io_sync, - .stat = ntfs_device_gekko_io_stat, - .ioctl = ntfs_device_gekko_io_ioctl, -}; +struct ntfs_device_operations ntfs_device_gekko_io_ops = { .open = ntfs_device_gekko_io_open, + .close = ntfs_device_gekko_io_close, .seek = ntfs_device_gekko_io_seek, .read = ntfs_device_gekko_io_read, + .write = ntfs_device_gekko_io_write, .pread = ntfs_device_gekko_io_pread, + .pwrite = ntfs_device_gekko_io_pwrite, .sync = ntfs_device_gekko_io_sync, .stat = ntfs_device_gekko_io_stat, + .ioctl = ntfs_device_gekko_io_ioctl, }; diff --git a/source/libntfs/gekko_io.h b/source/libntfs/gekko_io.h index d5018e89..a9d6c588 100644 --- a/source/libntfs/gekko_io.h +++ b/source/libntfs/gekko_io.h @@ -1,22 +1,22 @@ /* -* gekko_io.h - Platform specifics for device io. -* -* Copyright (c) 2009 Rhys "Shareese" Koedijk -* -* 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 -* (at your option) any later version. -* -* This program/include file is distributed in the hope that it will be -* useful, but WITHOUT ANY WARRANTY; without even the implied warranty -* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software Foundation, -* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + * gekko_io.h - Platform specifics for device io. + * + * Copyright (c) 2009 Rhys "Shareese" Koedijk + * + * 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 + * (at your option) any later version. + * + * This program/include file is distributed in the hope that it will be + * useful, but WITHOUT ANY WARRANTY; without even the implied warranty + * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #ifndef _GEKKO_IO_H #define _GEKKO_IO_H @@ -33,18 +33,19 @@ /** * gekko_fd - Gekko device driver descriptor */ -typedef struct _gekko_fd { - const DISC_INTERFACE* interface; /* Device disc interface */ - sec_t startSector; /* LBA of partition start */ - sec_t hiddenSectors; /* LBA offset to true partition start (as described by boot sector) */ - u16 sectorSize; /* Device sector size (in bytes) */ - u64 sectorCount; /* Total number of sectors in partition */ - 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 */ - u32 cachePageCount; /* The number of pages in the cache */ - u32 cachePageSize; /* The number of sectors per cache page */ +typedef struct _gekko_fd +{ + const DISC_INTERFACE* interface; /* Device disc interface */ + sec_t startSector; /* LBA of partition start */ + sec_t hiddenSectors; /* LBA offset to true partition start (as described by boot sector) */ + u16 sectorSize; /* Device sector size (in bytes) */ + u64 sectorCount; /* Total number of sectors in partition */ + 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 */ + u32 cachePageCount; /* The number of pages in the cache */ + u32 cachePageSize; /* The number of sectors per cache page */ } gekko_fd; /* Forward declarations */ diff --git a/source/libntfs/index.c b/source/libntfs/index.c index 7df0deec..a11a8dff 100644 --- a/source/libntfs/index.c +++ b/source/libntfs/index.c @@ -64,47 +64,45 @@ */ 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; + 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; + 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; + 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; + 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; + if (ntfs_ib_write(icx, icx->ib)) return STATUS_ERROR; + + icx->ib_dirty = FALSE; + + return STATUS_OK; } /** @@ -116,48 +114,47 @@ static int ntfs_icx_ib_write(ntfs_index_context *icx) * Allocate a new index context, initialize it with @ni and return it. * Return NULL if allocation failed. */ -ntfs_index_context *ntfs_index_ctx_get(ntfs_inode *ni, - ntfschar *name, u32 name_len) +ntfs_index_context *ntfs_index_ctx_get(ntfs_inode *ni, ntfschar *name, u32 name_len) { - ntfs_index_context *icx; + 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"); - - if (!icx->entry) - return; + ntfs_log_trace("Entering\n"); - if (icx->actx) - ntfs_attr_put_search_ctx(icx->actx); + if (!icx->entry) return; - 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->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); } /** @@ -168,8 +165,8 @@ static void ntfs_index_ctx_free(ntfs_index_context *icx) */ void ntfs_index_ctx_put(ntfs_index_context *icx) { - ntfs_index_ctx_free(icx); - free(icx); + ntfs_index_ctx_free(icx); + free(icx); } /** @@ -180,20 +177,21 @@ void ntfs_index_ctx_put(ntfs_index_context *icx) */ 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, - }; -} + 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)); + return (VCN *) ((u8 *) ie + le16_to_cpu(ie->length) - sizeof(VCN)); } /** @@ -201,28 +199,28 @@ static VCN *ntfs_ie_get_vcn_addr(INDEX_ENTRY *ie) */ VCN ntfs_ie_get_vcn(INDEX_ENTRY *ie) { - return sle64_to_cpup(ntfs_ie_get_vcn_addr(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)); + 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)); + 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); + /* 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; + return ie->ie_flags & INDEX_ENTRY_END || !ie->length; } /** @@ -230,115 +228,116 @@ static int ntfs_ie_end(INDEX_ENTRY *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; + 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; + 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; + 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; + 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; + 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); - } + 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; + 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); + return (ntfs_ih_numof_entries(ih) == 1); } static int ntfs_ih_zero_entry(INDEX_HEADER *ih) { - return (ntfs_ih_numof_entries(ih) == 0); + 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)); + 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); + *ntfs_ie_get_vcn_addr(ie) = cpu_to_le64(vcn); } /** @@ -346,127 +345,126 @@ static void ntfs_ie_set_vcn(INDEX_ENTRY *ie, VCN vcn) */ 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); + 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; + 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; + 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; + 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) +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; + 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)); -err_out: - if (!ir) { - ntfs_attr_put_search_ctx(*ctx); - *ctx = NULL; - } - return ir; + 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; } static INDEX_ROOT *ntfs_ir_lookup2(ntfs_inode *ni, ntfschar *name, u32 len) { - ntfs_attr_search_ctx *ctx; - INDEX_ROOT *ir; + 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; } /** @@ -481,159 +479,164 @@ static INDEX_ROOT *ntfs_ir_lookup2(ntfs_inode *ni, ntfschar *name, u32 len) * @vcn will contain the node index block. * 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) +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_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. - */ - if (!icx->collate) { - ntfs_log_error("Collation function not defined\n"); - errno = EOPNOTSUPP; - return STATUS_ERROR; - } - rc = icx->collate(icx->ni->vol, 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; - } + INDEX_ENTRY *ie; + u8 *index_end; + int rc, item = 0; - ntfs_log_trace("Parent entry number %d\n", item); - icx->parent_pos[icx->pindex] = item; - - return STATUS_KEEP_SEARCHING; + 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. + */ + if (!icx->collate) + { + ntfs_log_error("Collation function not defined\n"); + errno = EOPNOTSUPP; + return STATUS_ERROR; + } + rc = icx->collate(icx->ni->vol, 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; } 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; + 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; + s64 pos, ret; - ntfs_log_trace("vcn: %lld\n", (long long)vcn); - - pos = ntfs_ib_vcn_to_pos(icx, vcn); + ntfs_log_trace("vcn: %lld\n", (long long)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 " + 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; + 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; + 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; + 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 @@ -668,523 +671,509 @@ static int ntfs_icx_parent_dec(ntfs_index_context *icx) */ 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; + 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"); - - if (!key || key_len <= 0) { - errno = EINVAL; - ntfs_log_perror("key: %p key_len: %d", key, key_len); - return -1; - } + ntfs_log_trace("Entering\n"); - 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 (!key || key_len <= 0) + { + errno = EINVAL; + ntfs_log_perror("key: %p key_len: %d", key, key_len); + return -1; + } - 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; - /* get the appropriate collation function */ - icx->collate = ntfs_get_collate_function(ir->collation_rule); - if (!icx->collate) { - err = errno = EOPNOTSUPP; - ntfs_log_perror("Unknown collation rule 0x%x", - (unsigned)le32_to_cpu(ir->collation_rule)); - 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: + ir = ntfs_ir_lookup(ni, icx->name, icx->name_len, &icx->actx); + if (!ir) + { + if (errno == ENOENT) errno = EIO; + return -1; + } - icx->parent_vcn[icx->pindex] = old_vcn; - if (ntfs_icx_parent_inc(icx)) { - err = errno; - goto err_out; - } - old_vcn = vcn; + 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; + } - 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 (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; + /* get the appropriate collation function */ + icx->collate = ntfs_get_collate_function(ir->collation_rule); + if (!icx->collate) + { + err = errno = EOPNOTSUPP; + ntfs_log_perror("Unknown collation rule 0x%x", + (unsigned)le32_to_cpu(ir->collation_rule)); + goto err_out; + } - 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; -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; + 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; + + 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 ((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; + 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; } -static INDEX_BLOCK *ntfs_ib_alloc(VCN ib_vcn, u32 ib_size, - INDEX_HEADER_FLAGS node_type) +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; -} + 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; +} /** * 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; + 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; + 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); + return ntfs_ib_pos_to_vcn(icx, pos * icx->block_size); } static int ntfs_ibm_add(ntfs_index_context *icx) { - u8 bmp[8]; + 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; + 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); - - 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; - } + ntfs_log_trace("%s vcn: %lld\n", set ? "set" : "clear", (long long)vcn); - 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; - } + 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) - 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 (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; + } + } + } - ret = STATUS_OK; -err_na: - ntfs_attr_close(na); - return ret; + 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; + err_na: ntfs_attr_close(na); + return ret; } - static int ntfs_ibm_set(ntfs_index_context *icx, VCN vcn) { - return ntfs_ibm_modify(icx, vcn, 1); + 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); + 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; + u8 *bm; + int bit; + s64 vcn, byte, size; - 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); + ntfs_log_trace("Entering\n"); - if (ntfs_ibm_set(icx, vcn)) - vcn = (VCN)-1; - - free(bm); - return 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; } 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; + 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; - } + 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) +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; - - 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); + u8 *ies_end; + INDEX_ENTRY *ie_head; /* first entry after the median */ + int tail_size, ret; + INDEX_BLOCK *dst; - free(dst); - return ret; + 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; } -static int ntfs_ib_cut_tail(ntfs_index_context *icx, INDEX_BLOCK *ib, - INDEX_ENTRY *ie) +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; - - 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; + 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; + if (ntfs_ibm_add(icx)) return -1; - return 0; + 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_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; -err_out: - free(ib); - ntfs_attr_put_search_ctx(ctx); -out: - return ret; -clear_bmp: - ntfs_ibm_clear(icx, new_ib_vcn); - goto err_out; + 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); + out: return ret; + clear_bmp: ntfs_ibm_clear(icx, new_ib_vcn); + goto err_out; } /** @@ -1193,37 +1182,38 @@ clear_bmp: * 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; +{ + 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 * @@ -1231,22 +1221,23 @@ static int ntfs_ir_truncate(ntfs_index_context *icx, int data_size) * On error return STATUS_ERROR. */ static int ntfs_ir_make_space(ntfs_index_context *icx, int data_size) -{ - int ret; +{ + 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_reparent(icx); - if (ret == STATUS_OK) - ret = STATUS_KEEP_SEARCHING; - else - ntfs_log_perror("Failed to nodify INDEX_ROOT"); - } + ret = ntfs_ir_truncate(icx, data_size); + if (ret == STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT) + { - return ret; + ret = ntfs_ir_reparent(icx); + if (ret == STATUS_OK) + ret = STATUS_KEEP_SEARCHING; + else + ntfs_log_perror("Failed to nodify INDEX_ROOT"); + } + + return ret; } /* @@ -1254,87 +1245,73 @@ static int ntfs_ir_make_space(ntfs_index_context *icx, int data_size) */ 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; + INDEX_ENTRY *p, *old = *ie; - return STATUS_OK; + 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; } -static int ntfs_ih_insert(INDEX_HEADER *ih, INDEX_ENTRY *orig_ie, VCN new_vcn, - int pos) +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; + INDEX_ENTRY *ie_node, *ie; + int ret = STATUS_ERROR; + VCN old_vcn; - 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; + 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; } static VCN ntfs_icx_parent_vcn(ntfs_index_context *icx) { - return icx->parent_vcn[icx->pindex]; + return icx->parent_vcn[icx->pindex]; } static VCN ntfs_icx_parent_pos(ntfs_index_context *icx) { - return icx->parent_pos[icx->pindex]; + return icx->parent_pos[icx->pindex]; } - -static int ntfs_ir_insert_median(ntfs_index_context *icx, INDEX_ENTRY *median, - VCN new_vcn) +static int ntfs_ir_insert_median(ntfs_index_context *icx, INDEX_ENTRY *median, 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; + u32 new_size; + int ret; - 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); + ntfs_log_trace("Entering\n"); - 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; + 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)); + 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)); } static int ntfs_ib_split(ntfs_index_context *icx, INDEX_BLOCK *ib); @@ -1344,43 +1321,38 @@ static int ntfs_ib_split(ntfs_index_context *icx, INDEX_BLOCK *ib); * 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; +{ + INDEX_BLOCK *ib; + u32 idx_size, allocated_size; + int err = STATUS_ERROR; + VCN old_vcn; - 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; + ntfs_log_trace("Entering\n"); - 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; + 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; } /** @@ -1390,102 +1362,103 @@ err_out: * 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; +{ + 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; - + 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; -err_out: - ntfs_log_trace("%s\n", ret ? "Failed" : "Done"); - return ret; + + 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; } /** @@ -1498,70 +1471,62 @@ err_out: */ 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; + INDEX_ENTRY *ie; + ntfs_index_context *icx; + int fn_size, ie_size, err, ret = -1; - 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; + ntfs_log_trace("Entering\n"); - 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; + 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; + out: free(ie); + return ret; } -static int ntfs_ih_takeout(ntfs_index_context *icx, INDEX_HEADER *ih, - INDEX_ENTRY *ie, INDEX_BLOCK *ib) +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; - - ntfs_log_trace("Entering\n"); - - ie_roam = ntfs_ie_dup_novcn(ie); - if (!ie_roam) - return STATUS_ERROR; + INDEX_ENTRY *ie_roam; + int ret = STATUS_ERROR; - ntfs_ie_delete(ih, ie); + ntfs_log_trace("Entering\n"); - 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); + ie_roam = ntfs_ie_dup_novcn(ie); + if (!ie_roam) return STATUS_ERROR; - ret = ntfs_ie_add(icx, ie_roam); -out: - free(ie_roam); - return ret; + 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); + out: free(ie_roam); + return ret; } /** @@ -1570,200 +1535,187 @@ out: */ 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)); + 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 * 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) +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_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; - - ntfs_log_trace("pindex: %d\n", icx->pindex); - - if (ntfs_icx_parent_dec(icx)) - return STATUS_ERROR; + INDEX_BLOCK *ib = NULL; + INDEX_HEADER *parent_ih; + INDEX_ENTRY *ie; + int ret = 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; -out: - free(ib); - return ret; + 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; + out: 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; + 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"); - - if (!icx->ia_na) { - icx->ia_na = ntfs_ia_open(icx, icx->ni); - if (!icx->ia_na) - return STATUS_ERROR; - } + ntfs_log_trace("Entering\n"); - 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; - - ie_succ = ntfs_ie_get_first(&ib->index); + if (!icx->ia_na) + { + icx->ia_na = ntfs_ia_open(icx, icx->ni); + if (!icx->ia_na) return STATUS_ERROR; + } - if (ntfs_icx_parent_inc(icx)) - goto out; - - icx->parent_vcn[icx->pindex] = vcn; - icx->parent_pos[icx->pindex] = 0; + ib = ntfs_malloc(icx->block_size); + if (!ib) return STATUS_ERROR; - if ((ib->index.ih_flags & NODE_MASK) == INDEX_NODE) - goto descend; + 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; - if (ntfs_ih_zero_entry(&ib->index)) { - errno = EIO; - ntfs_log_perror("Empty index block"); - goto out; - } + ie_succ = ntfs_ie_get_first(&ib->index); - ie = ntfs_ie_dup(ie_succ); - if (!ie) - goto out; - - if (ntfs_ie_add_vcn(&ie)) - goto out2; + if (ntfs_icx_parent_inc(icx)) goto out; - ntfs_ie_set_vcn(ie, ntfs_ie_get_vcn(icx->entry)); + icx->parent_vcn[icx->pindex] = vcn; + icx->parent_pos[icx->pindex] = 0; - if (icx->is_in_root) - ih = &icx->ir->index; - else - ih = &icx->ib->index; + if ((ib->index.ih_flags & NODE_MASK) == INDEX_NODE) goto descend; - 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; - } - } + if (ntfs_ih_zero_entry(&ib->index)) + { + errno = EIO; + ntfs_log_perror("Empty index block"); + goto out; + } - 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; + ie = ntfs_ie_dup(ie_succ); + if (!ie) goto out; - ret = STATUS_OK; -out2: - free(ie); -out: - free(ib); - return ret; + if (ntfs_ie_add_vcn(&ie)) goto out2; + + ntfs_ie_set_vcn(ie, ntfs_ie_get_vcn(icx->entry)); + + 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; + out2: free(ie); + out: free(ib); + return ret; } /** @@ -1779,87 +1731,82 @@ out: /*static JPA*/ int ntfs_index_rm(ntfs_index_context *icx) { - INDEX_HEADER *ih; - int err, ret = STATUS_OK; + INDEX_HEADER *ih; + int err, ret = STATUS_OK; - 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); + ntfs_log_trace("Entering\n"); - } 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; -err_out: - ret = STATUS_ERROR; - goto out; + 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; + } + out: return ret; + err_out: ret = STATUS_ERROR; + goto out; } -int ntfs_index_remove(ntfs_inode *dir_ni, ntfs_inode *ni, - const void *key, const int keylen) +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; + 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) { - - if (ntfs_index_lookup(key, keylen, icx)) - goto err_out; + while (1) + { - if ((((FILE_NAME_ATTR *)icx->data)->file_attributes & - FILE_ATTR_REPARSE_POINT) - && !ntfs_possible_symlink(ni)) { - errno = EOPNOTSUPP; - goto err_out; - } + if (ntfs_index_lookup(key, keylen, icx)) 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); - } + if ((((FILE_NAME_ATTR *) icx->data)->file_attributes & FILE_ATTR_REPARSE_POINT) && !ntfs_possible_symlink(ni)) + { + errno = EOPNOTSUPP; + goto err_out; + } - 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 = 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; + err_out: ret = STATUS_ERROR; + ntfs_log_perror("Delete failed"); + goto out; } /** @@ -1876,65 +1823,64 @@ err_out: */ INDEX_ROOT *ntfs_index_root_get(ntfs_inode *ni, ATTR_RECORD *attr) { - ntfs_attr_search_ctx *ctx; - ntfschar *name; - INDEX_ROOT *root = NULL; + 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; } - /* * Walk down the index tree (leaf bound) * until there are no subnode in the first index entry * returns the entry at the bottom left in subnode */ -static INDEX_ENTRY *ntfs_index_walk_down(INDEX_ENTRY *ie, - ntfs_index_context *ictx) +static INDEX_ENTRY *ntfs_index_walk_down(INDEX_ENTRY *ie, ntfs_index_context *ictx) { - INDEX_ENTRY *entry; - s64 vcn; + 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); } /* @@ -1943,51 +1889,47 @@ static INDEX_ENTRY *ntfs_index_walk_down(INDEX_ENTRY *ie, * returns the parent entry or NULL if no more parent */ -static INDEX_ENTRY *ntfs_index_walk_up(INDEX_ENTRY *ie, - ntfs_index_context *ictx) +static INDEX_ENTRY *ntfs_index_walk_up(INDEX_ENTRY *ie, ntfs_index_context *ictx) { - INDEX_ENTRY *entry; - s64 vcn; + 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); } /* @@ -2019,45 +1961,48 @@ 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 *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 c0e76180..2a71193b 100644 --- a/source/libntfs/index.h +++ b/source/libntfs/index.h @@ -63,8 +63,7 @@ #define MAX_PARENT_VCN 32 -typedef int (*COLLATE)(ntfs_volume *vol, const void *data1, int len1, - const void *data2, int len2); +typedef int (*COLLATE)(ntfs_volume *vol, const void *data1, int len1, const void *data2, int len2); /** * struct ntfs_index_context - @@ -112,42 +111,38 @@ typedef int (*COLLATE)(ntfs_volume *vol, const void *data1, int len1, * the call to ntfs_index_ctx_put() to ensure that the changes are written * to disk. */ -typedef struct { - ntfs_inode *ni; - ntfschar *name; - u32 name_len; - INDEX_ENTRY *entry; - void *data; - u16 data_len; - COLLATE collate; - 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; +typedef struct +{ + ntfs_inode *ni; + ntfschar *name; + u32 name_len; + INDEX_ENTRY *entry; + void *data; + u16 data_len; + COLLATE collate; + 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); +extern ntfs_index_context *ntfs_index_ctx_get(ntfs_inode *ni, 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__; +extern int ntfs_index_lookup(const void *key, const int key_len, ntfs_index_context *ictx) __attribute_warn_unused_result__; -extern INDEX_ENTRY *ntfs_index_next(INDEX_ENTRY *ie, - ntfs_index_context *ictx); +extern INDEX_ENTRY *ntfs_index_next(INDEX_ENTRY *ie, ntfs_index_context *ictx); -extern int ntfs_index_add_filename(ntfs_inode *ni, FILE_NAME_ATTR *fn, - MFT_REF mref); -extern int ntfs_index_remove(ntfs_inode *dir_ni, ntfs_inode *ni, - const void *key, const int keylen); +extern int ntfs_index_add_filename(ntfs_inode *ni, FILE_NAME_ATTR *fn, MFT_REF mref); +extern int ntfs_index_remove(ntfs_inode *dir_ni, ntfs_inode *ni, 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 6f3fa060..25c2e5c3 100644 --- a/source/libntfs/inode.c +++ b/source/libntfs/inode.c @@ -60,9 +60,8 @@ ntfs_inode *ntfs_inode_base(ntfs_inode *ni) { - if (ni->nr_extents == -1) - return ni->base_ni; - return ni; + if (ni->nr_extents == -1) return ni->base_ni; + return ni; } /** @@ -77,9 +76,8 @@ ntfs_inode *ntfs_inode_base(ntfs_inode *ni) */ void ntfs_inode_mark_dirty(ntfs_inode *ni) { - NInoSetDirty(ni); - if (ni->nr_extents == -1) - NInoSetDirty(ni->base_ni); + NInoSetDirty(ni); + if (ni->nr_extents == -1) NInoSetDirty(ni->base_ni); } /** @@ -92,12 +90,11 @@ void ntfs_inode_mark_dirty(ntfs_inode *ni) */ static ntfs_inode *__ntfs_inode_allocate(ntfs_volume *vol) { - ntfs_inode *ni; + 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; } /** @@ -110,7 +107,7 @@ static ntfs_inode *__ntfs_inode_allocate(ntfs_volume *vol) */ ntfs_inode *ntfs_inode_allocate(ntfs_volume *vol) { - return __ntfs_inode_allocate(vol); + return __ntfs_inode_allocate(vol); } /** @@ -123,14 +120,12 @@ ntfs_inode *ntfs_inode_allocate(ntfs_volume *vol) */ 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; + 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; } /** @@ -158,131 +153,129 @@ static void __ntfs_inode_release(ntfs_inode *ni) */ static ntfs_inode *ntfs_inode_real_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; + 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 = std_info->creation_time; - ni->last_data_change_time = std_info->last_data_change_time; - ni->last_mft_change_time = std_info->last_mft_change_time; - ni->last_access_time = 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 = const_cpu_to_le32(0); - ni->security_id = const_cpu_to_le32(0); - } - /* Set attribute list information. */ - olderrno = errno; - if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, AT_UNNAMED, 0, - CASE_SENSITIVE, 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; - } - set_nino_flag(ni,KnownSize); - } - ntfs_attr_put_search_ctx(ctx); -out: - ntfs_log_leave("\n"); - return ni; + 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 = std_info->creation_time; + ni->last_data_change_time = std_info->last_data_change_time; + ni->last_mft_change_time = std_info->last_mft_change_time; + ni->last_access_time = 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 = const_cpu_to_le32(0); + ni->security_id = const_cpu_to_le32(0); + } + /* Set attribute list information. */ + olderrno = errno; + if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, AT_UNNAMED, 0, CASE_SENSITIVE, 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; + } + set_nino_flag(ni,KnownSize); + } + ntfs_attr_put_search_ctx(ctx); + out: + ntfs_log_leave("\n"); + return ni; -put_err_out: - ntfs_attr_put_search_ctx(ctx); -err_out: - __ntfs_inode_release(ni); - ni = NULL; - goto out; + put_err_out: ntfs_attr_put_search_ctx(ctx); + err_out: __ntfs_inode_release(ni); + ni = NULL; + goto out; } /** @@ -312,87 +305,90 @@ err_out: int ntfs_inode_real_close(ntfs_inode *ni) { - int ret = -1; - - if (!ni) - return 0; + int ret = -1; - ntfs_log_enter("Entering for inode %lld\n", (long long)ni->mft_no); + if (!ni) return 0; - /* 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_real_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; + ntfs_log_enter("Entering for inode %lld\n", (long long)ni->mft_no); - /* - * 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); - base_ni->extent_nis = (ntfs_inode**)NULL; - } - /* 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; + /* 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_real_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); + base_ni->extent_nis = (ntfs_inode**) NULL; + } + /* 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; } #if CACHE_NIDATA_SIZE @@ -404,7 +400,7 @@ err: void ntfs_inode_nidata_free(const struct CACHED_GENERIC *cached) { - ntfs_inode_real_close(((const struct CACHED_NIDATA*)cached)->ni); + ntfs_inode_real_close(((const struct CACHED_NIDATA*) cached)->ni); } /* @@ -413,19 +409,16 @@ void ntfs_inode_nidata_free(const struct CACHED_GENERIC *cached) int ntfs_inode_nidata_hash(const struct CACHED_GENERIC *item) { - return (((const struct CACHED_NIDATA*)item)->inum - % (2*CACHE_NIDATA_SIZE)); + return (((const struct CACHED_NIDATA*) item)->inum % (2 * CACHE_NIDATA_SIZE)); } /* * inum comparing for entering/fetching from cache */ -static int idata_cache_compare(const struct CACHED_GENERIC *cached, - const struct CACHED_GENERIC *wanted) +static int idata_cache_compare(const struct CACHED_GENERIC *cached, const struct CACHED_GENERIC *wanted) { - return (((const struct CACHED_NIDATA*)cached)->inum - != ((const struct CACHED_NIDATA*)wanted)->inum); + return (((const struct CACHED_NIDATA*) cached)->inum != ((const struct CACHED_NIDATA*) wanted)->inum); } /* @@ -436,15 +429,14 @@ static int idata_cache_compare(const struct CACHED_GENERIC *cached, void ntfs_inode_invalidate(ntfs_volume *vol, const MFT_REF mref) { - struct CACHED_NIDATA item; - int count; + struct CACHED_NIDATA item; + int count; - item.inum = MREF(mref); - item.ni = (ntfs_inode*)NULL; - item.pathname = (const char*)NULL; - item.varsize = 0; - count = ntfs_invalidate_cache(vol->nidata_cache, - GENERIC(&item),idata_cache_compare,CACHE_FREE); + item.inum = MREF(mref); + item.ni = (ntfs_inode*) NULL; + item.pathname = (const char*) NULL; + item.varsize = 0; + count = ntfs_invalidate_cache(vol->nidata_cache, GENERIC(&item), idata_cache_compare, CACHE_FREE); } #endif @@ -461,30 +453,31 @@ void ntfs_inode_invalidate(ntfs_volume *vol, const MFT_REF mref) ntfs_inode *ntfs_inode_open(ntfs_volume *vol, const MFT_REF mref) { - ntfs_inode *ni; + ntfs_inode *ni; #if CACHE_NIDATA_SIZE - struct CACHED_NIDATA item; - struct CACHED_NIDATA *cached; + struct CACHED_NIDATA item; + struct CACHED_NIDATA *cached; - /* fetch idata from cache */ - item.inum = MREF(mref); - debug_double_inode(item.inum,1); - item.pathname = (const char*)NULL; - item.varsize = 0; - cached = (struct CACHED_NIDATA*)ntfs_fetch_cache(vol->nidata_cache, - GENERIC(&item),idata_cache_compare); - if (cached) { - ni = cached->ni; - /* do not keep open entries in cache */ - ntfs_remove_cache(vol->nidata_cache, - (struct CACHED_GENERIC*)cached,0); - } else { - ni = ntfs_inode_real_open(vol, mref); - } + /* fetch idata from cache */ + item.inum = MREF(mref); + debug_double_inode(item.inum,1); + item.pathname = (const char*) NULL; + item.varsize = 0; + cached = (struct CACHED_NIDATA*) ntfs_fetch_cache(vol->nidata_cache, GENERIC(&item), idata_cache_compare); + if (cached) + { + ni = cached->ni; + /* do not keep open entries in cache */ + ntfs_remove_cache(vol->nidata_cache, (struct CACHED_GENERIC*) cached, 0); + } + else + { + ni = ntfs_inode_real_open(vol, mref); + } #else - ni = ntfs_inode_real_open(vol, mref); + ni = ntfs_inode_real_open(vol, mref); #endif - return (ni); + return (ni); } /* @@ -499,48 +492,50 @@ ntfs_inode *ntfs_inode_open(ntfs_volume *vol, const MFT_REF mref) int ntfs_inode_close(ntfs_inode *ni) { - int res; + int res; #if CACHE_NIDATA_SIZE - BOOL dirty; - struct CACHED_NIDATA item; + BOOL dirty; + struct CACHED_NIDATA item; - if (ni) { - debug_double_inode(ni->mft_no,0); - /* do not cache system files : could lead to double entries */ - if (ni->vol && ni->vol->nidata_cache - && ((ni->mft_no == FILE_root) - || ((ni->mft_no >= FILE_first_user) - && !(ni->mrec->flags & MFT_RECORD_IS_4)))) { - /* If we have dirty metadata, write it out. */ - dirty = NInoDirty(ni) || NInoAttrListDirty(ni); - if (dirty) { - res = ntfs_inode_sync(ni); - /* do a real close if sync failed */ - if (res) - ntfs_inode_real_close(ni); - } else - res = 0; + if (ni) + { + debug_double_inode(ni->mft_no,0); + /* do not cache system files : could lead to double entries */ + if (ni->vol && ni->vol->nidata_cache && ((ni->mft_no == FILE_root) || ((ni->mft_no >= FILE_first_user) + && !(ni->mrec->flags & MFT_RECORD_IS_4)))) + { + /* If we have dirty metadata, write it out. */ + dirty = NInoDirty(ni) || NInoAttrListDirty(ni); + if (dirty) + { + res = ntfs_inode_sync(ni); + /* do a real close if sync failed */ + if (res) ntfs_inode_real_close(ni); + } + else res = 0; - if (!res) { - /* feed idata into cache */ - item.inum = ni->mft_no; - item.ni = ni; - item.pathname = (const char*)NULL; - item.varsize = 0; - debug_cached_inode(ni); - ntfs_enter_cache(ni->vol->nidata_cache, - GENERIC(&item), idata_cache_compare); - } - } else { - /* cache not ready or system file, really close */ - res = ntfs_inode_real_close(ni); - } - } else - res = 0; + if (!res) + { + /* feed idata into cache */ + item.inum = ni->mft_no; + item.ni = ni; + item.pathname = (const char*) NULL; + item.varsize = 0; + debug_cached_inode(ni); + ntfs_enter_cache(ni->vol->nidata_cache, GENERIC(&item), idata_cache_compare); + } + } + else + { + /* cache not ready or system file, really close */ + res = ntfs_inode_real_close(ni); + } + } + else res = 0; #else - res = ntfs_inode_real_close(ni); + res = ntfs_inode_real_close(ni); #endif - return (res); + return (res); } /** @@ -570,74 +565,74 @@ int ntfs_inode_close(ntfs_inode *ni) */ 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; + 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; - } - - 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; + if (!base_ni) + { + errno = EINVAL; + ntfs_log_perror("%s", __FUNCTION__); + return NULL; + } - 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 *); + ntfs_log_enter("Opening extent inode %lld (base mft record %lld).\n", + (unsigned long long)mft_no, + (unsigned long long)base_ni->mft_no); - 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; -err_out: - __ntfs_inode_release(ni); - ni = NULL; - goto out; + /* 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; + out: + ntfs_log_leave("\n"); + return ni; + err_out: __ntfs_inode_release(ni); + ni = NULL; + goto out; } /** @@ -648,45 +643,47 @@ err_out: */ int ntfs_inode_attach_all_extents(ntfs_inode *ni) { - ATTR_LIST_ENTRY *ale; - u64 prev_attached = 0; + 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; } /** @@ -697,50 +694,48 @@ int ntfs_inode_attach_all_extents(ntfs_inode *ni) */ static int ntfs_inode_sync_standard_information(ntfs_inode *ni) { - ntfs_attr_search_ctx *ctx; - STANDARD_INFORMATION *std_info; - u32 lth; - le32 lthle; + 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, TimesSet)) { - std_info->creation_time = ni->creation_time; - std_info->last_data_change_time = ni->last_data_change_time; - std_info->last_mft_change_time = ni->last_mft_change_time; - std_info->last_access_time = 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, TimesSet)) + { + std_info->creation_time = ni->creation_time; + std_info->last_data_change_time = ni->last_data_change_time; + std_info->last_mft_change_time = ni->last_mft_change_time; + std_info->last_access_time = 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; } /** @@ -753,133 +748,130 @@ static int ntfs_inode_sync_standard_information(ntfs_inode *ni) */ static int ntfs_inode_sync_file_name(ntfs_inode *ni, ntfs_inode *dir_ni) { - ntfs_attr_search_ctx *ctx = NULL; - ntfs_index_context *ictx; - ntfs_inode *index_ni; - FILE_NAME_ATTR *fn; - FILE_NAME_ATTR *fnx; - REPARSE_POINT *rpp; - le32 reparse_tag; - int err = 0; + ntfs_attr_search_ctx *ctx = NULL; + ntfs_index_context *ictx; + ntfs_inode *index_ni; + FILE_NAME_ATTR *fn; + FILE_NAME_ATTR *fnx; + REPARSE_POINT *rpp; + le32 reparse_tag; + 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; - } - /* Collect the reparse tag, if any */ - reparse_tag = cpu_to_le32(0); - if (ni->flags & FILE_ATTR_REPARSE_POINT) { - if (!ntfs_attr_lookup(AT_REPARSE_POINT, NULL, - 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) { - rpp = (REPARSE_POINT*)((u8 *)ctx->attr + - le16_to_cpu(ctx->attr->value_offset)); - reparse_tag = rpp->reparse_tag; - } - ntfs_attr_reinit_search_ctx(ctx); - } - /* 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 - if (dir_ni) - index_ni = dir_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) && !dir_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. */ - fnx = (FILE_NAME_ATTR *)ictx->data; - fnx->file_attributes = - (fnx->file_attributes & ~FILE_ATTR_VALID_FLAGS) | - (ni->flags & FILE_ATTR_VALID_FLAGS); - if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) - fnx->data_size = fnx->allocated_size - = const_cpu_to_le64(0); - else { - fnx->allocated_size = cpu_to_sle64(ni->allocated_size); - fnx->data_size = cpu_to_sle64(ni->data_size); - } - /* update or clear the reparse tag in the index */ - fnx->reparse_point_tag = reparse_tag; - if (!test_nino_flag(ni, TimesSet)) { - fnx->creation_time = ni->creation_time; - fnx->last_data_change_time = ni->last_data_change_time; - fnx->last_mft_change_time = ni->last_mft_change_time; - fnx->last_access_time = ni->last_access_time; - } else { - fnx->creation_time = fn->creation_time; - fnx->last_data_change_time = fn->last_data_change_time; - fnx->last_mft_change_time = fn->last_mft_change_time; - fnx->last_access_time = fn->last_access_time; - } - ntfs_index_entry_mark_dirty(ictx); - ntfs_index_ctx_put(ictx); - if ((ni != index_ni) && !dir_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; + ctx = ntfs_attr_get_search_ctx(ni, NULL); + if (!ctx) + { + err = errno; + goto err_out; + } + /* Collect the reparse tag, if any */ + reparse_tag = cpu_to_le32(0); + if (ni->flags & FILE_ATTR_REPARSE_POINT) + { + if (!ntfs_attr_lookup(AT_REPARSE_POINT, NULL, 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) + { + rpp = (REPARSE_POINT*) ((u8 *) ctx->attr + le16_to_cpu(ctx->attr->value_offset)); + reparse_tag = rpp->reparse_tag; + } + ntfs_attr_reinit_search_ctx(ctx); + } + /* 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 if (dir_ni) + index_ni = dir_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) && !dir_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. */ + fnx = (FILE_NAME_ATTR *) ictx->data; + fnx->file_attributes = (fnx->file_attributes & ~FILE_ATTR_VALID_FLAGS) | (ni->flags & FILE_ATTR_VALID_FLAGS); + if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + fnx->data_size = fnx->allocated_size = const_cpu_to_le64(0); + else + { + fnx->allocated_size = cpu_to_sle64(ni->allocated_size); + fnx->data_size = cpu_to_sle64(ni->data_size); + } + /* update or clear the reparse tag in the index */ + fnx->reparse_point_tag = reparse_tag; + if (!test_nino_flag(ni, TimesSet)) + { + fnx->creation_time = ni->creation_time; + fnx->last_data_change_time = ni->last_data_change_time; + fnx->last_mft_change_time = ni->last_mft_change_time; + fnx->last_access_time = ni->last_access_time; + } + else + { + fnx->creation_time = fn->creation_time; + fnx->last_data_change_time = fn->last_data_change_time; + fnx->last_mft_change_time = fn->last_mft_change_time; + fnx->last_access_time = fn->last_access_time; + } + ntfs_index_entry_mark_dirty(ictx); + ntfs_index_ctx_put(ictx); + if ((ni != index_ni) && !dir_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; } /** @@ -903,135 +895,145 @@ err_out: */ static int ntfs_inode_sync_in_dir(ntfs_inode *ni, ntfs_inode *dir_ni) { - int ret = 0; - int err = 0; - if (!ni) { - errno = EINVAL; - ntfs_log_error("Failed to sync NULL inode\n"); - return -1; - } + int ret = 0; + int err = 0; + 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, dir_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, dir_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; + /* 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); - } - } + 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 this is a base inode with extents write all dirty extents, too. */ - if (ni->nr_extents > 0) { - s32 i; + 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); + } - for (i = 0; i < ni->nr_extents; ++i) { - ntfs_inode *eni; + 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); + } + } - 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 this is a base inode with extents write all dirty extents, too. */ + if (ni->nr_extents > 0) + { + s32 i; - if (err) { - errno = err; - ret = -1; - } - - ntfs_log_leave("\n"); - return ret; + for (i = 0; i < ni->nr_extents; ++i) + { + ntfs_inode *eni; + + 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 (err) + { + errno = err; + ret = -1; + } + + ntfs_log_leave("\n"); + return ret; } int ntfs_inode_sync(ntfs_inode *ni) { - return (ntfs_inode_sync_in_dir(ni, (ntfs_inode*)NULL)); + return (ntfs_inode_sync_in_dir(ni, (ntfs_inode*) NULL)); } /* @@ -1040,15 +1042,15 @@ int ntfs_inode_sync(ntfs_inode *ni) int ntfs_inode_close_in_dir(ntfs_inode *ni, ntfs_inode *dir_ni) { - int res; + int res; - res = ntfs_inode_sync_in_dir(ni, dir_ni); - if (res) { - if (errno != EIO) - errno = EBUSY; - } else - res = ntfs_inode_close(ni); - return (res); + res = ntfs_inode_sync_in_dir(ni, dir_ni); + if (res) + { + if (errno != EIO) errno = EBUSY; + } + else res = ntfs_inode_close(ni); + return (res); } /** @@ -1064,180 +1066,184 @@ int ntfs_inode_close_in_dir(ntfs_inode *ni, ntfs_inode *dir_ni) */ 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 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)) { - - 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; - } + /* 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)) + { - /* Set in-memory attribute list. */ - ni->attr_list = al; - ni->attr_list_size = al_len; - NInoSetAttrList(ni); - NInoAttrListSetDirty(ni); + int ale_size; - /* 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; - } - } + if (ctx->attr->type == AT_ATTRIBUTE_LIST) + { + err = EIO; + ntfs_log_perror("Attribute list already present"); + goto put_err_out; + } - /* 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; - } + ale_size = (sizeof(ATTR_LIST_ENTRY) + sizeof(ntfschar) * ctx->attr->name_length + 7) & ~7; + al_len += ale_size; - /* 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; + 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; -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); -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); -put_err_out: - ntfs_attr_put_search_ctx(ctx); -err_out: - free(al); - errno = err; - return -1; + 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; + + 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); + 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); + put_err_out: ntfs_attr_put_search_ctx(ctx); + err_out: free(al); + errno = err; + return -1; } /** @@ -1249,82 +1255,76 @@ err_out: */ int ntfs_inode_free_space(ntfs_inode *ni, int size) { - ntfs_attr_search_ctx *ctx; - int freed; + 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; - } -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; + /* 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; } /** @@ -1337,27 +1337,23 @@ put_err_out: */ void ntfs_inode_update_times(ntfs_inode *ni, ntfs_time_update_flags mask) { - ntfs_time now; + ntfs_time 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 = ntfs_current_time(); - 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; - - NInoFileNameSetDirty(ni); - NInoSetDirty(ni); + now = ntfs_current_time(); + 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; + + NInoFileNameSetDirty(ni); + NInoSetDirty(ni); } /** @@ -1374,34 +1370,32 @@ void ntfs_inode_update_times(ntfs_inode *ni, ntfs_time_update_flags mask) */ int ntfs_inode_badclus_bad(u64 mft_no, ATTR_RECORD *attr) { - int len, ret = 0; - ntfschar *ustr; + int len, ret = 0; + ntfschar *ustr; - if (!attr) { - ntfs_log_error("Invalid argument.\n"); - errno = EINVAL; - return -1; - } - - if (mft_no != FILE_BadClus) - return 0; + if (!attr) + { + ntfs_log_error("Invalid argument.\n"); + errno = EINVAL; + return -1; + } - if (attr->type != AT_DATA) - return 0; + if (mft_no != FILE_BadClus) return 0; - if ((ustr = ntfs_str2ucs("$Bad", &len)) == NULL) { - ntfs_log_perror("Couldn't convert '$Bad' to Unicode"); - return -1; - } + if (attr->type != AT_DATA) return 0; - 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_str2ucs("$Bad", &len)) == NULL) + { + ntfs_log_perror("Couldn't convert '$Bad' to Unicode"); + return -1; + } - ntfs_ucsfree(ustr); + 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; - return ret; + ntfs_ucsfree(ustr); + + return ret; } #ifdef HAVE_SETXATTR /* extended attributes interface required */ @@ -1418,46 +1412,55 @@ int ntfs_inode_badclus_bad(u64 mft_no, ATTR_RECORD *attr) int ntfs_inode_get_times(ntfs_inode *ni, char *value, size_t size) { - ntfs_attr_search_ctx *ctx; - STANDARD_INFORMATION *std_info; - u64 *times; - int ret; + 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); } /* @@ -1475,92 +1478,102 @@ int ntfs_inode_get_times(ntfs_inode *ni, char *value, size_t size) */ int ntfs_inode_set_times(ntfs_inode *ni, const char *value, size_t size, - int flags) + int flags) { - ntfs_attr_search_ctx *ctx; - STANDARD_INFORMATION *std_info; - FILE_NAME_ATTR *fn; - const u64 *times; - ntfs_time now; - int cnt; - int ret; + ntfs_attr_search_ctx *ctx; + STANDARD_INFORMATION *std_info; + FILE_NAME_ATTR *fn; + const u64 *times; + ntfs_time now; + int cnt; + int ret; - ret = -1; - if ((size >= 8) && !(flags & XATTR_CREATE)) { - times = (const u64*)value; - now = ntfs_current_time(); - /* 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)); - /* - * Mark times set to avoid overwriting - * them when the inode is closed. - * The inode structure must also be updated - * (with loss of precision) because of cacheing. - * TODO : use NTFS precision in inode, and - * return sub-second times in getattr() - */ - set_nino_flag(ni, TimesSet); - std_info->creation_time = cpu_to_le64(times[0]); - ni->creation_time - = std_info->creation_time; - if (size >= 16) { - std_info->last_data_change_time = cpu_to_le64(times[1]); - ni->last_data_change_time - = std_info->last_data_change_time; - } - if (size >= 24) { - std_info->last_access_time = cpu_to_le64(times[2]); - ni->last_access_time - = std_info->last_access_time; - } - std_info->last_mft_change_time = now; - ni->last_mft_change_time = now; - ntfs_inode_mark_dirty(ctx->ntfs_ino); - NInoFileNameSetDirty(ni); + ret = -1; + if ((size >= 8) && !(flags & XATTR_CREATE)) + { + times = (const u64*)value; + now = ntfs_current_time(); + /* 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)); + /* + * Mark times set to avoid overwriting + * them when the inode is closed. + * The inode structure must also be updated + * (with loss of precision) because of cacheing. + * TODO : use NTFS precision in inode, and + * return sub-second times in getattr() + */ + set_nino_flag(ni, TimesSet); + std_info->creation_time = cpu_to_le64(times[0]); + ni->creation_time + = std_info->creation_time; + if (size >= 16) + { + std_info->last_data_change_time = cpu_to_le64(times[1]); + ni->last_data_change_time + = std_info->last_data_change_time; + } + if (size >= 24) + { + std_info->last_access_time = cpu_to_le64(times[2]); + ni->last_access_time + = std_info->last_access_time; + } + std_info->last_mft_change_time = now; + ni->last_mft_change_time = now; + ntfs_inode_mark_dirty(ctx->ntfs_ino); + NInoFileNameSetDirty(ni); - /* 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)); - 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)); + 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 5a6f7da6..cb581225 100644 --- a/source/libntfs/inode.h +++ b/source/libntfs/inode.h @@ -40,18 +40,20 @@ typedef struct _ntfs_inode ntfs_inode; * Defined bits for the state field in the ntfs_inode structure. * (f) = files only, (d) = directories only */ -typedef enum { - NI_Dirty, /* 1: Mft record needs to be written to disk. */ +typedef enum +{ + 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 - mft record and then to disk. */ - NI_FileNameDirty, /* 1: FILE_NAME attributes need to be updated - in the index. */ - NI_v3_Extensions, /* 1: JPA v3.x extensions present. */ - NI_TimesSet, /* 1: Use times which were set */ - NI_KnownSize, /* 1: Set if sizes are meaningful */ + /* 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 + in the index. */ + NI_v3_Extensions, /* 1: JPA v3.x extensions present. */ + NI_TimesSet, /* 1: Use times which were set */ + NI_KnownSize, +/* 1: Set if sizes are meaningful */ } ntfs_inode_state_bits; #define test_nino_flag(ni, flag) test_bit(NI_##flag, (ni)->state) @@ -73,7 +75,6 @@ typedef enum { #define NInoSetAttrList(ni) set_nino_flag(ni, AttrList) #define NInoClearAttrList(ni) clear_nino_flag(ni, AttrList) - #define test_nino_al_flag(ni, flag) test_nino_flag(ni, AttrList##flag) #define set_nino_al_flag(ni, flag) set_nino_flag(ni, AttrList##flag) #define clear_nino_al_flag(ni, flag) clear_nino_flag(ni, AttrList##flag) @@ -103,73 +104,74 @@ typedef enum { * It is just used as an extension to the fields already provided in the VFS * 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. - See ntfs_inode_state_bits above. */ - 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 - 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 - 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 - inode of the base mft record. */ - }; +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. + See ntfs_inode_state_bits above. */ + 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 + 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 + 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 + 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). - * For directories, they hold the index size, provided the - * flag KnownSize is set. - */ - s64 data_size; /* Data size of unnamed DATA attribute - (or INDEX_ROOT for directories) */ - 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 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). + * For directories, they hold the index size, provided the + * flag KnownSize is set. + */ + s64 data_size; /* Data size of unnamed DATA attribute + (or INDEX_ROOT for directories) */ + 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. - */ - ntfs_time creation_time; - ntfs_time last_data_change_time; - ntfs_time last_mft_change_time; - ntfs_time 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. + */ + ntfs_time creation_time; + ntfs_time last_data_change_time; + ntfs_time last_mft_change_time; + ntfs_time 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, +typedef enum +{ + 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) @@ -195,9 +197,7 @@ extern int ntfs_inode_nidata_hash(const struct CACHED_GENERIC *item); #endif - -extern ntfs_inode *ntfs_extent_inode_open(ntfs_inode *base_ni, - const MFT_REF mref); +extern ntfs_inode *ntfs_extent_inode_open(ntfs_inode *base_ni, const MFT_REF mref); extern int ntfs_inode_attach_all_extents(ntfs_inode *ni); @@ -215,8 +215,7 @@ extern int ntfs_inode_badclus_bad(u64 mft_no, ATTR_RECORD *a); extern int ntfs_inode_get_times(ntfs_inode *ni, char *value, size_t size); -extern int ntfs_inode_set_times(ntfs_inode *ni, const char *value, - size_t size, int flags); +extern int ntfs_inode_set_times(ntfs_inode *ni, const char *value, size_t size, int flags); /* debugging */ #define debug_double_inode(num, type) diff --git a/source/libntfs/layout.h b/source/libntfs/layout.h index 8670557e..bdb783fd 100644 --- a/source/libntfs/layout.h +++ b/source/libntfs/layout.h @@ -46,53 +46,62 @@ /** * 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 - relative to the disk in sectors. - Required to boot Windows. */ -/*0x15*/u32 large_sectors; /* zero */ -/* sizeof() = 25 (0x19) bytes */ -} __attribute__((__packed__)) BIOS_PARAMETER_BLOCK; +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 + relative to the disk in sectors. + Required to boot Windows. */ + /*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 - 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 - 0xaa55 in little endian. */ -/* sizeof() = 512 (0x200) bytes */ -} __attribute__((__packed__)) NTFS_BOOT_SECTOR; +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 + 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 + 0xaa55 in little endian. */ + /* sizeof() = 512 (0x200) bytes */ +}__attribute__((__packed__)) NTFS_BOOT_SECTOR; /** * enum NTFS_RECORD_TYPES - @@ -100,31 +109,33 @@ typedef struct { * Magic identifiers present at the beginning of all ntfs record containing * 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+?) */ +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 $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 - transfer was detected. */ + /* 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 - to be initialized before - it can be used. */ + /* + * 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; /* @@ -160,7 +171,6 @@ typedef enum { #define ntfs_is_empty_record(x) ( ntfs_is_magic (x, empty) ) #define ntfs_is_empty_recordp(p) ( ntfs_is_magicp(p, empty) ) - #define NTFS_BLOCK_SIZE 512 #define NTFS_BLOCK_SIZE_BITS 9 @@ -182,16 +192,17 @@ typedef enum { * This formula can be used as a consistency check in that usa_ofs + * (usa_count * 2) has to be less than or equal to 510. */ -typedef struct { - 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) - from the start of the ntfs record. */ - 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. */ -} __attribute__((__packed__)) NTFS_RECORD; +typedef struct +{ + 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) + from the start of the ntfs record. */ + 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. */ +}__attribute__((__packed__)) NTFS_RECORD; /** * enum NTFS_SYSTEM_FILES - System files mft record numbers. @@ -201,43 +212,42 @@ typedef struct { * mft records. Also, the sequence number for each of the system files is * always equal to their mft record number and it is never modified. */ -typedef enum { - 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 - 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 - 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 - attribute. */ - 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 - attribute. */ - FILE_BadClus = 8, /* Contains all bad clusters in the non-resident - 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 - characters in data attribute. */ - 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 - whether to allow opening a file or not. */ +typedef enum +{ + 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 + 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 + 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 + attribute. */ + 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 + attribute. */ + FILE_BadClus = 8, /* Contains all bad clusters in the non-resident + 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 + characters in data attribute. */ + 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 + whether to allow opening a file or not. */ } NTFS_SYSTEM_FILES; /** @@ -254,14 +264,16 @@ typedef enum { * index, that means an INDEX_ROOT and an INDEX_ALLOCATION with a name other * 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 - 16-bit. */ -} __attribute__((__packed__)) MFT_RECORD_FLAGS; +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 + 16-bit. */ +}__attribute__((__packed__)) MFT_RECORD_FLAGS; /* * mft references (aka file references or file record segment references) are @@ -335,145 +347,167 @@ typedef u64 MFT_REF; * in that it only consists of the attribute type code AT_END and none of the * 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. */ +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. */ -/* 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 - 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 - directory entries referencing this record. - NOTE: Only used in mft base records. - NOTE: When deleting a directory entry we - check the link_count and if it is 1 we - delete the file. Otherwise we delete the - FILE_NAME_ATTR being referenced by the - 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 - 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 - 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. - NOTE: Must be aligned to 8-byte boundary. */ -/* 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. - 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 - locate the attribute list attribute present - in the base record which describes this - extension record and hence might need - modification when the extension record - itself is modified, also locating the - 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 - 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. - */ -} __attribute__((__packed__)) MFT_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 + 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 + directory entries referencing this record. + NOTE: Only used in mft base records. + NOTE: When deleting a directory entry we + check the link_count and if it is 1 we + delete the file. Otherwise we delete the + FILE_NAME_ATTR being referenced by the + 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 + 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 + 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. + NOTE: Must be aligned to 8-byte boundary. */ + /* 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. + 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 + locate the attribute list attribute present + in the base record which describes this + extension record and hence might need + modification when the extension record + itself is modified, also locating the + 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 + 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. + */ +}__attribute__((__packed__)) MFT_RECORD; /** * struct MFT_RECORD_OLD - An MFT record layout (NTFS <=3.0) * * 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. */ +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. */ -/* 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 - 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 - directory entries referencing this record. - NOTE: Only used in mft base records. - NOTE: When deleting a directory entry we - check the link_count and if it is 1 we - delete the file. Otherwise we delete the - FILE_NAME_ATTR being referenced by the - 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 - 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 - 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. - NOTE: Must be aligned to 8-byte boundary. */ -/* 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. - 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 - locate the attribute list attribute present - in the base record which describes this - extension record and hence might need - modification when the extension record - itself is modified, also locating the - 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 - 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. - */ -} __attribute__((__packed__)) MFT_RECORD_OLD; + /* 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 + 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 + directory entries referencing this record. + NOTE: Only used in mft base records. + NOTE: When deleting a directory entry we + check the link_count and if it is 1 we + delete the file. Otherwise we delete the + FILE_NAME_ATTR being referenced by the + 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 + 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 + 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. + NOTE: Must be aligned to 8-byte boundary. */ + /* 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. + 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 + locate the attribute list attribute present + in the base record which describes this + extension record and hence might need + modification when the extension record + itself is modified, also locating the + 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 + 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. + */ +}__attribute__((__packed__)) MFT_RECORD_OLD; /** * enum ATTR_TYPES - System defined attributes (32-bit). @@ -486,26 +520,27 @@ typedef struct { * 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), +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), } ATTR_TYPES; /** @@ -545,22 +580,23 @@ typedef enum { * the 2nd object_id. If the first u32 values of both object_ids were * equal then the second u32 values would be compared, etc. */ -typedef enum { - 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 - as Unicode strings. */ - 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), +typedef enum +{ + 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 + as Unicode strings. */ + 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_RULES; /** @@ -573,31 +609,33 @@ typedef enum { * name attribute has this flag set and this is the only attribute indexed in * NT4. */ -typedef enum { - ATTR_DEF_INDEXABLE = const_cpu_to_le32(0x02), /* Attribute can be - indexed. */ - 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 - must contain at least one non-zero - byte. */ - 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 - 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 - resident. */ - 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 - modifications if the attribute is - resident. */ +typedef enum +{ + ATTR_DEF_INDEXABLE = const_cpu_to_le32(0x02), /* Attribute can be + indexed. */ + 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 + must contain at least one non-zero + byte. */ + 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 + 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 + resident. */ + 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 + modifications if the attribute is + resident. */ } ATTR_DEF_FLAGS; /** @@ -611,31 +649,38 @@ typedef enum { * attribute can be resident/non-resident and possibly other things, but the * actual bits are unknown. */ -typedef struct { -/*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. - 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 */ -} __attribute__((__packed__)) ATTR_DEF; +typedef struct +{ + /*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. + 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 */ +}__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 - method mask. Also, first - illegal value. */ - ATTR_IS_ENCRYPTED = const_cpu_to_le16(0x4000), - ATTR_IS_SPARSE = const_cpu_to_le16(0x8000), -} __attribute__((__packed__)) ATTR_FLAGS; +typedef enum +{ + 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), +}__attribute__((__packed__)) ATTR_FLAGS; /* * Attribute compression. @@ -707,186 +752,217 @@ 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 - (has implications for deleting and - modifying the attribute). */ -} __attribute__((__packed__)) RESIDENT_ATTR_FLAGS; +typedef enum +{ + RESIDENT_ATTR_IS_INDEXED = 0x01, +/* Attribute is referenced in an index + (has implications for deleting and + modifying the attribute). */ +}__attribute__((__packed__)) RESIDENT_ATTR_FLAGS; /** * struct ATTR_RECORD - Attribute record header. * * 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 - attribute (aligned to 8-byte boundary). - Used to get to the next attribute. */ -/* 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. - 0 if unnamed. */ -/* 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 - just at the end of the record header. Then, - follow with attribute value or mapping pairs - 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 - 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 - 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 - boundary. */ -/* 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 - 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 - 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 - 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 - 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 - 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 - compression block size (2^compression_unit) and - 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 - value. Can be larger than allocated_size if - attribute value is compressed or sparse. */ -/* 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, - non_resident_end) to get - size of a non resident - 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__)); -} __attribute__((__packed__)) ATTR_RECORD; +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 + attribute (aligned to 8-byte boundary). + Used to get to the next attribute. */ + /* 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. + 0 if unnamed. */ + /* 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 + just at the end of the record header. Then, + follow with attribute value or mapping pairs + 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 + 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 + 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 + boundary. */ + /* 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 + 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 + 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 + 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 + 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 + 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 + compression block size (2^compression_unit) and + 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 + value. Can be larger than allocated_size if + attribute value is compressed or sparse. */ + /* 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, + non_resident_end) to get + size of a non resident + 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__)); +}__attribute__((__packed__)) ATTR_RECORD; 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), */ +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), */ - 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), -} __attribute__((__packed__)) FILE_ATTR_FLAGS; + /** + * 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; /* * NOTE on times in NTFS: All times are in MS standard time format, i.e. they @@ -905,87 +981,107 @@ typedef enum { * correct by practical experimentation on Windows NT4 SP6a and is hence * assumed to be the one and only correct interpretation. */ -typedef struct { -/*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 - modified. */ -/* 16*/ s64 last_mft_change_time; /* Time this mft record was last - modified. */ -/* 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 - accessed if some time delta has - 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 - 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 - file. Zero if version numbering is disabled. */ - /* 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 - class id index (?). */ - /* 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. - 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 - the quota for all streams of the file. Note: Is - zero if quotas are disabled. */ - /* 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. - NOTE: To disable the journal need to delete - the journal file itself and to then walk the - whole mft and set all Usn entries in all mft - records to zero! (This can take a while!) - The journal is FILE_Extend/$UsnJrnl. Win2k - will recreate the journal and initiate - logging if necessary when mounting the - 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) */ -} __attribute__((__packed__)) STANDARD_INFORMATION; +typedef struct +{ + /*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 + modified. */ + /* 16*/ + s64 last_mft_change_time; /* Time this mft record was last + modified. */ + /* 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 + accessed if some time delta has + 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 + 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 + file. Zero if version numbering is disabled. */ + /* 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 + class id index (?). */ + /* 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. + 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 + the quota for all streams of the file. Note: Is + zero if quotas are disabled. */ + /* 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. + NOTE: To disable the journal need to delete + the journal file itself and to then walk the + whole mft and set all Usn entries in all mft + records to zero! (This can take a while!) + The journal is FILE_Extend/$UsnJrnl. Win2k + will recreate the journal and initiate + logging if necessary when mounting the + 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) */ +}__attribute__((__packed__)) STANDARD_INFORMATION; /** * struct ATTR_LIST_ENTRY - Attribute: Attribute list (0x20). @@ -1016,37 +1112,46 @@ typedef struct { * NTFS 3.0 volumes). * - 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 - attribute or 0 if unnamed. */ -/* 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 - 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 - several mft records are allocated to hold - this attribute. In the latter case, each mft - record holds one extent of the attribute and - there is one attribute list entry for each - extent. NOTE: This is DEFINITELY a signed - 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 - the ATTR_RECORD for this portion of the - attribute value. */ -/* 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 - name_offset to determine the location of the - name. */ -/* sizeof() = 26 + (attribute_name_length * 2) bytes */ -} __attribute__((__packed__)) ATTR_LIST_ENTRY; +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 + attribute or 0 if unnamed. */ + /* 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 + 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 + several mft records are allocated to hold + this attribute. In the latter case, each mft + record holds one extent of the attribute and + there is one attribute list entry for each + extent. NOTE: This is DEFINITELY a signed + 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 + the ATTR_RECORD for this portion of the + attribute value. */ + /* 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 + name_offset to determine the location of the + name. */ + /* sizeof() = 26 + (attribute_name_length * 2) bytes */ +}__attribute__((__packed__)) ATTR_LIST_ENTRY; /* * The maximum allowed length for a file name. @@ -1057,28 +1162,29 @@ typedef struct { * enum FILE_NAME_TYPE_FLAGS - Possible namespaces for filenames in ntfs. * (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. */ -} __attribute__((__packed__)) FILE_NAME_TYPE_FLAGS; +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. */ +}__attribute__((__packed__)) FILE_NAME_TYPE_FLAGS; /** * struct FILE_NAME_ATTR - Attribute: Filename (0x30). @@ -1093,46 +1199,65 @@ typedef enum { * correct by practical experimentation on Windows NT4 SP6a and is hence * assumed to be the one and only correct interpretation. */ -typedef struct { -/*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 - modified. */ -/* 18*/ s64 last_mft_change_time; /* Time this mft record was last - modified. */ -/* 20*/ s64 last_access_time; /* Last time this mft record was - accessed. */ -/* 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 - $DATA attribute and for compressed - and/or sparse $DATA, this is the - 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 - 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 - 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, - present only in reparse - points and only if there are - no EAs. */ - } __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. */ -} __attribute__((__packed__)) FILE_NAME_ATTR; +typedef struct +{ + /*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 + modified. */ + /* 18*/ + s64 last_mft_change_time; /* Time this mft record was last + modified. */ + /* 20*/ + s64 last_access_time; /* Last time this mft record was + accessed. */ + /* 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 + $DATA attribute and for compressed + and/or sparse $DATA, this is the + 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 + 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 + 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, + present only in reparse + points and only if there are + no EAs. */ + }__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. */ +}__attribute__((__packed__)) FILE_NAME_ATTR; /** * struct GUID - GUID structures store globally unique identifiers (GUID). @@ -1146,14 +1271,15 @@ typedef struct { * Example of a GUID: * 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 - hexadecimal digits. The remaining six bytes are the - final 12 hexadecimal digits. */ -} __attribute__((__packed__)) GUID; +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 + hexadecimal digits. The remaining six bytes are the + final 12 hexadecimal digits. */ +}__attribute__((__packed__)) GUID; /** * struct OBJ_ID_INDEX_DATA - FILE_Extend/$ObjId contains an index named $O. @@ -1168,45 +1294,51 @@ typedef struct { * equals the object_id. Optional (i.e. can be zero). * domain_id - Reserved (always zero). */ -typedef struct { - 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__)); -} __attribute__((__packed__)) OBJ_ID_INDEX_DATA; +typedef struct +{ + 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__)); +}__attribute__((__packed__)) OBJ_ID_INDEX_DATA; /** * struct OBJECT_ID_ATTR - Attribute: Object id (NTFS 3.0+) (0x40). * * NOTE: Always resident. */ -typedef struct { - 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 file was first created.*/ - 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__)); -} __attribute__((__packed__)) OBJECT_ID_ATTR; +typedef struct +{ + 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 file was first created.*/ + 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__)); +}__attribute__((__packed__)) OBJECT_ID_ATTR; #if 0 /** @@ -1215,14 +1347,21 @@ typedef struct { * The pre-defined IDENTIFIER_AUTHORITIES used as SID_IDENTIFIER_AUTHORITY in * 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; +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; #endif /** @@ -1237,74 +1376,75 @@ typedef enum { /* SID string prefix. */ * made up of the identifier authority SECURITY_CREATOR_SID_AUTHORITY (3) and * 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 */ +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_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; /* @@ -1349,13 +1489,15 @@ 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. */ -} __attribute__((__packed__)) SID_IDENTIFIER_AUTHORITY; +typedef union +{ + 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; /** * struct SID - @@ -1385,50 +1527,54 @@ typedef union { * sub_authority[0] = 32, // SECURITY_BUILTIN_DOMAIN_RID * 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. */ -} __attribute__((__packed__)) SID; +typedef struct +{ + 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 - a future revision. */ +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 + a future revision. */ } SID_CONSTANTS; /** * 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, +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_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, -} __attribute__((__packed__)) ACE_TYPES; + /* This one is for WinNT&2k. */ + ACCESS_MAX_MS_ACE_TYPE = 8, +}__attribute__((__packed__)) ACE_TYPES; /** * enum ACE_FLAGS - The ACE flags (8-bit) for audit and inheritance. @@ -1440,19 +1586,20 @@ typedef enum { * FAILED_ACCESS_ACE_FLAG is only used with system audit and alarm ACE types * 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, +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 audit flags. */ - SUCCESSFUL_ACCESS_ACE_FLAG = 0x40, - FAILED_ACCESS_ACE_FLAG = 0x80, -} __attribute__((__packed__)) ACE_FLAGS; + /* The audit flags. */ + SUCCESSFUL_ACCESS_ACE_FLAG = 0x40, + FAILED_ACCESS_ACE_FLAG = 0x80, +}__attribute__((__packed__)) ACE_FLAGS; /** * struct ACE_HEADER - @@ -1467,145 +1614,147 @@ typedef enum { * which specifies the type and size of the ACE. The format of the subsequent * 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. */ -} __attribute__((__packed__)) ACE_HEADER; +typedef struct +{ + 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; /** * enum ACCESS_MASK - The access mask (32-bit). * * 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. - */ +typedef enum +{ + /* + * 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; /** @@ -1616,12 +1765,13 @@ 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; -} __attribute__((__packed__)) GENERIC_MAPPING; +typedef struct +{ + ACCESS_MASK generic_read; + ACCESS_MASK generic_write; + ACCESS_MASK generic_execute; + ACCESS_MASK generic_all; +}__attribute__((__packed__)) GENERIC_MAPPING; /* * The predefined ACE type structures are as defined below. @@ -1632,43 +1782,49 @@ 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. */ +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. */ -/* 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; + /* 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; /** * 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), +typedef enum +{ + 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. */ +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. */ -/* 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; + /* 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; /** * struct ACL - An ACL is an access-control list (ACL). @@ -1678,31 +1834,33 @@ typedef struct { * zero or more access control entries (ACEs). The ACL as well as each 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 - header, the ACEs and the remaining free space. */ - u16 ace_count; /* Number of ACEs in the ACL. */ - u16 alignment2; -/* sizeof() = 8 bytes */ -} __attribute__((__packed__)) ACL; +typedef struct +{ + 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 */ +}__attribute__((__packed__)) ACL; /** * enum ACL_CONSTANTS - Current constants for ACLs. */ -typedef enum { - /* Current revision. */ - ACL_REVISION = 2, - ACL_REVISION_DS = 4, +typedef enum +{ + /* 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; /** @@ -1754,22 +1912,23 @@ typedef enum { * and all pointer fields are expressed as offsets from the * 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), -} __attribute__((__packed__)) SECURITY_DESCRIPTOR_CONTROL; +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), +}__attribute__((__packed__)) SECURITY_DESCRIPTOR_CONTROL; /** * struct SECURITY_DESCRIPTOR_RELATIVE - @@ -1777,27 +1936,28 @@ typedef enum { * Self-relative security descriptor. Contains the owner and group SIDs as well * 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 - the descriptor as well as the following fields. */ - 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 - 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 - 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 - 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 */ -} __attribute__((__packed__)) SECURITY_DESCRIPTOR_RELATIVE; +typedef struct +{ + 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 + owner. If this is NULL, no owner SID is present in + the descriptor. */ + 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 + 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 + 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 */ +}__attribute__((__packed__)) SECURITY_DESCRIPTOR_RELATIVE; /** * struct SECURITY_DESCRIPTOR - Absolute security descriptor. @@ -1809,40 +1969,41 @@ 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 - the descriptor as well as the following fields. */ - 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 - group. If this is NULL, no primary group SID is - present in the descriptor. */ - 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 - 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. */ -} __attribute__((__packed__)) SECURITY_DESCRIPTOR; +typedef struct +{ + 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 + this is NULL, no owner SID is present in the + descriptor. */ + 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 + 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 + 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. */ +}__attribute__((__packed__)) SECURITY_DESCRIPTOR; /** * enum SECURITY_DESCRIPTOR_CONSTANTS - * * Current constants for security descriptors. */ -typedef enum { - /* Current revision. */ - SECURITY_DESCRIPTOR_REVISION = 1, - SECURITY_DESCRIPTOR_REVISION1 = 1, +typedef enum +{ + /* 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; /* @@ -1902,24 +2063,26 @@ typedef SECURITY_DESCRIPTOR_RELATIVE SECURITY_DESCRIPTOR_ATTR; * This header precedes each security descriptor in the $SDS data stream. * 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. */ -} __attribute__((__packed__)) SECURITY_DESCRIPTOR_HEADER; +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. */ +}__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 - isn't counted in INDEX_ENTRY's data_length. */ -} __attribute__((__packed__)) 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 + isn't counted in INDEX_ENTRY's data_length. */ +}__attribute__((__packed__)) SDH_INDEX_DATA; /** * struct SII_INDEX_DATA - @@ -1939,25 +2102,28 @@ typedef SECURITY_DESCRIPTOR_HEADER SII_INDEX_DATA; * the first copy of the security descriptor will be at offset 0x51d0 in the * $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 - descriptor. */ -} __attribute__((__packed__)) SDS_ENTRY; +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 + descriptor. */ +}__attribute__((__packed__)) SDS_ENTRY; /** * struct SII_INDEX_KEY - The index entry key used in the $SII index. * * The collation type is COLLATION_NTOFS_ULONG. */ -typedef struct { - u32 security_id; /* The security_id assigned to the descriptor. */ -} __attribute__((__packed__)) SII_INDEX_KEY; +typedef struct +{ + u32 security_id; /* The security_id assigned to the descriptor. */ +}__attribute__((__packed__)) SII_INDEX_KEY; /** * struct SDH_INDEX_KEY - The index entry key used in the $SDH index. @@ -1965,10 +2131,11 @@ typedef struct { * The keys are sorted first by hash and then by security_id. * 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. */ -} __attribute__((__packed__)) SDH_INDEX_KEY; +typedef struct +{ + u32 hash; /* Hash of the security descriptor. */ + u32 security_id; /* The security_id assigned to the descriptor. */ +}__attribute__((__packed__)) SDH_INDEX_KEY; /** * struct VOLUME_NAME - Attribute: Volume name (0x60). @@ -1976,24 +2143,26 @@ typedef struct { * NOTE: Always resident. * NOTE: Present only in FILE_Volume. */ -typedef struct { - ntfschar name[0]; /* The name of the volume in Unicode. */ -} __attribute__((__packed__)) VOLUME_NAME; +typedef struct +{ + 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), -} __attribute__((__packed__)) VOLUME_FLAGS; +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), +}__attribute__((__packed__)) VOLUME_FLAGS; /** * struct VOLUME_INFORMATION - Attribute: Volume information (0x70). @@ -2003,12 +2172,13 @@ typedef enum { * NOTE: Windows 2000 uses NTFS 3.0 while Windows NT4 service pack 6a uses * 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. */ -} __attribute__((__packed__)) VOLUME_INFORMATION; +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. */ +}__attribute__((__packed__)) VOLUME_INFORMATION; /** * struct DATA_ATTR - Attribute: Data attribute (0x80). @@ -2017,31 +2187,34 @@ 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. */ -} __attribute__((__packed__)) DATA_ATTR; +typedef struct +{ + 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 - index root attribute and there is no index - allocation attribute present. */ - 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 - nodes branching off it. */ - INDEX_NODE = 1, /* This node indexes other nodes, i.e. is not a - leaf node. */ - NODE_MASK = 1, /* Mask for accessing the *_NODE bits. */ -} __attribute__((__packed__)) INDEX_HEADER_FLAGS; +typedef enum +{ + /* 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 + 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 + nodes branching off it. */ + INDEX_NODE = 1, /* This node indexes other nodes, i.e. is not a + leaf node. */ + NODE_MASK = 1, +/* Mask for accessing the *_NODE bits. */ +}__attribute__((__packed__)) INDEX_HEADER_FLAGS; /** * struct INDEX_HEADER - @@ -2054,26 +2227,32 @@ typedef enum { * relative to the start of the index header structure and not relative to the * start of the index root or index allocation structures themselves. */ -typedef struct { -/* 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, - including the INDEX_HEADER, aligned to 8. */ -/* 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 */ -} __attribute__((__packed__)) INDEX_HEADER; +typedef struct +{ + /* 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, + including the INDEX_HEADER, aligned to 8. */ + /* 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 */ +}__attribute__((__packed__)) INDEX_HEADER; /** * struct INDEX_ROOT - Attribute: Index root (0x90). @@ -2094,25 +2273,32 @@ typedef struct { * NOTE: The root directory (FILE_root) contains an entry for itself. Other * directories do not contain entries for themselves, though. */ -typedef struct { -/* 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 - 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 - the index allocation attribute). */ -/* 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 - following index entries. */ -/* sizeof()= 32 bytes */ -} __attribute__((__packed__)) INDEX_ROOT; +typedef struct +{ + /* 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 + 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 + the index allocation attribute). */ + /* 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 + following index entries. */ + /* sizeof()= 32 bytes */ +}__attribute__((__packed__)) INDEX_ROOT; /** * struct INDEX_BLOCK - Attribute: Index allocation (0xa0). @@ -2123,27 +2309,31 @@ typedef struct { * INDEX_BLOCK structure containing an index header, followed by a sequence of * 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. */ +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. */ -/* 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. - */ -} __attribute__((__packed__)) INDEX_BLOCK; + /* 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. + */ +}__attribute__((__packed__)) INDEX_BLOCK; typedef INDEX_BLOCK INDEX_ALLOCATION; @@ -2158,34 +2348,36 @@ typedef INDEX_BLOCK INDEX_ALLOCATION; * COLLATION_NTOFS_ULONGS. FIXME: Verify whether the reparse_tag is not the * 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 - reparse point attribute. */ -} __attribute__((__packed__)) REPARSE_INDEX_KEY; +typedef struct +{ + 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; /** * 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), +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), - 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; /** @@ -2211,58 +2403,63 @@ 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 - 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 - the data_length field. If the sid is present - then this structure is padded with zeros to - multiply of 8 and the padding is counted in - the INDEX_ENTRY's data_length. */ -} __attribute__((__packed__)) QUOTA_CONTROL_ENTRY; +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 + 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 + the data_length field. If the sid is present + then this structure is padded with zeros to + multiply of 8 and the padding is counted in + the INDEX_ENTRY's data_length. */ +}__attribute__((__packed__)) QUOTA_CONTROL_ENTRY; /** * struct QUOTA_O_INDEX_DATA - */ -typedef struct { - 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; +typedef struct +{ + 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; /** * 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), +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), } 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 - 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 - 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. */ -} __attribute__((__packed__)) INDEX_ENTRY_FLAGS; +typedef enum +{ + 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 + 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. */ +}__attribute__((__packed__)) INDEX_ENTRY_FLAGS; /** * struct INDEX_ENTRY_HEADER - This the index entry header (see below). @@ -2271,21 +2468,29 @@ typedef enum { * !!!!! 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 */ -} __attribute__((__packed__)) INDEX_ENTRY_HEADER; +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 */ +}__attribute__((__packed__)) INDEX_ENTRY_HEADER; /** * struct INDEX_ENTRY - This is an index entry. @@ -2296,63 +2501,72 @@ 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 - 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 - 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 - 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 - 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 - 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 - object_id of the mft record found in - the data part of the index. */ - REPARSE_INDEX_KEY reparse; /* $R index in - FILE_Extend/$Reparse. */ - 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: - 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__)) INDEX_ENTRY; +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 + 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 + 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 + 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 + 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 + 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 + object_id of the mft record found in + the data part of the index. */ + REPARSE_INDEX_KEY reparse; /* $R index in + FILE_Extend/$Reparse. */ + 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: + 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__)) INDEX_ENTRY; /** * struct BITMAP_ATTR - Attribute: Bitmap (0xb0). @@ -2364,9 +2578,10 @@ typedef struct { * the number of bits in the bitmap * index block size / cluster size is the * number of clusters in the index allocation attribute. */ -typedef struct { - u8 bitmap[0]; /* Array of bits. */ -} __attribute__((__packed__)) BITMAP_ATTR; +typedef struct +{ + u8 bitmap[0]; /* Array of bits. */ +}__attribute__((__packed__)) BITMAP_ATTR; /** * enum PREDEFINED_REPARSE_TAGS - @@ -2388,27 +2603,28 @@ typedef struct { * bit 31: Microsoft bit. If set, the tag is owned by Microsoft. User * 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), +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_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; /** @@ -2416,39 +2632,43 @@ 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. */ -} __attribute__((__packed__)) REPARSE_POINT; +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. */ +}__attribute__((__packed__)) REPARSE_POINT; /** * struct EA_INFORMATION - Attribute: Extended attribute information (0xd0). * * NOTE: Always resident. */ -typedef struct { - u16 ea_length; /* Byte size of the packed extended - attributes. */ - 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 - the extended attributes when calling - ZwQueryEaFile() in Windows NT/2k. I.e. the - byte size of the unpacked extended - attributes. */ -} __attribute__((__packed__)) EA_INFORMATION; +typedef struct +{ + u16 ea_length; /* Byte size of the packed extended + attributes. */ + 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 + the extended attributes when calling + ZwQueryEaFile() in Windows NT/2k. I.e. the + byte size of the unpacked extended + attributes. */ +}__attribute__((__packed__)) EA_INFORMATION; /** * enum EA_FLAGS - Extended attribute flags (8-bit). */ -typedef enum { - NEED_EA = 0x80, /* Indicate that the file to which the EA - belongs cannot be interpreted without - understanding the associated extended - attributes. */ -} __attribute__((__packed__)) EA_FLAGS; +typedef enum +{ + NEED_EA = 0x80, +/* Indicate that the file to which the EA + belongs cannot be interpreted without + understanding the associated extended + attributes. */ +}__attribute__((__packed__)) EA_FLAGS; /** * struct EA_ATTR - Attribute: Extended attribute (EA) (0xe0). @@ -2459,16 +2679,17 @@ typedef enum { * FIXME: It appears weird that the EA name is not Unicode. Is it true? * 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 - 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 - follows the name. */ -} __attribute__((__packed__)) EA_ATTR; +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 + 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 + follows the name. */ +}__attribute__((__packed__)) EA_ATTR; /** * struct PROPERTY_SET - Attribute: Property set (0xf0). @@ -2476,9 +2697,10 @@ typedef struct { * Intended to support Native Structure Storage (NSS) - a feature removed from * NTFS 3.0 during beta testing. */ -typedef struct { - /* Irrelevant as feature unused. */ -} __attribute__((__packed__)) PROPERTY_SET; +typedef struct +{ + /* Irrelevant as feature unused. */ +}__attribute__((__packed__)) PROPERTY_SET; /** * struct LOGGED_UTILITY_STREAM - Attribute: Logged utility stream (0x100). @@ -2491,9 +2713,10 @@ typedef struct { * Used by the Encrypting File System (EFS). All encrypted files have this * attribute with the name $EFS. See below for the relevant structures. */ -typedef struct { - /* Can be anything the creator chooses. */ -} __attribute__((__packed__)) LOGGED_UTILITY_STREAM; +typedef struct +{ + /* Can be anything the creator chooses. */ +}__attribute__((__packed__)) LOGGED_UTILITY_STREAM; /* * $EFS Data Structure: @@ -2527,135 +2750,162 @@ 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 - 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 - decryption fields (DDF), see below. Zero if - no DDFs are present. */ - 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. */ -} __attribute__((__packed__)) EFS_ATTR_HEADER; +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 + 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 + decryption fields (DDF), see below. Zero if + no DDFs are present. */ + 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. */ +}__attribute__((__packed__)) EFS_ATTR_HEADER; /** * struct EFS_DF_ARRAY_HEADER - */ -typedef struct { - u32 df_count; /* Number of data decryption/recovery fields in - the array. */ -} __attribute__((__packed__)) EFS_DF_ARRAY_HEADER; +typedef struct +{ + u32 df_count; /* Number of data decryption/recovery fields in + the array. */ +}__attribute__((__packed__)) EFS_DF_ARRAY_HEADER; /** * struct EFS_DF_HEADER - */ -typedef struct { -/* 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 - encryption key (FEK). */ - 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. */ -} __attribute__((__packed__)) EFS_DF_HEADER; +typedef struct +{ + /* 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 + encryption key (FEK). */ + 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. */ +}__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 - of this structure. Zero if no sid is - present. */ -/* 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 - the name of the container from start of this - structure (may not be zero). */ -/* 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 - the public key blob from start of this - structure. */ -/* 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 - bytes of the header of the certificate - thumbprint. */ -/* 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__)); -} __attribute__((__packed__)) 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 + of this structure. Zero if no sid is + present. */ + /* 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 + the name of the container from start of this + structure (may not be zero). */ + /* 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 + the public key blob from start of this + structure. */ + /* 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 + bytes of the header of the certificate + thumbprint. */ + /* 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__)); +}__attribute__((__packed__)) EFS_DF_CREDENTIAL_HEADER; 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 - container from start of this - structure or 0 if no name present. */ - 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 - from start of this structure or 0 if - no user name present. (This is also - known as lpDisplayInformation.) */ -} __attribute__((__packed__)) 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 + container from start of this + structure or 0 if no name present. */ + 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 + from start of this structure or 0 if + no user name present. (This is also + known as lpDisplayInformation.) */ +}__attribute__((__packed__)) EFS_DF_CERTIFICATE_THUMBPRINT_HEADER; 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" */ +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_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__)); -} __attribute__((__packed__)) INTX_FILE; +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__)); +}__attribute__((__packed__)) INTX_FILE; #endif /* defined _NTFS_LAYOUT_H */ diff --git a/source/libntfs/lcnalloc.c b/source/libntfs/lcnalloc.c index e84d2431..d5a62cfb 100644 --- a/source/libntfs/lcnalloc.c +++ b/source/libntfs/lcnalloc.c @@ -55,35 +55,30 @@ #define NTFS_LCNALLOC_BSIZE 4096 #define NTFS_LCNALLOC_SKIP NTFS_LCNALLOC_BSIZE -enum { - ZONE_MFT = 1, - ZONE_DATA1 = 2, - ZONE_DATA2 = 4 -} ; +enum +{ + 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); + 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); + 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); } /* @@ -94,102 +89,114 @@ static void ntfs_cluster_update_zone_pos(ntfs_volume *vol, u8 zone, LCN tc) 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; - } - } + 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; + 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 int bitmap_writeback(ntfs_volume *vol, s64 pos, s64 size, void *b, - u8 *writeback) +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; - } + s64 written; - return 0; + 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; } /** @@ -232,338 +239,344 @@ static int bitmap_writeback(ntfs_volume *vol, s64 pos, s64 size, void *b, * 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) +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 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"); - - 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; - } + 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"); - /* 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; - } + 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; + } - 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; + /* 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; + } - /* 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; - } + 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; - /* 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; + if (zone_start < 0) + { + if (zone == DATA_ZONE) + zone_start = vol->data1_zone_pos; + else zone_start = vol->mft_zone_pos; + has_guess = 0; + } -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 */ -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 = 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; - } -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; + used_zone_pos = has_guess ? 0 : 1; -wb_err_ret: - 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; + 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; + + 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 */ + 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 = 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; + } + 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; + + wb_err_ret: + 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; } /** @@ -575,38 +588,38 @@ err_ret: */ int ntfs_cluster_free_from_rl(ntfs_volume *vol, runlist *rl) { - s64 nr_freed = 0; - int ret = -1; + 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; -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; + 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; } /* @@ -616,33 +629,32 @@ out: int ntfs_cluster_free_basic(ntfs_volume *vol, s64 lcn, s64 count) { - s64 nr_freed = 0; - int ret = -1; + s64 nr_freed = 0; + int ret = -1; - ntfs_log_trace("Entering.\n"); - ntfs_log_trace("Dealloc lcn 0x%llx, len 0x%llx.\n", - (long long)lcn, (long long)count); + ntfs_log_trace("Entering.\n"); + ntfs_log_trace("Dealloc lcn 0x%llx, len 0x%llx.\n", + (long long)lcn, (long long)count); - if (lcn >= 0) { - update_full_status(vol,lcn); - if (ntfs_bitmap_clear_run(vol->lcnbmp_na, lcn, - count)) { - ntfs_log_perror("Cluster deallocation failed " - "(%lld, %lld)", - (long long)lcn, - (long long)count); - goto out; - } - nr_freed += count; - } - 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; + if (lcn >= 0) + { + update_full_status(vol, lcn); + if (ntfs_bitmap_clear_run(vol->lcnbmp_na, lcn, count)) + { + ntfs_log_perror("Cluster deallocation failed " + "(%lld, %lld)", + (long long)lcn, + (long long)count); + goto out; + } + nr_freed += count; + } + 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; } /** @@ -663,109 +675,107 @@ out: */ 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; + 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; - } - - 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); + if (!vol || !vol->lcnbmp_na || !na || start_vcn < 0 || (count < 0 && count != -1)) + { + ntfs_log_trace("Invalid arguments!\n"); + errno = EINVAL; + return -1; + } - rl = ntfs_attr_find_vcn(na, start_vcn); - if (!rl) { - if (errno == ENOENT) - ret = 0; - goto leave; - } + 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); - if (rl->lcn < 0 && rl->lcn != LCN_HOLE) { - errno = EIO; - ntfs_log_perror("%s: Unexpected lcn (%lld)", __FUNCTION__, - (long long)rl->lcn); - goto leave; - } + rl = ntfs_attr_find_vcn(na, start_vcn); + if (!rl) + { + if (errno == ENOENT) ret = 0; + goto leave; + } - /* Find the starting cluster inside the run that needs freeing. */ - delta = start_vcn - rl->vcn; + if (rl->lcn < 0 && rl->lcn != LCN_HOLE) + { + errno = EIO; + ntfs_log_perror("%s: Unexpected lcn (%lld)", __FUNCTION__, + (long long)rl->lcn); + goto leave; + } - /* The number of clusters in this run that need freeing. */ - to_free = rl->length - delta; - if (count >= 0 && to_free > count) - to_free = count; + /* Find the starting cluster inside the run that needs freeing. */ + delta = start_vcn - rl->vcn; - 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; - } + /* The number of clusters in this run that need freeing. */ + to_free = rl->length - delta; + if (count >= 0 && to_free > count) to_free = count; - /* Go to the next run and adjust the number of clusters left to free. */ - ++rl; - if (count >= 0) - count -= 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; + } - /* - * 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; - } + /* Go to the next run and adjust the number of clusters left to free. */ + ++rl; + if (count >= 0) count -= to_free; - /* The number of clusters in this run that need freeing. */ - to_free = rl->length; - if (count >= 0 && to_free > count) - to_free = count; + /* + * 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; + } - 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; - } + /* The number of clusters in this run that need freeing. */ + to_free = rl->length; + if (count >= 0 && to_free > count) to_free = count; - if (count >= 0) - count -= 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 != -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 >= 0) count -= to_free; + } - 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; + 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; + 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; } diff --git a/source/libntfs/lcnalloc.h b/source/libntfs/lcnalloc.h index cbf4c5cd..18ae1f6b 100644 --- a/source/libntfs/lcnalloc.h +++ b/source/libntfs/lcnalloc.h @@ -31,21 +31,22 @@ /** * 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. */ +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. */ } 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); +extern runlist *ntfs_cluster_alloc(ntfs_volume *vol, VCN start_vcn, s64 count, 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_basic(ntfs_volume *vol, s64 lcn, s64 count); -extern int ntfs_cluster_free(ntfs_volume *vol, ntfs_attr *na, VCN start_vcn, - s64 count); +extern int ntfs_cluster_free(ntfs_volume *vol, ntfs_attr *na, VCN start_vcn, s64 count); #endif /* defined _NTFS_LCNALLOC_H */ diff --git a/source/libntfs/logfile.c b/source/libntfs/logfile.c index 277ad142..83d4c6e7 100644 --- a/source/libntfs/logfile.c +++ b/source/libntfs/logfile.c @@ -56,93 +56,96 @@ */ 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; + 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; - } -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; + 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; } /** @@ -160,103 +163,101 @@ skip_usa_checks: */ 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; + 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; } /** @@ -275,51 +276,49 @@ static BOOL ntfs_check_restart_area(RESTART_PAGE_HEADER *rp) */ 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; + 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; -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; -err_out: - ntfs_log_error("$LogFile log client array is corrupt.\n"); - return FALSE; + 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; + err_out: ntfs_log_error("$LogFile log client array is corrupt.\n"); + return FALSE; } /** @@ -349,98 +348,98 @@ err_out: * ENOMEM - Not enough memory to load the restart page. * 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) +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_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 { -err_out: - free(trp); - } - return 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 + { + err_out: free(trp); + } + return err; } /** @@ -462,170 +461,167 @@ err_out: */ 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; + 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); -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; -err_out: - free(kaddr); - free(rstr1_ph); - free(rstr2_ph); - return FALSE; + /* + * 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; + err_out: free(kaddr); + free(rstr1_ph); + free(rstr2_ph); + return FALSE; } /** @@ -650,40 +646,42 @@ err_out: */ BOOL ntfs_is_logfile_clean(ntfs_attr *log_na, RESTART_PAGE_HEADER *rp) { - RESTART_AREA *ra; + 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; } /** @@ -699,39 +697,39 @@ BOOL ntfs_is_logfile_clean(ntfs_attr *log_na, RESTART_PAGE_HEADER *rp) */ int ntfs_empty_logfile(ntfs_attr *na) { - s64 pos, count; - char buf[NTFS_BUF_SIZE]; + s64 pos, count; + char buf[NTFS_BUF_SIZE]; - ntfs_log_trace("Entering.\n"); - - if (NVolLogFileEmpty(na->ni->vol)) - return 0; + ntfs_log_trace("Entering.\n"); - if (!NAttrNonResident(na)) { - errno = EIO; - ntfs_log_perror("Resident $LogFile $DATA attribute"); - return -1; - } + if (NVolLogFileEmpty(na->ni->vol)) return 0; - memset(buf, -1, NTFS_BUF_SIZE); + if (!NAttrNonResident(na)) + { + errno = EIO; + ntfs_log_perror("Resident $LogFile $DATA attribute"); + return -1; + } - pos = 0; - while ((count = na->data_size - pos) > 0) { - - if (count > NTFS_BUF_SIZE) - count = NTFS_BUF_SIZE; + memset(buf, -1, 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; - } + pos = 0; + while ((count = na->data_size - pos) > 0) + { - NVolSetLogFileEmpty(na->ni->vol); - - return 0; + 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; } diff --git a/source/libntfs/logfile.h b/source/libntfs/logfile.h index 798d562d..b75099ad 100644 --- a/source/libntfs/logfile.h +++ b/source/libntfs/logfile.h @@ -61,40 +61,50 @@ * * 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. - 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. */ +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. + 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. */ -/* 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 - 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 >= - 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 - 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 - version is 1. */ -/* 28*/ sle16 major_ver; /* Log file major version. We only support - version 1.1. */ -/* sizeof() = 30 (0x1e) bytes */ -} __attribute__((__packed__)) RESTART_PAGE_HEADER; + /* 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 + 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 >= + 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 + 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 + version is 1. */ + /* 28*/ + sle16 major_ver; /* Log file major version. We only support + version 1.1. */ + /* sizeof() = 30 (0x1e) bytes */ +}__attribute__((__packed__)) RESTART_PAGE_HEADER; /* * Constant for the log client indices meaning that there are no client records @@ -108,10 +118,11 @@ typedef struct { * These are the so far known RESTART_AREA_* flags (16-bit) which contain * 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. */ -} __attribute__((__packed__)); +enum +{ + 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; @@ -122,139 +133,154 @@ typedef le16 RESTART_AREA_FLAGS; * RESTART_PAGE_HEADER to the restart_area_offset value found in it. * See notes at restart_area_offset above. */ -typedef struct { -/*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 - 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 - in the array of log client records. - LOGFILE_NO_CLIENT means that there are no - free log client records in the array. - If != LOGFILE_NO_CLIENT, check that - log_clients > client_free_list. On Win2k - and presumably earlier, on a clean volume - this is != LOGFILE_NO_CLIENT, and it should - be 0, i.e. the first (and only) client - record is free and thus the logfile is - closed and hence clean. A dirty volume - would have left the logfile open and hence - this would be LOGFILE_NO_CLIENT. On WinXP - 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 - 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 - != LOGFILE_NO_CLIENT check that log_clients - > client_in_use_list. On Win2k and - presumably earlier, on a clean volume this - is LOGFILE_NO_CLIENT, i.e. there are no - client records in use and thus the logfile - is closed and hence clean. A dirty volume - would have left the logfile open and hence - this would be != LOGFILE_NO_CLIENT, and it - should be 0, i.e. the first (and only) - client record is in use. On WinXP and - 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 - and presumably earlier this is always 0. On - WinXP and presumably later, if the logfile - was shutdown cleanly, the second bit, - RESTART_VOLUME_IS_CLEAN, is set. This bit - is cleared when the volume is mounted by - WinXP and set when the volume is dismounted, - thus if the logfile is dirty, this bit is - clear. Thus we don't need to check the - Windows version to determine if the logfile - is clean. Instead if the logfile is closed, - we know it must be clean. If it is open and - this bit is set, we also know it must be - 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 - 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 - client array. Following checks required if - version matches. Otherwise, skip them. - restart_area_offset + restart_area_length - has to be <= system_page_size. Also, - 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 - the first log client record if versions are - matched. When creating, set this to be - after this restart area structure, aligned - to 8-bytes boundary. If the versions do not - match, this is ignored and the offset is - assumed to be (sizeof(RESTART_AREA) + 7) & - ~7, i.e. rounded up to first 8-byte - boundary. Either way, client_array_offset - has to be aligned to an 8-byte boundary. - Also, restart_area_offset + - client_array_offset has to be <= 510. - Finally, client_array_offset + (log_clients - * sizeof(log client record)) has to be <= - system_page_size. On Win2k and presumably - earlier, this is 0x30, i.e. immediately - following this record. On WinXP and - presumably later, this is 0x40, i.e. there - are 16 extra bytes between this record and - 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 - restart_area_offset + the offset of the - file_size are > 510 then corruption has - occurred. This is the very first check when - starting with the restart_area as if it - fails it means that some of the above values - will be corrupted by the multi sector - transfer protection. The file_size has to - be rounded down to be a multiple of the - log_page_size in the RESTART_PAGE_HEADER and - 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 - the log record header. On create set to - 0. */ -/* 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. - (log_record_header_length + 7) & ~7 == - 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 - 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 - 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 */ -} __attribute__((__packed__)) RESTART_AREA; +typedef struct +{ + /*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 + 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 + in the array of log client records. + LOGFILE_NO_CLIENT means that there are no + free log client records in the array. + If != LOGFILE_NO_CLIENT, check that + log_clients > client_free_list. On Win2k + and presumably earlier, on a clean volume + this is != LOGFILE_NO_CLIENT, and it should + be 0, i.e. the first (and only) client + record is free and thus the logfile is + closed and hence clean. A dirty volume + would have left the logfile open and hence + this would be LOGFILE_NO_CLIENT. On WinXP + 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 + 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 + != LOGFILE_NO_CLIENT check that log_clients + > client_in_use_list. On Win2k and + presumably earlier, on a clean volume this + is LOGFILE_NO_CLIENT, i.e. there are no + client records in use and thus the logfile + is closed and hence clean. A dirty volume + would have left the logfile open and hence + this would be != LOGFILE_NO_CLIENT, and it + should be 0, i.e. the first (and only) + client record is in use. On WinXP and + 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 + and presumably earlier this is always 0. On + WinXP and presumably later, if the logfile + was shutdown cleanly, the second bit, + RESTART_VOLUME_IS_CLEAN, is set. This bit + is cleared when the volume is mounted by + WinXP and set when the volume is dismounted, + thus if the logfile is dirty, this bit is + clear. Thus we don't need to check the + Windows version to determine if the logfile + is clean. Instead if the logfile is closed, + we know it must be clean. If it is open and + this bit is set, we also know it must be + 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 + 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 + client array. Following checks required if + version matches. Otherwise, skip them. + restart_area_offset + restart_area_length + has to be <= system_page_size. Also, + 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 + the first log client record if versions are + matched. When creating, set this to be + after this restart area structure, aligned + to 8-bytes boundary. If the versions do not + match, this is ignored and the offset is + assumed to be (sizeof(RESTART_AREA) + 7) & + ~7, i.e. rounded up to first 8-byte + boundary. Either way, client_array_offset + has to be aligned to an 8-byte boundary. + Also, restart_area_offset + + client_array_offset has to be <= 510. + Finally, client_array_offset + (log_clients + * sizeof(log client record)) has to be <= + system_page_size. On Win2k and presumably + earlier, this is 0x30, i.e. immediately + following this record. On WinXP and + presumably later, this is 0x40, i.e. there + are 16 extra bytes between this record and + 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 + restart_area_offset + the offset of the + file_size are > 510 then corruption has + occurred. This is the very first check when + starting with the restart_area as if it + fails it means that some of the above values + will be corrupted by the multi sector + transfer protection. The file_size has to + be rounded down to be a multiple of the + log_page_size in the RESTART_PAGE_HEADER and + 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 + the log record header. On create set to + 0. */ + /* 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. + (log_record_header_length + 7) & ~7 == + 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 + 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 + 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 */ +}__attribute__((__packed__)) RESTART_AREA; /** * struct LOG_CLIENT_RECORD - Log client record. @@ -262,40 +288,49 @@ typedef struct { * The offset of this record is found by adding the offset of the * 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 - set to 0. */ -/* 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 - 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 - 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 - 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 - always be 8. */ -/* 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 */ -} __attribute__((__packed__)) LOG_CLIENT_RECORD; +typedef struct +{ + /*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 + 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 + 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 + 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 + 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 + always be 8. */ + /* 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 */ +}__attribute__((__packed__)) LOG_CLIENT_RECORD; /** * struct RECORD_PAGE_HEADER - Log page record page header. @@ -305,87 +340,95 @@ typedef struct { * following update sequence array and then aligned to 8 byte boundary, but is * 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. - When creating, set this to be immediately - after this header structure (without any - alignment). */ - u16 usa_count; /* See NTFS_RECORD definition in layout.h. */ +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. + When creating, set this to be immediately + after this header structure (without any + alignment). */ + 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; -} __attribute__((__packed__)) RECORD_PAGE_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; /** * enum LOG_RECORD_FLAGS - Possible 16-bit flags for log records. * * (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. */ -} __attribute__((__packed__)) LOG_RECORD_FLAGS; +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. */ +}__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; -} __attribute__((__packed__)) LOG_CLIENT_ID; +typedef struct +{ + u16 seq_number; + u16 client_index; +}__attribute__((__packed__)) LOG_CLIENT_ID; /** * struct LOG_RECORD - Log record header. * * 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 - 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 - is not 0. */ - LCN lcn; - } __attribute__((__packed__)) lcn_list[0]; -} __attribute__((__packed__)) LOG_RECORD; +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 + 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 + is not 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); extern BOOL ntfs_is_logfile_clean(ntfs_attr *log_na, RESTART_PAGE_HEADER *rp); diff --git a/source/libntfs/logging.c b/source/libntfs/logging.c index 385bcaa6..8569d93b 100644 --- a/source/libntfs/logging.c +++ b/source/libntfs/logging.c @@ -67,10 +67,11 @@ static int tab; * @flags: Flags which affect the output style * @handler: Function to perform the actual logging */ -struct ntfs_logging { - u32 levels; - u32 flags; - ntfs_log_handler *handler BROKEN_GCC_FORMAT_ATTRIBUTE; +struct ntfs_logging +{ + u32 levels; + u32 flags; + ntfs_log_handler *handler BROKEN_GCC_FORMAT_ATTRIBUTE; }; /** @@ -79,20 +80,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 -}; - + }; /** * ntfs_log_get_levels - Get a list of the current logging levels @@ -103,7 +101,7 @@ static struct ntfs_logging ntfs_log = { */ u32 ntfs_log_get_levels(void) { - return ntfs_log.levels; + return ntfs_log.levels; } /** @@ -117,10 +115,10 @@ u32 ntfs_log_get_levels(void) */ u32 ntfs_log_set_levels(u32 levels) { - u32 old; - old = ntfs_log.levels; - ntfs_log.levels |= levels; - return old; + u32 old; + old = ntfs_log.levels; + ntfs_log.levels |= levels; + return old; } /** @@ -134,13 +132,12 @@ u32 ntfs_log_set_levels(u32 levels) */ u32 ntfs_log_clear_levels(u32 levels) { - u32 old; - old = ntfs_log.levels; - ntfs_log.levels &= (~levels); - return old; + u32 old; + old = ntfs_log.levels; + ntfs_log.levels &= (~levels); + return old; } - /** * ntfs_log_get_flags - Get a list of logging style flags * @@ -150,7 +147,7 @@ u32 ntfs_log_clear_levels(u32 levels) */ u32 ntfs_log_get_flags(void) { - return ntfs_log.flags; + return ntfs_log.flags; } /** @@ -164,10 +161,10 @@ u32 ntfs_log_get_flags(void) */ u32 ntfs_log_set_flags(u32 flags) { - u32 old; - old = ntfs_log.flags; - ntfs_log.flags |= flags; - return old; + u32 old; + old = ntfs_log.flags; + ntfs_log.flags |= flags; + return old; } /** @@ -181,13 +178,12 @@ u32 ntfs_log_set_flags(u32 flags) */ u32 ntfs_log_clear_flags(u32 flags) { - u32 old; - old = ntfs_log.flags; - ntfs_log.flags &= (~flags); - return old; + u32 old; + old = ntfs_log.flags; + ntfs_log.flags &= (~flags); + return old; } - /** * ntfs_log_get_stream - Default output streams for logging levels * @level: Log level @@ -199,30 +195,31 @@ u32 ntfs_log_clear_flags(u32 flags) */ static FILE * ntfs_log_get_stream(u32 level) { - FILE *stream; + 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; } /** @@ -235,48 +232,48 @@ static FILE * ntfs_log_get_stream(u32 level) */ static const char * ntfs_log_get_prefix(u32 level) { - const char *prefix; + 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; } - /** * ntfs_log_set_handler - Provide an alternate logging handler * @handler: function to perform the logging @@ -286,14 +283,15 @@ static const char * ntfs_log_get_prefix(u32 level) */ void ntfs_log_set_handler(ntfs_log_handler *handler) { - if (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; } /** @@ -313,26 +311,24 @@ void ntfs_log_set_handler(ntfs_log_handler *handler) * 0 Message wasn't logged * 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 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 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; } - /** * ntfs_log_handler_syslog - syslog logging handler * @function: Function in which the log line occurred @@ -350,41 +346,42 @@ int ntfs_log_redirect(const char *function, const char *file, * num Number of output characters */ - #ifdef HAVE_SYSLOG_H #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) +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; + char logbuf[LOG_LINE_LEN]; + int ret, olderr = errno; #ifndef DEBUG - if ((level & NTFS_LOG_LEVEL_PERROR) && errno == ENOSPC) - return 1; + 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; + 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; } #endif @@ -409,59 +406,57 @@ out: * 0 Message wasn't logged * 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 ntfs_log_handler_fprintf(const char *function, const char *file, 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; - } - - for (i = 0; i < tab; i++) - ret += fprintf(stream, " "); + 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; + 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++; + if (level == NTFS_LOG_LEVEL_ENTER) + tab++; #endif - fflush(stream); - errno = olderr; - return ret; + fflush(stream); + errno = olderr; + return ret; } /** @@ -479,11 +474,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))) +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; + return 0; } /** @@ -507,13 +501,12 @@ int ntfs_log_handler_null(const char *function __attribute__((unused)), const ch * 0 Message wasn't logged * 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) +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; + 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); } /** @@ -538,13 +531,12 @@ int ntfs_log_handler_stdout(const char *function, const char *file, * 0 Message wasn't logged * 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) +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); + 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); } /** @@ -568,16 +560,14 @@ int ntfs_log_handler_outerr(const char *function, const char *file, * 0 Message wasn't logged * 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) +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; + 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); } - /** * ntfs_log_parse_option - Act upon command line options * @option: Option flag @@ -593,21 +583,28 @@ int ntfs_log_handler_stderr(const char *function, const char *file, */ 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; - } + 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 401f5c97..f1c84531 100644 --- a/source/libntfs/logging.h +++ b/source/libntfs/logging.h @@ -34,20 +34,20 @@ #include "types.h" /* 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); +typedef int ( ntfs_log_handler)(const char *function, const char *file, int line, 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)))); /* Logging handlers */ -ntfs_log_handler ntfs_log_handler_syslog __attribute__((format(printf, 6, 0))); +ntfs_log_handler ntfs_log_handler_syslog __attribute__((format(printf, 6, 0))); ntfs_log_handler ntfs_log_handler_fprintf __attribute__((format(printf, 6, 0))); -ntfs_log_handler ntfs_log_handler_null __attribute__((format(printf, 6, 0))); -ntfs_log_handler ntfs_log_handler_stdout __attribute__((format(printf, 6, 0))); -ntfs_log_handler ntfs_log_handler_outerr __attribute__((format(printf, 6, 0))); -ntfs_log_handler ntfs_log_handler_stderr __attribute__((format(printf, 6, 0))); +ntfs_log_handler ntfs_log_handler_null __attribute__((format(printf, 6, 0))); +ntfs_log_handler ntfs_log_handler_stdout __attribute__((format(printf, 6, 0))); +ntfs_log_handler ntfs_log_handler_outerr __attribute__((format(printf, 6, 0))); +ntfs_log_handler ntfs_log_handler_stderr __attribute__((format(printf, 6, 0))); /* Enable/disable certain log levels */ u32 ntfs_log_set_levels(u32 levels); @@ -62,9 +62,8 @@ u32 ntfs_log_get_flags(void); /* Turn command-line options into logging flags */ 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))); +int ntfs_log_redirect(const char *function, const char *file, int line, 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 600e5a93..ca3dce70 100644 --- a/source/libntfs/mem_allocate.h +++ b/source/libntfs/mem_allocate.h @@ -24,19 +24,22 @@ #include -static inline void* ntfs_alloc (size_t size) { +static inline void* ntfs_alloc(size_t size) +{ return malloc(size); } -static inline void* ntfs_align (size_t size) { - #ifdef __wii__ +static inline void* ntfs_align(size_t size) +{ +#ifdef __wii__ return memalign(32, size); - #else +#else return malloc(size); - #endif +#endif } -static inline void ntfs_free (void* mem) { +static inline void ntfs_free(void* mem) +{ free(mem); } diff --git a/source/libntfs/mft.c b/source/libntfs/mft.c index e93c6646..648ea493 100644 --- a/source/libntfs/mft.c +++ b/source/libntfs/mft.c @@ -78,42 +78,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) +int ntfs_mft_records_read(const ntfs_volume *vol, const MFT_REF mref, const s64 count, MFT_RECORD *b) { - s64 br; - VCN m; + 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,107 +139,103 @@ int ntfs_mft_records_read(const ntfs_volume *vol, const MFT_REF mref, * record was successfully written, we write the appropriate mft records from * 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) +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; + 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; -err_out: - if (ret) - errno = EIO; - return ret; +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; } /** @@ -274,44 +269,40 @@ err_out: * Note: We do not check if the mft record is flagged in use. The caller can * check if desired. */ -int ntfs_file_record_read(const ntfs_volume *vol, const MFT_REF mref, - MFT_RECORD **mrec, ATTR_RECORD **attr) +int ntfs_file_record_read(const ntfs_volume *vol, const MFT_REF mref, MFT_RECORD **mrec, ATTR_RECORD **attr) { - MFT_RECORD *m; + MFT_RECORD *m; - 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; + if (!vol || !mrec) + { + errno = EINVAL; + ntfs_log_perror("%s: mrec=%p", __FUNCTION__, mrec); + return -1; + } - 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; + 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; + err_out: if (m != *mrec) free(m); + return -1; } /** @@ -327,71 +318,74 @@ 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) +int ntfs_mft_record_layout(const ntfs_volume *vol, const MFT_REF mref, MFT_RECORD *mrec) { - ATTR_RECORD *a; + 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; } /** @@ -406,27 +400,23 @@ int ntfs_mft_record_layout(const ntfs_volume *vol, const MFT_REF mref, */ int ntfs_mft_record_format(const ntfs_volume *vol, const MFT_REF mref) { - MFT_RECORD *m; - int ret = -1; + 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; -free_m: - free(m); -out: - ntfs_log_leave("\n"); - return ret; + 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; } static const char *es = " Leaving inconsistent metadata. Run chkdsk."; @@ -441,14 +431,13 @@ static const char *es = " Leaving inconsistent metadata. Run chkdsk."; */ static inline unsigned int ntfs_ffz(unsigned int word) { - return ffs(~word) - 1; + return ffs(~word) - 1; } static int ntfs_is_mft(ntfs_inode *ni) { - if (ni && ni->mft_no == FILE_MFT) - return 1; - return 0; + if (ni && ni->mft_no == FILE_MFT) return 1; + return 0; } #ifndef PAGE_SIZE @@ -476,166 +465,167 @@ static int ntfs_is_mft(ntfs_inode *ni) */ 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; + 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; -leave: - ntfs_log_leave("\n"); - return ret; + /* 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; } static int ntfs_mft_attr_extend(ntfs_attr *na) { - int ret = STATUS_ERROR; - ntfs_log_enter("Entering\n"); + 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; } /** @@ -643,196 +633,188 @@ out: */ 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; + 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; - - 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; + 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; - 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; + 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; -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; -undo_alloc: - err = errno; + 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; - /* 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; + 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; + undo_alloc: 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; } /** @@ -848,12 +830,12 @@ undo_alloc: */ 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; + 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 @@ -869,84 +851,82 @@ static int ntfs_mft_bitmap_extend_allocation(ntfs_volume *vol) */ 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; + 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"); - - mftbmp_na = vol->mftbmp_na; - ctx = ntfs_attr_get_search_ctx(mftbmp_na->ni, NULL); - if (!ctx) - goto out; + ntfs_log_enter("Entering\n"); - 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; + 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.%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); -err_out: - errno = err; -out: - ntfs_log_leave("\n"); - return ret; + 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); + 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); + err_out: errno = err; + out: + ntfs_log_leave("\n"); + return ret; } /** @@ -964,541 +944,517 @@ out: */ 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; + 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"); - - 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; + ntfs_log_enter("Extending mft data allocation.\n"); - 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; -out: - ntfs_log_leave("\n"); - return ret; + 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); -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; -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; + 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; + } + 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; + + 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; + 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; } - 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; + int ret = -1; + ntfs_attr *mft_na, *mftbmp_na; + s64 old_data_initialized, old_data_size; + ntfs_attr_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"); - 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; + 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; } 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; + int ret = -1; + ntfs_attr *mft_na, *mftbmp_na; + s64 old_data_initialized, old_data_size; + ntfs_attr_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"); - 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); + ntfs_log_enter("Entering\n"); - /* 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 = 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; + + undo_data_init: 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; + 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; -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; - } - - 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; - } + 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; - 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; + 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; + } - 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 = ntfs_current_time(); - /* 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; + 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; -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_out: - if (!errno) - errno = EIO; - ni = NULL; - goto out; + 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 + = ntfs_current_time(); + /* 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; + + 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_out: if (!errno) errno = EIO; + ni = NULL; + goto out; } /** @@ -1586,222 +1542,236 @@ err_out: */ 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; + 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 (ntfs_is_mft(base_ni)) { - ni = ntfs_mft_rec_alloc(vol); - 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; + } - 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) { + if (ntfs_is_mft(base_ni)) + { + ni = ntfs_mft_rec_alloc(vol); + goto out; + } - int ret = ntfs_mft_bitmap_extend_allocation(vol); + 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) + { - 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; - } + int ret = ntfs_mft_bitmap_extend_allocation(vol); - 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; - } - - /* 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; + 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; + } - /* - * 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; + 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; + } - 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 = ntfs_current_time(); - /* 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; + /* 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; -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_out: - if (!errno) - errno = EIO; - ni = NULL; - goto out; + /* + * 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 = ntfs_current_time(); + /* 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; + + 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_out: + if (!errno) + errno = EIO; + ni = NULL; + goto out; } /** @@ -1817,70 +1787,72 @@ err_out: */ int ntfs_mft_record_free(ntfs_volume *vol, ntfs_inode *ni) { - u64 mft_no; - int err; - u16 seq_no; - le16 old_seq_no; + 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. */ + /* Throw away the now freed inode. */ #if CACHE_NIDATA_SIZE - if (!ntfs_inode_real_close(ni)) { + if (!ntfs_inode_real_close(ni)) + { #else - if (!ntfs_inode_close(ni)) { + if (!ntfs_inode_close(ni)) + { #endif - vol->free_mft_records++; - return 0; - } - err = errno; + vol->free_mft_records++; + return 0; + } + err = errno; - /* 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"); -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; + /* 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"); + 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; } /** @@ -1891,19 +1863,19 @@ sync_rollback: */ int ntfs_mft_usn_dec(MFT_RECORD *mrec) { - u16 usn; - le16 *usnp; + 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 bb15f0f3..6c7c4502 100644 --- a/source/libntfs/mft.h +++ b/source/libntfs/mft.h @@ -29,8 +29,7 @@ #include "layout.h" #include "logging.h" -extern int ntfs_mft_records_read(const ntfs_volume *vol, const MFT_REF mref, - const s64 count, MFT_RECORD *b); +extern int ntfs_mft_records_read(const ntfs_volume *vol, const MFT_REF mref, const s64 count, MFT_RECORD *b); /** * ntfs_mft_record_read - read a record from the mft @@ -47,25 +46,21 @@ 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) +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; + 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); +extern int ntfs_file_record_read(const ntfs_volume *vol, const MFT_REF mref, 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); +extern int ntfs_mft_records_write(const ntfs_volume *vol, const MFT_REF mref, const s64 count, MFT_RECORD *b); /** * ntfs_mft_record_write - write an mft record to disk @@ -82,15 +77,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) +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; + 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; } /** @@ -111,14 +105,12 @@ static __inline__ int ntfs_mft_record_write(const ntfs_volume *vol, */ 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); + 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); +extern int ntfs_mft_record_layout(const ntfs_volume *vol, const MFT_REF mref, 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 b2e17cbf..1493b0fc 100644 --- a/source/libntfs/misc.c +++ b/source/libntfs/misc.c @@ -42,20 +42,18 @@ */ 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 *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 *p; + + p = malloc(size); + if (!p) ntfs_log_perror("Failed to malloc %lld bytes", (long long)size); + return p; } diff --git a/source/libntfs/mst.c b/source/libntfs/mst.c index 470942d6..c1f6a659 100644 --- a/source/libntfs/mst.c +++ b/source/libntfs/mst.c @@ -49,73 +49,76 @@ */ int ntfs_mst_post_read_fixup(NTFS_RECORD *b, const u32 size) { - u16 usa_ofs, usa_count, usn; - u16 *usa_pos, *data_pos; + 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; } /** @@ -140,56 +143,56 @@ int ntfs_mst_post_read_fixup(NTFS_RECORD *b, const u32 size) */ int ntfs_mst_pre_write_fixup(NTFS_RECORD *b, const u32 size) { - u16 usa_ofs, usa_count, usn; - u16 *usa_pos, *data_pos; + 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; } /** @@ -203,29 +206,30 @@ int ntfs_mst_pre_write_fixup(NTFS_RECORD *b, const u32 size) */ void ntfs_mst_post_write_fixup(NTFS_RECORD *b) { - u16 *usa_pos, *data_pos; + 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 c2421c25..2c87dfc3 100644 --- a/source/libntfs/ntfs.c +++ b/source/libntfs/ntfs.c @@ -41,46 +41,27 @@ #include "cache.h" // NTFS device driver devoptab -static const devoptab_t devops_ntfs = { - NULL, /* Device name */ - sizeof (ntfs_file_state), - ntfs_open_r, - ntfs_close_r, - ntfs_write_r, - ntfs_read_r, - ntfs_seek_r, - ntfs_fstat_r, - ntfs_stat_r, - ntfs_link_r, - ntfs_unlink_r, - ntfs_chdir_r, - ntfs_rename_r, - ntfs_mkdir_r, - sizeof (ntfs_dir_state), - ntfs_diropen_r, - ntfs_dirreset_r, - ntfs_dirnext_r, - ntfs_dirclose_r, - ntfs_statvfs_r, - ntfs_ftruncate_r, - ntfs_fsync_r, - NULL /* Device data */ +static const devoptab_t devops_ntfs = { NULL, /* Device name */ +sizeof(ntfs_file_state), ntfs_open_r, ntfs_close_r, ntfs_write_r, ntfs_read_r, ntfs_seek_r, ntfs_fstat_r, ntfs_stat_r, + ntfs_link_r, ntfs_unlink_r, ntfs_chdir_r, ntfs_rename_r, ntfs_mkdir_r, sizeof(ntfs_dir_state), ntfs_diropen_r, + ntfs_dirreset_r, ntfs_dirnext_r, ntfs_dirclose_r, ntfs_statvfs_r, ntfs_ftruncate_r, ntfs_fsync_r, NULL /* Device data */ }; -void ntfsInit (void) +void ntfsInit(void) { static bool isInit = false; // Initialise ntfs-3g (if not already done so) - if (!isInit) { + 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(); @@ -89,16 +70,17 @@ void ntfsInit (void) 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}; + sec_t partition_starts[NTFS_MAX_PARTITIONS] = { 0 }; int partition_count = 0; sec_t part_lba = 0; int i; - union { + union + { u8 buffer[512]; MASTER_BOOT_RECORD mbr; EXTENDED_BOOT_RECORD ebr; @@ -106,65 +88,77 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) } sector; // Sanity check - if (!interface) { + if (!interface) + { errno = EINVAL; return -1; } - if (!partitions) - return 0; + if (!partitions) return 0; // Initialise ntfs-3g ntfsInit(); // Start the device and check that it is inserted - if (!interface->startup()) { + if (!interface->startup()) + { errno = EIO; return -1; } - if (!interface->isInserted()) { + if (!interface->isInserted()) + { return 0; } // Read the first sector on the device - if (!interface->readSectors(0, 1, §or.buffer)) { + if (!interface->readSectors(0, 1, §or.buffer)) + { errno = EIO; return -1; } // If this is the devices master boot record - if (sector.mbr.signature == MBR_SIGNATURE) { + 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++) { + 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); + partition->status == PARTITION_STATUS_BOOTABLE ? "bootable (active)" : "non-bootable", + part_lba, partition->type); // Figure out what type of partition this is - switch (partition->type) { + switch (partition->type) + { // Ignore empty partitions case PARTITION_TYPE_EMPTY: continue; - // NTFS partition - case PARTITION_TYPE_NTFS: { + // NTFS partition + 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) { + 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_count < NTFS_MAX_PARTITIONS) { + if (partition_count < NTFS_MAX_PARTITIONS) + { partition_starts[partition_count] = part_lba; partition_count++; } - } else { + } + else + { ntfs_log_debug("Partition %i: Invalid NTFS boot sector, not actually NTFS\n", i + 1); } } @@ -173,22 +167,26 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) } - // DOS 3.3+ or Windows 95 extended partition + // DOS 3.3+ or Windows 95 extended partition case PARTITION_TYPE_DOS33_EXTENDED: - case PARTITION_TYPE_WIN95_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 { + do + { // Read and validate the extended boot record - if (interface->readSectors(ebr_lba + next_erb_lba, 1, §or)) { - if (sector.ebr.signature == EBR_SIGNATURE) { + 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); + 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 @@ -196,20 +194,26 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) next_erb_lba = le32_to_cpu(sector.ebr.next_ebr.lba_start); // Check if this partition has a valid NTFS boot record - if (interface->readSectors(part_lba, 1, §or)) { - if (sector.boot.oem_id == NTFS_OEM_ID) { + 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) { + if (partition_count < NTFS_MAX_PARTITIONS) + { partition_starts[partition_count] = part_lba; partition_count++; } } } - } else { + } + else + { next_erb_lba = 0; } } @@ -220,18 +224,23 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) } - // Unknown or unsupported partition type - default: { + // Unknown or unsupported partition type + 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) { + 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) { + if (partition_count < NTFS_MAX_PARTITIONS) + { partition_starts[partition_count] = part_lba; partition_count++; } @@ -246,16 +255,22 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) } - // Else it is assumed this device has no master boot record - } else { + // Else it is assumed this device has no master boot record + } + else + { ntfs_log_debug("No Master Boot Record was found!\n"); // As a last-ditched effort, search the first 64 sectors of the device for stray NTFS partitions - for (i = 0; i < 64; i++) { - if (interface->readSectors(i, 1, §or)) { - if (sector.boot.oem_id == NTFS_OEM_ID) { + for (i = 0; i < 64; i++) + { + if (interface->readSectors(i, 1, §or)) + { + if (sector.boot.oem_id == NTFS_OEM_ID) + { ntfs_log_debug("Valid NTFS boot sector found at sector %d!\n", i); - if (partition_count < NTFS_MAX_PARTITIONS) { + if (partition_count < NTFS_MAX_PARTITIONS) + { partition_starts[partition_count] = i; partition_count++; } @@ -269,9 +284,11 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) /*interface->shutdown();*/ // Return the found partitions (if any) - if (partition_count > 0) { - *partitions = (sec_t*)ntfs_alloc(sizeof(sec_t) * partition_count); - if (*partitions) { + if (partition_count > 0) + { + *partitions = (sec_t*) ntfs_alloc(sizeof(sec_t) * partition_count); + if (*partitions) + { memcpy(*partitions, &partition_starts, sizeof(sec_t) * partition_count); return partition_count; } @@ -280,7 +297,7 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) 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; @@ -295,16 +312,21 @@ int ntfsMountAll (ntfs_md **mounts, u32 flags) ntfsInit(); // Find and mount all NTFS partitions on all known devices - for (i = 0; discs[i].name != NULL && discs[i].interface != NULL; i++) { + for (i = 0; discs[i].name != NULL && discs[i].interface != NULL; i++) + { disc = &discs[i]; partition_count = ntfsFindPartitions(disc->interface, &partitions); - if (partition_count > 0 && partitions) { - for (j = 0, k = 0; j < partition_count; j++) { + 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) { + if (k >= NTFS_MAX_MOUNTS) + { ntfs_free(partitions); errno = EADDRNOTAVAIL; return -1; @@ -312,8 +334,11 @@ int ntfsMountAll (ntfs_md **mounts, u32 flags) } 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)) { + if (mount_count < NTFS_MAX_MOUNTS) + { + if (ntfsMount(name, disc->interface, partitions[j], CACHE_DEFAULT_PAGE_SIZE, + CACHE_DEFAULT_PAGE_COUNT, flags)) + { strcpy(mount_points[mount_count].name, name); mount_points[mount_count].interface = disc->interface; mount_points[mount_count].startSector = partitions[j]; @@ -327,9 +352,11 @@ int ntfsMountAll (ntfs_md **mounts, u32 flags) } // Return the mounts (if any) - if (mount_count > 0 && mounts) { - *mounts = (ntfs_md*)ntfs_alloc(sizeof(ntfs_md) * mount_count); - if (*mounts) { + if (mount_count > 0 && mounts) + { + *mounts = (ntfs_md*) ntfs_alloc(sizeof(ntfs_md) * mount_count); + if (*mounts) + { memcpy(*mounts, &mount_points, sizeof(ntfs_md) * mount_count); return mount_count; } @@ -338,7 +365,7 @@ int ntfsMountAll (ntfs_md **mounts, u32 flags) 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; @@ -350,7 +377,8 @@ int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flag int i, j, k; // Sanity check - if (!interface) { + if (!interface) + { errno = EINVAL; return -1; } @@ -359,17 +387,23 @@ int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flag 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) { + for (i = 0; discs[i].name != NULL && discs[i].interface != NULL; i++) + { + if (discs[i].interface == interface) + { disc = &discs[i]; partition_count = ntfsFindPartitions(disc->interface, &partitions); - if (partition_count > 0 && partitions) { - for (j = 0, k = 0; j < partition_count; j++) { + 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) { + if (k >= NTFS_MAX_MOUNTS) + { ntfs_free(partitions); errno = EADDRNOTAVAIL; return -1; @@ -377,8 +411,11 @@ int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flag } 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)) { + if (mount_count < NTFS_MAX_MOUNTS) + { + if (ntfsMount(name, disc->interface, partitions[j], CACHE_DEFAULT_PAGE_SIZE, + CACHE_DEFAULT_PAGE_COUNT, flags)) + { strcpy(mount_points[mount_count].name, name); mount_points[mount_count].interface = disc->interface; mount_points[mount_count].startSector = partitions[j]; @@ -394,15 +431,18 @@ int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flag } // If we couldn't find the device then return with error status - if (!disc) { + if (!disc) + { errno = ENODEV; return -1; } // Return the mounts (if any) - if (mount_count > 0 && mounts) { - *mounts = (ntfs_md*)ntfs_alloc(sizeof(ntfs_md) * mount_count); - if (*mounts) { + if (mount_count > 0 && mounts) + { + *mounts = (ntfs_md*) ntfs_alloc(sizeof(ntfs_md) * mount_count); + if (*mounts) + { memcpy(*mounts, &mount_points, sizeof(ntfs_md) * mount_count); return mount_count; } @@ -411,13 +451,15 @@ 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) { + if (!name || !interface) + { errno = EINVAL; return false; } @@ -426,20 +468,23 @@ bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSe ntfsInit(); // Check that the requested mount name is free - if (ntfsGetDevice(name, false)) { + if (ntfsGetDevice(name, false)) + { errno = EADDRINUSE; return false; } // Check that we can at least read from this device - if (!(interface->features & FEATURE_MEDIUM_CANREAD)) { + if (!(interface->features & FEATURE_MEDIUM_CANREAD)) + { errno = EPERM; return false; } // Allocate the volume descriptor - vd = (ntfs_vd*)ntfs_alloc(sizeof(ntfs_vd)); - if (!vd) { + vd = (ntfs_vd*) ntfs_alloc(sizeof(ntfs_vd)); + if (!vd) + { errno = ENOMEM; return false; } @@ -456,8 +501,9 @@ bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSe vd->showSystemFiles = (flags & NTFS_SHOW_SYSTEM_FILES); // Allocate the device driver descriptor - fd = (gekko_fd*)ntfs_alloc(sizeof(gekko_fd)); - if (!fd) { + fd = (gekko_fd*) ntfs_alloc(sizeof(gekko_fd)); + if (!fd) + { ntfs_free(vd); errno = ENOMEM; return false; @@ -473,7 +519,8 @@ bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSe // Allocate the device driver vd->dev = ntfs_device_alloc(name, 0, &ntfs_device_gekko_io_ops, fd); - if (!vd->dev) { + if (!vd->dev) + { ntfs_free(fd); ntfs_free(vd); return false; @@ -481,49 +528,59 @@ bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSe // Build the mount flags if (flags & NTFS_READ_ONLY) - vd->flags |= MS_RDONLY; + 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 (!(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 (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); + 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; + 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; } ntfs_device_free(vd->dev); ntfs_free(vd); return false; } - if (flags & NTFS_IGNORE_CASE) - ntfs_set_ignore_case(vd->vol); + if (flags & NTFS_IGNORE_CASE) ntfs_set_ignore_case(vd->vol); // Initialise the volume descriptor - if (ntfsInitVolume(vd)) { + if (ntfsInitVolume(vd)) + { ntfs_umount(vd->vol, true); ntfs_free(vd); return false; } // Add the device to the devoptab table - if (ntfsAddDevice(name, vd)) { + if (ntfsAddDevice(name, vd)) + { ntfsDeinitVolume(vd); ntfs_umount(vd->vol, true); ntfs_free(vd); @@ -533,14 +590,13 @@ bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSe 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; + if (!vd) return; // Remove the device from the devoptab table ntfsRemoveDevice(name); @@ -557,7 +613,7 @@ void ntfsUnmount (const char *name, bool force) return; } -const char *ntfsGetVolumeName (const char *name) +const char *ntfsGetVolumeName(const char *name) { ntfs_vd *vd = NULL; //ntfs_attr *na = NULL; @@ -565,79 +621,81 @@ const char *ntfsGetVolumeName (const char *name) //char *volumeName = NULL; // Sanity check - if (!name) { + if (!name) + { errno = EINVAL; return NULL; } // Get the devices volume descriptor vd = ntfsGetVolume(name); - if (!vd) { + if (!vd) + { errno = ENODEV; 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; + // If the volume name has already been cached then just use that + if (vd->name[0]) + return vd->name; - // Lock - ntfsLock(vd); + // 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; - } + // 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; - } + // 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; - } + // 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; - } + // 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); + // 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); + // Close the volume name attribute + if (na) + ntfs_attr_close(na); - // Clean up - ntfs_free(volumeName); - ntfs_free(ulabel); + // Clean up + ntfs_free(volumeName); + ntfs_free(ulabel); - // Unlock - ntfsUnlock(vd); + // Unlock + ntfsUnlock(vd); - return vd->name; -*/ + 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; @@ -645,14 +703,16 @@ bool ntfsSetVolumeName (const char *name, const char *volumeName) int ulabel_len; // Sanity check - if (!name) { + if (!name) + { errno = EINVAL; return false; } // Get the devices volume descriptor vd = ntfsGetVolume(name); - if (!vd) { + if (!vd) + { errno = ENODEV; return false; } @@ -662,7 +722,8 @@ bool ntfsSetVolumeName (const char *name, const char *volumeName) // Convert the new volume name to unicode ulabel_len = ntfsLocalToUnicode(volumeName, &ulabel) * sizeof(ntfschar); - if (ulabel_len < 0) { + if (ulabel_len < 0) + { ntfsUnlock(vd); errno = EINVAL; return false; @@ -670,26 +731,32 @@ bool ntfsSetVolumeName (const char *name, const char *volumeName) // Check if the volume name attribute exists na = ntfs_attr_open(vd->vol->vol_ni, AT_VOLUME_NAME, NULL, 0); - if (na) { + if (na) + { // It does, resize it to match the length of the new volume name - if (ntfs_attr_truncate(na, ulabel_len)) { + 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) { + if (ntfs_attr_pwrite(na, 0, ulabel_len, ulabel) != ulabel_len) + { ntfs_free(ulabel); ntfsUnlock(vd); return false; } - } else { + } + else + { // It doesn't, create it now - if (ntfs_attr_add(vd->vol->vol_ni, AT_VOLUME_NAME, NULL, 0, (u8*)ulabel, ulabel_len)) { + if (ntfs_attr_add(vd->vol->vol_ni, AT_VOLUME_NAME, NULL, 0, (u8*) ulabel, ulabel_len)) + { ntfs_free(ulabel); ntfsUnlock(vd); return false; @@ -701,11 +768,11 @@ bool ntfsSetVolumeName (const char *name, const char *volumeName) vd->name[0] = '\0'; // Close the volume name attribute - if (na) - ntfs_attr_close(na); + if (na) ntfs_attr_close(na); // Sync the volume node - if (ntfs_inode_sync(vd->vol->vol_ni)) { + if (ntfs_inode_sync(vd->vol->vol_ni)) + { ntfs_free(ulabel); ntfsUnlock(vd); return false; @@ -720,7 +787,7 @@ bool ntfsSetVolumeName (const char *name, const char *volumeName) 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 e26af8ce..6260416c 100644 --- a/source/libntfs/ntfs.h +++ b/source/libntfs/ntfs.h @@ -23,24 +23,25 @@ #define _LIBNTFS_H #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #include #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 */ @@ -52,96 +53,98 @@ 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); -typedef int ( *_ntfs_frag_append_t )( void *ff, u32 offset, u32 sector, u32 count ); -int _NTFS_get_fragments ( const char *path, _ntfs_frag_append_t append_fragment, void *callback_data ); + typedef int (*_ntfs_frag_append_t)(void *ff, u32 offset, u32 sector, u32 count); + int _NTFS_get_fragments(const char *path, _ntfs_frag_append_t append_fragment, void *callback_data); #ifdef __cplusplus } diff --git a/source/libntfs/ntfsdir.c b/source/libntfs/ntfsdir.c index ad54b514..e587714a 100644 --- a/source/libntfs/ntfsdir.c +++ b/source/libntfs/ntfsdir.c @@ -47,14 +47,14 @@ #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; + if (!dir || !dir->vd) return; // Free the directory entries (if any) - while (dir->first) { + while (dir->first) + { ntfs_dir_entry *next = dir->first->next; ntfs_free(dir->first->name); ntfs_free(dir->first); @@ -62,8 +62,7 @@ void ntfsCloseDir (ntfs_dir_state *dir) } // Close the directory (if open) - if (dir->ni) - ntfsCloseEntry(dir->vd, dir->ni); + if (dir->ni) ntfsCloseEntry(dir->vd, dir->ni); // Reset the directory state dir->ni = NULL; @@ -73,11 +72,10 @@ 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; + if (!st || !path) return 0; ntfs_log_trace("path %s, st %p\n", path, st); @@ -86,12 +84,13 @@ int ntfs_stat_r (struct _reent *r, const char *path, struct stat *st) // Get the volume descriptor for this path vd = ntfsGetVolume(path); - if (!vd) { + if (!vd) + { r->_errno = ENODEV; 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; @@ -103,7 +102,8 @@ int ntfs_stat_r (struct _reent *r, const char *path, struct stat *st) // Find the entry ni = ntfsOpenEntry(vd, path); - if (!ni) { + if (!ni) + { r->_errno = errno; ntfsUnlock(vd); return -1; @@ -111,8 +111,7 @@ int ntfs_stat_r (struct _reent *r, const char *path, struct stat *st) // Get the entry stats int ret = ntfsStat(vd, ni, st); - if (ret) - r->_errno = errno; + if (ret) r->_errno = errno; // Close the entry ntfsCloseEntry(vd, ni); @@ -122,7 +121,7 @@ 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); @@ -131,7 +130,8 @@ int ntfs_link_r (struct _reent *r, const char *existing, const char *newLink) // Get the volume descriptor for this path vd = ntfsGetVolume(existing); - if (!vd) { + if (!vd) + { r->_errno = ENODEV; return -1; } @@ -141,7 +141,8 @@ int ntfs_link_r (struct _reent *r, const char *existing, const char *newLink) // Create a symbolic link between the two paths ni = ntfsCreate(vd, existing, S_IFLNK, newLink); - if (!ni) { + if (!ni) + { ntfsUnlock(vd); r->_errno = errno; return -1; @@ -156,19 +157,18 @@ 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 int ret = ntfsUnlink(ntfsGetVolume(name), name); - if (ret) - r->_errno = errno; + if (ret) r->_errno = errno; 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); @@ -177,7 +177,8 @@ int ntfs_chdir_r (struct _reent *r, const char *name) // Get the volume descriptor for this path vd = ntfsGetVolume(name); - if (!vd) { + if (!vd) + { r->_errno = ENODEV; return -1; } @@ -187,14 +188,16 @@ int ntfs_chdir_r (struct _reent *r, const char *name) // Find the directory ni = ntfsOpenEntry(vd, name); - if (!ni) { + if (!ni) + { ntfsUnlock(vd); r->_errno = ENOENT; return -1; } // Ensure that this directory is indeed a directory - if (!(ni->mrec->flags && MFT_RECORD_IS_DIRECTORY)) { + if (!(ni->mrec->flags && MFT_RECORD_IS_DIRECTORY)) + { ntfsCloseEntry(vd, ni); ntfsUnlock(vd); r->_errno = ENOTDIR; @@ -202,8 +205,7 @@ int ntfs_chdir_r (struct _reent *r, const char *name) } // Close the old current directory (if any) - if (vd->cwd_ni) - ntfsCloseEntry(vd, vd->cwd_ni); + if (vd->cwd_ni) ntfsCloseEntry(vd, vd->cwd_ni); // Set the new current directory vd->cwd_ni = ni; @@ -214,7 +216,7 @@ 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); @@ -223,7 +225,8 @@ int ntfs_rename_r (struct _reent *r, const char *oldName, const char *newName) // Get the volume descriptor for this path vd = ntfsGetVolume(oldName); - if (!vd) { + if (!vd) + { r->_errno = ENODEV; return -1; } @@ -232,7 +235,8 @@ 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; @@ -240,7 +244,8 @@ int ntfs_rename_r (struct _reent *r, const char *oldName, const char *newName) // Check that there is no existing entry with the new name ni = ntfsOpenEntry(vd, newName); - if (ni) { + if (ni) + { ntfsCloseEntry(vd, ni); ntfsUnlock(vd); r->_errno = EEXIST; @@ -248,14 +253,17 @@ int ntfs_rename_r (struct _reent *r, const char *oldName, const char *newName) } // Link the old entry with the new one - if (ntfsLink(vd, oldName, newName)) { + if (ntfsLink(vd, oldName, newName)) + { ntfsUnlock(vd); return -1; } // Unlink the old entry - if (ntfsUnlink(vd, oldName)) { - if (ntfsUnlink(vd, newName)) { + if (ntfsUnlink(vd, oldName)) + { + if (ntfsUnlink(vd, newName)) + { ntfsUnlock(vd); return -1; } @@ -269,7 +277,7 @@ 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); @@ -278,7 +286,8 @@ int ntfs_mkdir_r (struct _reent *r, const char *path, int mode) // Get the volume descriptor for this path vd = ntfsGetVolume(path); - if (!vd) { + if (!vd) + { r->_errno = ENODEV; return -1; } @@ -288,7 +297,8 @@ int ntfs_mkdir_r (struct _reent *r, const char *path, int mode) // Create the directory ni = ntfsCreate(vd, path, S_IFDIR, NULL); - if (!ni) { + if (!ni) + { ntfsUnlock(vd); r->_errno = errno; return -1; @@ -303,7 +313,7 @@ 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); @@ -313,14 +323,14 @@ int ntfs_statvfs_r (struct _reent *r, const char *path, struct statvfs *buf) // Get the volume descriptor for this path vd = ntfsGetVolume(path); - if (!vd) { + if (!vd) + { r->_errno = ENODEV; return -1; } // Short circuit cases were we don't actually have to do anything - if (!buf) - return 0; + if (!buf) return 0; // Lock ntfsLock(vd); @@ -328,7 +338,7 @@ 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) + if (ntfs_volume_get_free_space(vd->vol) < 0) { ntfsUnlock(vd); return -1; @@ -351,8 +361,7 @@ int ntfs_statvfs_r (struct _reent *r, const char *path, struct statvfs *buf) delta_bits = vd->vol->cluster_size_bits - vd->vol->mft_record_size_bits; if (delta_bits >= 0) size <<= delta_bits; - else - size >>= -delta_bits; + else size >>= -delta_bits; // Number of inodes at this point in time buf->f_files = (vd->vol->mftbmp_na->allocated_size << 3) + size; @@ -379,49 +388,53 @@ 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) +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) { ntfs_dir_state *dir = STATE(dirState); ntfs_dir_entry *entry = NULL; char *entry_name = NULL; // Sanity check - if (!dir || !dir->vd) { + if (!dir || !dir->vd) + { errno = EINVAL; return -1; } // Ignore DOS file names - if (name_type == FILE_NAME_DOS) { + if (name_type == FILE_NAME_DOS) + { return 0; } // Preliminary check that this entry can be enumerated (as described by the volume descriptor) - if (MREF(mref) == FILE_root || MREF(mref) >= FILE_first_user || dir->vd->showSystemFiles) { + if (MREF(mref) == FILE_root || MREF(mref) >= FILE_first_user || dir->vd->showSystemFiles) + { // Convert the entry name to our current local - if (ntfsUnicodeToLocal(name, name_len, &entry_name, 0) < 0) { + if (ntfsUnicodeToLocal(name, name_len, &entry_name, 0) < 0) + { return -1; } - if(dir->first && dir->first->mref == FILE_root && - MREF(mref) == FILE_root && strcmp(entry_name, "..") == 0) + if (dir->first && dir->first->mref == FILE_root && MREF(mref) == FILE_root && strcmp(entry_name, "..") == 0) { return 0; } // If this is not the parent or self directory reference - if ((strcmp(entry_name, ".") != 0) && (strcmp(entry_name, "..") != 0)) { + if ((strcmp(entry_name, ".") != 0) && (strcmp(entry_name, "..") != 0)) + { // Open the entry ntfs_inode *ni = ntfs_pathname_to_inode(dir->vd->vol, dir->ni, entry_name); - if (!ni) - return -1; + if (!ni) return -1; // 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)) { + if (((ni->flags & FILE_ATTR_HIDDEN) && !dir->vd->showHiddenFiles) || ((ni->flags & FILE_ATTR_SYSTEM) + && !dir->vd->showSystemFiles)) + { ntfs_inode_close(ni); return 0; } @@ -433,8 +446,7 @@ int ntfs_readdir_filler (DIR_ITER *dirState, const ntfschar *name, const int nam // Allocate a new directory entry entry = (ntfs_dir_entry *) ntfs_alloc(sizeof(ntfs_dir_entry)); - if (!entry) - return -1; + if (!entry) return -1; // Setup the entry entry->name = entry_name; @@ -442,11 +454,15 @@ int ntfs_readdir_filler (DIR_ITER *dirState, const ntfschar *name, const int nam entry->mref = MREF(mref); // Link the entry to the directory - if (!dir->first) { + if (!dir->first) + { dir->first = entry; - } else { + } + else + { ntfs_dir_entry *last = dir->first; - while (last->next) last = last->next; + while (last->next) + last = last->next; last->next = entry; } @@ -455,7 +471,7 @@ 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); @@ -464,7 +480,8 @@ DIR_ITER *ntfs_diropen_r (struct _reent *r, DIR_ITER *dirState, const char *path // Get the volume descriptor for this path dir->vd = ntfsGetVolume(path); - if (!dir->vd) { + if (!dir->vd) + { r->_errno = ENODEV; return NULL; } @@ -474,14 +491,16 @@ DIR_ITER *ntfs_diropen_r (struct _reent *r, DIR_ITER *dirState, const char *path // Find the directory dir->ni = ntfsOpenEntry(dir->vd, path); - if (!dir->ni) { + if (!dir->ni) + { ntfsUnlock(dir->vd); r->_errno = ENOENT; return NULL; } // Ensure that this directory is indeed a directory - if (!(dir->ni->mrec->flags && MFT_RECORD_IS_DIRECTORY)) { + if (!(dir->ni->mrec->flags && MFT_RECORD_IS_DIRECTORY)) + { ntfsCloseEntry(dir->vd, dir->ni); ntfsUnlock(dir->vd); r->_errno = ENOTDIR; @@ -490,7 +509,8 @@ DIR_ITER *ntfs_diropen_r (struct _reent *r, DIR_ITER *dirState, const char *path // Read the directory dir->first = dir->current = NULL; - if (ntfs_readdir(dir->ni, &position, dirState, (ntfs_filldir_t)ntfs_readdir_filler)) { + if (ntfs_readdir(dir->ni, &position, dirState, (ntfs_filldir_t) ntfs_readdir_filler)) + { ntfsCloseDir(dir); ntfsUnlock(dir->vd); r->_errno = errno; @@ -504,10 +524,13 @@ DIR_ITER *ntfs_diropen_r (struct _reent *r, DIR_ITER *dirState, const char *path ntfsUpdateTimes(dir->vd, dir->ni, NTFS_UPDATE_ATIME); // Insert the directory into the double-linked FILO list of open directories - if (dir->vd->firstOpenDir) { + if (dir->vd->firstOpenDir) + { dir->nextOpenDir = dir->vd->firstOpenDir; dir->vd->firstOpenDir->prevOpenDir = dir; - } else { + } + else + { dir->nextOpenDir = NULL; } dir->prevOpenDir = NULL; @@ -521,14 +544,15 @@ 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); // Sanity check - if (!dir || !dir->vd || !dir->ni) { + if (!dir || !dir->vd || !dir->ni) + { r->_errno = EBADF; return -1; } @@ -548,7 +572,7 @@ 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); @@ -556,7 +580,8 @@ int ntfs_dirnext_r (struct _reent *r, DIR_ITER *dirState, char *filename, struct ntfs_inode *ni = NULL; // Sanity check - if (!dir || !dir->vd || !dir->ni) { + if (!dir || !dir->vd || !dir->ni) + { r->_errno = EBADF; return -1; } @@ -565,7 +590,8 @@ int ntfs_dirnext_r (struct _reent *r, DIR_ITER *dirState, char *filename, struct ntfsLock(dir->vd); // Check that there is a entry waiting to be fetched - if (!dir->current) { + if (!dir->current) + { ntfsUnlock(dir->vd); r->_errno = ENOENT; return -1; @@ -573,9 +599,9 @@ 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 (filestat != NULL) { - if(strcmp(dir->current->name, ".") == 0 || strcmp(dir->current->name, "..") == 0) + if (strcmp(dir->current->name, ".") == 0 || strcmp(dir->current->name, "..") == 0) { memset(filestat, 0, sizeof(struct stat)); filestat->st_mode = S_IFDIR; @@ -583,7 +609,8 @@ int ntfs_dirnext_r (struct _reent *r, DIR_ITER *dirState, char *filename, struct else { ni = ntfsOpenEntry(dir->vd, dir->current->name); - if (ni) { + if (ni) + { ntfsStat(dir->vd, ni, filestat); ntfsCloseEntry(dir->vd, ni); } @@ -602,14 +629,15 @@ 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); // Sanity check - if (!dir || !dir->vd) { + if (!dir || !dir->vd) + { r->_errno = EBADF; return -1; } @@ -622,12 +650,10 @@ int ntfs_dirclose_r (struct _reent *r, DIR_ITER *dirState) // Remove the directory from the double-linked FILO list of open directories dir->vd->openDirCount--; - if (dir->nextOpenDir) - dir->nextOpenDir->prevOpenDir = dir->prevOpenDir; + if (dir->nextOpenDir) dir->nextOpenDir->prevOpenDir = dir->prevOpenDir; if (dir->prevOpenDir) dir->prevOpenDir->nextOpenDir = dir->nextOpenDir; - else - dir->vd->firstOpenDir = dir->nextOpenDir; + else dir->vd->firstOpenDir = dir->nextOpenDir; // Unlock ntfsUnlock(dir->vd); diff --git a/source/libntfs/ntfsdir.h b/source/libntfs/ntfsdir.h index 0550592f..d2b920d1 100644 --- a/source/libntfs/ntfsdir.h +++ b/source/libntfs/ntfsdir.h @@ -28,41 +28,43 @@ /** * ntfs_dir_entry - Directory entry */ -typedef struct _ntfs_dir_entry { - char *name; - u64 mref; - struct _ntfs_dir_entry *next; +typedef struct _ntfs_dir_entry +{ + char *name; + u64 mref; + struct _ntfs_dir_entry *next; } ntfs_dir_entry; /** * ntfs_dir_state - Directory state */ -typedef struct _ntfs_dir_state { - ntfs_vd *vd; /* Volume this directory belongs to */ - ntfs_inode *ni; /* Directory descriptor */ - ntfs_dir_entry *first; /* The first entry in the directory */ - ntfs_dir_entry *current; /* The current entry in the directory */ - struct _ntfs_dir_state *prevOpenDir; /* The previous entry in a double-linked FILO list of open directories */ - struct _ntfs_dir_state *nextOpenDir; /* The next entry in a double-linked FILO list of open directories */ +typedef struct _ntfs_dir_state +{ + ntfs_vd *vd; /* Volume this directory belongs to */ + ntfs_inode *ni; /* Directory descriptor */ + ntfs_dir_entry *first; /* The first entry in the directory */ + ntfs_dir_entry *current; /* The current entry in the directory */ + struct _ntfs_dir_state *prevOpenDir; /* The previous entry in a double-linked FILO list of open directories */ + struct _ntfs_dir_state *nextOpenDir; /* The next entry in a double-linked FILO list of open directories */ } ntfs_dir_state; /* Directory state routines */ -void ntfsCloseDir (ntfs_dir_state *file); +void ntfsCloseDir(ntfs_dir_state *file); /* Gekko devoptab directory routines for NTFS-based devices */ -extern int ntfs_stat_r (struct _reent *r, const char *path, struct stat *st); -extern int ntfs_link_r (struct _reent *r, const char *existing, const char *newLink); -extern int ntfs_unlink_r (struct _reent *r, const char *name); -extern int ntfs_chdir_r (struct _reent *r, const char *name); -extern int ntfs_rename_r (struct _reent *r, const char *oldName, const char *newName); -extern int ntfs_mkdir_r (struct _reent *r, const char *path, int mode); -extern int ntfs_statvfs_r (struct _reent *r, const char *path, struct statvfs *buf); +extern int ntfs_stat_r(struct _reent *r, const char *path, struct stat *st); +extern int ntfs_link_r(struct _reent *r, const char *existing, const char *newLink); +extern int ntfs_unlink_r(struct _reent *r, const char *name); +extern int ntfs_chdir_r(struct _reent *r, const char *name); +extern int ntfs_rename_r(struct _reent *r, const char *oldName, const char *newName); +extern int ntfs_mkdir_r(struct _reent *r, const char *path, int mode); +extern int ntfs_statvfs_r(struct _reent *r, const char *path, struct statvfs *buf); /* Gekko devoptab directory walking routines for NTFS-based devices */ -extern DIR_ITER *ntfs_diropen_r (struct _reent *r, DIR_ITER *dirState, const char *path); -extern int ntfs_dirreset_r (struct _reent *r, DIR_ITER *dirState); -extern int ntfs_dirnext_r (struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *filestat); -extern int ntfs_dirclose_r (struct _reent *r, DIR_ITER *dirState); +extern DIR_ITER *ntfs_diropen_r(struct _reent *r, DIR_ITER *dirState, const char *path); +extern int ntfs_dirreset_r(struct _reent *r, DIR_ITER *dirState); +extern int ntfs_dirnext_r(struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *filestat); +extern int ntfs_dirclose_r(struct _reent *r, DIR_ITER *dirState); #endif /* _NTFSDIR_H */ diff --git a/source/libntfs/ntfsfile.c b/source/libntfs/ntfsfile.c index 84aa5372..b050003e 100644 --- a/source/libntfs/ntfsfile.c +++ b/source/libntfs/ntfsfile.c @@ -45,36 +45,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; + if (!file || !file->vd) return; // Special case fix ups for compressed and/or encrypted files - if (file->compressed) - ntfs_attr_pclose(file->data_na); + if (file->compressed) ntfs_attr_pclose(file->data_na); #ifdef HAVE_SETXATTR if (file->encrypted) - ntfs_efs_fixup_attribute(NULL, file->data_na); + ntfs_efs_fixup_attribute(NULL, file->data_na); #endif // Close the file data attribute (if open) - if (file->data_na) - ntfs_attr_close(file->data_na); + if (file->data_na) ntfs_attr_close(file->data_na); // Sync the file (and its attributes) to disc - if(file->write) + if (file->write) { ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_ATIME | NTFS_UPDATE_CTIME); ntfsSync(file->vd, file->ni); } - if (file->read) - ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_ATIME); + if (file->read) ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_ATIME); // Close the file (if open) - if (file->ni) - ntfsCloseEntry(file->vd, file->ni); + if (file->ni) ntfsCloseEntry(file->vd, file->ni); // Reset the file state file->ni = NULL; @@ -89,7 +84,7 @@ 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); @@ -97,7 +92,8 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags // Get the volume descriptor for this path file->vd = ntfsGetVolume(path); - if (!file->vd) { + if (!file->vd) + { r->_errno = ENODEV; return -1; } @@ -107,19 +103,26 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags // Determine which mode the file is opened for file->flags = flags; - if ((flags & 0x03) == O_RDONLY) { + if ((flags & 0x03) == O_RDONLY) + { file->read = true; file->write = false; file->append = false; - } else if ((flags & 0x03) == O_WRONLY) { + } + else if ((flags & 0x03) == O_WRONLY) + { file->read = false; file->write = true; file->append = (flags & O_APPEND); - } else if ((flags & 0x03) == O_RDWR) { + } + else if ((flags & 0x03) == O_RDWR) + { file->read = true; file->write = true; file->append = (flags & O_APPEND); - } else { + } + else + { r->_errno = EACCES; ntfsUnlock(file->vd); return -1; @@ -127,7 +130,8 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags // 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)) { + if (file->ni && (file->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) + { ntfsCloseEntry(file->vd, file->ni); ntfsUnlock(file->vd); r->_errno = EISDIR; @@ -135,11 +139,13 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags } // Are we creating this file? - if ((flags & O_CREAT) && !file->ni) { + if ((flags & O_CREAT) && !file->ni) + { // Create the file file->ni = ntfsCreate(file->vd, path, S_IFREG, NULL); - if (!file->ni) { + if (!file->ni) + { ntfsUnlock(file->vd); return -1; } @@ -147,7 +153,8 @@ 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) { + if (!file->ni) + { ntfsUnlock(file->vd); r->_errno = ENOENT; return -1; @@ -155,7 +162,8 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags // 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; @@ -166,7 +174,8 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags file->encrypted = NAttrEncrypted(file->data_na) || (file->ni->flags & FILE_ATTR_ENCRYPTED); // We cannot read/write encrypted files - if (file->encrypted) { + if (file->encrypted) + { ntfs_attr_close(file->data_na); ntfsCloseEntry(file->vd, file->ni); ntfsUnlock(file->vd); @@ -175,7 +184,8 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags } // Make sure we aren't trying to write to a read-only file - if ((file->ni->flags & FILE_ATTR_READONLY) && file->write) { + if ((file->ni->flags & FILE_ATTR_READONLY) && file->write) + { ntfs_attr_close(file->data_na); ntfsCloseEntry(file->vd, file->ni); ntfsUnlock(file->vd); @@ -184,8 +194,10 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags } // Truncate the file if requested - if ((flags & O_TRUNC) && file->write) { - if (ntfs_attr_truncate(file->data_na, 0)) { + if ((flags & O_TRUNC) && file->write) + { + if (ntfs_attr_truncate(file->data_na, 0)) + { ntfs_attr_close(file->data_na); ntfsCloseEntry(file->vd, file->ni); ntfsUnlock(file->vd); @@ -204,10 +216,13 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_ATIME); // Insert the file into the double-linked FILO list of open files - if (file->vd->firstOpenFile) { + if (file->vd->firstOpenFile) + { file->nextOpenFile = file->vd->firstOpenFile; file->vd->firstOpenFile->prevOpenFile = file; - } else { + } + else + { file->nextOpenFile = NULL; } file->prevOpenFile = NULL; @@ -217,17 +232,18 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags // Unlock ntfsUnlock(file->vd); - return (int)fileStruct; + 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) { + if (!file || !file->vd) + { r->_errno = EBADF; return -1; } @@ -240,12 +256,10 @@ int ntfs_close_r (struct _reent *r, int fd) // Remove the file from the double-linked FILO list of open files file->vd->openFileCount--; - if (file->nextOpenFile) - file->nextOpenFile->prevOpenFile = file->prevOpenFile; + if (file->nextOpenFile) file->nextOpenFile->prevOpenFile = file->prevOpenFile; if (file->prevOpenFile) file->prevOpenFile->nextOpenFile = file->nextOpenFile; - else - file->vd->firstOpenFile = file->nextOpenFile; + else file->vd->firstOpenFile = file->nextOpenFile; // Unlock ntfsUnlock(file->vd); @@ -253,7 +267,7 @@ int ntfs_close_r (struct _reent *r, int fd) 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); @@ -262,13 +276,15 @@ ssize_t ntfs_write_r (struct _reent *r, int fd, const char *ptr, size_t len) off_t old_pos = 0; // Sanity check - if (!file || !file->vd || !file->ni || !file->data_na) { + 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) { + if (!ptr || len <= 0) + { return 0; } @@ -276,22 +292,26 @@ ssize_t ntfs_write_r (struct _reent *r, int fd, const char *ptr, size_t len) ntfsLock(file->vd); // Check that we are allowed to write to this file - if (!file->write) { + 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) { + if (file->append) + { old_pos = file->pos; file->pos = file->len; } // Write to the files data atrribute - while (len) { + while (len) + { ssize_t ret = ntfs_attr_pwrite(file->data_na, file->pos, len, ptr); - if (ret <= 0) { + if (ret <= 0) + { ntfsUnlock(file->vd); r->_errno = errno; return -1; @@ -302,13 +322,13 @@ ssize_t ntfs_write_r (struct _reent *r, int fd, const char *ptr, size_t len) } // If we are in append mode, restore the current position to were it was prior to this write - if (file->append) { + 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; + if (written) file->ni->flags |= FILE_ATTR_ARCHIVE; // Update the files data length file->len = file->data_na->data_size; @@ -319,7 +339,7 @@ ssize_t ntfs_write_r (struct _reent *r, int fd, const char *ptr, size_t len) 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); @@ -327,13 +347,15 @@ ssize_t ntfs_read_r (struct _reent *r, int fd, char *ptr, size_t len) ssize_t read = 0; // Sanity check - if (!file || !file->vd || !file->ni || !file->data_na) { + 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) { + if (!ptr || len <= 0) + { return 0; } @@ -341,25 +363,29 @@ ssize_t ntfs_read_r (struct _reent *r, int fd, char *ptr, size_t len) ntfsLock(file->vd); // Check that we are allowed to read from this file - if (!file->read) { + 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) { + if (file->pos + len > file->len) + { r->_errno = EOVERFLOW; len = file->len - file->pos; 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) { + while (len) + { ssize_t ret = ntfs_attr_pread(file->data_na, file->pos, len, ptr); - if (ret <= 0 || ret > len) { + if (ret <= 0 || ret > len) + { ntfsUnlock(file->vd); r->_errno = errno; return -1; @@ -378,7 +404,7 @@ ssize_t ntfs_read_r (struct _reent *r, int fd, char *ptr, size_t len) 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); @@ -386,7 +412,8 @@ off_t ntfs_seek_r (struct _reent *r, int fd, off_t pos, int dir) off_t position = 0; // Sanity check - if (!file || !file->vd || !file->ni || !file->data_na) { + if (!file || !file->vd || !file->ni || !file->data_na) + { r->_errno = EINVAL; return -1; } @@ -395,10 +422,17 @@ off_t ntfs_seek_r (struct _reent *r, int fd, off_t pos, int dir) 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 @@ -406,7 +440,7 @@ off_t ntfs_seek_r (struct _reent *r, int fd, off_t pos, int dir) 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); @@ -414,31 +448,31 @@ int ntfs_fstat_r (struct _reent *r, int fd, struct stat *st) int ret = 0; // Sanity check - if (!file || !file->vd || !file->ni || !file->data_na) { + 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; + if (!st) return 0; // Get the file stats ret = ntfsStat(file->vd, file->ni, st); - if (ret) - r->_errno = errno; + 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) { + if (!file || !file->vd || !file->ni || !file->data_na) + { r->_errno = EINVAL; return -1; } @@ -447,31 +481,36 @@ int ntfs_ftruncate_r (struct _reent *r, int fd, off_t len) ntfsLock(file->vd); // Check that we are allowed to write to this file - if (!file->write) { + 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) { + if (file->compressed && len > 0 && len < file->data_na->initialized_size) + { ntfsUnlock(file->vd); r->_errno = EOPNOTSUPP; return -1; } // Resize the files data attribute, either by expanding or truncating - if (file->compressed && len > file->data_na->initialized_size) { + if (file->compressed && len > file->data_na->initialized_size) + { char zero = 0; - if (ntfs_attr_pwrite(file->data_na, len - 1, 1, &zero) <= 0) { + if (ntfs_attr_pwrite(file->data_na, len - 1, 1, &zero) <= 0) + { ntfsUnlock(file->vd); r->_errno = errno; return -1; } - } else { - if (ntfs_attr_truncate(file->data_na, len)) { + } + else + { + if (ntfs_attr_truncate(file->data_na, len)) + { ntfsUnlock(file->vd); r->_errno = errno; return -1; @@ -479,12 +518,10 @@ 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; + 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_AMCTIME); + if (file->len != file->data_na->data_size) ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_AMCTIME); // Update the files data length file->len = file->data_na->data_size; @@ -498,7 +535,7 @@ int ntfs_ftruncate_r (struct _reent *r, int fd, off_t len) 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); @@ -506,7 +543,8 @@ int ntfs_fsync_r (struct _reent *r, int fd) int ret = 0; // Sanity check - if (!file || !file->vd || !file->ni || !file->data_na) { + if (!file || !file->vd || !file->ni || !file->data_na) + { r->_errno = EINVAL; return -1; } @@ -516,8 +554,7 @@ int ntfs_fsync_r (struct _reent *r, int fd) // Sync the file (and its attributes) to disc ret = ntfsSync(file->vd, file->ni); - if (ret) - r->_errno = errno; + if (ret) r->_errno = errno; // Unlock ntfsUnlock(file->vd); diff --git a/source/libntfs/ntfsfile.h b/source/libntfs/ntfsfile.h index 8e5ffcc6..8ef3fc72 100644 --- a/source/libntfs/ntfsfile.h +++ b/source/libntfs/ntfsfile.h @@ -32,34 +32,35 @@ /** * ntfs_file_state - File state */ -typedef struct _ntfs_file_state { - ntfs_vd *vd; /* Volume this file belongs to */ - ntfs_inode *ni; /* File descriptor */ - ntfs_attr *data_na; /* File data descriptor */ - int flags; /* Opening flags */ - bool read; /* True if allowed to read from file */ - bool write; /* True if allowed to write to file */ - bool append; /* True if allowed to append to file */ - bool compressed; /* True if file data is compressed */ - bool encrypted; /* True if file data is encryted */ - off_t pos; /* Current position within the file (in bytes) */ - u64 len; /* Total length of the file (in bytes) */ - struct _ntfs_file_state *prevOpenFile; /* The previous entry in a double-linked FILO list of open files */ - struct _ntfs_file_state *nextOpenFile; /* The next entry in a double-linked FILO list of open files */ +typedef struct _ntfs_file_state +{ + ntfs_vd *vd; /* Volume this file belongs to */ + ntfs_inode *ni; /* File descriptor */ + ntfs_attr *data_na; /* File data descriptor */ + int flags; /* Opening flags */ + bool read; /* True if allowed to read from file */ + bool write; /* True if allowed to write to file */ + bool append; /* True if allowed to append to file */ + bool compressed; /* True if file data is compressed */ + bool encrypted; /* True if file data is encryted */ + off_t pos; /* Current position within the file (in bytes) */ + u64 len; /* Total length of the file (in bytes) */ + struct _ntfs_file_state *prevOpenFile; /* The previous entry in a double-linked FILO list of open files */ + struct _ntfs_file_state *nextOpenFile; /* The next entry in a double-linked FILO list of open files */ } ntfs_file_state; /* File state routines */ -void ntfsCloseFile (ntfs_file_state *file); +void ntfsCloseFile(ntfs_file_state *file); /* Gekko devoptab file routines for NTFS-based devices */ -extern int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags, int mode); -extern int ntfs_close_r (struct _reent *r, int fd); -extern ssize_t ntfs_write_r (struct _reent *r, int fd, const char *ptr, size_t len); -extern ssize_t ntfs_read_r (struct _reent *r, int fd, char *ptr, size_t len); -extern off_t ntfs_seek_r (struct _reent *r, int fd, off_t pos, int dir); -extern int ntfs_fstat_r (struct _reent *r, int fd, struct stat *st); -extern int ntfs_ftruncate_r (struct _reent *r, int fd, off_t len); -extern int ntfs_fsync_r (struct _reent *r, int fd); +extern int ntfs_open_r(struct _reent *r, void *fileStruct, const char *path, int flags, int mode); +extern int ntfs_close_r(struct _reent *r, int fd); +extern ssize_t ntfs_write_r(struct _reent *r, int fd, const char *ptr, size_t len); +extern ssize_t ntfs_read_r(struct _reent *r, int fd, char *ptr, size_t len); +extern off_t ntfs_seek_r(struct _reent *r, int fd, off_t pos, int dir); +extern int ntfs_fstat_r(struct _reent *r, int fd, struct stat *st); +extern int ntfs_ftruncate_r(struct _reent *r, int fd, off_t len); +extern int ntfs_fsync_r(struct _reent *r, int fd); #endif /* _NTFSFILE_H */ diff --git a/source/libntfs/ntfsfile_frag.c b/source/libntfs/ntfsfile_frag.c index 4ebd6193..0c5f5e9c 100644 --- a/source/libntfs/ntfsfile_frag.c +++ b/source/libntfs/ntfsfile_frag.c @@ -54,18 +54,18 @@ void ntfsCloseFile ( ntfs_file_state *file ) { // Sanity check if ( !file || !file->vd ) - return; + 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 ); #ifdef HAVE_SETXATTR if ( file->encrypted ) - ntfs_efs_fixup_attribute( NULL, file->data_na ); + ntfs_efs_fixup_attribute( NULL, file->data_na ); #endif // Close the file data attribute (if open) if ( file->data_na ) - ntfs_attr_close( file->data_na ); + ntfs_attr_close( file->data_na ); // Sync the file (and its attributes) to disc if ( file->write ) @@ -75,11 +75,11 @@ void ntfsCloseFile ( ntfs_file_state *file ) } if ( file->read ) - ntfsUpdateTimes( file->vd, file->ni, NTFS_UPDATE_ATIME ); + ntfsUpdateTimes( file->vd, file->ni, NTFS_UPDATE_ATIME ); // Close the file (if open) if ( file->ni ) - ntfsCloseEntry( file->vd, file->ni ); + ntfsCloseEntry( file->vd, file->ni ); // Reset the file state file->ni = NULL; @@ -276,11 +276,11 @@ int ntfs_close_r ( struct _reent *r, int fd ) // Remove the file from the double-linked FILO list of open files file->vd->openFileCount--; if ( file->nextOpenFile ) - file->nextOpenFile->prevOpenFile = file->prevOpenFile; + file->nextOpenFile->prevOpenFile = file->prevOpenFile; if ( file->prevOpenFile ) - file->prevOpenFile->nextOpenFile = file->nextOpenFile; + file->prevOpenFile->nextOpenFile = file->nextOpenFile; else - file->vd->firstOpenFile = file->nextOpenFile; + file->vd->firstOpenFile = file->nextOpenFile; // Unlock ntfsUnlock( file->vd ); @@ -350,7 +350,7 @@ ssize_t ntfs_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) // Mark the file for archiving (if we actually wrote something) if ( written ) - file->ni->flags |= FILE_ATTR_ARCHIVE; + file->ni->flags |= FILE_ATTR_ARCHIVE; // Update the files data length file->len = file->data_na->data_size; @@ -363,11 +363,10 @@ ssize_t ntfs_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) #endif -s64 ntfs_attr_getfragments( ntfs_attr *na, const s64 pos, s64 count, u64 offset, - _ntfs_frag_append_t append_fragment, void *callback_data ); +s64 ntfs_attr_getfragments(ntfs_attr *na, const s64 pos, s64 count, u64 offset, _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 ) +int _NTFS_get_fragments(const char *path, _ntfs_frag_append_t append_fragment, void *callback_data) { struct _reent r; ntfs_file_state file_st, *file = &file_st; @@ -376,59 +375,54 @@ int _NTFS_get_fragments ( const char *path, // Open File r._errno = 0; - int fd = ntfs_open_r( &r, file, path, O_RDONLY, 0 ); - if ( fd != ( int )file ) return -12; - - - - + int fd = ntfs_open_r(&r, file, path, O_RDONLY, 0); + if (fd != (int) file) return -12; // Sanity check - if ( !file || !file->vd || !file->ni || !file->data_na ) + if (!file || !file->vd || !file->ni || !file->data_na) { //r->_errno = EINVAL; return -13; } /* - // Short circuit cases where we don't actually have to do anything - if (!ptr || len <= 0) { - return 0; - } - */ + // Short circuit cases where we don't actually have to do anything + if (!ptr || len <= 0) { + return 0; + } + */ // Lock - ntfsLock( file->vd ); + ntfsLock(file->vd); /* - // Check that we are allowed to read from this file - if (!file->read) { - ntfsUnlock(file->vd); - r->_errno = EACCES; - return -1; - } + // 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; - len = file->len - file->pos; - ntfs_log_trace("EOVERFLOW"); - } - */ + // Don't read past the end of file + if (file->pos + len > file->len) { + r->_errno = EOVERFLOW; + len = file->len - file->pos; + ntfs_log_trace("EOVERFLOW"); + } + */ u64 offset = 0; u64 len = file->len; // Read from the files data attribute - while ( len ) + while (len) { - s64 ret = ntfs_attr_getfragments( file->data_na, file->pos, - len, offset, append_fragment, callback_data ); - if ( ret <= 0 || ret > len ) + s64 ret = ntfs_attr_getfragments(file->data_na, file->pos, len, offset, append_fragment, callback_data); + if (ret <= 0 || ret > len) { - ntfsUnlock( file->vd ); + ntfsUnlock(file->vd); //r->_errno = errno; ret_val = -14; - if ( ret < 0 ) ret_val = ret; + if (ret < 0) ret_val = ret; goto out; } offset += ret; @@ -438,22 +432,22 @@ int _NTFS_get_fragments ( const char *path, } // set file size - append_fragment( callback_data, file->len >> 9, 0, 0 ); + append_fragment(callback_data, file->len >> 9, 0, 0); // success ret_val = 0; /* - //ntfs_log_trace("file->pos: %d \n", (u32)file->pos); - // Update file times (if we actually read something) - if (read) - ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_ATIME); - */ + //ntfs_log_trace("file->pos: %d \n", (u32)file->pos); + // Update file times (if we actually read something) + if (read) + ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_ATIME); + */ -out: + out: // Unlock - ntfsUnlock( file->vd ); + ntfsUnlock(file->vd); // Close the file - ntfs_close_r ( &r, fd ); + ntfs_close_r(&r, fd); return ret_val; } @@ -506,12 +500,12 @@ int ntfs_fstat_r ( struct _reent *r, int fd, struct stat *st ) // Short circuit cases were we don't actually have to do anything if ( !st ) - return 0; + return 0; // Get the file stats ret = ntfsStat( file->vd, file->ni, st ); if ( ret ) - r->_errno = errno; + r->_errno = errno; return ret; } @@ -573,11 +567,11 @@ 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; + 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_AMCTIME ); + ntfsUpdateTimes( file->vd, file->ni, NTFS_UPDATE_AMCTIME ); // Update the files data length file->len = file->data_na->data_size; @@ -611,7 +605,7 @@ int ntfs_fsync_r ( struct _reent *r, int fd ) // Sync the file (and its attributes) to disc ret = ntfsSync( file->vd, file->ni ); if ( ret ) - r->_errno = errno; + r->_errno = errno; // Unlock ntfsUnlock( file->vd ); diff --git a/source/libntfs/ntfsinternal.c b/source/libntfs/ntfsinternal.c index fed15bce..98d21429 100644 --- a/source/libntfs/ntfsinternal.c +++ b/source/libntfs/ntfsinternal.c @@ -43,26 +43,28 @@ #include #include -const INTERFACE_ID ntfs_disc_interfaces[] = { - { "sd", &__io_wiisd }, - { "usb", &__io_usbstorage }, - { "carda", &__io_gcsda }, - { "cardb", &__io_gcsdb }, - { NULL, NULL } +const INTERFACE_ID ntfs_disc_interfaces[] = +{ + { "sd", &__io_wiisd}, + { "usb", &__io_usbstorage}, + { "carda", &__io_gcsda}, + { "cardb", &__io_gcsdb}, + { NULL, NULL} }; #elif defined(__gamecube__) #include -const INTERFACE_ID ntfs_disc_interfaces[] = { - { "carda", &__io_gcsda }, - { "cardb", &__io_gcsdb }, - { NULL, NULL } +const INTERFACE_ID ntfs_disc_interfaces[] = +{ + { "carda", &__io_gcsda}, + { "cardb", &__io_gcsdb}, + { NULL, NULL} }; #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; @@ -70,20 +72,22 @@ int ntfsAddDevice (const char *name, void *deviceData) int i; // Sanity check - if (!name || !deviceData || !devoptab_ntfs) { + if (!name || !deviceData || !devoptab_ntfs) + { errno = EINVAL; return -1; } // Allocate a devoptab for this device dev = (devoptab_t *) ntfs_alloc(sizeof(devoptab_t) + strlen(name) + 1); - if (!dev) { + if (!dev) + { errno = ENOMEM; return false; } // Use the space allocated at the end of the devoptab for storing the device name - devname = (char*)(dev + 1); + devname = (char*) (dev + 1); strcpy(devname, name); // Setup the devoptab @@ -92,8 +96,10 @@ int ntfsAddDevice (const char *name, void *deviceData) dev->deviceData = deviceData; // Add the device to the devoptab table (if there is a free slot) - for (i = 0; i < STD_MAX; i++) { - if (devoptab_list[i] == devoptab_list[0] && i != 0) { + for (i = 0; i < STD_MAX; i++) + { + if (devoptab_list[i] == devoptab_list[0] && i != 0) + { devoptab_list[i] = dev; return 0; } @@ -104,10 +110,10 @@ 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}; + char name[128] = { 0 }; int i; // Get the device name from the path @@ -118,12 +124,15 @@ void ntfsRemoveDevice (const char *path) // NOTE: We do this manually due to a 'bug' in RemoveDevice // which ignores names with suffixes and causes names // like "ntfs" and "ntfs1" to be seen as equals - for (i = 0; i < STD_MAX; i++) { + for (i = 0; i < STD_MAX; i++) + { devoptab = devoptab_list[i]; - if (devoptab && devoptab->name) { - if (strcmp(name, devoptab->name) == 0) { + if (devoptab && devoptab->name) + { + if (strcmp(name, devoptab->name) == 0) + { devoptab_list[i] = devoptab_list[0]; - ntfs_free((devoptab_t*)devoptab); + ntfs_free((devoptab_t*) devoptab); break; } } @@ -132,10 +141,10 @@ 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}; + char name[128] = { 0 }; int i; // Get the device name from the path @@ -146,10 +155,13 @@ const devoptab_t *ntfsGetDevice (const char *path, bool useDefaultDevice) // NOTE: We do this manually due to a 'bug' in GetDeviceOpTab // which ignores names with suffixes and causes names // like "ntfs" and "ntfs1" to be seen as equals - for (i = 0; i < STD_MAX; i++) { + for (i = 0; i < STD_MAX; i++) + { devoptab = devoptab_list[i]; - if (devoptab && devoptab->name) { - if (strcmp(name, devoptab->name) == 0) { + if (devoptab && devoptab->name) + { + if (strcmp(name, devoptab->name) == 0) + { return devoptab; } } @@ -158,33 +170,32 @@ const devoptab_t *ntfsGetDevice (const char *path, bool useDefaultDevice) // If we reach here then we couldn't find the device name, // chances are that this path has no device name in it. // Call GetDeviceOpTab to get our default device (chdir). - if (useDefaultDevice) - return GetDeviceOpTab(""); + if (useDefaultDevice) return GetDeviceOpTab(""); 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); - if (devoptab && devoptab_ntfs && (devoptab->open_r == devoptab_ntfs->open_r)) - return (ntfs_vd*)devoptab->deviceData; + if (devoptab && devoptab_ntfs && (devoptab->open_r == devoptab_ntfs->open_r)) return (ntfs_vd*) devoptab->deviceData; return NULL; } -int ntfsInitVolume (ntfs_vd *vd) +int ntfsInitVolume(ntfs_vd *vd) { // Sanity check - if (!vd) { + if (!vd) + { errno = ENODEV; return -1; } @@ -207,10 +218,11 @@ int ntfsInitVolume (ntfs_vd *vd) return 0; } -void ntfsDeinitVolume (ntfs_vd *vd) +void ntfsDeinitVolume(ntfs_vd *vd) { // Sanity check - if (!vd) { + if (!vd) + { errno = ENODEV; return; } @@ -220,7 +232,8 @@ void ntfsDeinitVolume (ntfs_vd *vd) // Close any directories which are still open (lazy programmers!) ntfs_dir_state *nextDir = vd->firstOpenDir; - while (nextDir) { + while (nextDir) + { ntfs_log_warning("Cleaning up orphaned directory @ %p\n", nextDir); ntfsCloseDir(nextDir); nextDir = nextDir->nextOpenDir; @@ -228,7 +241,8 @@ void ntfsDeinitVolume (ntfs_vd *vd) // Close any files which are still open (lazy programmers!) ntfs_file_state *nextFile = vd->firstOpenFile; - while (nextFile) { + while (nextFile) + { ntfs_log_warning("Cleaning up orphaned file @ %p\n", nextFile); ntfsCloseFile(nextFile); nextFile = nextFile->nextOpenFile; @@ -242,8 +256,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 @@ -258,45 +272,51 @@ 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; // Sanity check - if (!vd) { + if (!vd) + { errno = ENODEV; return NULL; } // Get the actual path of the entry path = ntfsRealPath(path); - if (!path) { + if (!path) + { errno = EINVAL; return NULL; - } else if (path[0] == '\0') { + } + else if (path[0] == '\0') + { path = "."; } // Find the entry, taking into account our current directory (if any) if (path[0] != PATH_SEP) ni = ntfs_pathname_to_inode(vd->vol, vd->cwd_ni, path++); - else - ni = ntfs_pathname_to_inode(vd->vol, NULL, path); + else ni = ntfs_pathname_to_inode(vd->vol, NULL, path); // If the entry was found and it has reparse data then parse its true path; // this resolves the true location of symbolic links and directory junctions - if (ni && (ni->flags & FILE_ATTR_REPARSE_POINT)) { - if (ntfs_possible_symlink(ni)) { + if (ni && (ni->flags & FILE_ATTR_REPARSE_POINT)) + { + if (ntfs_possible_symlink(ni)) + { // Sanity check, give up if we are parsing to deep - if (reparseLevel > NTFS_MAX_SYMLINK_DEPTH) { + if (reparseLevel > NTFS_MAX_SYMLINK_DEPTH) + { ntfsCloseEntry(vd, ni); errno = ELOOP; return NULL; @@ -304,7 +324,8 @@ ntfs_inode *ntfsParseEntry (ntfs_vd *vd, const char *path, int reparseLevel) // Get the target path of this entry target = ntfs_make_symlink(ni, path, &attr_size); - if (!target) { + if (!target) + { ntfsCloseEntry(vd, ni); return NULL; } @@ -324,10 +345,11 @@ 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) { + if (!vd) + { errno = ENODEV; return; } @@ -336,8 +358,7 @@ void ntfsCloseEntry (ntfs_vd *vd, ntfs_inode *ni) ntfsLock(vd); // Sync the entry (if it is dirty) - if (NInoDirty(ni)) - ntfsSync(vd, ni); + if (NInoDirty(ni)) ntfsSync(vd, ni); // Close the entry ntfs_inode_close(ni); @@ -348,8 +369,7 @@ void ntfsCloseEntry (ntfs_vd *vd, ntfs_inode *ni) return; } - -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; @@ -358,14 +378,17 @@ ntfs_inode *ntfsCreate (ntfs_vd *vd, const char *path, mode_t type, const char * int uname_len, utarget_len; // Sanity check - if (!vd) { + if (!vd) + { errno = ENODEV; return NULL; } // You cannot link between devices - if(target) { - if(vd != ntfsGetVolume(target)) { + if (target) + { + if (vd != ntfsGetVolume(target)) + { errno = EXDEV; return NULL; } @@ -374,7 +397,8 @@ ntfs_inode *ntfsCreate (ntfs_vd *vd, const char *path, mode_t type, const char * // Get the actual paths of the entry path = ntfsRealPath(path); target = ntfsRealPath(target); - if (!path) { + if (!path) + { errno = EINVAL; return NULL; } @@ -385,22 +409,23 @@ ntfs_inode *ntfsCreate (ntfs_vd *vd, const char *path, mode_t type, const char * // Get the unicode name for the entry and find its parent directory // TODO: This looks horrible, clean it up dir = strdup(path); - if (!dir) { + if (!dir) + { errno = EINVAL; goto cleanup; } name = strrchr(dir, '/'); if (name) name++; - else - name = dir; + else name = dir; uname_len = ntfsLocalToUnicode(name, &uname); - if (uname_len < 0) { + if (uname_len < 0) + { errno = EINVAL; goto cleanup; } name = strrchr(dir, '/'); - if(name) + if (name) { name++; name[0] = 0; @@ -408,28 +433,32 @@ ntfs_inode *ntfsCreate (ntfs_vd *vd, const char *path, mode_t type, const char * // Open the entries parent directory dir_ni = ntfsOpenEntry(vd, dir); - if (!dir_ni) { + if (!dir_ni) + { goto cleanup; } // Create the entry - switch (type) { + switch (type) + { // Symbolic link case S_IFLNK: - if (!target) { + if (!target) + { errno = EINVAL; goto cleanup; } utarget_len = ntfsLocalToUnicode(target, &utarget); - if (utarget_len < 0) { + if (utarget_len < 0) + { errno = EINVAL; goto cleanup; } - ni = ntfs_create_symlink(dir_ni, 0, uname, uname_len, utarget, utarget_len); + ni = ntfs_create_symlink(dir_ni, 0, uname, uname_len, utarget, utarget_len); break; - // Directory or file + // Directory or file case S_IFDIR: case S_IFREG: ni = ntfs_create(dir_ni, 0, uname, uname_len, type); @@ -438,7 +467,8 @@ ntfs_inode *ntfsCreate (ntfs_vd *vd, const char *path, mode_t type, const char * } // If the entry was created - if (ni) { + if (ni) + { // Mark the entry for archiving ni->flags |= FILE_ATTR_ARCHIVE; @@ -454,19 +484,15 @@ ntfs_inode *ntfsCreate (ntfs_vd *vd, const char *path, mode_t type, const char * } -cleanup: + cleanup: - if(dir_ni) - ntfsCloseEntry(vd, dir_ni); + if (dir_ni) ntfsCloseEntry(vd, dir_ni); - if(utarget) - ntfs_free(utarget); + if (utarget) ntfs_free(utarget); - if(uname) - ntfs_free(uname); + if (uname) ntfs_free(uname); - if(dir) - ntfs_free(dir); + if (dir) ntfs_free(dir); // Unlock ntfsUnlock(vd); @@ -474,7 +500,7 @@ 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; @@ -484,13 +510,15 @@ int ntfsLink (ntfs_vd *vd, const char *old_path, const char *new_path) int res = 0; // Sanity check - if (!vd) { + if (!vd) + { errno = ENODEV; return -1; } // You cannot link between devices - if(vd != ntfsGetVolume(new_path)) { + if (vd != ntfsGetVolume(new_path)) + { errno = EXDEV; return -1; } @@ -498,7 +526,8 @@ int ntfsLink (ntfs_vd *vd, const char *old_path, const char *new_path) // Get the actual paths of the entry old_path = ntfsRealPath(old_path); new_path = ntfsRealPath(new_path); - if (!old_path || !new_path) { + if (!old_path || !new_path) + { errno = EINVAL; return -1; } @@ -509,17 +538,18 @@ int ntfsLink (ntfs_vd *vd, const char *old_path, const char *new_path) // Get the unicode name for the entry and find its parent directory // TODO: This looks horrible, clean it up dir = strdup(new_path); - if (!dir) { + if (!dir) + { errno = EINVAL; goto cleanup; } name = strrchr(dir, '/'); if (name) name++; - else - name = dir; + else name = dir; uname_len = ntfsLocalToUnicode(name, &uname); - if (uname_len < 0) { + if (uname_len < 0) + { errno = EINVAL; goto cleanup; } @@ -527,7 +557,8 @@ int ntfsLink (ntfs_vd *vd, const char *old_path, const char *new_path) // Find the entry ni = ntfsOpenEntry(vd, old_path); - if (!ni) { + if (!ni) + { errno = ENOENT; res = -1; goto cleanup; @@ -535,14 +566,16 @@ int ntfsLink (ntfs_vd *vd, const char *old_path, const char *new_path) // Open the entries new parent directory dir_ni = ntfsOpenEntry(vd, dir); - if (!dir_ni) { + if (!dir_ni) + { errno = ENOENT; res = -1; goto cleanup; } // Link the entry to its new parent - if (ntfs_link(ni, dir_ni, uname, uname_len)) { + if (ntfs_link(ni, dir_ni, uname, uname_len)) + { res = -1; goto cleanup; } @@ -553,19 +586,15 @@ int ntfsLink (ntfs_vd *vd, const char *old_path, const char *new_path) // Sync the entry to disc ntfsSync(vd, ni); -cleanup: + cleanup: - if(dir_ni) - ntfsCloseEntry(vd, dir_ni); + if (dir_ni) ntfsCloseEntry(vd, dir_ni); - if(ni) - ntfsCloseEntry(vd, ni); + if (ni) ntfsCloseEntry(vd, ni); - if(uname) - ntfs_free(uname); + if (uname) ntfs_free(uname); - if(dir) - ntfs_free(dir); + if (dir) ntfs_free(dir); // Unlock ntfsUnlock(vd); @@ -573,7 +602,7 @@ 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; @@ -583,14 +612,16 @@ int ntfsUnlink (ntfs_vd *vd, const char *path) int res = 0; // Sanity check - if (!vd) { + if (!vd) + { errno = ENODEV; return -1; } // Get the actual path of the entry path = ntfsRealPath(path); - if (!path) { + if (!path) + { errno = EINVAL; return -1; } @@ -601,22 +632,23 @@ int ntfsUnlink (ntfs_vd *vd, const char *path) // Get the unicode name for the entry and find its parent directory // TODO: This looks horrible dir = strdup(path); - if (!dir) { + if (!dir) + { errno = EINVAL; goto cleanup; } name = strrchr(dir, '/'); if (name) name++; - else - name = dir; + else name = dir; uname_len = ntfsLocalToUnicode(name, &uname); - if (uname_len < 0) { + if (uname_len < 0) + { errno = EINVAL; goto cleanup; } name = strrchr(dir, '/'); - if(name) + if (name) { name++; name[0] = 0; @@ -624,7 +656,8 @@ int ntfsUnlink (ntfs_vd *vd, const char *path) // Find the entry ni = ntfsOpenEntry(vd, path); - if (!ni) { + if (!ni) + { errno = ENOENT; res = -1; goto cleanup; @@ -632,14 +665,16 @@ int ntfsUnlink (ntfs_vd *vd, const char *path) // Open the entries parent directory dir_ni = ntfsOpenEntry(vd, dir); - if (!dir_ni) { + if (!dir_ni) + { errno = ENOENT; res = -1; goto cleanup; } // Unlink the entry from its parent - if (ntfs_delete(vd->vol, path, ni, dir_ni, uname, uname_len)) { + if (ntfs_delete(vd->vol, path, ni, dir_ni, uname, uname_len)) + { res = -1; } @@ -649,19 +684,15 @@ int ntfsUnlink (ntfs_vd *vd, const char *path) // ntfs_delete() ALWAYS closes ni and dir_ni; so no need for us to anymore dir_ni = ni = NULL; -cleanup: + cleanup: - if(dir_ni) - ntfsCloseEntry(vd, dir_ni); + if (dir_ni) ntfsCloseEntry(vd, dir_ni); - if(ni) - ntfsCloseEntry(vd, ni); + if (ni) ntfsCloseEntry(vd, ni); - if(uname) - ntfs_free(uname); + if (uname) ntfs_free(uname); - if(dir) - ntfs_free(dir); + if (dir) ntfs_free(dir); // Unlock ntfsUnlock(vd); @@ -669,18 +700,20 @@ cleanup: return 0; } -int ntfsSync (ntfs_vd *vd, ntfs_inode *ni) +int ntfsSync(ntfs_vd *vd, ntfs_inode *ni) { int res = 0; // Sanity check - if (!vd) { + if (!vd) + { errno = ENODEV; return -1; } // Sanity check - if (!ni) { + if (!ni) + { errno = ENOENT; return -1; } @@ -701,26 +734,27 @@ 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; // Sanity check - if (!vd) { + if (!vd) + { errno = ENODEV; return -1; } // Sanity check - if (!ni) { + if (!ni) + { errno = ENOENT; return -1; } // Short circuit cases were we don't actually have to do anything - if (!st) - return 0; + if (!st) return 0; // Lock ntfsLock(vd); @@ -729,20 +763,24 @@ int ntfsStat (ntfs_vd *vd, ntfs_inode *ni, struct stat *st) memset(st, 0, sizeof(struct stat)); // Is this entry a directory - if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { + if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) + { st->st_mode = S_IFDIR | (0777 & ~vd->dmask); st->st_nlink = 1; // Open the directories index allocation table attribute na = ntfs_attr_open(ni, AT_INDEX_ALLOCATION, NTFS_INDEX_I30, 4); - if (na) { + if (na) + { st->st_size = na->data_size; st->st_blocks = na->allocated_size >> 9; ntfs_attr_close(na); } - // Else it must be a file - } else { + // Else it must be a file + } + else + { st->st_mode = S_IFREG | (0777 & ~vd->fmask); st->st_size = ni->data_size; st->st_blocks = (ni->allocated_size + 511) >> 9; @@ -767,66 +805,68 @@ 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; + if (vd && vd->atime == ATIME_DISABLED) mask &= ~NTFS_UPDATE_ATIME; // Update entry times - if (ni && mask) - ntfs_inode_update_times(ni, mask); + if (ni && mask) ntfs_inode_update_times(ni, mask); return; } -const char *ntfsRealPath (const char *path) +const char *ntfsRealPath(const char *path) { // Sanity check - if (!path) - return NULL; + if (!path) return NULL; // Move the path pointer to the start of the actual path - if (strchr(path, ':') != NULL) { + if (strchr(path, ':') != NULL) + { path = strchr(path, ':') + 1; } - if (strchr(path, ':') != NULL) { + if (strchr(path, ':') != NULL) + { return NULL; } 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; // Sanity check - if (!ins || !ins_len || !outs) - return 0; + if (!ins || !ins_len || !outs) return 0; // Convert the unicode string to our current local len = ntfs_ucstombs(ins, ins_len, outs, outs_len); - if (len == -1 && errno == EILSEQ) { + if (len == -1 && errno == EILSEQ) + { // The string could not be converted to the current local, // do it manually by replacing non-ASCII characters with underscores - if (!*outs || outs_len >= ins_len) { - if (!*outs) { + if (!*outs || outs_len >= ins_len) + { + if (!*outs) + { *outs = (char *) ntfs_alloc(ins_len + 1); - if (!*outs) { + if (!*outs) + { errno = ENOMEM; return -1; } } - for (i = 0; i < ins_len; i++) { + for (i = 0; i < ins_len; i++) + { ntfschar uc = le16_to_cpu(ins[i]); - if (uc > 0xff) - uc = (ntfschar)'_'; - *outs[i] = (char)uc; + if (uc > 0xff) uc = (ntfschar) '_'; + *outs[i] = (char) uc; } - *outs[ins_len] = (ntfschar)'\0'; + *outs[ins_len] = (ntfschar) '\0'; len = ins_len; } @@ -835,11 +875,10 @@ 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; + if (!ins || !outs) return 0; // Convert the local string to unicode return ntfs_mbstoucs(ins, outs); diff --git a/source/libntfs/ntfsinternal.h b/source/libntfs/ntfsinternal.h index 11dfb8fd..0868c9cd 100644 --- a/source/libntfs/ntfsinternal.h +++ b/source/libntfs/ntfsinternal.h @@ -69,110 +69,117 @@ struct _ntfs_dir_state; /** * PRIMARY_PARTITION - Block device partition record */ -typedef struct _PARTITION_RECORD { - u8 status; /* Partition status; see above */ - u8 chs_start[3]; /* Cylinder-head-sector address to first block of partition */ - u8 type; /* Partition type; see above */ - u8 chs_end[3]; /* Cylinder-head-sector address to last block of partition */ - u32 lba_start; /* Local block address to first sector of partition */ - u32 block_count; /* Number of blocks in partition */ -} __attribute__((__packed__)) PARTITION_RECORD; +typedef struct _PARTITION_RECORD +{ + u8 status; /* Partition status; see above */ + u8 chs_start[3]; /* Cylinder-head-sector address to first block of partition */ + u8 type; /* Partition type; see above */ + u8 chs_end[3]; /* Cylinder-head-sector address to last block of partition */ + u32 lba_start; /* Local block address to first sector of partition */ + u32 block_count; /* Number of blocks in partition */ +}__attribute__((__packed__)) PARTITION_RECORD; /** * MASTER_BOOT_RECORD - Block device master boot record */ -typedef struct _MASTER_BOOT_RECORD { - u8 code_area[446]; /* Code area; normally empty */ - PARTITION_RECORD partitions[4]; /* 4 primary partitions */ - u16 signature; /* MBR signature; 0xAA55 */ -} __attribute__((__packed__)) MASTER_BOOT_RECORD; +typedef struct _MASTER_BOOT_RECORD +{ + u8 code_area[446]; /* Code area; normally empty */ + PARTITION_RECORD partitions[4]; /* 4 primary partitions */ + u16 signature; /* MBR signature; 0xAA55 */ +}__attribute__((__packed__)) MASTER_BOOT_RECORD; /** * EXTENDED_PARTITION - Block device extended boot record */ -typedef struct _EXTENDED_BOOT_RECORD { - u8 code_area[446]; /* Code area; normally empty */ - PARTITION_RECORD partition; /* Primary partition */ - PARTITION_RECORD next_ebr; /* Next extended boot record in the chain */ - u8 reserved[32]; /* Normally empty */ - u16 signature; /* EBR signature; 0xAA55 */ -} __attribute__((__packed__)) EXTENDED_BOOT_RECORD; +typedef struct _EXTENDED_BOOT_RECORD +{ + u8 code_area[446]; /* Code area; normally empty */ + PARTITION_RECORD partition; /* Primary partition */ + PARTITION_RECORD next_ebr; /* Next extended boot record in the chain */ + u8 reserved[32]; /* Normally empty */ + u16 signature; /* EBR signature; 0xAA55 */ +}__attribute__((__packed__)) EXTENDED_BOOT_RECORD; /** * INTERFACE_ID - Disc interface identifier */ -typedef struct _INTERFACE_ID { - const char *name; /* Interface name */ - const DISC_INTERFACE *interface; /* Disc interface */ +typedef struct _INTERFACE_ID +{ + const char *name; /* Interface name */ + const DISC_INTERFACE *interface; /* Disc interface */ } INTERFACE_ID; /** * ntfs_atime_t - File access time update strategies */ -typedef enum { - ATIME_ENABLED, /* Update access times */ - ATIME_DISABLED /* Don't update access times */ +typedef enum +{ + ATIME_ENABLED, /* Update access times */ + ATIME_DISABLED +/* Don't update access times */ } ntfs_atime_t; /** * ntfs_vd - NTFS volume descriptor */ -typedef struct _ntfs_vd { - struct ntfs_device *dev; /* NTFS device handle */ - ntfs_volume *vol; /* NTFS volume handle */ - mutex_t lock; /* Volume lock mutex */ - s64 id; /* Filesystem id */ - u32 flags; /* Mount flags */ - char name[128]; /* Volume name (cached) */ - u16 uid; /* User id for entry creation */ - u16 gid; /* Group id for entry creation */ - u16 fmask; /* Unix style permission mask for file creation */ - u16 dmask; /* Unix style permission mask for directory creation */ - ntfs_atime_t atime; /* Entry access time update strategy */ - bool showHiddenFiles; /* If true, show hidden files when enumerating directories */ - bool showSystemFiles; /* If true, show system files when enumerating directories */ - ntfs_inode *cwd_ni; /* Current directory */ - struct _ntfs_dir_state *firstOpenDir; /* The start of a FILO linked list of currently opened directories */ - struct _ntfs_file_state *firstOpenFile; /* The start of a FILO linked list of currently opened files */ - u16 openDirCount; /* The total number of directories currently open in this volume */ - u16 openFileCount; /* The total number of files currently open in this volume */ +typedef struct _ntfs_vd +{ + struct ntfs_device *dev; /* NTFS device handle */ + ntfs_volume *vol; /* NTFS volume handle */ + mutex_t lock; /* Volume lock mutex */ + s64 id; /* Filesystem id */ + u32 flags; /* Mount flags */ + char name[128]; /* Volume name (cached) */ + u16 uid; /* User id for entry creation */ + u16 gid; /* Group id for entry creation */ + u16 fmask; /* Unix style permission mask for file creation */ + u16 dmask; /* Unix style permission mask for directory creation */ + ntfs_atime_t atime; /* Entry access time update strategy */ + bool showHiddenFiles; /* If true, show hidden files when enumerating directories */ + bool showSystemFiles; /* If true, show system files when enumerating directories */ + ntfs_inode *cwd_ni; /* Current directory */ + struct _ntfs_dir_state *firstOpenDir; /* The start of a FILO linked list of currently opened directories */ + struct _ntfs_file_state *firstOpenFile; /* The start of a FILO linked list of currently opened files */ + u16 openDirCount; /* The total number of directories currently open in this volume */ + u16 openFileCount; /* The total number of files currently open in this volume */ } 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); } /* Gekko device related routines */ -int ntfsAddDevice (const char *name, void *deviceData); -void ntfsRemoveDevice (const char *path); -const devoptab_t *ntfsGetDevice (const char *path, bool useDefaultDevice); -const devoptab_t *ntfsGetDevOpTab (void); -const INTERFACE_ID* ntfsGetDiscInterfaces (void); +int ntfsAddDevice(const char *name, void *deviceData); +void ntfsRemoveDevice(const char *path); +const devoptab_t *ntfsGetDevice(const char *path, bool useDefaultDevice); +const devoptab_t *ntfsGetDevOpTab(void); +const INTERFACE_ID* ntfsGetDiscInterfaces(void); /* Miscellaneous helper/support routines */ -int ntfsInitVolume (ntfs_vd *vd); -void ntfsDeinitVolume (ntfs_vd *vd); -ntfs_vd *ntfsGetVolume (const char *path); -ntfs_inode *ntfsOpenEntry (ntfs_vd *vd, const char *path); -ntfs_inode *ntfsParseEntry (ntfs_vd *vd, const char *path, int reparseLevel); -void ntfsCloseEntry (ntfs_vd *vd, ntfs_inode *ni); -ntfs_inode *ntfsCreate (ntfs_vd *vd, const char *path, mode_t type, const char *target); -int ntfsLink (ntfs_vd *vd, const char *old_path, const char *new_path); -int ntfsUnlink (ntfs_vd *vd, const char *path); -int ntfsSync (ntfs_vd *vd, ntfs_inode *ni); -int ntfsStat (ntfs_vd *vd, ntfs_inode *ni, struct stat *st); -void ntfsUpdateTimes (ntfs_vd *vd, ntfs_inode *ni, ntfs_time_update_flags mask); +int ntfsInitVolume(ntfs_vd *vd); +void ntfsDeinitVolume(ntfs_vd *vd); +ntfs_vd *ntfsGetVolume(const char *path); +ntfs_inode *ntfsOpenEntry(ntfs_vd *vd, const char *path); +ntfs_inode *ntfsParseEntry(ntfs_vd *vd, const char *path, int reparseLevel); +void ntfsCloseEntry(ntfs_vd *vd, ntfs_inode *ni); +ntfs_inode *ntfsCreate(ntfs_vd *vd, const char *path, mode_t type, const char *target); +int ntfsLink(ntfs_vd *vd, const char *old_path, const char *new_path); +int ntfsUnlink(ntfs_vd *vd, const char *path); +int ntfsSync(ntfs_vd *vd, ntfs_inode *ni); +int ntfsStat(ntfs_vd *vd, ntfs_inode *ni, struct stat *st); +void ntfsUpdateTimes(ntfs_vd *vd, ntfs_inode *ni, ntfs_time_update_flags mask); -const char *ntfsRealPath (const char *path); -int ntfsUnicodeToLocal (const ntfschar *ins, const int ins_len, char **outs, int outs_len); -int ntfsLocalToUnicode (const char *ins, ntfschar **outs); +const char *ntfsRealPath(const char *path); +int ntfsUnicodeToLocal(const ntfschar *ins, const int ins_len, char **outs, int outs_len); +int ntfsLocalToUnicode(const char *ins, ntfschar **outs); #endif /* _NTFSINTERNAL_H */ diff --git a/source/libntfs/ntfstime.h b/source/libntfs/ntfstime.h index 426269d7..c47e3774 100644 --- a/source/libntfs/ntfstime.h +++ b/source/libntfs/ntfstime.h @@ -57,17 +57,15 @@ typedef sle64 ntfs_time; */ static __inline__ struct timespec ntfs2timespec(ntfs_time ntfstime) { - struct timespec spec; - s64 cputime; + struct timespec spec; + s64 cputime; - cputime = sle64_to_cpu(ntfstime); - spec.tv_sec = (cputime - (NTFS_TIME_OFFSET)) / 10000000; - spec.tv_nsec = (cputime - (NTFS_TIME_OFFSET) - - (s64)spec.tv_sec*10000000)*100; - /* force zero nsec for overflowing dates */ - if ((spec.tv_nsec < 0) || (spec.tv_nsec > 999999999)) - spec.tv_nsec = 0; - return (spec); + cputime = sle64_to_cpu(ntfstime); + spec.tv_sec = (cputime - (NTFS_TIME_OFFSET)) / 10000000; + spec.tv_nsec = (cputime - (NTFS_TIME_OFFSET) - (s64) spec.tv_sec * 10000000) * 100; + /* force zero nsec for overflowing dates */ + if ((spec.tv_nsec < 0) || (spec.tv_nsec > 999999999)) spec.tv_nsec = 0; + return (spec); } /** @@ -88,11 +86,10 @@ static __inline__ struct timespec ntfs2timespec(ntfs_time ntfstime) */ static __inline__ ntfs_time timespec2ntfs(struct timespec spec) { - s64 units; + s64 units; - units = (s64)spec.tv_sec * 10000000 - + NTFS_TIME_OFFSET + spec.tv_nsec/100; - return (cpu_to_le64(units)); + units = (s64) spec.tv_sec * 10000000 + NTFS_TIME_OFFSET + spec.tv_nsec / 100; + return (cpu_to_le64(units)); } /* @@ -101,21 +98,21 @@ static __inline__ ntfs_time timespec2ntfs(struct timespec spec) static __inline__ ntfs_time ntfs_current_time(void) { - struct timespec now; + struct timespec now; #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_SYS_CLOCK_GETTIME) - clock_gettime(CLOCK_REALTIME, &now); + clock_gettime(CLOCK_REALTIME, &now); #elif defined(HAVE_GETTIMEOFDAY) - struct timeval microseconds; + struct timeval microseconds; - gettimeofday(µseconds, (struct timezone*)NULL); - now.tv_sec = microseconds.tv_sec; - now.tv_nsec = microseconds.tv_usec*1000; + gettimeofday(µseconds, (struct timezone*)NULL); + now.tv_sec = microseconds.tv_sec; + now.tv_nsec = microseconds.tv_usec*1000; #else - now.tv_sec = time((time_t*)NULL); - now.tv_nsec = 0; + now.tv_sec = time((time_t*) NULL); + now.tv_nsec = 0; #endif - return (timespec2ntfs(now)); + return (timespec2ntfs(now)); } #endif /* _NTFS_NTFSTIME_H */ diff --git a/source/libntfs/object_id.c b/source/libntfs/object_id.c index 555dd137..7b636e0d 100644 --- a/source/libntfs/object_id.c +++ b/source/libntfs/object_id.c @@ -106,25 +106,27 @@ * ---------------------- end from RFC 4122 ----------------------- */ -typedef struct { - GUID object_id; +typedef struct +{ + GUID object_id; } OBJECT_ID_INDEX_KEY; -typedef struct { - le64 file_id; - GUID birth_volume_id; - GUID birth_object_id; - GUID domain_id; +typedef struct +{ + le64 file_id; + GUID birth_volume_id; + GUID birth_object_id; + GUID domain_id; } OBJECT_ID_INDEX_DATA; // known as OBJ_ID_INDEX_DATA -struct OBJECT_ID_INDEX { /* index entry in $Extend/$ObjId */ - INDEX_ENTRY_HEADER header; - OBJECT_ID_INDEX_KEY key; - OBJECT_ID_INDEX_DATA data; -} ; +struct OBJECT_ID_INDEX +{ /* index entry in $Extend/$ObjId */ + INDEX_ENTRY_HEADER header; + OBJECT_ID_INDEX_KEY key; + OBJECT_ID_INDEX_DATA data; +}; -static ntfschar objid_index_name[] = { const_cpu_to_le16('$'), - const_cpu_to_le16('O') }; +static ntfschar objid_index_name[] = { const_cpu_to_le16('$'), const_cpu_to_le16('O') }; #ifdef HAVE_SETXATTR /* extended attributes interface required */ /* @@ -135,40 +137,40 @@ static ntfschar objid_index_name[] = { const_cpu_to_le16('$'), */ static int set_object_id_index(ntfs_inode *ni, ntfs_index_context *xo, - const OBJECT_ID_ATTR *object_id) + const OBJECT_ID_ATTR *object_id) { - struct OBJECT_ID_INDEX indx; - u64 file_id_cpu; - le64 file_id; - le16 seqn; + struct OBJECT_ID_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(OBJECT_ID_INDEX_KEY)); - indx.header.data_length = const_cpu_to_le16( - sizeof(OBJECT_ID_INDEX_DATA)); - indx.header.reservedV = const_cpu_to_le32(0); - indx.header.length = const_cpu_to_le16( - sizeof(struct OBJECT_ID_INDEX)); - indx.header.key_length = const_cpu_to_le16( - sizeof(OBJECT_ID_INDEX_KEY)); - indx.header.flags = const_cpu_to_le16(0); - indx.header.reserved = const_cpu_to_le16(0); + 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(OBJECT_ID_INDEX_KEY)); + indx.header.data_length = const_cpu_to_le16( + sizeof(OBJECT_ID_INDEX_DATA)); + indx.header.reservedV = const_cpu_to_le32(0); + indx.header.length = const_cpu_to_le16( + sizeof(struct OBJECT_ID_INDEX)); + indx.header.key_length = const_cpu_to_le16( + sizeof(OBJECT_ID_INDEX_KEY)); + indx.header.flags = const_cpu_to_le16(0); + indx.header.reserved = const_cpu_to_le16(0); - memcpy(&indx.key.object_id,object_id,sizeof(GUID)); + memcpy(&indx.key.object_id,object_id,sizeof(GUID)); - indx.data.file_id = file_id; - memcpy(&indx.data.birth_volume_id, - &object_id->birth_volume_id,sizeof(GUID)); - memcpy(&indx.data.birth_object_id, - &object_id->birth_object_id,sizeof(GUID)); - memcpy(&indx.data.domain_id, - &object_id->domain_id,sizeof(GUID)); - ntfs_index_ctx_reinit(xo); - return (ntfs_ie_add(xo,(INDEX_ENTRY*)&indx)); + indx.data.file_id = file_id; + memcpy(&indx.data.birth_volume_id, + &object_id->birth_volume_id,sizeof(GUID)); + memcpy(&indx.data.birth_object_id, + &object_id->birth_object_id,sizeof(GUID)); + memcpy(&indx.data.domain_id, + &object_id->domain_id,sizeof(GUID)); + ntfs_index_ctx_reinit(xo); + return (ntfs_ie_add(xo,(INDEX_ENTRY*)&indx)); } #endif /* HAVE_SETXATTR */ @@ -184,28 +186,30 @@ static int set_object_id_index(ntfs_inode *ni, ntfs_index_context *xo, static ntfs_index_context *open_object_id_index(ntfs_volume *vol) { - u64 inum; - ntfs_inode *ni; - ntfs_inode *dir_ni; - ntfs_index_context *xo; + u64 inum; + ntfs_inode *ni; + ntfs_inode *dir_ni; + ntfs_index_context *xo; - /* do not use path_name_to inode - could reopen root */ - dir_ni = ntfs_inode_open(vol, FILE_Extend); - ni = (ntfs_inode*)NULL; - if (dir_ni) { - inum = ntfs_inode_lookup_by_mbsname(dir_ni,"$ObjId"); - if (inum != (u64)-1) - ni = ntfs_inode_open(vol, inum); - ntfs_inode_close(dir_ni); - } - if (ni) { - xo = ntfs_index_ctx_get(ni, objid_index_name, 2); - if (!xo) { - ntfs_inode_close(ni); - } - } else - xo = (ntfs_index_context*)NULL; - return (xo); + /* do not use path_name_to inode - could reopen root */ + dir_ni = ntfs_inode_open(vol, FILE_Extend); + ni = (ntfs_inode*) NULL; + if (dir_ni) + { + inum = ntfs_inode_lookup_by_mbsname(dir_ni, "$ObjId"); + if (inum != (u64) -1) ni = ntfs_inode_open(vol, inum); + ntfs_inode_close(dir_ni); + } + if (ni) + { + xo = ntfs_index_ctx_get(ni, objid_index_name, 2); + if (!xo) + { + ntfs_inode_close(ni); + } + } + else xo = (ntfs_index_context*) NULL; + return (xo); } #ifdef HAVE_SETXATTR /* extended attributes interface required */ @@ -219,43 +223,46 @@ static ntfs_index_context *open_object_id_index(ntfs_volume *vol) */ static int merge_index_data(ntfs_inode *ni, - const OBJECT_ID_ATTR *objectid_attr, - OBJECT_ID_ATTR *full_objectid) + const OBJECT_ID_ATTR *objectid_attr, + OBJECT_ID_ATTR *full_objectid) { - OBJECT_ID_INDEX_KEY key; - struct OBJECT_ID_INDEX *entry; - ntfs_index_context *xo; - ntfs_inode *xoni; - int res; + OBJECT_ID_INDEX_KEY key; + struct OBJECT_ID_INDEX *entry; + ntfs_index_context *xo; + ntfs_inode *xoni; + int res; - res = -1; - xo = open_object_id_index(ni->vol); - if (xo) { - memcpy(&key.object_id,objectid_attr,sizeof(GUID)); - if (!ntfs_index_lookup(&key, - sizeof(OBJECT_ID_INDEX_KEY), xo)) { - entry = (struct OBJECT_ID_INDEX*)xo->entry; - /* make sure inode numbers match */ - if (entry - && (MREF(le64_to_cpu(entry->data.file_id)) - == ni->mft_no)) { - memcpy(&full_objectid->birth_volume_id, - &entry->data.birth_volume_id, - sizeof(GUID)); - memcpy(&full_objectid->birth_object_id, - &entry->data.birth_object_id, - sizeof(GUID)); - memcpy(&full_objectid->domain_id, - &entry->data.domain_id, - sizeof(GUID)); - res = 0; - } - } - xoni = xo->ni; - ntfs_index_ctx_put(xo); - ntfs_inode_close(xoni); - } - return (res); + res = -1; + xo = open_object_id_index(ni->vol); + if (xo) + { + memcpy(&key.object_id,objectid_attr,sizeof(GUID)); + if (!ntfs_index_lookup(&key, + sizeof(OBJECT_ID_INDEX_KEY), xo)) + { + entry = (struct OBJECT_ID_INDEX*)xo->entry; + /* make sure inode numbers match */ + if (entry + && (MREF(le64_to_cpu(entry->data.file_id)) + == ni->mft_no)) + { + memcpy(&full_objectid->birth_volume_id, + &entry->data.birth_volume_id, + sizeof(GUID)); + memcpy(&full_objectid->birth_object_id, + &entry->data.birth_object_id, + sizeof(GUID)); + memcpy(&full_objectid->domain_id, + &entry->data.domain_id, + sizeof(GUID)); + res = 0; + } + } + xoni = xo->ni; + ntfs_index_ctx_put(xo); + ntfs_inode_close(xoni); + } + return (res); } #endif /* HAVE_SETXATTR */ @@ -268,44 +275,39 @@ static int merge_index_data(ntfs_inode *ni, * -1 if failure, explained by errno */ -static int remove_object_id_index(ntfs_attr *na, ntfs_index_context *xo, - OBJECT_ID_ATTR *old_attr) +static int remove_object_id_index(ntfs_attr *na, ntfs_index_context *xo, OBJECT_ID_ATTR *old_attr) { - OBJECT_ID_INDEX_KEY key; - struct OBJECT_ID_INDEX *entry; - s64 size; - int ret; + OBJECT_ID_INDEX_KEY key; + struct OBJECT_ID_INDEX *entry; + s64 size; + int ret; - ret = na->data_size; - if (ret) { - /* read the existing object id attribute */ - size = ntfs_attr_pread(na, 0, sizeof(GUID), old_attr); - if (size >= (s64)sizeof(GUID)) { - memcpy(&key.object_id, - &old_attr->object_id,sizeof(GUID)); - size = sizeof(GUID); - if (!ntfs_index_lookup(&key, - sizeof(OBJECT_ID_INDEX_KEY), xo)) { - entry = (struct OBJECT_ID_INDEX*)xo->entry; - memcpy(&old_attr->birth_volume_id, - &entry->data.birth_volume_id, - sizeof(GUID)); - memcpy(&old_attr->birth_object_id, - &entry->data.birth_object_id, - sizeof(GUID)); - memcpy(&old_attr->domain_id, - &entry->data.domain_id, - sizeof(GUID)); - size = sizeof(OBJECT_ID_ATTR); - if (ntfs_index_rm(xo)) - ret = -1; - } - } else { - ret = -1; - errno = ENODATA; - } - } - return (ret); + ret = na->data_size; + if (ret) + { + /* read the existing object id attribute */ + size = ntfs_attr_pread(na, 0, sizeof(GUID), old_attr); + if (size >= (s64) sizeof(GUID)) + { + memcpy(&key.object_id, &old_attr->object_id, sizeof(GUID)); + size = sizeof(GUID); + if (!ntfs_index_lookup(&key, sizeof(OBJECT_ID_INDEX_KEY), xo)) + { + entry = (struct OBJECT_ID_INDEX*) xo->entry; + memcpy(&old_attr->birth_volume_id, &entry->data.birth_volume_id, sizeof(GUID)); + memcpy(&old_attr->birth_object_id, &entry->data.birth_object_id, sizeof(GUID)); + memcpy(&old_attr->domain_id, &entry->data.domain_id, sizeof(GUID)); + size = sizeof(OBJECT_ID_ATTR); + if (ntfs_index_rm(xo)) ret = -1; + } + } + else + { + ret = -1; + errno = ENODATA; + } + } + return (ret); } #ifdef HAVE_SETXATTR /* extended attributes interface required */ @@ -324,57 +326,63 @@ static int remove_object_id_index(ntfs_attr *na, ntfs_index_context *xo, */ static int update_object_id(ntfs_inode *ni, ntfs_index_context *xo, - const OBJECT_ID_ATTR *value, size_t size) + const OBJECT_ID_ATTR *value, size_t size) { - OBJECT_ID_ATTR old_attr; - ntfs_attr *na; - int oldsize; - int written; - int res; + OBJECT_ID_ATTR old_attr; + ntfs_attr *na; + int oldsize; + int written; + int res; - res = 0; + res = 0; - na = ntfs_attr_open(ni, AT_OBJECT_ID, AT_UNNAMED, 0); - if (na) { + na = ntfs_attr_open(ni, AT_OBJECT_ID, AT_UNNAMED, 0); + if (na) + { - /* remove the existing index entry */ - oldsize = remove_object_id_index(na,xo,&old_attr); - if (oldsize < 0) - res = -1; - else { - /* resize attribute */ - res = ntfs_attr_truncate(na, (s64)sizeof(GUID)); - /* write the object_id in attribute */ - if (!res && value) { - written = (int)ntfs_attr_pwrite(na, - (s64)0, (s64)sizeof(GUID), - &value->object_id); - if (written != (s64)sizeof(GUID)) { - ntfs_log_error("Failed to update " - "object id\n"); - errno = EIO; - res = -1; - } - } - /* write index part if provided */ - if (!res - && ((size < sizeof(OBJECT_ID_ATTR)) - || set_object_id_index(ni,xo,value))) { - /* - * If cannot index, try to remove the object - * id and log the error. There will be an - * inconsistency if removal fails. - */ - ntfs_attr_rm(na); - ntfs_log_error("Failed to index object id." - " Possible corruption.\n"); - } - } - ntfs_attr_close(na); - NInoSetDirty(ni); - } else - res = -1; - return (res); + /* remove the existing index entry */ + oldsize = remove_object_id_index(na,xo,&old_attr); + if (oldsize < 0) + res = -1; + else + { + /* resize attribute */ + res = ntfs_attr_truncate(na, (s64)sizeof(GUID)); + /* write the object_id in attribute */ + if (!res && value) + { + written = (int)ntfs_attr_pwrite(na, + (s64)0, (s64)sizeof(GUID), + &value->object_id); + if (written != (s64)sizeof(GUID)) + { + ntfs_log_error("Failed to update " + "object id\n"); + errno = EIO; + res = -1; + } + } + /* write index part if provided */ + if (!res + && ((size < sizeof(OBJECT_ID_ATTR)) + || set_object_id_index(ni,xo,value))) + { + /* + * If cannot index, try to remove the object + * id and log the error. There will be an + * inconsistency if removal fails. + */ + ntfs_attr_rm(na); + ntfs_log_error("Failed to index object id." + " Possible corruption.\n"); + } + } + ntfs_attr_close(na); + NInoSetDirty(ni); + } + else + res = -1; + return (res); } /* @@ -386,32 +394,39 @@ static int update_object_id(ntfs_inode *ni, ntfs_index_context *xo, static int add_object_id(ntfs_inode *ni, int flags) { - int res; - u8 dummy; + int res; + u8 dummy; - res = -1; /* default return */ - if (!ntfs_attr_exist(ni,AT_OBJECT_ID, AT_UNNAMED,0)) { - if (!(flags & XATTR_REPLACE)) { - /* - * no object id 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_OBJECT_ID, - AT_UNNAMED, 0, &dummy, (s64)0); - NInoSetDirty(ni); - } else - errno = EOPNOTSUPP; - } else - errno = ENODATA; - } else { - if (flags & XATTR_CREATE) - errno = EEXIST; - else - res = 0; - } - return (res); + res = -1; /* default return */ + if (!ntfs_attr_exist(ni,AT_OBJECT_ID, AT_UNNAMED,0)) + { + if (!(flags & XATTR_REPLACE)) + { + /* + * no object id 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_OBJECT_ID, + AT_UNNAMED, 0, &dummy, (s64)0); + NInoSetDirty(ni); + } + else + errno = EOPNOTSUPP; + } + else + errno = ENODATA; + } + else + { + if (flags & XATTR_CREATE) + errno = EEXIST; + else + res = 0; + } + return (res); } #endif /* HAVE_SETXATTR */ @@ -425,32 +440,33 @@ static int add_object_id(ntfs_inode *ni, int flags) int ntfs_delete_object_id_index(ntfs_inode *ni) { - ntfs_index_context *xo; - ntfs_inode *xoni; - ntfs_attr *na; - OBJECT_ID_ATTR old_attr; - int res; + ntfs_index_context *xo; + ntfs_inode *xoni; + ntfs_attr *na; + OBJECT_ID_ATTR old_attr; + int res; - res = 0; - na = ntfs_attr_open(ni, AT_OBJECT_ID, AT_UNNAMED, 0); - if (na) { - /* - * read the existing object id - * and un-index it - */ - xo = open_object_id_index(ni->vol); - if (xo) { - if (remove_object_id_index(na,xo,&old_attr) < 0) - res = -1; - xoni = xo->ni; - ntfs_index_entry_mark_dirty(xo); - NInoSetDirty(xoni); - ntfs_index_ctx_put(xo); - ntfs_inode_close(xoni); - } - ntfs_attr_close(na); - } - return (res); + res = 0; + na = ntfs_attr_open(ni, AT_OBJECT_ID, AT_UNNAMED, 0); + if (na) + { + /* + * read the existing object id + * and un-index it + */ + xo = open_object_id_index(ni->vol); + if (xo) + { + if (remove_object_id_index(na, xo, &old_attr) < 0) res = -1; + xoni = xo->ni; + ntfs_index_entry_mark_dirty(xo); + NInoSetDirty(xoni); + ntfs_index_ctx_put(xo); + ntfs_inode_close(xoni); + } + ntfs_attr_close(na); + } + return (res); } #ifdef HAVE_SETXATTR /* extended attributes interface required */ @@ -467,43 +483,51 @@ int ntfs_delete_object_id_index(ntfs_inode *ni) int ntfs_get_ntfs_object_id(ntfs_inode *ni, char *value, size_t size) { - OBJECT_ID_ATTR full_objectid; - OBJECT_ID_ATTR *objectid_attr; - s64 attr_size; - int full_size; + OBJECT_ID_ATTR full_objectid; + OBJECT_ID_ATTR *objectid_attr; + s64 attr_size; + int full_size; - full_size = 0; /* default to no data and some error to be defined */ - if (ni) { - objectid_attr = (OBJECT_ID_ATTR*)ntfs_attr_readall(ni, - AT_OBJECT_ID,(ntfschar*)NULL, 0, &attr_size); - if (objectid_attr) { - /* restrict to only GUID present in attr */ - if (attr_size == sizeof(GUID)) { - memcpy(&full_objectid.object_id, - objectid_attr,sizeof(GUID)); - full_size = sizeof(GUID); - /* get data from index, if any */ - if (!merge_index_data(ni, objectid_attr, - &full_objectid)) { - full_size = sizeof(OBJECT_ID_ATTR); - } - if (full_size <= (s64)size) { - if (value) - memcpy(value,&full_objectid, - full_size); - else - errno = EINVAL; - } - } else { - /* unexpected size, better return unsupported */ - errno = EOPNOTSUPP; - full_size = 0; - } - free(objectid_attr); - } else - errno = ENODATA; - } - return (full_size ? (int)full_size : -errno); + full_size = 0; /* default to no data and some error to be defined */ + if (ni) + { + objectid_attr = (OBJECT_ID_ATTR*)ntfs_attr_readall(ni, + AT_OBJECT_ID,(ntfschar*)NULL, 0, &attr_size); + if (objectid_attr) + { + /* restrict to only GUID present in attr */ + if (attr_size == sizeof(GUID)) + { + memcpy(&full_objectid.object_id, + objectid_attr,sizeof(GUID)); + full_size = sizeof(GUID); + /* get data from index, if any */ + if (!merge_index_data(ni, objectid_attr, + &full_objectid)) + { + full_size = sizeof(OBJECT_ID_ATTR); + } + if (full_size <= (s64)size) + { + if (value) + memcpy(value,&full_objectid, + full_size); + else + errno = EINVAL; + } + } + else + { + /* unexpected size, better return unsupported */ + errno = EOPNOTSUPP; + full_size = 0; + } + free(objectid_attr); + } + else + errno = ENODATA; + } + return (full_size ? (int)full_size : -errno); } /* @@ -517,47 +541,57 @@ int ntfs_get_ntfs_object_id(ntfs_inode *ni, char *value, size_t size) */ int ntfs_set_ntfs_object_id(ntfs_inode *ni, - const char *value, size_t size, int flags) + const char *value, size_t size, int flags) { - OBJECT_ID_INDEX_KEY key; - ntfs_inode *xoni; - ntfs_index_context *xo; - int res; + OBJECT_ID_INDEX_KEY key; + ntfs_inode *xoni; + ntfs_index_context *xo; + int res; - res = 0; - if (ni && value && (size >= sizeof(GUID))) { - xo = open_object_id_index(ni->vol); - if (xo) { - /* make sure the GUID was not used somewhere */ - memcpy(&key.object_id, value, sizeof(GUID)); - if (ntfs_index_lookup(&key, - sizeof(OBJECT_ID_INDEX_KEY), xo)) { - ntfs_index_ctx_reinit(xo); - res = add_object_id(ni, flags); - if (!res) { - /* update value and index */ - res = update_object_id(ni,xo, - (const OBJECT_ID_ATTR*)value, - size); - } - } else { - /* GUID is present elsewhere */ - res = -1; - errno = EEXIST; - } - xoni = xo->ni; - ntfs_index_entry_mark_dirty(xo); - NInoSetDirty(xoni); - ntfs_index_ctx_put(xo); - ntfs_inode_close(xoni); - } else { - res = -1; - } - } else { - errno = EINVAL; - res = -1; - } - return (res ? -1 : 0); + res = 0; + if (ni && value && (size >= sizeof(GUID))) + { + xo = open_object_id_index(ni->vol); + if (xo) + { + /* make sure the GUID was not used somewhere */ + memcpy(&key.object_id, value, sizeof(GUID)); + if (ntfs_index_lookup(&key, + sizeof(OBJECT_ID_INDEX_KEY), xo)) + { + ntfs_index_ctx_reinit(xo); + res = add_object_id(ni, flags); + if (!res) + { + /* update value and index */ + res = update_object_id(ni,xo, + (const OBJECT_ID_ATTR*)value, + size); + } + } + else + { + /* GUID is present elsewhere */ + res = -1; + errno = EEXIST; + } + xoni = xo->ni; + ntfs_index_entry_mark_dirty(xo); + NInoSetDirty(xoni); + ntfs_index_ctx_put(xo); + ntfs_inode_close(xoni); + } + else + { + res = -1; + } + } + else + { + errno = EINVAL; + res = -1; + } + return (res ? -1 : 0); } /* @@ -568,70 +602,81 @@ int ntfs_set_ntfs_object_id(ntfs_inode *ni, int ntfs_remove_ntfs_object_id(ntfs_inode *ni) { - int res; - int olderrno; - ntfs_attr *na; - ntfs_inode *xoni; - ntfs_index_context *xo; - int oldsize; - OBJECT_ID_ATTR old_attr; + int res; + int olderrno; + ntfs_attr *na; + ntfs_inode *xoni; + ntfs_index_context *xo; + int oldsize; + OBJECT_ID_ATTR old_attr; - res = 0; - if (ni) { - /* - * open and delete the object id - */ - na = ntfs_attr_open(ni, AT_OBJECT_ID, - AT_UNNAMED,0); - if (na) { - /* first remove index (old object id needed) */ - xo = open_object_id_index(ni->vol); - if (xo) { - oldsize = remove_object_id_index(na,xo, - &old_attr); - if (oldsize < 0) { - res = -1; - } else { - /* now remove attribute */ - res = ntfs_attr_rm(na); - if (res - && (oldsize > (int)sizeof(GUID))) { - /* - * 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_object_id_index(ni, xo, - &old_attr); - ntfs_log_error( - "Failed to remove object id." - " Possible corruption.\n"); - } - } + res = 0; + if (ni) + { + /* + * open and delete the object id + */ + na = ntfs_attr_open(ni, AT_OBJECT_ID, + AT_UNNAMED,0); + if (na) + { + /* first remove index (old object id needed) */ + xo = open_object_id_index(ni->vol); + if (xo) + { + oldsize = remove_object_id_index(na,xo, + &old_attr); + if (oldsize < 0) + { + res = -1; + } + else + { + /* now remove attribute */ + res = ntfs_attr_rm(na); + if (res + && (oldsize > (int)sizeof(GUID))) + { + /* + * 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_object_id_index(ni, xo, + &old_attr); + ntfs_log_error( + "Failed to remove object id." + " Possible corruption.\n"); + } + } - xoni = xo->ni; - ntfs_index_entry_mark_dirty(xo); - NInoSetDirty(xoni); - ntfs_index_ctx_put(xo); - ntfs_inode_close(xoni); - } - 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); + xoni = xo->ni; + ntfs_index_entry_mark_dirty(xo); + NInoSetDirty(xoni); + ntfs_index_ctx_put(xo); + ntfs_inode_close(xoni); + } + 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/object_id.h b/source/libntfs/object_id.h index 31af9fd8..27f48515 100644 --- a/source/libntfs/object_id.h +++ b/source/libntfs/object_id.h @@ -26,8 +26,7 @@ int ntfs_get_ntfs_object_id(ntfs_inode *ni, char *value, size_t size); -int ntfs_set_ntfs_object_id(ntfs_inode *ni, const char *value, - size_t size, int flags); +int ntfs_set_ntfs_object_id(ntfs_inode *ni, const char *value, size_t size, int flags); int ntfs_remove_ntfs_object_id(ntfs_inode *ni); int ntfs_delete_object_id_index(ntfs_inode *ni); diff --git a/source/libntfs/param.h b/source/libntfs/param.h index f21bd653..60d491c6 100644 --- a/source/libntfs/param.h +++ b/source/libntfs/param.h @@ -31,23 +31,22 @@ #define FORCE_FORMAT_v1x 0 /* Insert security data as in NTFS v1.x */ #define OWNERFROMACL 1 /* Get the owner from ACL (not Windows owner) */ - /* default security sub-authorities */ -enum { - DEFSECAUTH1 = -1153374643, /* 3141592653 */ - DEFSECAUTH2 = 589793238, - DEFSECAUTH3 = 462843383, - DEFSECBASE = 10000 +/* default security sub-authorities */ +enum +{ + DEFSECAUTH1 = -1153374643, /* 3141592653 */ + DEFSECAUTH2 = 589793238, DEFSECAUTH3 = 462843383, DEFSECBASE = 10000 }; /* * Parameters for compression */ - /* default option for compression */ +/* default option for compression */ #define DEFAULT_COMPRESSION FALSE - /* (log2 of) number of clusters in a compression block for new files */ +/* (log2 of) number of clusters in a compression block for new files */ #define STANDARD_COMPRESSION_UNIT 4 - /* maximum cluster size for allowing compression for new files */ +/* maximum cluster size for allowing compression for new files */ #define MAX_COMPRESSION_CLUSTER_SIZE 4096 /* diff --git a/source/libntfs/reparse.c b/source/libntfs/reparse.c index 0f6360e1..eb32a6b2 100644 --- a/source/libntfs/reparse.c +++ b/source/libntfs/reparse.c @@ -60,8 +60,8 @@ #include "reparse.h" /* the definitions in layout.h are wrong, we use names defined in - http://msdn.microsoft.com/en-us/library/aa365740(VS.85).aspx -*/ + http://msdn.microsoft.com/en-us/library/aa365740(VS.85).aspx + */ #define IO_REPARSE_TAG_DFS const_cpu_to_le32(0x8000000A) #define IO_REPARSE_TAG_DFSR const_cpu_to_le32(0x80000012) @@ -71,52 +71,40 @@ #define IO_REPARSE_TAG_SIS const_cpu_to_le32(0x80000007) #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 */ -} ; +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 */ +}; -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 */ -} ; +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 */ +}; -struct REPARSE_INDEX { /* index entry in $Extend/$Reparse */ - INDEX_ENTRY_HEADER header; - REPARSE_INDEX_KEY key; - le32 filling; -} ; +struct REPARSE_INDEX +{ /* index entry in $Extend/$Reparse */ + 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('\\') -} ; +static const ntfschar dir_junction_head[] = { 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('{'), -} ; +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('{'), }; -static ntfschar reparse_index_name[] = { const_cpu_to_le16('$'), - const_cpu_to_le16('R') }; +static ntfschar reparse_index_name[] = { const_cpu_to_le16('$'), const_cpu_to_le16('R') }; static const char mappingdir[] = ".NTFS-3G/"; @@ -133,80 +121,74 @@ static const char mappingdir[] = ".NTFS-3G/"; * first candidate if any. */ -static u64 ntfs_fix_file_name(ntfs_inode *dir_ni, ntfschar *uname, - int uname_len) +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; + 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_are_equal(find.attr.file_name, - find.attr.file_name_length, - found->file_name, found->file_name_length, - IGNORE_CASE, - vol->upcase, vol->upcase_len)) - lkup = 0; - if (!lkup) { - /* - * name found : - * fix original name and return inode - */ - lemref = entry->indexed_file; - 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; i < uname_len; i++) + { + cpuchar = le16_to_cpu(uname[i]); + /* + * We need upper or lower value, whichever is smaller, + * but we can only convert to upper case, so we + * will fail when searching for an upper case char + * whose lower case is smaller (such as umlauted Y) + */ + if ((cpuchar < vol->upcase_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_are_equal(find.attr.file_name, find.attr.file_name_length, found->file_name, + found->file_name_length, IGNORE_CASE, vol->upcase, vol->upcase_len)) lkup = 0; + if (!lkup) + { + /* + * name found : + * fix original name and return inode + */ + lemref = entry->indexed_file; + mref = le64_to_cpu(lemref); + for (i = 0; i < found->file_name_length; i++) + uname[i] = found->file_name[i]; + } + } + ntfs_index_ctx_put(icx); + } + return (mref); } /* @@ -217,49 +199,47 @@ static u64 ntfs_fix_file_name(ntfs_inode *dir_ni, ntfschar *uname, * or NULL if the path is not valid */ -static char *search_absolute(ntfs_volume *vol, ntfschar *path, - int count, BOOL isdir) +static char *search_absolute(ntfs_volume *vol, ntfschar *path, int count, BOOL isdir) { - ntfs_inode *ni; - u64 inum; - char *target; - int start; - int len; + 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); } /* @@ -276,78 +256,77 @@ static char *search_absolute(ntfs_volume *vol, ntfschar *path, static char *search_relative(ntfs_inode *ni, ntfschar *path, int count) { - char *target = (char*)NULL; - ntfs_inode *curni; - ntfs_inode *newni; - u64 inum; - int pos; - int lth; - BOOL ok; - int max = 32; /* safety */ + char *target = (char*) NULL; + ntfs_inode *curni; + ntfs_inode *newni; + u64 inum; + int pos; + int lth; + BOOL ok; + int max = 32; /* safety */ - pos = 0; - ok = TRUE; - curni = ntfs_dir_parent_inode(ni); - while (curni && ok && (pos < (count - 1)) && --max) { - if ((count >= (pos + 2)) - && (path[pos] == const_cpu_to_le16('.')) - && (path[pos+1] == const_cpu_to_le16('\\'))) { - path[1] = const_cpu_to_le16('/'); - pos += 2; - } else { - if ((count >= (pos + 3)) - && (path[pos] == const_cpu_to_le16('.')) - &&(path[pos+1] == const_cpu_to_le16('.')) - && (path[pos+2] == const_cpu_to_le16('\\'))) { - path[2] = const_cpu_to_le16('/'); - pos += 3; - newni = ntfs_dir_parent_inode(curni); - if (curni != ni) - ntfs_inode_close(curni); - curni = newni; - if (!curni) - ok = FALSE; - } else { - lth = 0; - while (((pos + lth) < count) - && (path[pos + lth] != const_cpu_to_le16('\\'))) - lth++; - if (lth > 0) - inum = ntfs_fix_file_name(curni,&path[pos],lth); - else - inum = (u64)-1; - if (!lth - || ((curni != ni) - && ntfs_inode_close(curni)) - || (inum == (u64)-1)) - ok = FALSE; - else { - curni = ntfs_inode_open(ni->vol, MREF(inum)); - if (!curni) - ok = FALSE; - else { - if (ok && ((pos + lth) < count)) { - path[pos + lth] = const_cpu_to_le16('/'); - pos += lth + 1; - } else { - pos += lth; - if ((ni->mrec->flags ^ curni->mrec->flags) - & MFT_RECORD_IS_DIRECTORY) - ok = FALSE; - if (ntfs_inode_close(curni)) - ok = FALSE; - } - } - } - } - } - } + pos = 0; + ok = TRUE; + curni = ntfs_dir_parent_inode(ni); + while (curni && ok && (pos < (count - 1)) && --max) + { + if ((count >= (pos + 2)) && (path[pos] == const_cpu_to_le16('.')) && (path[pos + 1] == const_cpu_to_le16('\\'))) + { + path[1] = const_cpu_to_le16('/'); + pos += 2; + } + else + { + if ((count >= (pos + 3)) && (path[pos] == const_cpu_to_le16('.')) && (path[pos + 1] + == const_cpu_to_le16('.')) && (path[pos + 2] == const_cpu_to_le16('\\'))) + { + path[2] = const_cpu_to_le16('/'); + pos += 3; + newni = ntfs_dir_parent_inode(curni); + if (curni != ni) ntfs_inode_close(curni); + curni = newni; + if (!curni) ok = FALSE; + } + else + { + lth = 0; + while (((pos + lth) < count) && (path[pos + lth] != const_cpu_to_le16('\\'))) + lth++; + if (lth > 0) + inum = ntfs_fix_file_name(curni, &path[pos], lth); + else inum = (u64) -1; + if (!lth || ((curni != ni) && ntfs_inode_close(curni)) || (inum == (u64) -1)) + ok = FALSE; + else + { + curni = ntfs_inode_open(ni->vol, MREF(inum)); + if (!curni) + ok = FALSE; + else + { + if (ok && ((pos + lth) < count)) + { + path[pos + lth] = const_cpu_to_le16('/'); + pos += lth + 1; + } + else + { + pos += lth; + if ((ni->mrec->flags ^ curni->mrec->flags) & MFT_RECORD_IS_DIRECTORY) ok = FALSE; + if (ntfs_inode_close(curni)) ok = FALSE; + } + } + } + } + } + } - if (ok && (ntfs_ucstombs(path, count, &target, 0) < 0)) { - free(target); // needed ? - target = (char*)NULL; - } - return (target); + if (ok && (ntfs_ucstombs(path, count, &target, 0) < 0)) + { + free(target); // needed ? + target = (char*) NULL; + } + return (target); } /* @@ -360,36 +339,35 @@ static char *search_relative(ntfs_inode *ni, ntfschar *path, int count) 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; + 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); } /* @@ -402,50 +380,41 @@ static int ntfs_drive_letter(ntfs_volume *vol, ntfschar letter) * */ -static BOOL valid_reparse_data(ntfs_inode *ni, - const REPARSE_POINT *reparse_attr, size_t size) +static BOOL valid_reparse_data(ntfs_inode *ni, const REPARSE_POINT *reparse_attr, size_t size) { - BOOL ok; - unsigned int offs; - unsigned int lth; - const struct MOUNT_POINT_REPARSE_DATA *mount_point_data; - const struct SYMLINK_REPARSE_DATA *symlink_data; + BOOL ok; + unsigned int offs; + unsigned int lth; + const struct MOUNT_POINT_REPARSE_DATA *mount_point_data; + const struct SYMLINK_REPARSE_DATA *symlink_data; - ok = ni && reparse_attr - && (size >= sizeof(REPARSE_POINT)) - && (((size_t)le16_to_cpu(reparse_attr->reparse_data_length) - + sizeof(REPARSE_POINT)) == size); - if (ok) { - switch (reparse_attr->reparse_tag) { - case IO_REPARSE_TAG_MOUNT_POINT : - mount_point_data = (const 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 (!(ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) - || ((size_t)((sizeof(REPARSE_POINT) - + sizeof(struct MOUNT_POINT_REPARSE_DATA) - + offs + lth)) > size)) - ok = FALSE; - break; - case IO_REPARSE_TAG_SYMLINK : - symlink_data = (const 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); - if ((size_t)((sizeof(REPARSE_POINT) - + sizeof(struct SYMLINK_REPARSE_DATA) - + offs + lth)) > size) - ok = FALSE; - break; - default : - break; - } - } - if (!ok) - errno = EINVAL; - return (ok); + ok = ni && reparse_attr && (size >= sizeof(REPARSE_POINT)) + && (((size_t) le16_to_cpu(reparse_attr->reparse_data_length) + sizeof(REPARSE_POINT)) == size); + if (ok) + { + switch (reparse_attr->reparse_tag) + { + case IO_REPARSE_TAG_MOUNT_POINT: + mount_point_data = (const 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 (!(ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) || ((size_t) ((sizeof(REPARSE_POINT) + + sizeof(struct MOUNT_POINT_REPARSE_DATA) + offs + lth)) > size)) ok = FALSE; + break; + case IO_REPARSE_TAG_SYMLINK: + symlink_data = (const 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); + if ((size_t) ((sizeof(REPARSE_POINT) + sizeof(struct SYMLINK_REPARSE_DATA) + offs + lth)) > size) ok + = FALSE; + break; + default: + break; + } + } + if (!ok) errno = EINVAL; + return (ok); } /* @@ -463,93 +432,82 @@ static BOOL valid_reparse_data(ntfs_inode *ni, * or NULL if there were some problem, as described by errno */ -static char *ntfs_get_fulllink(ntfs_volume *vol, ntfschar *junction, - int count, const char *mnt_point, BOOL isdir) +static char *ntfs_get_fulllink(ntfs_volume *vol, ntfschar *junction, int count, const char *mnt_point, BOOL isdir) { - char *target; - char *fulltarget; - int sz; - char *q; - enum { DIR_JUNCTION, VOL_JUNCTION, NO_JUNCTION } kind; + char *target; + char *fulltarget; + int sz; + char *q; + enum + { + DIR_JUNCTION, VOL_JUNCTION, NO_JUNCTION + } kind; - target = (char*)NULL; - fulltarget = (char*)NULL; - /* - * For a valid directory junction we want \??\x:\ + 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) { - fulltarget = (char*)ntfs_malloc(strlen(mnt_point) - + strlen(target) + 2); - if (fulltarget) { - strcpy(fulltarget,mnt_point); - strcat(fulltarget,"/"); - strcat(fulltarget,target); - } - free(target); - } - } - /* - * Volume junctions or directory junctions with - * target not found on current volume : - * link to /.NTFS-3G/target which the user can - * define as a symbolic link to the real target - */ - if (((kind == DIR_JUNCTION) && !fulltarget) - || (kind == VOL_JUNCTION)) { - sz = ntfs_ucstombs(&junction[4], - (kind == VOL_JUNCTION ? count - 5 : count - 4), - &target, 0); - if ((sz > 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'; - fulltarget = (char*)ntfs_malloc(strlen(mnt_point) - + sizeof(mappingdir) + strlen(target) + 1); - if (fulltarget) { - strcpy(fulltarget,mnt_point); - strcat(fulltarget,"/"); - strcat(fulltarget,mappingdir); - strcat(fulltarget,target); - } - } - if (target) - free(target); - } - return (fulltarget); + */ + 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) + { + fulltarget = (char*) ntfs_malloc(strlen(mnt_point) + strlen(target) + 2); + if (fulltarget) + { + strcpy(fulltarget, mnt_point); + strcat(fulltarget, "/"); + strcat(fulltarget, target); + } + free(target); + } + } + /* + * Volume junctions or directory junctions with + * target not found on current volume : + * link to /.NTFS-3G/target which the user can + * define as a symbolic link to the real target + */ + if (((kind == DIR_JUNCTION) && !fulltarget) || (kind == VOL_JUNCTION)) + { + sz = ntfs_ucstombs(&junction[4], (kind == VOL_JUNCTION ? count - 5 : count - 4), &target, 0); + if ((sz > 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'; + fulltarget = (char*) ntfs_malloc(strlen(mnt_point) + sizeof(mappingdir) + strlen(target) + 1); + if (fulltarget) + { + strcpy(fulltarget, mnt_point); + strcat(fulltarget, "/"); + strcat(fulltarget, mappingdir); + strcat(fulltarget, target); + } + } + if (target) free(target); + } + return (fulltarget); } /* @@ -566,94 +524,84 @@ static char *ntfs_get_fulllink(ntfs_volume *vol, ntfschar *junction, * or NULL if there were some problem, as described by errno */ -static char *ntfs_get_abslink(ntfs_volume *vol, ntfschar *junction, - int count, const char *mnt_point, BOOL isdir) +static char *ntfs_get_abslink(ntfs_volume *vol, ntfschar *junction, int count, const char *mnt_point, BOOL isdir) { - char *target; - char *fulltarget; - int sz; - char *q; - enum { FULL_PATH, ABS_PATH, REJECTED_PATH } kind; + char *target; + char *fulltarget; + int sz; + char *q; + enum + { + FULL_PATH, ABS_PATH, REJECTED_PATH + } kind; - target = (char*)NULL; - fulltarget = (char*)NULL; - /* - * For a full valid path we want x:\ + target = (char*) NULL; + fulltarget = (char*) NULL; + /* + * For a full valid path we want x:\ * where \ is an individual char and x a non-null char + */ + if ((count >= 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 >= 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) { - fulltarget = (char*)ntfs_malloc(strlen(mnt_point) - + strlen(target) + 2); - if (fulltarget) { - strcpy(fulltarget,mnt_point); - strcat(fulltarget,"/"); - strcat(fulltarget,target); - } - free(target); - } - } - /* - * full path with target not found on current volume : - * link to /.NTFS-3G/target which the user can - * define as a symbolic link to the real target - */ - if ((kind == FULL_PATH) && !fulltarget) { - sz = ntfs_ucstombs(&junction[0], - count,&target, 0); - if ((sz > 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'; - fulltarget = (char*)ntfs_malloc(strlen(mnt_point) - + sizeof(mappingdir) + strlen(target) + 1); - if (fulltarget) { - strcpy(fulltarget,mnt_point); - strcat(fulltarget,"/"); - strcat(fulltarget,mappingdir); - strcat(fulltarget,target); - } - } - if (target) - free(target); - } - return (fulltarget); + 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) + { + fulltarget = (char*) ntfs_malloc(strlen(mnt_point) + strlen(target) + 2); + if (fulltarget) + { + strcpy(fulltarget, mnt_point); + strcat(fulltarget, "/"); + strcat(fulltarget, target); + } + free(target); + } + } + /* + * full path with target not found on current volume : + * link to /.NTFS-3G/target which the user can + * define as a symbolic link to the real target + */ + if ((kind == FULL_PATH) && !fulltarget) + { + sz = ntfs_ucstombs(&junction[0], count, &target, 0); + if ((sz > 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'; + fulltarget = (char*) ntfs_malloc(strlen(mnt_point) + sizeof(mappingdir) + strlen(target) + 1); + if (fulltarget) + { + strcpy(fulltarget, mnt_point); + strcat(fulltarget, "/"); + strcat(fulltarget, mappingdir); + strcat(fulltarget, target); + } + } + if (target) free(target); + } + return (fulltarget); } /* @@ -670,10 +618,10 @@ static char *ntfs_get_abslink(ntfs_volume *vol, ntfschar *junction, static char *ntfs_get_rellink(ntfs_inode *ni, ntfschar *junction, int count) { - char *target; + char *target; - target = search_relative(ni,junction,count); - return (target); + target = search_relative(ni, junction, count); + return (target); } /* @@ -686,106 +634,93 @@ static char *ntfs_get_rellink(ntfs_inode *ni, ntfschar *junction, int count) * symbolic link or directory junction */ -char *ntfs_make_symlink(ntfs_inode *ni, const char *mnt_point, - int *pattr_size) +char *ntfs_make_symlink(ntfs_inode *ni, const char *mnt_point, int *pattr_size) { - s64 attr_size = 0; - char *target; - unsigned int offs; - unsigned int lth; - ntfs_volume *vol; - REPARSE_POINT *reparse_attr; - struct MOUNT_POINT_REPARSE_DATA *mount_point_data; - struct SYMLINK_REPARSE_DATA *symlink_data; - enum { FULL_TARGET, ABS_TARGET, REL_TARGET } kind; - ntfschar *p; - BOOL bad; - BOOL isdir; + s64 attr_size = 0; + char *target; + unsigned int offs; + unsigned int lth; + ntfs_volume *vol; + REPARSE_POINT *reparse_attr; + struct MOUNT_POINT_REPARSE_DATA *mount_point_data; + struct SYMLINK_REPARSE_DATA *symlink_data; + enum + { + FULL_TARGET, ABS_TARGET, REL_TARGET + } kind; + ntfschar *p; + BOOL bad; + BOOL isdir; - 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 - && valid_reparse_data(ni, 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); - /* reparse data consistency has been checked */ - target = ntfs_get_fulllink(vol, - (ntfschar*)&mount_point_data->path_buffer[offs], - lth/2, mnt_point, 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--; - /* reparse data consistency has been checked */ - switch (kind) { - case FULL_TARGET : - if (!(symlink_data->flags - & const_cpu_to_le32(1))) { - target = ntfs_get_fulllink(vol, - p, lth/2, - mnt_point, 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, - mnt_point, isdir); - if (target) - bad = FALSE; - } - break; - case REL_TARGET : - if (symlink_data->flags - & const_cpu_to_le32(1)) { - target = ntfs_get_rellink(ni, - p, lth/2); - 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 && valid_reparse_data(ni, 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); + /* reparse data consistency has been checked */ + target = ntfs_get_fulllink(vol, (ntfschar*) &mount_point_data->path_buffer[offs], lth / 2, mnt_point, + 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--; + /* reparse data consistency has been checked */ + switch (kind) + { + case FULL_TARGET: + if (!(symlink_data->flags & const_cpu_to_le32(1))) + { + target = ntfs_get_fulllink(vol, p, lth / 2, mnt_point, 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, mnt_point, isdir); + if (target) bad = FALSE; + } + break; + case REL_TARGET: + if (symlink_data->flags & const_cpu_to_le32(1)) + { + target = ntfs_get_rellink(ni, p, lth / 2); + if (target) bad = FALSE; + } + break; + } + break; + } + free(reparse_attr); + } + *pattr_size = attr_size; + if (bad) errno = EOPNOTSUPP; + return (target); } /* @@ -798,23 +733,25 @@ char *ntfs_make_symlink(ntfs_inode *ni, const char *mnt_point, BOOL ntfs_possible_symlink(ntfs_inode *ni) { - s64 attr_size = 0; - REPARSE_POINT *reparse_attr; - BOOL possible; + 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 */ @@ -827,33 +764,33 @@ BOOL ntfs_possible_symlink(ntfs_inode *ni) */ static int set_reparse_index(ntfs_inode *ni, ntfs_index_context *xr, - le32 reparse_tag) + le32 reparse_tag) { - struct REPARSE_INDEX indx; - u64 file_id_cpu; - le64 file_id; - le16 seqn; + 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 */ @@ -866,36 +803,37 @@ static int set_reparse_index(ntfs_inode *ni, ntfs_index_context *xr, * -1 if failure, explained by errno */ -static int remove_reparse_index(ntfs_attr *na, ntfs_index_context *xr, - le32 *preparse_tag) +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; + 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) - && ntfs_index_rm(xr)) - ret = -1; - } 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) && ntfs_index_rm(xr)) ret = -1; + } + else + { + ret = -1; + errno = ENODATA; + } + } + return (ret); } /* @@ -909,28 +847,30 @@ static int remove_reparse_index(ntfs_attr *na, ntfs_index_context *xr, static ntfs_index_context *open_reparse_index(ntfs_volume *vol) { - u64 inum; - ntfs_inode *ni; - ntfs_inode *dir_ni; - ntfs_index_context *xr; + u64 inum; + ntfs_inode *ni; + ntfs_inode *dir_ni; + ntfs_index_context *xr; - /* do not use path_name_to inode - could reopen root */ - dir_ni = ntfs_inode_open(vol, FILE_Extend); - ni = (ntfs_inode*)NULL; - if (dir_ni) { - inum = ntfs_inode_lookup_by_mbsname(dir_ni,"$Reparse"); - if (inum != (u64)-1) - ni = ntfs_inode_open(vol, inum); - ntfs_inode_close(dir_ni); - } - 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); + /* do not use path_name_to inode - could reopen root */ + dir_ni = ntfs_inode_open(vol, FILE_Extend); + ni = (ntfs_inode*) NULL; + if (dir_ni) + { + inum = ntfs_inode_lookup_by_mbsname(dir_ni, "$Reparse"); + if (inum != (u64) -1) ni = ntfs_inode_open(vol, inum); + ntfs_inode_close(dir_ni); + } + 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 */ @@ -949,54 +889,60 @@ 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) + const char *value, size_t size) { - int res; - int written; - int oldsize; - ntfs_attr *na; - le32 reparse_tag; + 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 */ @@ -1010,32 +956,33 @@ static int update_reparse_data(ntfs_inode *ni, ntfs_index_context *xr, int ntfs_delete_reparse_index(ntfs_inode *ni) { - ntfs_index_context *xr; - ntfs_inode *xrni; - ntfs_attr *na; - le32 reparse_tag; - int res; + 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 */ @@ -1049,28 +996,33 @@ int ntfs_delete_reparse_index(ntfs_inode *ni) int ntfs_get_ntfs_reparse_data(ntfs_inode *ni, char *value, size_t size) { - REPARSE_POINT *reparse_attr; - s64 attr_size; + 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); } /* @@ -1082,67 +1034,85 @@ int ntfs_get_ntfs_reparse_data(ntfs_inode *ni, char *value, size_t size) */ int ntfs_set_ntfs_reparse_data(ntfs_inode *ni, - const char *value, size_t size, int flags) + const char *value, size_t size, int flags) { - int res; - u8 dummy; - ntfs_inode *xrni; - ntfs_index_context *xr; + int res; + u8 dummy; + ntfs_inode *xrni; + ntfs_index_context *xr; - res = 0; - if (ni && valid_reparse_data(ni, (const REPARSE_POINT*)value, size)) { - 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; - NInoFileNameSetDirty(ni); - } - 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 && valid_reparse_data(ni, (const REPARSE_POINT*)value, size)) + { + 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; + NInoFileNameSetDirty(ni); + } + 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); } /* @@ -1153,70 +1123,83 @@ int ntfs_set_ntfs_reparse_data(ntfs_inode *ni, int ntfs_remove_ntfs_reparse_data(ntfs_inode *ni) { - int res; - int olderrno; - ntfs_attr *na; - ntfs_inode *xrni; - ntfs_index_context *xr; - le32 reparse_tag; + 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; - NInoFileNameSetDirty(ni); - } 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; + NInoFileNameSetDirty(ni); + } + 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 35f4aa45..d7a38dac 100644 --- a/source/libntfs/reparse.h +++ b/source/libntfs/reparse.h @@ -24,14 +24,12 @@ #ifndef REPARSE_H #define REPARSE_H -char *ntfs_make_symlink(ntfs_inode *ni, const char *mnt_point, - int *pattr_size); +char *ntfs_make_symlink(ntfs_inode *ni, const char *mnt_point, int *pattr_size); BOOL ntfs_possible_symlink(ntfs_inode *ni); int ntfs_get_ntfs_reparse_data(ntfs_inode *ni, char *value, size_t size); -int ntfs_set_ntfs_reparse_data(ntfs_inode *ni, const char *value, - size_t size, int flags); +int ntfs_set_ntfs_reparse_data(ntfs_inode *ni, const char *value, size_t size, int flags); int ntfs_remove_ntfs_reparse_data(ntfs_inode *ni); int ntfs_delete_reparse_index(ntfs_inode *ni); diff --git a/source/libntfs/runlist.c b/source/libntfs/runlist.c index cea24672..098e8e2a 100644 --- a/source/libntfs/runlist.c +++ b/source/libntfs/runlist.c @@ -62,8 +62,7 @@ */ 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)); + if ((dst != src) && (size > 0)) memmove(base + dst, base + src, size * sizeof(*base)); } /** @@ -78,11 +77,9 @@ 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) +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)); + if (size > 0) memcpy(dstbase + dst, srcbase + src, size * sizeof(*dstbase)); } /** @@ -101,14 +98,12 @@ 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) +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); + 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); } /* @@ -120,31 +115,34 @@ static runlist_element *ntfs_rl_realloc(runlist_element *rl, int old_size, * the runlist is left unchanged if the reallocation fails */ -runlist_element *ntfs_rl_extend(ntfs_attr *na, runlist_element *rl, - int more_entries) +runlist_element *ntfs_rl_extend(ntfs_attr *na, runlist_element *rl, int more_entries) { - runlist_element *newrl; - int last; - int irl; + runlist_element *newrl; + int last; + int irl; - if (na->rl && rl) { - irl = (int)(rl - na->rl); - last = irl; - while (na->rl[last].length) - last++; - newrl = ntfs_rl_realloc(na->rl,last+1,last+more_entries+1); - if (!newrl) { - errno = ENOMEM; - rl = (runlist_element*)NULL; - } else - na->rl = newrl; - rl = &newrl[irl]; - } else { - ntfs_log_error("Cannot extend unmapped runlist"); - errno = EIO; - rl = (runlist_element*)NULL; - } - return (rl); + if (na->rl && rl) + { + irl = (int) (rl - na->rl); + last = irl; + while (na->rl[last].length) + last++; + newrl = ntfs_rl_realloc(na->rl, last + 1, last + more_entries + 1); + if (!newrl) + { + errno = ENOMEM; + rl = (runlist_element*) NULL; + } + else na->rl = newrl; + rl = &newrl[irl]; + } + else + { + ntfs_log_error("Cannot extend unmapped runlist"); + errno = EIO; + rl = (runlist_element*) NULL; + } + return (rl); } /** @@ -160,27 +158,23 @@ runlist_element *ntfs_rl_extend(ntfs_attr *na, runlist_element *rl, */ 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; - } + 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; } /** @@ -194,7 +188,7 @@ static BOOL ntfs_rl_are_mergeable(runlist_element *dst, runlist_element *src) */ static void __ntfs_rl_merge(runlist_element *dst, runlist_element *src) { - dst->length += src->length; + dst->length += src->length; } /** @@ -217,51 +211,47 @@ static void __ntfs_rl_merge(runlist_element *dst, runlist_element *src) * On error, return NULL, with errno set to the error code. Both runlists are * left unmodified. */ -static runlist_element *ntfs_rl_append(runlist_element *dst, int dsize, - runlist_element *src, int ssize, int loc) +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 */ + 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; } /** @@ -284,81 +274,83 @@ static runlist_element *ntfs_rl_append(runlist_element *dst, int dsize, * On error, return NULL, with errno set to the error code. Both runlists are * left unmodified. */ -static runlist_element *ntfs_rl_insert(runlist_element *dst, int dsize, - runlist_element *src, int ssize, int loc) +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 */ + 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; } /** @@ -380,72 +372,67 @@ static runlist_element *ntfs_rl_insert(runlist_element *dst, int dsize, * On error, return NULL, with errno set to the error code. Both runlists are * left unmodified. */ -static runlist_element *ntfs_rl_replace(runlist_element *dst, int dsize, - runlist_element *src, int ssize, - int loc) +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 */ + 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; } /** @@ -468,245 +455,245 @@ static runlist_element *ntfs_rl_replace(runlist_element *dst, int dsize, * On error, return NULL, with errno set to the error code. Both runlists are * left unmodified. */ -static runlist_element *ntfs_rl_split(runlist_element *dst, int dsize, - runlist_element *src, int ssize, int loc) +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; - } + 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) +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 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; - 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; + finished: + /* 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: + /* 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; } /** @@ -741,15 +728,14 @@ critical_error: * EINVAL Invalid parameters were passed in. * ERANGE The runlists overlap and cannot be merged. */ -runlist_element *ntfs_runlists_merge(runlist_element *drl, - runlist_element *srl) +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 *rl; + + ntfs_log_enter("Entering\n"); + rl = ntfs_runlists_merge_i(drl, srl); + ntfs_log_leave("\n"); + return rl; } /** @@ -779,239 +765,250 @@ runlist_element *ntfs_runlists_merge(runlist_element *drl, * two into one, if that is possible (we check for overlap and discard the new * runlist if overlap present before returning NULL, with errno = ERANGE). */ -static runlist_element *ntfs_mapping_pairs_decompress_i(const ntfs_volume *vol, - const ATTR_RECORD *attr, runlist_element *old_rl) +static 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 - runlist_elements. */ - u8 b; /* Current byte offset in buf. */ + 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. */ - 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) { -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; + /* 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; - 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; -io_error: - ntfs_log_debug("Corrupt attribute.\n"); -err_out: - free(rl); - errno = EIO; - 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"); + err_out: 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 *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; + runlist_element *rle; + + ntfs_log_enter("Entering\n"); + rle = ntfs_mapping_pairs_decompress_i(vol, attr, old_rl); + ntfs_log_leave("\n"); + return rle; } /** @@ -1035,37 +1032,34 @@ runlist_element *ntfs_mapping_pairs_decompress(const ntfs_volume *vol, */ LCN ntfs_rl_vcn_to_lcn(const runlist_element *rl, const VCN vcn) { - int i; + 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; } /** @@ -1092,70 +1086,63 @@ LCN ntfs_rl_vcn_to_lcn(const runlist_element *rl, const VCN vcn) * NOTE: If we encounter EOF while reading we return EIO because we assume that * 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 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; + 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); -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; -rl_err_out: - if (total) - return total; - errno = err; - return -1; + 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; + rl_err_out: if (total) return total; + errno = err; + return -1; } /** @@ -1181,78 +1168,68 @@ rl_err_out: * appropriately to the return code of ntfs_pwrite(), or to to EINVAL in case * 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 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 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); -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; - } -out: - return total; -rl_err_out: - if (total) - goto out; - errno = err; -errno_set: - total = -1; - goto out; + 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; + } + out: return total; + rl_err_out: if (total) goto out; + errno = err; + errno_set: total = -1; + goto out; } /** @@ -1270,19 +1247,21 @@ errno_set: */ int ntfs_get_nr_significant_bytes(const s64 n) { - u64 l; - int i; + 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; } /** @@ -1305,95 +1284,95 @@ int ntfs_get_nr_significant_bytes(const s64 n) * - @start_vcn is invalid. * 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) +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; + 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; -err_out: - if (rl->lcn == LCN_RL_NOT_MAPPED) - errno = EINVAL; - else - errno = EIO; -errno_set: - rls = -1; - goto out; + /* 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; } /** @@ -1416,35 +1395,35 @@ errno_set: */ int ntfs_write_significant_bytes(u8 *dst, const u8 *dst_max, const s64 n) { - s64 l = n; - int i; - s8 j; + 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; -err_out: - errno = ENOSPC; - return -1; + 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; } /** @@ -1478,143 +1457,121 @@ err_out: * EIO - The runlist is corrupt. * 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) +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; + 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; -out: - return ret; -size_err: - /* Set stop vcn. */ - if (stop_rl) - *stop_rl = rl; - /* Add terminator byte. */ - *dst = 0; -nospc_err: - errno = ENOSPC; - goto errno_set; -val_err: - errno = EINVAL; - goto errno_set; -err_out: - if (rl->lcn == LCN_RL_NOT_MAPPED) - errno = EINVAL; - else - errno = EIO; -errno_set: - ret = -1; - goto out; + /* 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; + size_err: + /* Set stop vcn. */ + if (stop_rl) *stop_rl = rl; + /* Add terminator byte. */ + *dst = 0; + nospc_err: errno = ENOSPC; + goto errno_set; + val_err: errno = EINVAL; + goto errno_set; + err_out: if (rl->lcn == LCN_RL_NOT_MAPPED) + errno = EINVAL; + else errno = EIO; + errno_set: ret = -1; + goto out; } /** @@ -1632,70 +1589,73 @@ errno_set: */ int ntfs_rl_truncate(runlist **arl, const VCN start_vcn) { - runlist *rl; - BOOL is_end = FALSE; + runlist *rl; + BOOL is_end = FALSE; - if (!arl || !*arl) { - errno = EINVAL; - if (!arl) - ntfs_log_perror("rl_truncate error: arl: %p", arl); - else - ntfs_log_perror("rl_truncate error:" + if (!arl || !*arl) + { + errno = EINVAL; + if (!arl) + ntfs_log_perror("rl_truncate error: arl: %p", arl); + else + 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; + 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; } /** @@ -1706,24 +1666,27 @@ int ntfs_rl_truncate(runlist **arl, const VCN start_vcn) */ int ntfs_rl_sparse(runlist *rl) { - runlist *rlc; + 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; } /** @@ -1735,29 +1698,32 @@ int ntfs_rl_sparse(runlist *rl) */ s64 ntfs_rl_get_compressed_size(ntfs_volume *vol, runlist *rl) { - runlist *rlc; - s64 ret = 0; + 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; } - #ifdef NTFS_TEST /** * test_rl_helper @@ -1767,8 +1733,8 @@ s64 ntfs_rl_get_compressed_size(ntfs_volume *vol, runlist *rl) (R)->lcn = L; \ (R)->length = S; /* -} -*/ + } + */ /** * test_rl_dump_runlist - Runlist test: Display the contents of a runlist * @rl: @@ -1779,46 +1745,52 @@ s64 ntfs_rl_get_compressed_size(ntfs_volume *vol, runlist *rl) */ 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" }; + 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"); } /** @@ -1832,19 +1804,19 @@ static void test_rl_dump_runlist(const runlist_element *rl) */ static runlist_element * test_rl_runlists_merge(runlist_element *drl, runlist_element *srl) { - runlist_element *res = NULL; + 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; } /** @@ -1859,21 +1831,23 @@ static runlist_element * test_rl_runlists_merge(runlist_element *drl, runlist_el */ static int test_rl_read_buffer(const char *file, u8 *buf, int bufsize) { - FILE *fptr; + 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; } /** @@ -1889,29 +1863,32 @@ static int test_rl_read_buffer(const char *file, u8 *buf, int bufsize) */ static runlist_element * test_rl_pure_src(BOOL contig, BOOL multi, int vcn, int len) { - runlist_element *result; - int fudge; + 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; } /** @@ -1930,23 +1907,24 @@ static runlist_element * test_rl_pure_src(BOOL contig, BOOL multi, int vcn, int */ 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; + 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); } /** @@ -1960,93 +1938,101 @@ static void test_rl_pure_test(int test, BOOL contig, BOOL multi, int vcn, int le */ 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; + /* 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)); } /** @@ -2058,21 +2044,21 @@ static void test_rl_pure(char *contig, char *multi) */ static void test_rl_zero(void) { - runlist_element *jim = NULL; - runlist_element *bob = NULL; + 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); } /** @@ -2088,27 +2074,27 @@ static void test_rl_zero(void) */ 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; + 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); } /** @@ -2121,40 +2107,40 @@ static void test_rl_frag_combine(ntfs_volume *vol, ATTR_RECORD *attr1, ATTR_RECO */ 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); + 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); + out: + free(attr1); + free(attr2); + free(attr3); } /** @@ -2168,13 +2154,13 @@ out: */ 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"); + 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 4b73af9f..38378e99 100644 --- a/source/libntfs/runlist.h +++ b/source/libntfs/runlist.h @@ -43,39 +43,35 @@ typedef runlist_element runlist; * When lcn == -1 this means that the count vcns starting at vcn are not * 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. */ +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. */ }; -extern runlist_element *ntfs_rl_extend(ntfs_attr *na, runlist_element *rl, - int more_entries); +extern runlist_element *ntfs_rl_extend(ntfs_attr *na, 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); -extern s64 ntfs_rl_pwrite(const ntfs_volume *vol, const runlist_element *rl, - s64 ofs, const s64 pos, s64 count, void *b); +extern s64 ntfs_rl_pread(const ntfs_volume *vol, const runlist_element *rl, 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); -extern runlist_element *ntfs_runlists_merge(runlist_element *drl, - runlist_element *srl); +extern runlist_element *ntfs_runlists_merge(runlist_element *drl, runlist_element *srl); -extern runlist_element *ntfs_mapping_pairs_decompress(const ntfs_volume *vol, - const ATTR_RECORD *attr, runlist_element *old_rl); +extern runlist_element *ntfs_mapping_pairs_decompress(const ntfs_volume *vol, 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); +extern int ntfs_get_size_for_mapping_pairs(const ntfs_volume *vol, 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); +extern int ntfs_write_significant_bytes(u8 *dst, const u8 *dst_max, 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); +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); extern int ntfs_rl_truncate(runlist **arl, const VCN start_vcn); diff --git a/source/libntfs/security.c b/source/libntfs/security.c index ecf3ca07..a9e110b6 100644 --- a/source/libntfs/security.c +++ b/source/libntfs/security.c @@ -74,7 +74,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 \ @@ -83,58 +83,54 @@ | FILE_ATTR_OFFLINE \ | 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; +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; - /* 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; +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; - /* 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) }; -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) }; +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) }; +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) }; /* * null SID (S-1-0-0) @@ -146,9 +142,9 @@ extern const SID *nullsid; * The zero GUID. */ -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 } }; -static const GUID *const zero_guid = &__zero_guid; +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 } }; +static const GUID * const zero_guid = &__zero_guid; /** * ntfs_guid_is_zero - check if a GUID is zero @@ -159,7 +155,7 @@ static const GUID *const zero_guid = &__zero_guid; */ BOOL ntfs_guid_is_zero(const GUID *guid) { - return (memcmp(guid, zero_guid, sizeof(*zero_guid))); + return (memcmp(guid, zero_guid, sizeof(*zero_guid))); } /** @@ -180,32 +176,28 @@ BOOL ntfs_guid_is_zero(const GUID *guid) */ char *ntfs_guid_to_mbs(const GUID *guid, char *guid_str) { - char *_guid_str; - int res; + 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; } /** @@ -221,39 +213,39 @@ char *ntfs_guid_to_mbs(const GUID *guid, char *guid_str) */ int ntfs_sid_to_mbs_size(const SID *sid) { - int size, i; + 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); } /** @@ -288,71 +280,66 @@ int ntfs_sid_to_mbs_size(const SID *sid) */ 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; + 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; -err_out: - if (i >= cnt) - i = EMSGSIZE; - else - i = errno; - if (!sid_str_size) - free(sid_str); - errno = i; - return NULL; + /* + * 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; } /** @@ -363,16 +350,15 @@ err_out: */ void ntfs_generate_guid(GUID *guid) { - unsigned int i; - u8 *p = (u8 *)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; + } } /** @@ -393,15 +379,16 @@ void ntfs_generate_guid(GUID *guid) */ 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; + 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); } /* @@ -410,85 +397,81 @@ le32 ntfs_security_hash(const SECURITY_DESCRIPTOR_RELATIVE *sd, const u32 len) * of fuse context */ -static int ntfs_local_read(ntfs_inode *ni, - ntfschar *stream_name, int stream_name_len, - char *buf, size_t size, off_t offset) +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; + 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; -exit: - if (na) - ntfs_attr_close(na); - return res; + 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; } - /* * Internal write * copied and pasted from ntfs_fuse_write() and made independent * of fuse context */ -static int ntfs_local_write(ntfs_inode *ni, - ntfschar *stream_name, int stream_name_len, - char *buf, size_t size, off_t offset) +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; + 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; -exit: - if (na) - ntfs_attr_close(na); - return res; + 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; } - /* * Get the first entry of current index block * cut and pasted form ntfs_ie_get_first() in index.c @@ -496,7 +479,7 @@ exit: static INDEX_ENTRY *ntfs_ie_get_first(INDEX_HEADER *ih) { - return (INDEX_ENTRY*)((u8*)ih + le32_to_cpu(ih->entries_offset)); + return (INDEX_ENTRY*) ((u8*) ih + le32_to_cpu(ih->entries_offset)); } /* @@ -520,33 +503,39 @@ static INDEX_ENTRY *ntfs_ie_get_first(INDEX_HEADER *ih) static int entersecurity_stuff(ntfs_volume *vol, off_t offs) { - int res; - int written; - unsigned long total; - char *stuff; + 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); } /* @@ -558,52 +547,44 @@ static int entersecurity_stuff(ntfs_volume *vol, off_t offs) * Returns zero if sucessful */ -static int entersecurity_data(ntfs_volume *vol, - const SECURITY_DESCRIPTOR_RELATIVE *attr, s64 attrsz, - le32 hash, le32 keyid, off_t offs, int gap) +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; + 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); } /* @@ -614,73 +595,74 @@ static int entersecurity_data(ntfs_volume *vol, * Returns zero if sucessful */ -static int entersecurity_indexes(ntfs_volume *vol, s64 attrsz, - le32 hash, le32 keyid, off_t offs) +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; + 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); } /* @@ -692,179 +674,184 @@ static int entersecurity_indexes(ntfs_volume *vol, s64 attrsz, * needed while fuse is not multithreaded */ -static le32 entersecurityattr(ntfs_volume *vol, - const SECURITY_DESCRIPTOR_RELATIVE *attr, s64 attrsz, - le32 hash) +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; - int retries; - ntfs_attr *na; - int olderrno; + 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; + int retries; + 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. - * This was however found not to be true : chkdsk - * sometimes deletes all the (unused) keys in the last - * index block without rebalancing the tree. - * When this happens, a new search is restarted from - * the smallest key. - */ - keyid = const_cpu_to_le32(0); - retries = 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 (!entry && !keyid && !retries) { - /* search failed, retry from smallest key */ - ntfs_index_ctx_reinit(xsii); - found = !ntfs_index_lookup((char*)&keyid, - sizeof(SII_INDEX_KEY), xsii); - if (!found && (errno != ENOENT)) { - ntfs_log_perror("Index $SII is broken"); - } else { - /* restore errno */ - errno = olderrno; - entry = xsii->entry; - } - retries++; - } - } - } - 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. + * This was however found not to be true : chkdsk + * sometimes deletes all the (unused) keys in the last + * index block without rebalancing the tree. + * When this happens, a new search is restarted from + * the smallest key. + */ + keyid = const_cpu_to_le32(0); + retries = 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 (!entry && !keyid && !retries) + { + /* search failed, retry from smallest key */ + ntfs_index_ctx_reinit(xsii); + found = !ntfs_index_lookup((char*) &keyid, sizeof(SII_INDEX_KEY), xsii); + if (!found && (errno != ENOENT)) + { + ntfs_log_perror("Index $SII is broken"); + } + else + { + /* restore errno */ + errno = olderrno; + entry = xsii->entry; + } + retries++; + } + } + } + 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); } /* @@ -876,121 +863,119 @@ static le32 entersecurityattr(ntfs_volume *vol, * needed while fuse is not multithreaded */ -static le32 setsecurityattr(ntfs_volume *vol, - const SECURITY_DESCRIPTOR_RELATIVE *attr, s64 attrsz) +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; + 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); } - /* * Update the security descriptor of a file * Either as an attribute (complying with pre v3.x NTFS version) @@ -999,109 +984,112 @@ static le32 setsecurityattr(ntfs_volume *vol, * returns 0 if success */ -static int update_secur_descr(ntfs_volume *vol, - char *newattr, ntfs_inode *ni) +static int update_secur_descr(ntfs_volume *vol, char *newattr, ntfs_inode *ni) { - int newattrsz; - int written; - int res; - ntfs_attr *na; + 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); - return (res); + /* mark node as dirty */ + NInoSetDirty(ni); + return (res); } /* @@ -1125,56 +1113,54 @@ static int update_secur_descr(ntfs_volume *vol, * -1 if there is a problem */ -static int upgrade_secur_desc(ntfs_volume *vol, - const char *attr, ntfs_inode *ni) +static int upgrade_secur_desc(ntfs_volume *vol, const char *attr, ntfs_inode *ni) { - int attrsz; - int res; - le32 securid; - ntfs_attr *na; + int attrsz; + int res; + le32 securid; + ntfs_attr *na; - /* - * upgrade requires NTFS format v3.x - * also refuse upgrading for special files - * whose number is less than FILE_first_user - */ + /* + * upgrade requires NTFS format v3.x + * also refuse upgrading for special files + * whose number is less than FILE_first_user + */ - if ((vol->major_ver >= 3) - && (ni->mft_no >= FILE_first_user)) { - 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); - } else - res = 1; + if ((vol->major_ver >= 3) && (ni->mft_no >= FILE_first_user)) + { + 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); + } + else res = 1; - return (res); + return (res); } /* @@ -1194,27 +1180,30 @@ static int upgrade_secur_desc(ntfs_volume *vol, static BOOL staticgroupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid) { - BOOL ingroup; - int grcnt; - gid_t *groups; - struct MAPPING *user; + 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); } - /* * Check whether current thread owner is member of file group * @@ -1238,86 +1227,93 @@ static BOOL staticgroupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid 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 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); } /* @@ -1357,30 +1353,28 @@ static BOOL groupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid) * and 30% if the cache is disabled. */ -static struct PERMISSIONS_CACHE *create_caches(struct SECURITY_CONTEXT *scx, - u32 securindex) +static struct PERMISSIONS_CACHE *create_caches(struct SECURITY_CONTEXT *scx, u32 securindex) { - struct PERMISSIONS_CACHE *cache; - unsigned int index1; - unsigned int i; + 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); } /* @@ -1390,69 +1384,68 @@ static struct PERMISSIONS_CACHE *create_caches(struct SECURITY_CONTEXT *scx, static void free_caches(struct SECURITY_CONTEXT *scx) { - unsigned int index1; - struct PERMISSIONS_CACHE *pseccache; + 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) +static int compare(const struct CACHED_SECURID *cached, 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) +static int leg_compare(const struct CACHED_PERMISSIONS_LEGACY *cached, const struct CACHED_PERMISSIONS_LEGACY *item) { - return (cached->mft_no != item->mft_no); + return (cached->mft_no != item->mft_no); } /* @@ -1464,42 +1457,37 @@ static int leg_compare(const struct CACHED_PERMISSIONS_LEGACY *cached, * consistent and errno is not set. */ -static void resize_cache(struct SECURITY_CONTEXT *scx, - u32 securindex) +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; + 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; + } + } } /* @@ -1512,156 +1500,175 @@ 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) +static struct CACHED_PERMISSIONS *enter_cache(struct SECURITY_CONTEXT *scx, 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); } /* @@ -1673,60 +1680,58 @@ static struct CACHED_PERMISSIONS *enter_cache(struct SECURITY_CONTEXT *scx, * returns the cache entry, or NULL if not available */ -static struct CACHED_PERMISSIONS *fetch_cache(struct SECURITY_CONTEXT *scx, - ntfs_inode *ni) +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; + 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); } /* @@ -1735,63 +1740,60 @@ static struct CACHED_PERMISSIONS *fetch_cache(struct SECURITY_CONTEXT *scx, 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; + 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); } /* @@ -1809,50 +1811,52 @@ static char *retrievesecurityattr(ntfs_volume *vol, SII_INDEX_KEY id) static char *getsecurityattr(ntfs_volume *vol, ntfs_inode *ni) { - SII_INDEX_KEY securid; - char *securattr; - s64 readallsz; + 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 inode %lld\n", - (long long)ni->mft_no); - 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 inode %lld\n", - (long long)ni->mft_no); - 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 inode %lld\n", + (long long)ni->mft_no); + 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 inode %lld\n", + (long long)ni->mft_no); + securattr = ntfs_build_descr(0, 0, adminsid, adminsid); + } + return (securattr); } #if POSIXACLS @@ -1865,116 +1869,130 @@ static char *getsecurityattr(ntfs_volume *vol, ntfs_inode *ni) */ static int access_check_posix(struct SECURITY_CONTEXT *scx, - struct POSIX_SECURITY *pxdesc, mode_t request, - uid_t uid, gid_t gid) + 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; - BOOL needgroups; - mode_t perms; - int i; + struct POSIX_ACE *pxace; + int userperms; + int groupperms; + int mask; + BOOL somegroup; + BOOL needgroups; + 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, get mask - * and identify whether we need to check - * the group memberships. The groups are - * not needed when all groups have the - * same permissions as other for the - * requested modes. - */ - userperms = -1; - groupperms = -1; - needgroups = FALSE; - 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; - case POSIX_ACL_GROUP_OBJ : - case POSIX_ACL_GROUP : - if (((pxace->perms & mask) ^ perms) - & (request >> 6) & 7) - needgroups = TRUE; - break; - default : - break; - } - } - /* designated users */ - if (userperms >= 0) - perms = (perms & 07000) + (userperms & mask); - else if (!needgroups) - perms &= 07007; - 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, get mask + * and identify whether we need to check + * the group memberships. The groups are + * not needed when all groups have the + * same permissions as other for the + * requested modes. + */ + userperms = -1; + groupperms = -1; + needgroups = FALSE; + 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; + case POSIX_ACL_GROUP_OBJ : + case POSIX_ACL_GROUP : + if (((pxace->perms & mask) ^ perms) + & (request >> 6) & 7) + needgroups = TRUE; + break; + default : + break; + } + } + /* designated users */ + if (userperms >= 0) + perms = (perms & 07000) + (userperms & mask); + else if (!needgroups) + perms &= 07007; + 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); } /* @@ -1987,96 +2005,108 @@ static int access_check_posix(struct SECURITY_CONTEXT *scx, */ static int ntfs_get_perm(struct SECURITY_CONTEXT *scx, - ntfs_inode * ni, mode_t request) + 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 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, 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, 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, - 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, + 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); } /* @@ -2088,132 +2118,151 @@ static int ntfs_get_perm(struct SECURITY_CONTEXT *scx, */ int ntfs_get_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - const char *name, char *value, size_t size) + const char *name, char *value, size_t size) { - 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 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, 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, 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, - 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, + 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 */ - /* * Get permissions to access a file * Takes into account the relation of user to file (owner, group, ...) @@ -2222,108 +2271,106 @@ int ntfs_get_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, * returns -1 if there is a problem */ -static int ntfs_get_perm(struct SECURITY_CONTEXT *scx, - ntfs_inode *ni, mode_t request) +static int ntfs_get_perm(struct SECURITY_CONTEXT *scx, 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 */ - BOOL isdir; - uid_t uid; - gid_t gid; - int perm; + 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 && !(request & S_IEXEC))) - 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, 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 && !(request & S_IEXEC))) + 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, 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, - 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 (!scx->uid) { - /* root access and execution */ - if (perm & 0111) - perm = 07777; - else - perm = 0; - } else - if (uid == scx->uid) - perm &= 07700; - else - /* - * avoid checking group membership - * when the requested perms for group - * are the same as perms for other - */ - if ((gid == scx->gid) - || ((((perm >> 3) ^ perm) - & (request >> 6) & 7) - && 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, 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 (!scx->uid) + { + /* root access and execution */ + if (perm & 0111) + perm = 07777; + else perm = 0; + } + else if (uid == scx->uid) + perm &= 07700; + else + /* + * avoid checking group membership + * when the requested perms for group + * are the same as perms for other + */ + if ((gid == scx->gid) || ((((perm >> 3) ^ perm) & (request >> 6) & 7) && groupmember(scx, scx->uid, gid))) + perm &= 07070; + else perm &= 07007; + } + } + return (perm); } #endif /* POSIXACLS */ @@ -2336,22 +2383,23 @@ static int ntfs_get_perm(struct SECURITY_CONTEXT *scx, * the caller is expected to issue a new call */ -int ntfs_get_ntfs_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - char *value, size_t size) +int ntfs_get_ntfs_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, char *value, size_t size) { - char *securattr; - size_t outsize; + char *securattr; + size_t outsize; - outsize = 0; /* default to no data and no error */ - securattr = getsecurityattr(scx->vol, 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, ni); + if (securattr) + { + outsize = ntfs_attr_size(securattr); + if (outsize <= size) + { + memcpy(value, securattr, outsize); + } + free(securattr); + } + return (outsize ? (int) outsize : -errno); } /* @@ -2359,101 +2407,99 @@ int ntfs_get_ntfs_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, * returns permissions, or -1 if there is a problem */ -int ntfs_get_owner_mode(struct SECURITY_CONTEXT *scx, - ntfs_inode * ni, struct stat *stbuf) +int ntfs_get_owner_mode(struct SECURITY_CONTEXT *scx, 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 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, 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, 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, - 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, 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 @@ -2464,79 +2510,89 @@ int ntfs_get_owner_mode(struct SECURITY_CONTEXT *scx, */ static struct POSIX_SECURITY *inherit_posix(struct SECURITY_CONTEXT *scx, - ntfs_inode *dir_ni, mode_t mode, BOOL isdir) + 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 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_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_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, - 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, + 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); } /* @@ -2546,80 +2602,87 @@ static struct POSIX_SECURITY *inherit_posix(struct SECURITY_CONTEXT *scx, */ le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, - uid_t uid, gid_t gid, ntfs_inode *dir_ni, - mode_t mode, BOOL isdir) + uid_t uid, gid_t gid, 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_ni, mode, isdir); - if (pxdesc) { - /* check whether target securid is known in cache */ + pxdesc = inherit_posix(scx, 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); } /* @@ -2628,134 +2691,140 @@ 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, - ntfs_inode *dir_ni, mode_t mode) + ntfs_inode *ni, uid_t uid, gid_t gid, + 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; + 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_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 && !isdir) { - 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_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 && !isdir) + { + 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,0); - } + 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,0); + } #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) +le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, 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 @@ -2769,125 +2838,129 @@ le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, #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) +int ntfs_set_owner_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, 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 (!isdir) { - if (mode & S_IWUSR) - ni->flags &= ~FILE_ATTR_READONLY; - else - ni->flags |= FILE_ATTR_READONLY; - NInoFileNameSetDirty(ni); - } - /* 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 (!isdir) + { + if (mode & S_IWUSR) + ni->flags &= ~FILE_ATTR_READONLY; + else ni->flags |= FILE_ATTR_READONLY; + NInoFileNameSetDirty(ni); + } + /* 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,0); - } + ntfs_invalidate_cache(scx->vol->legacy_cache, GENERIC(&legacy), (cache_compare) leg_compare, 0); + } #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); } /* @@ -2899,58 +2972,62 @@ int ntfs_set_owner_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, BOOL ntfs_allowed_as_owner(struct SECURITY_CONTEXT *scx, ntfs_inode *ni) { - const struct CACHED_PERMISSIONS *cached; - char *oldattr; - const SID *usid; - uid_t processuid; - uid_t uid; - BOOL gotowner; - int allowed; + const struct CACHED_PERMISSIONS *cached; + char *oldattr; + const SID *usid; + uid_t processuid; + uid_t uid; + BOOL gotowner; + int allowed; - processuid = scx->uid; -/* TODO : use CAP_FOWNER process capability */ - /* - * Always allow for root - * Also always allow if no mapping has been defined - */ - if (!scx->mapping[MAPUSERS] || !processuid) - allowed = TRUE; - else { - gotowner = FALSE; /* default */ - /* 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, ni); - if (oldattr) { + processuid = scx->uid; + /* TODO : use CAP_FOWNER process capability */ + /* + * Always allow for root + * Also always allow if no mapping has been defined + */ + if (!scx->mapping[MAPUSERS] || !processuid) + allowed = TRUE; + else + { + gotowner = FALSE; /* default */ + /* 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, 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 */ @@ -2966,100 +3043,115 @@ BOOL ntfs_allowed_as_owner(struct SECURITY_CONTEXT *scx, ntfs_inode *ni) */ int ntfs_set_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - const char *name, const char *value, size_t size, - int flags) + const char *name, const char *value, size_t size, + int flags) { - 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 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, 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, 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); } /* @@ -3069,10 +3161,10 @@ int ntfs_set_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, */ int ntfs_remove_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - const char *name) + const char *name) { - return (ntfs_set_posix_acl(scx, ni, name, - (const char*)NULL, 0, 0)); + return (ntfs_set_posix_acl(scx, ni, name, + (const char*)NULL, 0, 0)); } #endif @@ -3084,53 +3176,58 @@ int ntfs_remove_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, */ int ntfs_set_ntfs_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - const char *value, size_t size, int flags) + const char *value, size_t size, int flags) { - char *attr; - int res; + 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,0); - } + 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,0); + } #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 */ @@ -3147,107 +3244,121 @@ int ntfs_set_ntfs_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, int ntfs_set_mode(struct SECURITY_CONTEXT *scx, 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 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, ni); - if (oldattr) { - phead = (const SECURITY_DESCRIPTOR_RELATIVE*)oldattr; + } + else + { + oldattr = getsecurityattr(scx->vol, 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); } /* @@ -3257,67 +3368,63 @@ int ntfs_set_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, mode_t mode) 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; + /* JPA SECURITY_DESCRIPTOR_ATTR *sd; */ + SECURITY_DESCRIPTOR_RELATIVE *sd; + ACL *acl; + ACCESS_ALLOWED_ACE *ace; + SID *sid; + int ret, sd_len; - 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; + /* 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; } /* @@ -3332,78 +3439,74 @@ int ntfs_sd_add_everyone(ntfs_inode *ni) * This is used for Posix ACL and checking creation of DOS file names */ -int ntfs_allowed_access(struct SECURITY_CONTEXT *scx, - ntfs_inode *ni, - int accesstype) /* access type required (S_Ixxx values) */ +int ntfs_allowed_access(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, int accesstype) /* access type required (S_Ixxx values) */ { - int perm; - int res; - int allow; - struct stat stbuf; + int perm; + int res; + int allow; + struct stat stbuf; - /* - * 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, 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,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; - case S_IREAD + S_IWRITE + S_IEXEC: - allow = ((perm & (S_IRUSR | S_IRGRP | S_IROTH)) != 0) - && ((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, 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, 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; + case S_IREAD + S_IWRITE + S_IEXEC: + allow = ((perm & (S_IRUSR | S_IRGRP | S_IROTH)) != 0) && ((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); } #if 0 /* not needed any more */ @@ -3421,46 +3524,50 @@ int ntfs_allowed_access(struct SECURITY_CONTEXT *scx, */ BOOL old_ntfs_allowed_dir_access(struct SECURITY_CONTEXT *scx, - const char *path, int accesstype) + const char *path, int accesstype) { - int allow; - char *dirpath; - char *name; - ntfs_inode *ni; - ntfs_inode *dir_ni; - struct stat stbuf; + int allow; + char *dirpath; + char *name; + ntfs_inode *ni; + ntfs_inode *dir_ni; + struct stat stbuf; - 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, - 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,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, + 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,ni,&stbuf) >= 0) + && (stbuf.st_uid == scx->uid); + ntfs_inode_close(ni); + } + } + } + free(dirpath); + } + return (allow); /* errno is set if not allowed */ } #endif @@ -3471,120 +3578,123 @@ BOOL old_ntfs_allowed_dir_access(struct SECURITY_CONTEXT *scx, * returns zero if successful */ -int ntfs_set_owner(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - uid_t uid, gid_t gid) +int ntfs_set_owner(struct SECURITY_CONTEXT *scx, 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 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, 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, 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); } /* @@ -3593,113 +3703,119 @@ int ntfs_set_owner(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, * returns zero if successful */ -int ntfs_set_ownmod(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - uid_t uid, gid_t gid, const mode_t mode) +int ntfs_set_ownmod(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, uid_t uid, gid_t gid, const mode_t mode) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - const struct CACHED_PERMISSIONS *cached; - char *oldattr; - const SID *usid; - const SID *gsid; - uid_t fileuid; - uid_t filegid; - BOOL isdir; - int res; + const SECURITY_DESCRIPTOR_RELATIVE *phead; + const struct CACHED_PERMISSIONS *cached; + char *oldattr; + const SID *usid; + const SID *gsid; + uid_t fileuid; + uid_t filegid; + BOOL isdir; + int res; #if POSIXACLS - const struct POSIX_SECURITY *oldpxdesc; - struct POSIX_SECURITY *newpxdesc = (struct POSIX_SECURITY*)NULL; - int pxsize; + const struct POSIX_SECURITY *oldpxdesc; + struct POSIX_SECURITY *newpxdesc = (struct POSIX_SECURITY*)NULL; + int pxsize; #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; + 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; #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; - } + 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; + } #endif - } else { - fileuid = 0; - filegid = 0; - oldattr = getsecurityattr(scx->vol, 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; + oldattr = getsecurityattr(scx->vol, 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 - newpxdesc = ntfs_build_permissions_posix(scx->mapping, oldattr, - usid, gsid, isdir); - if (!newpxdesc || ntfs_merge_mode_posix(newpxdesc, mode)) - res = -1; - else { - fileuid = ntfs_find_user(scx->mapping[MAPUSERS],usid); - filegid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); - } + newpxdesc = ntfs_build_permissions_posix(scx->mapping, oldattr, + usid, gsid, isdir); + if (!newpxdesc || ntfs_merge_mode_posix(newpxdesc, mode)) + res = -1; + else + { + fileuid = ntfs_find_user(scx->mapping[MAPUSERS],usid); + filegid = ntfs_find_group(scx->mapping[MAPGROUPS],gsid); + } #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; + 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; #if POSIXACLS - res = ntfs_set_owner_mode(scx, ni, uid, gid, - mode, newpxdesc); + 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 { - res = -1; /* neither owner nor root */ - errno = EPERM; - } - } 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 + { + res = -1; /* neither owner nor root */ + errno = EPERM; + } + } + 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 - free(newpxdesc); + free(newpxdesc); #endif - return (res ? -1 : 0); + return (res ? -1 : 0); } /* @@ -3707,119 +3823,122 @@ int ntfs_set_ownmod(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, * parent directory the Windows way */ -static le32 build_inherited_id(struct SECURITY_CONTEXT *scx, - const char *parentattr, BOOL fordir) +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 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); } /* @@ -3838,50 +3957,49 @@ static le32 build_inherited_id(struct SECURITY_CONTEXT *scx, * Returns the inherited id, or zero if not possible (eg on NTFS 1.x) */ -le32 ntfs_inherited_id(struct SECURITY_CONTEXT *scx, - ntfs_inode *dir_ni, BOOL fordir) +le32 ntfs_inherited_id(struct SECURITY_CONTEXT *scx, ntfs_inode *dir_ni, BOOL fordir) { - struct CACHED_PERMISSIONS *cached; - char *parentattr; - le32 securid; + 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_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_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); } /* @@ -3890,43 +4008,42 @@ le32 ntfs_inherited_id(struct SECURITY_CONTEXT *scx, * Returns 0 if OK, -1 (and errno set) if error */ -static int link_single_group(struct MAPPING *usermapping, struct passwd *user, - gid_t gid) +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; + 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); } - /* * Statically link group to users * This is based on groups defined in /etc/group and does not take @@ -3941,31 +4058,27 @@ 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; + 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); } /* @@ -3973,37 +4086,39 @@ static int link_group_members(struct SECURITY_CONTEXT *scx) * returns zero if successful */ -static int ntfs_do_default_mapping(struct SECURITY_CONTEXT *scx, - uid_t uid, gid_t gid, const SID *usid) +static int ntfs_do_default_mapping(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid, const SID *usid) { - struct MAPPING *usermapping; - struct MAPPING *groupmapping; - SID *sid; - int sidsz; - int res; + 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 = uid; - usermapping->next = (struct MAPPING*)NULL; - groupmapping->sid = sid; - groupmapping->xid = gid; - 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 = uid; + usermapping->next = (struct MAPPING*) NULL; + groupmapping->sid = sid; + groupmapping->xid = gid; + groupmapping->next = (struct MAPPING*) NULL; + scx->mapping[MAPUSERS] = usermapping; + scx->mapping[MAPGROUPS] = groupmapping; + res = 0; + } + } + } + return (res); } /* @@ -4015,32 +4130,38 @@ 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 *groupmapping) { - const struct MAPPING *mapping1; - const struct MAPPING *mapping2; - BOOL ambiguous; + 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 @@ -4054,27 +4175,29 @@ static BOOL check_mapping(const struct MAPPING *usermapping, static int ntfs_default_mapping(struct SECURITY_CONTEXT *scx) { - const SECURITY_DESCRIPTOR_RELATIVE *phead; - ntfs_inode *ni; - char *securattr; - const SID *usid; - int res; + 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, - scx->uid, scx->gid, 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, + scx->uid, scx->gid, usid); + free(securattr); + } + ntfs_inode_close(ni); + } + return (res); } #endif @@ -4085,18 +4208,16 @@ static int ntfs_default_mapping(struct SECURITY_CONTEXT *scx) static int basicread(void *fileid, char *buf, size_t size, off_t offs __attribute__((unused))) { - return (read(*(int*)fileid, buf, size)); + return (read(*(int*) fileid, buf, size)); } - /* * 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)); + return (ntfs_local_read((ntfs_inode*) fileid, AT_UNNAMED, 0, buf, size, offs)); } /* @@ -4111,78 +4232,84 @@ 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, - BOOL allowdef) +int ntfs_build_mapping(struct SECURITY_CONTEXT *scx, const char *usermap_path, BOOL allowdef) { - struct MAPLIST *item; - struct MAPLIST *firstitem; - struct MAPPING *usermapping; - struct MAPPING *groupmapping; - ntfs_inode *ni; - int fd; - static struct { - u8 revision; - u8 levels; - be16 highbase; - be32 lowbase; - le32 level1; - le32 level2; - le32 level3; - le32 level4; - le32 level5; - } defmap = { - 1, 5, const_cpu_to_be16(0), const_cpu_to_be32(5), - const_cpu_to_le32(21), - const_cpu_to_le32(DEFSECAUTH1), const_cpu_to_le32(DEFSECAUTH2), - const_cpu_to_le32(DEFSECAUTH3), const_cpu_to_le32(DEFSECBASE) - } ; + struct MAPLIST *item; + struct MAPLIST *firstitem; + struct MAPPING *usermapping; + struct MAPPING *groupmapping; + ntfs_inode *ni; + int fd; + static struct + { + u8 revision; + u8 levels; + be16 highbase; + be32 lowbase; + le32 level1; + le32 level2; + le32 level3; + le32 level4; + le32 level5; + } defmap = { 1, 5, const_cpu_to_be16(0), const_cpu_to_be32(5), const_cpu_to_le32(21), + const_cpu_to_le32(DEFSECAUTH1), const_cpu_to_le32(DEFSECAUTH2), const_cpu_to_le32(DEFSECAUTH3), + const_cpu_to_le32(DEFSECBASE) }; - /* 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 a default mapping */ - if (allowdef) { - if (!ntfs_do_default_mapping(scx, - 0, 0, (const SID*)&defmap)) - 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 a default mapping */ + if (allowdef) + { + if (!ntfs_do_default_mapping(scx, 0, 0, (const SID*) &defmap)) ntfs_log_info("Using default user mapping\n"); + } + } + return (!scx->mapping[MAPUSERS] || link_group_members(scx)); } #ifdef HAVE_SETXATTR /* extended attributes interface required */ @@ -4194,27 +4321,29 @@ int ntfs_build_mapping(struct SECURITY_CONTEXT *scx, const char *usermap_path, int ntfs_get_ntfs_attrib(ntfs_inode *ni, char *value, size_t size) { - u32 attrib; - size_t outsize; + 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); } /* @@ -4225,50 +4354,57 @@ int ntfs_get_ntfs_attrib(ntfs_inode *ni, char *value, size_t size) */ int ntfs_set_ntfs_attrib(ntfs_inode *ni, - const char *value, size_t size, int flags) + const char *value, size_t size, int flags) { - u32 attrib; - le32 settable; - ATTR_FLAGS dirflags; - int res; + 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); - NInoFileNameSetDirty(ni); - 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); + NInoFileNameSetDirty(ni); + NInoSetDirty(ni); + } + } + else + errno = EEXIST; + } + else + errno = EINVAL; + return (res ? -1 : 0); } #endif /* HAVE_SETXATTR */ @@ -4279,32 +4415,32 @@ int ntfs_set_ntfs_attrib(ntfs_inode *ni, * non-zero if it fails. This is not an error (on NTFS v1.x) */ - int ntfs_open_secure(ntfs_volume *vol) { - ntfs_inode *ni; - int res; + 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); } /* @@ -4314,17 +4450,18 @@ int ntfs_open_secure(ntfs_volume *vol) void ntfs_close_secure(struct SECURITY_CONTEXT *scx) { - ntfs_volume *vol; + 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); } /* @@ -4332,156 +4469,154 @@ void ntfs_close_secure(struct SECURITY_CONTEXT *scx) * based on Win32 API */ - /* * Selective feeding of a security descriptor into user buffer * * Returns TRUE if successful */ -static BOOL feedsecurityattr(const char *attr, u32 selection, - char *buf, u32 buflen, u32 *psize) +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; + 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); } /* @@ -4491,159 +4626,155 @@ static BOOL feedsecurityattr(const char *attr, u32 selection, * Returns TRUE if successful */ -static BOOL mergesecurityattr(ntfs_volume *vol, const char *oldattr, - const char *newattr, u32 selection, ntfs_inode *ni) +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 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); } /* @@ -4667,41 +4798,40 @@ 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) +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; + 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, 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, 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); } - /* * Set the security descriptor of a file or directory * This is intended to be similar to SetFileSecurity() from Win32 @@ -4720,59 +4850,52 @@ 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) +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 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, - 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, 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); } - /* * Return the attributes of a file * This is intended to be similar to GetFileAttributes() from Win32 @@ -4789,30 +4912,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; + 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); } - /* * Set attributes to a file or directory * This is intended to be similar to SetFileAttributes() from Win32 @@ -4831,76 +4953,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) +BOOL ntfs_set_file_attributes(struct SECURITY_API *scapi, const char *path, s32 attrib) { - ntfs_inode *ni; - le32 settable; - ATTR_FLAGS dirflags; - int res; + 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) +BOOL ntfs_read_directory(struct SECURITY_API *scapi, const char *path, ntfs_filldir_t callback, void *context) { - ntfs_inode *ni; - BOOL ok; - s64 pos; + 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); } /* @@ -4909,21 +5030,19 @@ BOOL ntfs_read_directory(struct SECURITY_API *scapi, * Returns the number or read bytes, or -1 if there is an error */ -int ntfs_read_sds(struct SECURITY_API *scapi, - char *buf, u32 size, u32 offset) +int ntfs_read_sds(struct SECURITY_API *scapi, char *buf, u32 size, u32 offset) { - int got; + 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); } /* @@ -4932,34 +5051,33 @@ int ntfs_read_sds(struct SECURITY_API *scapi, * Returns next entry, or NULL if there is an error */ -INDEX_ENTRY *ntfs_read_sii(struct SECURITY_API *scapi, - INDEX_ENTRY *entry) +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; + 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); } /* @@ -4968,34 +5086,34 @@ INDEX_ENTRY *ntfs_read_sii(struct SECURITY_API *scapi, * Returns next entry, or NULL if there is an error */ -INDEX_ENTRY *ntfs_read_sdh(struct SECURITY_API *scapi, - INDEX_ENTRY *entry) +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; + 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); } /* @@ -5007,21 +5125,23 @@ INDEX_ENTRY *ntfs_read_sdh(struct SECURITY_API *scapi, int ntfs_get_usid(struct SECURITY_API *scapi, uid_t uid, char *buf) { - const SID *usid; - BIGSID defusid; - int size; + 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); } /* @@ -5033,21 +5153,23 @@ int ntfs_get_usid(struct SECURITY_API *scapi, uid_t uid, char *buf) int ntfs_get_gsid(struct SECURITY_API *scapi, gid_t gid, char *buf) { - const SID *gsid; - BIGSID defgsid; - int size; + 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); } /* @@ -5058,22 +5180,25 @@ int ntfs_get_gsid(struct SECURITY_API *scapi, gid_t gid, char *buf) int ntfs_get_user(struct SECURITY_API *scapi, const SID *usid) { - int uid; + 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); } /* @@ -5084,22 +5209,25 @@ int ntfs_get_user(struct SECURITY_API *scapi, const SID *usid) int ntfs_get_group(struct SECURITY_API *scapi, const SID *gsid) { - int gid; + 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); } /* @@ -5112,50 +5240,50 @@ int ntfs_get_group(struct SECURITY_API *scapi, const SID *gsid) * NULL if not root (EPERM) or device is mounted (EBUSY) */ -struct SECURITY_API *ntfs_initialize_file_security(const char *device, - int flags) +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; + 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,TRUE); - 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, TRUE); + 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); } /* @@ -5166,17 +5294,17 @@ struct SECURITY_API *ntfs_initialize_file_security(const char *device, BOOL ntfs_leave_file_security(struct SECURITY_API *scapi) { - int ok; - ntfs_volume *vol; + 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 4f3b5c54..24efb546 100644 --- a/source/libntfs/security.h +++ b/source/libntfs/security.h @@ -50,12 +50,13 @@ typedef u32 be32; * item in the mapping list */ -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 +{ + 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 */ }; /* @@ -63,153 +64,169 @@ struct MAPPING { * Note : this cache is not organized as a generic cache */ -struct CACHED_PERMISSIONS { - uid_t uid; - gid_t gid; - le32 inh_fileid; - le32 inh_dirid; +struct CACHED_PERMISSIONS +{ + 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; +}; /* * Entry in the permissions cache for directories with no security_id */ -struct CACHED_PERMISSIONS_LEGACY { - struct CACHED_PERMISSIONS_LEGACY *next; - struct CACHED_PERMISSIONS_LEGACY *previous; - void *variable; - size_t varsize; - /* above fields must match "struct CACHED_GENERIC" */ - u64 mft_no; - struct CACHED_PERMISSIONS perm; -} ; +struct CACHED_PERMISSIONS_LEGACY +{ + struct CACHED_PERMISSIONS_LEGACY *next; + struct CACHED_PERMISSIONS_LEGACY *previous; + void *variable; + size_t varsize; + /* above fields must match "struct CACHED_GENERIC" */ + u64 mft_no; + struct CACHED_PERMISSIONS perm; +}; /* * Entry in the securid cache */ -struct CACHED_SECURID { - struct CACHED_SECURID *next; - struct CACHED_SECURID *previous; - 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 +{ + struct CACHED_SECURID *next; + struct CACHED_SECURID *previous; + void *variable; + size_t varsize; + /* above fields must match "struct CACHED_GENERIC" */ + uid_t uid; + gid_t gid; + unsigned int dmode; + le32 securid; +}; /* * Header of the security cache * (has no cache structure by itself) */ -struct CACHED_PERMISSIONS_HEADER { - unsigned int last; - /* statistics for permissions */ - unsigned long p_writes; - unsigned long p_reads; - unsigned long p_hits; -} ; +struct CACHED_PERMISSIONS_HEADER +{ + unsigned int last; + /* statistics for permissions */ + unsigned long p_writes; + unsigned long p_reads; + unsigned long p_hits; +}; /* * The whole permissions cache */ -struct PERMISSIONS_CACHE { - struct CACHED_PERMISSIONS_HEADER head; - struct CACHED_PERMISSIONS *cachetable[1]; /* array of variable size */ -} ; +struct PERMISSIONS_CACHE +{ + struct CACHED_PERMISSIONS_HEADER head; + struct CACHED_PERMISSIONS *cachetable[1]; /* array of variable size */ +}; /* * Security flags values */ -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 */ -} ; +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 context, needed by most security functions */ -enum { MAPUSERS, MAPGROUPS, MAPCOUNT } ; +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 */ - } ; +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 */ +}; #if POSIXACLS /* * Posix ACL structures */ - -struct POSIX_ACE { - u16 tag; - u16 perms; - s32 id; -} ; - -struct POSIX_ACL { - 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; -} ; - +struct POSIX_ACE +{ + u16 tag; + u16 perms; + s32 id; +}; + +struct POSIX_ACL +{ + 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; +}; + /* * 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 @@ -228,80 +245,63 @@ extern char *ntfs_guid_to_mbs(const GUID *guid, char *guid_str); */ 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; + 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); +extern char *ntfs_sid_to_mbs(const SID *sid, char *sid_str, 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, - BOOL allowdef); -int ntfs_get_owner_mode(struct SECURITY_CONTEXT *scx, - ntfs_inode *ni, struct stat*); +int ntfs_build_mapping(struct SECURITY_CONTEXT *scx, const char *usermap_path, BOOL allowdef); +int ntfs_get_owner_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, struct stat*); int ntfs_set_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, mode_t mode); BOOL ntfs_allowed_as_owner(struct SECURITY_CONTEXT *scx, ntfs_inode *ni); -int ntfs_allowed_access(struct SECURITY_CONTEXT *scx, - ntfs_inode *ni, int accesstype); -BOOL old_ntfs_allowed_dir_access(struct SECURITY_CONTEXT *scx, - const char *path, int accesstype); +int ntfs_allowed_access(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, int accesstype); +BOOL old_ntfs_allowed_dir_access(struct SECURITY_CONTEXT *scx, const char *path, int accesstype); #if POSIXACLS le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, - uid_t uid, gid_t gid, ntfs_inode *dir_ni, - mode_t mode, BOOL isdir); + uid_t uid, gid_t gid, 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); +le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid, mode_t mode, BOOL isdir); #endif -int ntfs_set_owner(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - uid_t uid, gid_t gid); -int ntfs_set_ownmod(struct SECURITY_CONTEXT *scx, - ntfs_inode *ni, uid_t uid, gid_t gid, mode_t mode); +int ntfs_set_owner(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, uid_t uid, gid_t gid); +int ntfs_set_ownmod(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, uid_t uid, gid_t gid, mode_t mode); #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); +int ntfs_set_owner_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, uid_t uid, gid_t gid, mode_t mode); #endif -le32 ntfs_inherited_id(struct SECURITY_CONTEXT *scx, - ntfs_inode *dir_ni, BOOL fordir); +le32 ntfs_inherited_id(struct SECURITY_CONTEXT *scx, 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, - ntfs_inode *dir_ni, mode_t mode); + ntfs_inode *ni, uid_t uid, gid_t gid, + ntfs_inode *dir_ni, mode_t mode); int ntfs_get_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - const char *name, char *value, size_t size); + const char *name, char *value, size_t size); int ntfs_set_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - const char *name, const char *value, size_t size, - int flags); + const char *name, const char *value, size_t size, + int flags); int ntfs_remove_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - const char *name); + const char *name); #endif -int ntfs_get_ntfs_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - char *value, size_t size); -int ntfs_set_ntfs_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - const char *value, size_t size, int flags); +int ntfs_get_ntfs_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, char *value, size_t size); +int ntfs_set_ntfs_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, const char *value, size_t size, int flags); int ntfs_get_ntfs_attrib(ntfs_inode *ni, char *value, size_t size); -int ntfs_set_ntfs_attrib(ntfs_inode *ni, - const char *value, size_t size, int flags); - +int ntfs_set_ntfs_attrib(ntfs_inode *ni, const char *value, size_t size, int flags); /* * Security API for direct access to security descriptors @@ -310,11 +310,12 @@ int ntfs_set_ntfs_attrib(ntfs_inode *ni, #define MAGIC_API 0x09042009 -struct SECURITY_API { - u32 magic; - struct SECURITY_CONTEXT security; - struct PERMISSIONS_CACHE *seccache; -} ; +struct SECURITY_API +{ + u32 magic; + struct SECURITY_CONTEXT security; + struct PERMISSIONS_CACHE *seccache; +}; /* * The following constants are used in interfacing external programs. @@ -322,31 +323,24 @@ struct SECURITY_API { * native cpu representation. * 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 -} ; +enum +{ + OWNER_SECURITY_INFORMATION = 1, + 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); -int ntfs_set_file_security(struct SECURITY_API *scapi, - const char *path, u32 selection, const char *attr); -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); -BOOL ntfs_read_directory(struct SECURITY_API *scapi, - const char *path, ntfs_filldir_t callback, void *context); -int ntfs_read_sds(struct SECURITY_API *scapi, - char *buf, u32 size, u32 offset); -INDEX_ENTRY *ntfs_read_sii(struct SECURITY_API *scapi, - INDEX_ENTRY *entry); -INDEX_ENTRY *ntfs_read_sdh(struct SECURITY_API *scapi, - INDEX_ENTRY *entry); -struct SECURITY_API *ntfs_initialize_file_security(const char *device, - int flags); +int ntfs_get_file_security(struct SECURITY_API *scapi, 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); +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); +BOOL ntfs_read_directory(struct SECURITY_API *scapi, const char *path, ntfs_filldir_t callback, void *context); +int ntfs_read_sds(struct SECURITY_API *scapi, char *buf, u32 size, u32 offset); +INDEX_ENTRY *ntfs_read_sii(struct SECURITY_API *scapi, INDEX_ENTRY *entry); +INDEX_ENTRY *ntfs_read_sdh(struct SECURITY_API *scapi, INDEX_ENTRY *entry); +struct SECURITY_API *ntfs_initialize_file_security(const char *device, 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 3fafe8a7..80b9087d 100644 --- a/source/libntfs/types.h +++ b/source/libntfs/types.h @@ -39,12 +39,12 @@ #include "compat.h" #else /* GEKKO */ -typedef uint8_t u8; /* Unsigned types of an exact size */ +typedef uint8_t u8; /* Unsigned types of an exact size */ typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; -typedef int8_t s8; /* Signed types of an exact size */ +typedef int8_t s8; /* Signed types of an exact size */ typedef int16_t s16; typedef int32_t s32; typedef int64_t s64; @@ -63,7 +63,7 @@ typedef u16 sle16; typedef u32 sle32; typedef u64 sle64; -typedef u16 ntfschar; /* 2-byte Unicode character type. */ +typedef u16 ntfschar; /* 2-byte Unicode character type. */ #define UCHAR_T_SIZE_BITS 1 /* @@ -92,24 +92,25 @@ typedef sle64 leLSN; /** * enum BOOL - These are just to make the code more readable... */ -typedef enum { +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 /* defined _WINDEF_H */ @@ -118,9 +119,9 @@ typedef enum { /** * enum IGNORE_CASE_BOOL - */ -typedef enum { - CASE_SENSITIVE = 0, - IGNORE_CASE = 1, +typedef enum +{ + 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 cc3a1b8d..3969102e 100644 --- a/source/libntfs/unistr.c +++ b/source/libntfs/unistr.c @@ -88,18 +88,19 @@ static int nfconvert_utf8 = 1; * characters are (in)valid. */ #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, +static const u8 legal_ansi_char_array[0x40] = +{ + 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 @@ -117,19 +118,13 @@ static const u8 legal_ansi_char_array[0x40] = { * identical, or FALSE (0) if they are not identical. If @ic is IGNORE_CASE, * 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) +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; + 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; } /* @@ -148,86 +143,75 @@ BOOL ntfs_names_are_equal(const ntfschar *s1, size_t s1_len, * 1 if the second name collates before the first one, or * */ -int ntfs_names_full_collate(const ntfschar *name1, const u32 name1_len, - const ntfschar *name2, const u32 name2_len, - const IGNORE_CASE_BOOL ic, const ntfschar *upcase, - const u32 upcase_len) +int ntfs_names_full_collate(const ntfschar *name1, const u32 name1_len, const ntfschar *name2, const u32 name2_len, + const IGNORE_CASE_BOOL ic, const ntfschar *upcase, const u32 upcase_len) { - u32 cnt; - u16 c1, c2; - u16 u1, u2; + u32 cnt; + u16 c1, c2; + u16 u1, u2; #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); - if (cnt > 0) { - if (ic == CASE_SENSITIVE) { - do { - c1 = le16_to_cpu(*name1); - name1++; - c2 = le16_to_cpu(*name2); - name2++; - } while (--cnt && (c1 == c2)); - u1 = c1; - u2 = c2; - if (u1 < upcase_len) - u1 = le16_to_cpu(upcase[u1]); - if (u2 < upcase_len) - u2 = le16_to_cpu(upcase[u2]); - if ((u1 == u2) && cnt) - do { - u1 = le16_to_cpu(*name1); - name1++; - u2 = le16_to_cpu(*name2); - name2++; - if (u1 < upcase_len) - u1 = le16_to_cpu(upcase[u1]); - if (u2 < upcase_len) - u2 = le16_to_cpu(upcase[u2]); - } while ((u1 == u2) && --cnt); - if (u1 < u2) - return -1; - if (u1 > u2) - return 1; - if (name1_len < name2_len) - return -1; - if (name1_len > name2_len) - return 1; - if (c1 < c2) - return -1; - if (c1 > c2) - return 1; - } else { - do { - u1 = c1 = le16_to_cpu(*name1); - name1++; - u2 = c2 = le16_to_cpu(*name2); - name2++; - if (u1 < upcase_len) - u1 = le16_to_cpu(upcase[u1]); - if (u2 < upcase_len) - u2 = le16_to_cpu(upcase[u2]); - } while ((u1 == u2) && --cnt); - if (u1 < u2) - return -1; - if (u1 > u2) - return 1; - if (name1_len < name2_len) - return -1; - if (name1_len > name2_len) - return 1; - } - } else { - if (name1_len < name2_len) - return -1; - if (name1_len > name2_len) - return 1; - } - return 0; + cnt = min(name1_len, name2_len); + if (cnt > 0) + { + if (ic == CASE_SENSITIVE) + { + do + { + c1 = le16_to_cpu(*name1); + name1++; + c2 = le16_to_cpu(*name2); + name2++; + } while (--cnt && (c1 == c2)); + u1 = c1; + u2 = c2; + if (u1 < upcase_len) u1 = le16_to_cpu(upcase[u1]); + if (u2 < upcase_len) u2 = le16_to_cpu(upcase[u2]); + if ((u1 == u2) && cnt) do + { + u1 = le16_to_cpu(*name1); + name1++; + u2 = le16_to_cpu(*name2); + name2++; + if (u1 < upcase_len) u1 = le16_to_cpu(upcase[u1]); + if (u2 < upcase_len) u2 = le16_to_cpu(upcase[u2]); + } while ((u1 == u2) && --cnt); + if (u1 < u2) return -1; + if (u1 > u2) return 1; + if (name1_len < name2_len) return -1; + if (name1_len > name2_len) return 1; + if (c1 < c2) return -1; + if (c1 > c2) return 1; + } + else + { + do + { + u1 = c1 = le16_to_cpu(*name1); + name1++; + u2 = c2 = le16_to_cpu(*name2); + name2++; + if (u1 < upcase_len) u1 = le16_to_cpu(upcase[u1]); + if (u2 < upcase_len) u2 = le16_to_cpu(upcase[u2]); + } while ((u1 == u2) && --cnt); + if (u1 < u2) return -1; + if (u1 > u2) return 1; + if (name1_len < name2_len) return -1; + if (name1_len > name2_len) return 1; + } + } + else + { + if (name1_len < name2_len) return -1; + if (name1_len > name2_len) return 1; + } + return 0; } /** @@ -246,26 +230,25 @@ int ntfs_names_full_collate(const ntfschar *name1, const u32 name1_len, */ int ntfs_ucsncmp(const ntfschar *s1, const ntfschar *s2, size_t n) { - ntfschar c1, c2; - size_t i; + 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; } /** @@ -286,31 +269,27 @@ int ntfs_ucsncmp(const ntfschar *s1, const ntfschar *s2, size_t n) * 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_ucsncasecmp(const ntfschar *s1, const ntfschar *s2, size_t n, - const ntfschar *upcase, const u32 upcase_size) +int ntfs_ucsncasecmp(const ntfschar *s1, const ntfschar *s2, size_t n, const ntfschar *upcase, const u32 upcase_size) { - u16 c1, c2; - size_t i; + u16 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; } /** @@ -327,13 +306,13 @@ int ntfs_ucsncasecmp(const ntfschar *s1, const ntfschar *s2, size_t n, */ u32 ntfs_ucsnlen(const ntfschar *s, u32 maxlen) { - u32 i; + 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; } /** @@ -355,16 +334,17 @@ u32 ntfs_ucsnlen(const ntfschar *s, u32 maxlen) */ ntfschar *ntfs_ucsndup(const ntfschar *s, u32 maxlen) { - ntfschar *dst; - u32 len; + 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; } /** @@ -378,30 +358,25 @@ 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) +void ntfs_name_upcase(ntfschar *name, u32 name_len, const ntfschar *upcase, const u32 upcase_len) { - u32 i; - u16 u; + u32 i; + u16 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]; } /** * ntfs_name_locase - Map a Unicode name to its lowercase equivalent */ -void ntfs_name_locase(ntfschar *name, u32 name_len, const ntfschar *locase, - const u32 locase_len) +void ntfs_name_locase(ntfschar *name, u32 name_len, const ntfschar *locase, const u32 locase_len) { - u32 i; - u16 u; + u32 i; + u16 u; - if (locase) - for (i = 0; i < name_len; i++) - if ((u = le16_to_cpu(name[i])) < locase_len) - name[i] = locase[u]; + if (locase) for (i = 0; i < name_len; i++) + if ((u = le16_to_cpu(name[i])) < locase_len) name[i] = locase[u]; } /** @@ -414,37 +389,35 @@ void ntfs_name_locase(ntfschar *name, u32 name_len, const ntfschar *locase, * * Returns: */ -void ntfs_file_value_upcase(FILE_NAME_ATTR *file_name_attr, - const ntfschar *upcase, const u32 upcase_len) +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); + ntfs_name_upcase((ntfschar*) &file_name_attr->file_name, file_name_attr->file_name_length, upcase, upcase_len); } /* - NTFS uses Unicode (UTF-16LE [NTFS-3G uses UCS-2LE, which is enough - for now]) for path names, but the Unicode code points need to be - converted before a path can be accessed under NTFS. For 7 bit ASCII/ANSI, - glibc does this even without a locale in a hard-coded fashion as that - appears to be is easy because the low 7-bit ASCII range appears to be - available in all charsets but it does not convert anything if - there was some error with the locale setup or none set up like - when mount is called during early boot where he (by policy) do - not use locales (and may be not available if /usr is not yet mounted), - 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. -*/ + NTFS uses Unicode (UTF-16LE [NTFS-3G uses UCS-2LE, which is enough + for now]) for path names, but the Unicode code points need to be + converted before a path can be accessed under NTFS. For 7 bit ASCII/ANSI, + glibc does this even without a locale in a hard-coded fashion as that + appears to be is easy because the low 7-bit ASCII range appears to be + available in all charsets but it does not convert anything if + there was some error with the locale setup or none set up like + when mount is called during early boot where he (by policy) do + not use locales (and may be not available if /usr is not yet mounted), + 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. @@ -453,50 +426,50 @@ void ntfs_file_value_upcase(FILE_NAME_ATTR *file_name_attr, */ 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; + 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; -out: - return ret; -fail: - errno = EILSEQ; - goto out; + ret = count; + out: return ret; + fail: errno = EILSEQ; + goto out; } /* @@ -508,107 +481,119 @@ 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) +static int ntfs_utf16_to_utf8(const ntfschar *ins, const int ins_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; - int halfpair; + char *t; + int i, size, ret = -1; + int 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; + 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'; - 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; -out: - return ret; -fail: - errno = EILSEQ; - goto out; + + ret = t - *outs; + out: return ret; + fail: errno = EILSEQ; + goto out; } /* @@ -622,41 +607,36 @@ fail: */ static int utf8_to_utf16_size(const char *s) { - int ret = -1; - unsigned int byte; - size_t count = 0; + int ret = -1; + unsigned int byte; + size_t count = 0; - while ((byte = *((const unsigned char *)s++))) { - if (++count >= PATH_MAX) - goto fail; - if (byte >= 0xc0) { - 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; -fail: - errno = ENAMETOOLONG; - goto out; + while ((byte = *((const unsigned char *) s++))) + { + if (++count >= PATH_MAX) goto fail; + if (byte >= 0xc0) + { + 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; + fail: errno = ENAMETOOLONG; + goto out; } /* * This converts one UTF-8 sequence to cpu-endian Unicode value @@ -667,60 +647,64 @@ fail: */ static int utf8_to_unicode(u32 *wc, const char *s) { - unsigned int byte = *((const unsigned 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 ((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 (((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 ((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 (((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 (((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; + } + goto fail; + /* four-byte */ + } + else if (byte < 0xF5) + { + 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; } /** @@ -735,70 +719,75 @@ 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; - BOOL allocated; - ntfschar *outpos; - int shorts, ret = -1; + const char *t = ins; + u32 wc; + BOOL allocated; + 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; - allocated = FALSE; - if (!*outs) { - *outs = ntfs_malloc((shorts + 1) * sizeof(ntfschar)); - if (!*outs) - goto fail; - allocated = TRUE; - } + allocated = FALSE; + if (!*outs) + { + *outs = ntfs_malloc((shorts + 1) * sizeof(ntfschar)); + if (!*outs) goto fail; + allocated = TRUE; + } - outpos = *outs; + outpos = *outs; - while(1) { - int m = utf8_to_unicode(&wc, t); - if (m <= 0) { - if (m < 0) { - /* do not leave space allocated if failed */ - if (allocated) { - free(*outs); - *outs = (ntfschar*)NULL; - } - goto fail; - } - *outpos++ = const_cpu_to_le16(0); - break; - } - 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); - } - t += m; - } - - ret = --outpos - *outs; -fail: + while (1) + { + int m = utf8_to_unicode(&wc, t); + if (m <= 0) + { + if (m < 0) + { + /* do not leave space allocated if failed */ + if (allocated) + { + free(*outs); + *outs = (ntfschar*) NULL; + } + goto fail; + } + *outpos++ = const_cpu_to_le16(0); + break; + } + 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); + } + 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; } /** @@ -826,95 +815,96 @@ fail: * ENAMETOOLONG Destination buffer is too small for input string. * ENOMEM Not enough memory to allocate destination buffer. */ -int ntfs_ucstombs(const ntfschar *ins, const int ins_len, char **outs, - int outs_len) +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; + 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; -err_out: - if (mbs != *outs) { - int eo = errno; - free(mbs); - errno = eo; - } - return -1; + /* 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; } /** @@ -942,112 +932,113 @@ err_out: */ 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; + 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 (use_utf8) - return ntfs_utf8_to_utf16(ins, outs); + if (!ins || !outs) + { + errno = EINVAL; + return -1; + } - /* 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 (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; #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; -err_out: - free(ucs); - return -1; + /* Now write the NULL character. */ + ucs[o] = cpu_to_le16(L'\0'); + *outs = ucs; + return o; + err_out: free(ucs); + return -1; } /* @@ -1057,52 +1048,59 @@ err_out: * or NULL if there is an error (described by errno) */ -char *ntfs_uppercase_mbs(const char *low, - const ntfschar *upcase, u32 upcase_size) +char *ntfs_uppercase_mbs(const char *low, const ntfschar *upcase, u32 upcase_size) { - int size; - char *upp; - u32 wc; - int n; - const char *s; - char *t; + int size; + char *upp; + u32 wc; + int n; + const char *s; + char *t; - size = strlen(low); - upp = (char*)ntfs_malloc(3*size + 1); - if (upp) { - s = low; - t = upp; - do { - n = utf8_to_unicode(&wc, s); - if (n > 0) { - if (wc < upcase_size) - wc = le16_to_cpu(upcase[wc]); - if (wc < 0x80) - *t++ = wc; - else if (wc < 0x800) { - *t++ = (0xc0 | ((wc >> 6) & 0x3f)); - *t++ = 0x80 | (wc & 0x3f); - } else if (wc < 0x10000) { - *t++ = 0xe0 | (wc >> 12); - *t++ = 0x80 | ((wc >> 6) & 0x3f); - *t++ = 0x80 | (wc & 0x3f); - } else { - *t++ = 0xf0 | ((wc >> 18) & 7); - *t++ = 0x80 | ((wc >> 12) & 63); - *t++ = 0x80 | ((wc >> 6) & 0x3f); - *t++ = 0x80 | (wc & 0x3f); - } - s += n; - } - } while (n > 0); - if (n < 0) { - free(upp); - upp = (char*)NULL; - errno = EILSEQ; - } - *t = 0; - } - return (upp); + size = strlen(low); + upp = (char*) ntfs_malloc(3 * size + 1); + if (upp) + { + s = low; + t = upp; + do + { + n = utf8_to_unicode(&wc, s); + if (n > 0) + { + if (wc < upcase_size) wc = le16_to_cpu(upcase[wc]); + if (wc < 0x80) + *t++ = wc; + else if (wc < 0x800) + { + *t++ = (0xc0 | ((wc >> 6) & 0x3f)); + *t++ = 0x80 | (wc & 0x3f); + } + else if (wc < 0x10000) + { + *t++ = 0xe0 | (wc >> 12); + *t++ = 0x80 | ((wc >> 6) & 0x3f); + *t++ = 0x80 | (wc & 0x3f); + } + else + { + *t++ = 0xf0 | ((wc >> 18) & 7); + *t++ = 0x80 | ((wc >> 12) & 63); + *t++ = 0x80 | ((wc >> 6) & 0x3f); + *t++ = 0x80 | (wc & 0x3f); + } + s += n; + } + } while (n > 0); + if (n < 0) + { + free(upp); + upp = (char*) NULL; + errno = EILSEQ; + } + *t = 0; + } + return (upp); } /** @@ -1117,63 +1115,53 @@ char *ntfs_uppercase_mbs(const char *low, */ 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; + 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); + } } /* @@ -1190,22 +1178,24 @@ void ntfs_upcase_table_build(ntfschar *uc, u32 uc_len) ntfschar *ntfs_locase_table_build(const ntfschar *uc, u32 uc_cnt) { - ntfschar *lc; - u32 upp; - u32 i; + ntfschar *lc; + u32 upp; + u32 i; - lc = (ntfschar*)ntfs_malloc(uc_cnt*sizeof(ntfschar)); - if (lc) { - for (i=0; i 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; } /** @@ -1255,8 +1248,7 @@ ntfschar *ntfs_str2ucs(const char *s, int *len) */ void ntfs_ucsfree(ntfschar *ucs) { - if (ucs && (ucs != AT_UNNAMED)) - free(ucs); + if (ucs && (ucs != AT_UNNAMED)) free(ucs); } /* @@ -1268,32 +1260,21 @@ void ntfs_ucsfree(ntfschar *ucs) 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 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]) == ' ') - || (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 < shortlen; i++) + { + ch = le16_to_cpu(longname[i]); + if ((ch >= vol->upcase_len) || ((shortname[i] != longname[i]) && (shortname[i] != vol->upcase[ch]))) collapsible + = FALSE; + } + return (collapsible); } /* @@ -1331,95 +1309,103 @@ BOOL ntfs_collapsible_chars(ntfs_volume *vol, 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 */ + 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) { +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; - - /* 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"); + /* 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; - - CFRelease(cfMutableString); - - if(result != NULL) { - *target = result; - return resultLength - 1; - } - else - return -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"); + + 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 639c5033..7d38a59f 100644 --- a/source/libntfs/unistr.h +++ b/source/libntfs/unistr.h @@ -26,39 +26,31 @@ #include "types.h" #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); +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); -extern int ntfs_names_full_collate(const ntfschar *name1, const u32 name1_len, - const ntfschar *name2, const u32 name2_len, - const IGNORE_CASE_BOOL ic, - const ntfschar *upcase, const u32 upcase_len); +extern int ntfs_names_full_collate(const ntfschar *name1, const u32 name1_len, const ntfschar *name2, + const u32 name2_len, 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); +extern int ntfs_ucsncasecmp(const ntfschar *s1, const ntfschar *s2, size_t n, 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); +extern void ntfs_name_upcase(ntfschar *name, u32 name_len, const ntfschar *upcase, const u32 upcase_len); -extern void ntfs_name_locase(ntfschar *name, u32 name_len, - const ntfschar *locase, const u32 locase_len); +extern void ntfs_name_locase(ntfschar *name, u32 name_len, const ntfschar *locase, const u32 locase_len); -extern void ntfs_file_value_upcase(FILE_NAME_ATTR *file_name_attr, - 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); -extern int ntfs_ucstombs(const ntfschar *ins, const int ins_len, char **outs, - int outs_len); +extern int ntfs_ucstombs(const ntfschar *ins, const int ins_len, char **outs, int outs_len); extern int ntfs_mbstoucs(const char *ins, ntfschar **outs); -extern char *ntfs_uppercase_mbs(const char *low, - const ntfschar *upcase, u32 upcase_len); +extern char *ntfs_uppercase_mbs(const char *low, const ntfschar *upcase, u32 upcase_len); extern void ntfs_upcase_table_build(ntfschar *uc, u32 uc_len); extern ntfschar *ntfs_locase_table_build(const ntfschar *uc, u32 uc_cnt); @@ -68,9 +60,8 @@ extern ntfschar *ntfs_str2ucs(const char *s, int *len); 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); +extern BOOL ntfs_collapsible_chars(ntfs_volume *vol, const ntfschar *shortname, int shortlen, const ntfschar *longname, + int longlen); extern int ntfs_set_char_encoding(const char *locale); diff --git a/source/libntfs/volume.c b/source/libntfs/volume.c index 629ec92c..37d60a28 100644 --- a/source/libntfs/volume.c +++ b/source/libntfs/volume.c @@ -69,51 +69,43 @@ #include "cache.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"; +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"; -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"; +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"; -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"; +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"; -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"; +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"; -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"; +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"; -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"; +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"; -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"; +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"; /** * ntfs_volume_alloc - Create an NTFS volume object and initialise it @@ -124,33 +116,34 @@ static const char *access_denied_msg = */ ntfs_volume *ntfs_volume_alloc(void) { - return ntfs_calloc(sizeof(ntfs_volume)); + return ntfs_calloc(sizeof(ntfs_volume)); } static void ntfs_attr_free(ntfs_attr **na) { - if (na && *na) { - ntfs_attr_close(*na); - *na = NULL; - } + if (na && *na) + { + ntfs_attr_close(*na); + *na = NULL; + } } static int ntfs_inode_free(ntfs_inode **ni) { - int ret = -1; + 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; + if (!*err) *err = errno; } /** @@ -163,62 +156,55 @@ static void ntfs_error_set(int *err) */ static int __ntfs_volume_release(ntfs_volume *v) { - int err = 0; + 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 (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 (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 (dev->d_ops->sync(dev)) - ntfs_error_set(&err); - if (dev->d_ops->close(dev)) - 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); - ntfs_free_lru_caches(v); - free(v->vol_name); - free(v->upcase); - if (v->locase) free(v->locase); - free(v->attrdef); - free(v); + 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); - errno = err; - return errno ? -1 : 0; + 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); + if (v->locase) free(v->locase); + free(v->attrdef); + free(v); + + errno = err; + return errno ? -1 : 0; } static void ntfs_attr_setup_flag(ntfs_inode *ni) { - STANDARD_INFORMATION *si; + 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); + } } /** @@ -233,171 +219,177 @@ static void ntfs_attr_setup_flag(ntfs_inode *ni) */ 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; + 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; - } - - 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; + /* 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; + } - /* 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; - } + if (ntfs_mft_record_check(vol, 0, mb)) goto error_exit; -mft_has_no_attr_list: + ctx = ntfs_attr_get_search_ctx(vol->mft_ni, NULL); + if (!ctx) goto error_exit; - 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; + /* 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; - 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; + 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; + } - /* Get the lowest vcn for the next extent. */ - highest_vcn = sle64_to_cpu(a->highest_vcn); - next_vcn = highest_vcn + 1; + mft_has_no_attr_list: - /* Only one extent or error, which we catch below. */ - if (next_vcn <= 0) - break; + ntfs_attr_setup_flag(vol->mft_ni); - /* 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; -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; + /* 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; + + 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 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; + io_error_exit: 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; } /** @@ -413,37 +405,40 @@ error_exit: */ static int ntfs_mftmirr_load(ntfs_volume *vol) { - int err; + 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; + } -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; + 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; } /** @@ -460,153 +455,148 @@ error_exit: */ 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; + 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; - - /* 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)); - /* Default with no locase table and case sensitive file names */ - vol->locase = (ntfschar*)NULL; - NVolSetCaseSensitive(vol); - - /* by default, all files are shown and not marked hidden */ - NVolSetShowSysFiles(vol); - NVolSetShowHidFiles(vol); - NVolClearHideDotFiles(vol); - 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% */ + bs = ntfs_malloc(sizeof(NTFS_BOOT_SECTOR)); + if (!bs) return NULL; - /* 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); + /* Allocate the volume structure. */ + vol = ntfs_volume_alloc(); + if (!vol) 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); + /* Create the default upcase table. */ + vol->upcase_len = 65536; + vol->upcase = ntfs_malloc(vol->upcase_len * sizeof(ntfschar)); + if (!vol->upcase) goto error_exit; - /* - * 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); + ntfs_upcase_table_build(vol->upcase, vol->upcase_len * sizeof(ntfschar)); + /* Default with no locase table and case sensitive file names */ + vol->locase = (ntfschar*) NULL; + NVolSetCaseSensitive(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); + /* by default, all files are shown and not marked hidden */ + NVolSetShowSysFiles(vol); + NVolSetShowHidFiles(vol); + NVolClearHideDotFiles(vol); + if (flags & MS_RDONLY) NVolSetReadOnly(vol); - /* Set the mft data allocation position to mft record 24. */ - vol->mft_data_pos = 24; + /* ...->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; - /* - * The cluster allocator is now fully operational. - */ + /* 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; - /* 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; - } + 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 $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; + /* 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; + error_exit: eo = errno; + free(bs); + if (vol) __ntfs_volume_release(vol); + errno = eo; + return NULL; } /** @@ -617,37 +607,37 @@ error_exit: */ static int ntfs_volume_check_logfile(ntfs_volume *vol) { - ntfs_inode *ni; - ntfs_attr *na = NULL; - RESTART_PAGE_HEADER *rp = NULL; - int err = 0; + 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; } /** @@ -659,52 +649,56 @@ out: */ 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"; + 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; - } -out: - if (ntfs_inode_close(ni_root)) { - ntfs_inode_close(ni_hibr); - ni_hibr = NULL; - } - free(unicode); - return ni_hibr; + 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; } - #define NTFS_HIBERFILE_HEADER_SIZE 4096 /** @@ -717,57 +711,55 @@ out: */ int ntfs_volume_check_hiberfile(ntfs_volume *vol, int verbose) { - ntfs_inode *ni; - ntfs_attr *na = NULL; - int bytes_read, err; - char *buf = NULL; + 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; -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; + 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; } /* @@ -786,52 +778,54 @@ out: static int fix_txf_data(ntfs_volume *vol) { - void *txf_data; - s64 txf_data_size; - ntfs_inode *ni; - ntfs_attr *na; - int res; + void *txf_data; + s64 txf_data_size; + ntfs_inode *ni; + ntfs_attr *na; + int res; - res = 0; - ntfs_log_debug("Loading root directory\n"); - ni = ntfs_inode_open(vol, FILE_root); - if (!ni) { - ntfs_log_perror("Failed to open root directory"); - res = -1; - } else { - /* Get the $TXF_DATA attribute */ - na = ntfs_attr_open(ni, AT_LOGGED_UTILITY_STREAM, TXF_DATA, 9); - if (na) { - if (NAttrNonResident(na)) { - /* - * Fix the attribute by truncating, then - * rewriting it. - */ - ntfs_log_debug("Making $TXF_DATA resident\n"); - txf_data = ntfs_attr_readall(ni, - AT_LOGGED_UTILITY_STREAM, - TXF_DATA, 9, &txf_data_size); - if (txf_data) { - if (ntfs_attr_truncate(na, 0) - || (ntfs_attr_pwrite(na, 0, - txf_data_size, txf_data) - != txf_data_size)) - res = -1; - free(txf_data); - } - if (res) - ntfs_log_error("Failed to make $TXF_DATA resident\n"); - else - ntfs_log_error("$TXF_DATA made resident\n"); - } - ntfs_attr_close(na); - } - if (ntfs_inode_close(ni)) { - ntfs_log_perror("Failed to close root"); - res = -1; - } - } - return (res); + res = 0; + ntfs_log_debug("Loading root directory\n"); + ni = ntfs_inode_open(vol, FILE_root); + if (!ni) + { + ntfs_log_perror("Failed to open root directory"); + res = -1; + } + else + { + /* Get the $TXF_DATA attribute */ + na = ntfs_attr_open(ni, AT_LOGGED_UTILITY_STREAM, TXF_DATA, 9); + if (na) + { + if (NAttrNonResident(na)) + { + /* + * Fix the attribute by truncating, then + * rewriting it. + */ + ntfs_log_debug("Making $TXF_DATA resident\n"); + txf_data = ntfs_attr_readall(ni, AT_LOGGED_UTILITY_STREAM, TXF_DATA, 9, &txf_data_size); + if (txf_data) + { + if (ntfs_attr_truncate(na, 0) + || (ntfs_attr_pwrite(na, 0, txf_data_size, txf_data) != txf_data_size)) res = -1; + free(txf_data); + } + if (res) + ntfs_log_error("Failed to make $TXF_DATA resident\n"); + else + ntfs_log_error("$TXF_DATA made resident\n"); + } + ntfs_attr_close(na); + } + if (ntfs_inode_close(ni)) + { + ntfs_log_perror("Failed to close root"); + res = -1; + } + } + return (res); } /** @@ -858,349 +852,365 @@ static int fix_txf_data(ntfs_volume *vol) */ 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; + 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; - } - - 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; - } + /* 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 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; - } + 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 $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; + 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; + } - /* 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++) { - u16 uc = le16_to_cpu(vname[j]); - if (uc > 0xff) - uc = (u16)'_'; - 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; - } - } - /* make $TXF_DATA resident if present on the root directory */ - if (!NVolReadOnly(vol) && fix_txf_data(vol)) - 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; + } - return vol; -io_error_exit: - 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; + /* + * 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++) + { + u16 uc = le16_to_cpu(vname[j]); + if (uc > 0xff) uc = (u16) '_'; + 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; + } + } + /* make $TXF_DATA resident if present on the root directory */ + if (!NVolReadOnly(vol) && fix_txf_data(vol)) goto error_exit; + + return vol; + io_error_exit: 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; } /* @@ -1209,28 +1219,23 @@ error_exit: * Not set in ntfs_mount() to avoid breaking existing tools. */ -int ntfs_set_shown_files(ntfs_volume *vol, - BOOL show_sys_files, BOOL show_hid_files, - BOOL hide_dot_files) +int ntfs_set_shown_files(ntfs_volume *vol, BOOL show_sys_files, BOOL show_hid_files, BOOL hide_dot_files) { - int res; + int res; - res = -1; - if (vol) { - NVolClearShowSysFiles(vol); - NVolClearShowHidFiles(vol); - NVolClearHideDotFiles(vol); - if (show_sys_files) - NVolSetShowSysFiles(vol); - if (show_hid_files) - NVolSetShowHidFiles(vol); - if (hide_dot_files) - NVolSetHideDotFiles(vol); - res = 0; - } - if (res) - ntfs_log_error("Failed to set file visibility\n"); - return (res); + res = -1; + if (vol) + { + NVolClearShowSysFiles(vol); + NVolClearShowHidFiles(vol); + NVolClearHideDotFiles(vol); + if (show_sys_files) NVolSetShowSysFiles(vol); + if (show_hid_files) NVolSetShowHidFiles(vol); + if (hide_dot_files) NVolSetHideDotFiles(vol); + res = 0; + } + if (res) ntfs_log_error("Failed to set file visibility\n"); + return (res); } /* @@ -1239,20 +1244,20 @@ int ntfs_set_shown_files(ntfs_volume *vol, int ntfs_set_ignore_case(ntfs_volume *vol) { - int res; + int res; - res = -1; - if (vol && vol->upcase) { - vol->locase = ntfs_locase_table_build(vol->upcase, - vol->upcase_len); - if (vol->locase) { - NVolClearCaseSensitive(vol); - res = 0; - } - } - if (res) - ntfs_log_error("Failed to set ignore_case mode\n"); - return (res); + res = -1; + if (vol && vol->upcase) + { + vol->locase = ntfs_locase_table_build(vol->upcase, vol->upcase_len); + if (vol->locase) + { + NVolClearCaseSensitive(vol); + res = 0; + } + } + if (res) ntfs_log_error("Failed to set ignore_case mode\n"); + return (res); } /** @@ -1280,34 +1285,33 @@ int ntfs_set_ignore_case(ntfs_volume *vol) * Note, that a copy is made of @name, and hence it can be discarded as * soon as the function returns. */ -ntfs_volume *ntfs_mount(const char *name __attribute__((unused)), - unsigned long flags __attribute__((unused))) +ntfs_volume *ntfs_mount(const char *name __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 } @@ -1335,17 +1339,18 @@ ntfs_volume *ntfs_mount(const char *name __attribute__((unused)), */ int ntfs_umount(ntfs_volume *vol, const BOOL force __attribute__((unused))) { - struct ntfs_device *dev; - int ret; + 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 @@ -1356,9 +1361,9 @@ int ntfs_umount(ntfs_volume *vol, const BOOL force __attribute__((unused))) */ static char *realpath(const char *path, char *resolved_path) { - strncpy(resolved_path, path, PATH_MAX); - resolved_path[PATH_MAX] = '\0'; - return resolved_path; + strncpy(resolved_path, path, PATH_MAX); + resolved_path[PATH_MAX] = '\0'; + return resolved_path; } #endif @@ -1372,51 +1377,56 @@ static char *realpath(const char *path, char *resolved_path) */ 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; + 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; + exit: + free(real_file); + free(real_fsname); + if (err) + { + errno = err; + return -1; + } + return 0; } #endif /* HAVE_MNTENT_H */ @@ -1445,14 +1455,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) +int ntfs_check_if_mounted(const char *file __attribute__((unused)), unsigned long *mnt_flags) { - *mnt_flags = 0; + *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 } @@ -1474,27 +1483,25 @@ int ntfs_check_if_mounted(const char *file __attribute__((unused)), */ int ntfs_version_is_supported(ntfs_volume *vol) { - u8 major, minor; + 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; } /** @@ -1514,41 +1521,44 @@ int ntfs_version_is_supported(ntfs_volume *vol) */ int ntfs_logfile_reset(ntfs_volume *vol) { - ntfs_inode *ni; - ntfs_attr *na; - int eo; + 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; + } -error_exit: - ntfs_inode_close(ni); - errno = eo; - return -1; + ntfs_attr_close(na); + return ntfs_inode_close(ni); + + error_exit: ntfs_inode_close(ni); + errno = eo; + return -1; } /** @@ -1563,135 +1573,135 @@ error_exit: */ int ntfs_volume_write_flags(ntfs_volume *vol, const le16 flags) { - ATTR_RECORD *a; - VOLUME_INFORMATION *c; - ntfs_attr_search_ctx *ctx; - int ret = -1; /* failure */ + 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 */ -err_out: - ntfs_attr_put_search_ctx(ctx); - return ret; + ret = 0; /* success */ + err_out: ntfs_attr_put_search_ctx(ctx); + return ret; } int ntfs_volume_error(int err) { - int ret; + 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; - } + 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; + 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; } /* @@ -1700,24 +1710,25 @@ int ntfs_set_locale(void) int ntfs_volume_get_free_space(ntfs_volume *vol) { - ntfs_attr *na; - int ret; + 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 79193c53..26523ddb 100644 --- a/source/libntfs/volume.h +++ b/source/libntfs/volume.h @@ -74,28 +74,31 @@ 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. */ +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_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 +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_status; /** @@ -103,14 +106,16 @@ 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_ShowSysFiles, /* 1: Show NTFS metafiles. */ - NV_ShowHidFiles, /* 1: Show files marked hidden. */ - NV_HideDotFiles, /* 1: Set hidden flag on dot files */ - NV_Compression, /* 1: allow compression */ +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_ShowSysFiles, /* 1: Show NTFS metafiles. */ + NV_ShowHidFiles, /* 1: Show files marked hidden. */ + NV_HideDotFiles, /* 1: Set hidden flag on dot files */ + NV_Compression, +/* 1: allow compression */ } ntfs_volume_state_bits; #define test_nvol_flag(nv, flag) test_bit(NV_##flag, (nv)->state) @@ -163,109 +168,111 @@ typedef enum { /** * struct _ntfs_volume - structure describing an open volume in memory. */ -struct _ntfs_volume { - 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. - See ntfs_volume_state_bits above. */ +struct _ntfs_volume +{ + 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. + 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. */ - le16 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. */ + le16 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 - 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. */ + /* 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. */ - 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 - 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. */ + 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 + 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 - for FILE_MFT. */ - 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 - 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. */ + 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 + of FILE_MFT. */ + 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 - for FILE_MFTMirr. */ - ntfs_inode *mftmirr_ni; /* ntfs_inode structure for FILE_MFTMirr. */ - ntfs_attr *mftmirr_na; /* ntfs_attr structure for the data attribute - of FILE_MFTMirr. */ + 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 + of FILE_MFTMirr. */ - 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 - table. */ - ntfschar *locase; /* Lower case equivalents of all 65536 2-byte - Unicode characters. Only if option - case_ignore is set. */ + 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 + table. */ + ntfschar *locase; /* Lower case equivalents of all 65536 2-byte + Unicode characters. Only if option + case_ignore is set. */ - ATTR_DEF *attrdef; /* Attribute definitions. Obtained from - FILE_AttrDef. */ - s32 attrdef_len; /* Size of the attribute definition table in - bytes. */ + ATTR_DEF *attrdef; /* Attribute definitions. Obtained from + FILE_AttrDef. */ + s32 attrdef_len; /* Size of the attribute definition table in + bytes. */ - 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 - efs-encrypted files */ + 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 + efs-encrypted files */ #if CACHE_INODE_SIZE - struct CACHE_HEADER *xinode_cache; + struct CACHE_HEADER *xinode_cache; #endif #if CACHE_NIDATA_SIZE - struct CACHE_HEADER *nidata_cache; + struct CACHE_HEADER *nidata_cache; #endif #if CACHE_LOOKUP_SIZE - struct CACHE_HEADER *lookup_cache; + struct CACHE_HEADER *lookup_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 }; @@ -274,11 +281,9 @@ 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); +extern ntfs_volume *ntfs_volume_startup(struct ntfs_device *dev, unsigned long flags); -extern ntfs_volume *ntfs_device_mount(struct ntfs_device *dev, - unsigned long flags); +extern ntfs_volume *ntfs_device_mount(struct ntfs_device *dev, unsigned long flags); extern ntfs_volume *ntfs_mount(const char *name, unsigned long flags); extern int ntfs_umount(ntfs_volume *vol, const BOOL force); @@ -294,8 +299,7 @@ extern void ntfs_mount_error(const char *vol, const char *mntpoint, int err); extern int ntfs_volume_get_free_space(ntfs_volume *vol); -extern int ntfs_set_shown_files(ntfs_volume *vol, - BOOL show_sys_files, BOOL show_hid_files, BOOL hide_dot_files); +extern int ntfs_set_shown_files(ntfs_volume *vol, BOOL show_sys_files, BOOL show_hid_files, BOOL hide_dot_files); extern int ntfs_set_locale(void); extern int ntfs_set_ignore_case(ntfs_volume *vol); diff --git a/source/libwbfs/libwbfs.c b/source/libwbfs/libwbfs.c index 9e11eca9..5a273a19 100644 --- a/source/libwbfs/libwbfs.c +++ b/source/libwbfs/libwbfs.c @@ -4,7 +4,6 @@ // Modified by oggzee - #include "libwbfs.h" #define likely(x) __builtin_expect(!!(x), 1) @@ -17,15 +16,15 @@ wbfs_t wbfs_iso_file; static int force_mode = 0; -void wbfs_set_force_mode( int force ) +void wbfs_set_force_mode(int force) { force_mode = force; } -static u8 size_to_shift( u32 size ) +static u8 size_to_shift(u32 size) { u8 ret = 0; - while ( size ) + while (size) { ret++; size >>= 1; @@ -34,45 +33,39 @@ static u8 size_to_shift( u32 size ) } #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 ) +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; + 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 ) + 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 ); + 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 ) ) + 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_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.. + 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*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 ) ); @@ -80,46 +73,44 @@ wbfs_t*wbfs_open_partition( rw_sector_callback_t read_hdsector, //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->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 ) + 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->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++ ) + 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 << sz_s ) ) ) - break; + if (p->n_wii_sec < ((1U << 16) * (1 << sz_s))) break; } 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" ); + 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 << head->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->n_wii_sec = ( p->n_hd_sec / p->wii_sec_sz ) * ( p->hd_sec_sz ); + 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 << p->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->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); @@ -127,9 +118,9 @@ wbfs_t*wbfs_open_partition( rw_sector_callback_t 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; + p->freeblks_lba = (p->wbfs_sec_sz - p->n_wbfs_sec / 8) >> p->hd_sec_sz_s; - if ( !reset ) + if (!reset) p->freeblks = 0; // will alloc and read only if needed else { @@ -137,230 +128,206 @@ wbfs_t*wbfs_open_partition( rw_sector_callback_t read_hdsector, 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->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; -error: - wbfs_free( p ); + error: wbfs_free( p ); wbfs_iofree( head ); return 0; } -void wbfs_sync( wbfs_t*p ) +void wbfs_sync(wbfs_t*p) { // copy back descriptors - if ( p->write_hdsector ) + if (p->write_hdsector) { - p->write_hdsector( p->callback_data, p->part_lba + 0, 1, p->head ); + 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 ); + 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 ) +void wbfs_close(wbfs_t*p) { - wbfs_sync( p ); + wbfs_sync(p); - if ( p->n_disc_open ) - ERROR( "trying to close wbfs while discs still open" ); + 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 ); + if (p->freeblks) wbfs_iofree( p->freeblks ); wbfs_free( p ); -error: - return; + error: return; } -wbfs_disc_t *wbfs_open_disc( wbfs_t* p, u8 *discid ) +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; i < p->max_disc; i++ ) + for (i = 0; i < p->max_disc; i++) { - if ( p->head->disc_table[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 ) + 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" ); + 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])); + 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 0; -error: - if ( d ) - wbfs_iofree( d ); + error: if (d) wbfs_iofree( d ); return 0; } -void wbfs_close_disc( wbfs_disc_t*d ) +void wbfs_close_disc(wbfs_disc_t*d) { - d->p->n_disc_open --; + 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 ) +int wbfs_disc_read(wbfs_disc_t*d, u32 offset, u32 len, u8 *data) { - if ( d->p == &wbfs_iso_file ) + if (d->p == &wbfs_iso_file) { - return wbfs_iso_file_read( d, offset, data, len ); + return wbfs_iso_file_read(d, offset, data, len); } wbfs_t *p = d->p; - u16 wlba = offset >> ( p->wbfs_sec_sz_s - 2 ); + 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 ); + 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 ) ) + 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 << iwlba_shift ) + lba, 1, p->tmp_buffer ); - if ( err ) - return err; + err = p->read_hdsector(p->callback_data, p->part_lba + (iwlba << iwlba_shift) + lba, 1, p->tmp_buffer); + if (err) return err; len_copied = p->hd_sec_sz - off; - if ( likely( len < len_copied ) ) - len_copied = len; + 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 << iwlba_shift ) + lba, nlb, ptr ); - if ( err ) - return err; - len -= nlb << p->hd_sec_sz_s; - ptr += nlb << p->hd_sec_sz_s; - lba += nlb; - if ( unlikely( lba > lba_mask && len ) ) + if (unlikely( lba > lba_mask && len )) { lba = 0; iwlba = wbfs_ntohs( d->header->wlba_table[++wlba] ); - if ( unlikely( iwlba == 0 ) ) - return 1; + if (unlikely( iwlba == 0 )) return 1; } } - if ( unlikely( len ) ) + while (likely( len >= p->hd_sec_sz )) { - err = p->read_hdsector( p->callback_data, - p->part_lba + ( iwlba << iwlba_shift ) + lba, 1, p->tmp_buffer ); - if ( err ) - return err; + 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 << iwlba_shift) + lba, nlb, ptr); + if (err) return err; + len -= nlb << p->hd_sec_sz_s; + ptr += nlb << p->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 << iwlba_shift) + lba, 1, p->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 wbfs_count_discs(wbfs_t*p) { u32 i, count = 0; - for ( i = 0; i < p->max_disc; i++ ) - if ( p->head->disc_table[i] ) - count++; + for (i = 0; i < p->max_disc; i++) + if (p->head->disc_table[i]) count++; return count; } -u32 wbfs_sector_used( wbfs_t *p, wbfs_disc_info_t *di ) +u32 wbfs_sector_used(wbfs_t *p, wbfs_disc_info_t *di) { u32 tot_blk = 0, j; - for ( j = 0; j < p->n_wbfs_sec_per_disc; j++ ) - if ( wbfs_ntohs( di->wlba_table[j] ) ) - tot_blk++; + for (j = 0; j < p->n_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 wbfs_sector_used2(wbfs_t *p, wbfs_disc_info_t *di, u32 *last_blk) { u32 tot_blk = 0, j; - for ( j = 0; j < p->n_wbfs_sec_per_disc; j++ ) - if ( wbfs_ntohs( di->wlba_table[j] ) ) + for (j = 0; j < p->n_wbfs_sec_per_disc; j++) + if (wbfs_ntohs( di->wlba_table[j] )) { - if ( last_blk ) *last_blk = 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 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; + if (!p) return 1; int disc_info_sz_lba = p->disc_info_sz >> p->hd_sec_sz_s; - for ( i = 0; i < p->max_disc; i++ ) - if ( p->head->disc_table[i] ) + for (i = 0; i < p->max_disc; i++) + if (p->head->disc_table[i]) { - if ( count++ == index ) + 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; + 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 ) + if (magic != 0x5D1C9EA3) { p->head->disc_table[i] = 0; return 1; } - memcpy( header, p->tmp_buffer, header_size ); - if ( size ) + 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 ); + 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 ); + *size = sec_used << (p->wbfs_sec_sz_s - 2); } return 0; } @@ -368,79 +335,75 @@ u32 wbfs_get_disc_info( wbfs_t*p, u32 index, u8 *header, int header_size, u32 *s return 1; } -static void load_freeblocks( wbfs_t*p ) +static void load_freeblocks(wbfs_t*p) { - if ( p->freeblks ) - return; + 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 ); + 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 wbfs_count_usedblocks(wbfs_t*p) { u32 i, j, count = 0; - load_freeblocks( p ); - for ( i = 0; i < p->n_wbfs_sec / ( 8*4 ); i++ ) + load_freeblocks(p); + for (i = 0; i < p->n_wbfs_sec / (8 * 4); i++) { u32 v = wbfs_ntohl( p->freeblks[i] ); - if ( v == ~0U ) + if (v == ~0U) count += 32; - else if ( v != 0 ) - for ( j = 0; j < 32; j++ ) - if ( v & ( 1 << j ) ) - count++; + else if (v != 0) for (j = 0; j < 32; j++) + if (v & (1 << j)) count++; } return count; } - // write access //static -int block_used( u8 *used, u32 i, u32 wblk_sz ) +int block_used(u8 *used, u32 i, u32 wblk_sz) { u32 k; i *= wblk_sz; - for ( k = 0; k < wblk_sz; k++ ) - if ( i + k < 143432*2 && used[i+k] ) - return 1; + for (k = 0; k < wblk_sz; k++) + if (i + k < 143432 * 2 && used[i + k]) return 1; return 0; } -static u32 alloc_block( wbfs_t*p ) +static u32 alloc_block(wbfs_t*p) { u32 i, j; - for ( i = 0; i < p->n_wbfs_sec / ( 8*4 ); i++ ) + for (i = 0; i < p->n_wbfs_sec / (8 * 4); i++) { u32 v = wbfs_ntohl( p->freeblks[i] ); - if ( v != 0 ) + if (v != 0) { - for ( j = 0; j < 32; j++ ) - if ( v & ( 1 << j ) ) + for (j = 0; j < 32; j++) + if (v & (1 << j)) { p->freeblks[i] = wbfs_htonl( v & ~( 1 << j ) ); - return ( i*32 ) + j + 1; + return (i * 32) + j + 1; } } } return ~0; } -static void free_block( wbfs_t *p, int bl ) +static void free_block(wbfs_t *p, int bl) { - int i = ( bl - 1 ) / ( 32 ); - int j = ( bl - 1 ) & 31; + int i = (bl - 1) / (32); + int j = (bl - 1) & 31; u32 v = wbfs_ntohl( p->freeblks[i] ); p->freeblks[i] = wbfs_htonl( v | 1 << j ); } -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 ) +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) { int i, discn; u32 tot, cur; - u32 wii_sec_per_wbfs_sect = 1 << ( p->wbfs_sec_sz_s - p->wii_sec_sz_s ); + 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; @@ -450,52 +413,51 @@ u32 wbfs_add_disc( wbfs_t*p, read_wiidisc_callback_t read_src_wii_disc, u32 last_used; used = wbfs_malloc( p->n_wii_sec_per_disc ); - if ( !used ) - ERROR( "unable to alloc memory" ); + 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 = 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; i < p->max_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)" ); + for (i = 0; i < p->max_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 ); + 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 ); + 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" ); + 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 < num_wbfs_sect_to_copy; i++ ) + for (i = 0; i < num_wbfs_sect_to_copy; i++) { - if ( block_used( used, i, wii_sec_per_wbfs_sect ) ) + if (block_used(used, i, wii_sec_per_wbfs_sect)) { tot += wii_sec_per_wbfs_sect; last_used = i; } } - if ( copy_1_1 ) + if (copy_1_1) { // detect single or dual layer - if ( ( last_used + 1 ) > ( p->n_wbfs_sec_per_disc / 2 ) ) + if ((last_used + 1) > (p->n_wbfs_sec_per_disc / 2)) { // dual layer num_wbfs_sect_to_copy = p->n_wbfs_sec_per_disc; @@ -508,152 +470,141 @@ u32 wbfs_add_disc( wbfs_t*p, read_wiidisc_callback_t read_src_wii_disc, 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; - }*/ + // 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; i < num_wbfs_sect_to_copy; i++ ) + if (spinner) spinner(0, tot); + for (i = 0; i < num_wbfs_sect_to_copy; i++) { u16 bl = 0; - if ( copy_1_1 || block_used( used, i, wii_sec_per_wbfs_sect ) ) + if (copy_1_1 || block_used(used, i, wii_sec_per_wbfs_sect)) { u16 j; - bl = alloc_block( p ); - if ( bl == 0xffff ) - ERROR( "no space left on device (disc full)" ); - for ( j = 0; j < wii_sec_per_wbfs_sect; j++ ) + bl = alloc_block(p); + if (bl == 0xffff) + ERROR( "no space left on device (disc full)" ); + for (j = 0; j < wii_sec_per_wbfs_sect; j++) { - u32 offset = ( i * ( p->wbfs_sec_sz >> 2 ) ) + ( j * ( p->wii_sec_sz >> 2 ) ); + u32 offset = (i * (p->wbfs_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 ) + 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 ) + if (copy_1_1 && i > p->n_wbfs_sec_per_disc / 2) { // end of dual layer data - if ( j > 0 ) + if (j > 0) { info->wlba_table[i] = wbfs_htons( bl ); } - spinner( tot, tot ); + spinner(tot, tot); break; } //ERROR("read error"); - printf( "\rWARNING: read (%u) error (%d)\n", offset, ret ); + 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 ); + 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 (spinner) spinner(cur, tot); } } - if ( ret ) break; + if (ret) break; info->wlba_table[i] = wbfs_htons( bl ); - wbfs_sync( p ); + wbfs_sync(p); } // 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 ); + 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 ); + 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 return retval; } -u32 wbfs_rm_disc( wbfs_t*p, u8* discid ) +u32 wbfs_rm_disc(wbfs_t*p, u8* discid) { - wbfs_disc_t *d = wbfs_open_disc( p, 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 ); + if (!d) return 1; + load_freeblocks(p); discn = d->i; - for ( i = 0; i < p->n_wbfs_sec_per_disc; 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 ); + 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 ); + 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 ); + wbfs_close_disc(d); + wbfs_sync(p); return 0; } -u32 wbfs_ren_disc( wbfs_t*p, u8* discid, u8* newname ) +u32 wbfs_ren_disc(wbfs_t*p, u8* discid, u8* newname) { - wbfs_disc_t *d = wbfs_open_disc( p, discid ); + 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 ); + 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 ) +u32 wbfs_rID_disc(wbfs_t*p, u8* discid, u8* newID) { - wbfs_disc_t *d = wbfs_open_disc( p, discid ); + 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 ); + 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 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 ); + 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 ); + 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 ) +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; @@ -661,37 +612,32 @@ u32 wbfs_extract_disc( wbfs_disc_t*d, rw_sector_callback_t write_dst_wii_sector, 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" ); + if (!copy_buffer) + ERROR( "alloc memory" ); - for ( i = 0; i < p->n_wbfs_sec_per_disc; i++ ) + for (i = 0; i < p->n_wbfs_sec_per_disc; i++) { u32 iwlba = wbfs_ntohs( d->header->wlba_table[i] ); - if ( iwlba ) + 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 ); + 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; -error: - return 1; + error: return 1; } -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) { u8 *b; int i; u32 tot; - u32 wii_sec_per_wbfs_sect = 1 << ( p->wbfs_sec_sz_s - p->wii_sec_sz_s ); + 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; @@ -699,82 +645,74 @@ float wbfs_estimate_disc tot = 0; used = wbfs_malloc( p->n_wii_sec_per_disc ); - if ( !used ) + if (!used) { ERROR( "unable to alloc memory" ); } - d = wd_open_disc( read_src_wii_disc, callback_data ); - if ( !d ) + 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 ); + 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 ); + 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); - for ( i = 0; i < p->n_wbfs_sec_per_disc; i++ ) + for (i = 0; i < p->n_wbfs_sec_per_disc; i++) { - if ( block_used( used, i, wii_sec_per_wbfs_sect ) ) + if (block_used(used, i, wii_sec_per_wbfs_sect)) { tot++; } } //memcpy(header, b,0x100); -error: - if ( d ) - wd_close_disc( d ); + error: 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 ) +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 ); + 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 ); + 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; i < p->n_wbfs_sec_per_disc; i++ ) + for (i = 0; i < p->n_wbfs_sec_per_disc; i++) { - if ( block_used( used, i, wii_sec_per_wbfs_sect ) ) + 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 ); + error: if (d) wd_close_disc(d); + if (used) wbfs_free( used ); *comp_size = tot; *real_size = last; @@ -789,60 +727,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 ) +int read_wiidisc_wbfsdisc(void*fp, u32 offset, u32 count, void*iobuf) { - return wbfs_disc_read( ( wbfs_disc_t* )fp, offset, count, iobuf ); + return wbfs_disc_read((wbfs_disc_t*) fp, offset, count, iobuf); } -int wbfs_extract_file( wbfs_disc_t*d, char *path, void **data ) +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 ) + 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 ); + *data = wd_extract_file(wd, ONLY_GAME_PARTITION, path); ret = wd->extracted_size; - if ( !*data ) + if (!*data) { //ERROR("file not found"); ret = -1; } - wd_close_disc( wd ); -error: - return ret; + wd_close_disc(wd); + error: return ret; } -int wbfs_get_fragments( wbfs_disc_t *d, _frag_append_t append_fragment, void *callback_data ) +int wbfs_get_fragments(wbfs_disc_t *d, _frag_append_t append_fragment, void *callback_data) { - if ( !d ) return -1; + 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++ ) + for (i = 0; i < p->n_wbfs_sec_per_disc; i++) { u32 iwlba = wbfs_ntohs( d->header->wlba_table[i] ); - if ( iwlba ) + 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 + 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 ) + 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 + append_fragment(callback_data, size, 0, 0); // set size return 0; } @@ -852,41 +788,40 @@ int wbfs_get_fragments( wbfs_disc_t *d, _frag_append_t append_fragment, void *ca #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 ) +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; + 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; + 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 ) +u32 wbfs_disc_sector_used(wbfs_disc_t *d, u32 *num_blk) { - if ( d->p == &wbfs_iso_file ) + if (d->p == &wbfs_iso_file) { - int fd = ( int )d->header; + int fd = (int) d->header; struct stat st; - if ( fstat( fd, &st ) == -1 ) return 0; - if ( num_blk ) + if (fstat(fd, &st) == -1) return 0; + if (num_blk) { - *num_blk = ( st.st_size >> 9 ); // in 512 units + *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 ) + 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 7b82d31e..8921773a 100644 --- a/source/libwbfs/libwbfs.h +++ b/source/libwbfs/libwbfs.h @@ -1,4 +1,3 @@ - // Modified by oggzee #ifndef LIBWBFS_H @@ -12,233 +11,222 @@ extern "C" { #endif /* __cplusplus */ - enum { - WBFS_DEVICE_USB = 1, /* USB device */ - WBFS_DEVICE_SDHC /* SDHC device */ + enum + { + WBFS_DEVICE_USB = 1, /* USB device */ + WBFS_DEVICE_SDHC + /* SDHC device */ }; typedef u32 be32_t; typedef u16 be16_t; - - 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 - u8 hd_sec_sz_s; // sector size in this partition - 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 ; + 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 + u8 hd_sec_sz_s; // sector size in this partition + 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; typedef struct wbfs_disc_info { - u8 disc_header_copy[0x100]; - be16_t wlba_table[0]; + u8 disc_header_copy[0x100]; + be16_t wlba_table[0]; } wbfs_disc_info_t; -// WBFS first wbfs_sector structure: -// -// ----------- -// | wbfs_head | (hd_sec_sz) -// ----------- -// | | -// | disc_info | -// | | -// ----------- -// | | -// | disc_info | -// | | -// ----------- -// | | -// | ... | -// | | -// ----------- -// | | -// | disc_info | -// | | -// ----------- -// | | -// |freeblk_tbl| -// | | -// ----------- -// - -// 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 )( s64 status, s64 total ); + // WBFS first wbfs_sector structure: + // + // ----------- + // | wbfs_head | (hd_sec_sz) + // ----------- + // | | + // | disc_info | + // | | + // ----------- + // | | + // | disc_info | + // | | + // ----------- + // | | + // | ... | + // | | + // ----------- + // | | + // | disc_info | + // | | + // ----------- + // | | + // |freeblk_tbl| + // | | + // ----------- + // + // 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)(s64 status, s64 total); typedef struct wbfs_s { - wbfs_head_t *head; + wbfs_head_t *head; - /* hdsectors, the size of the sector provided by the hosting hard drive */ - u32 hd_sec_sz; - u8 hd_sec_sz_s; // the power of two of the last number - u32 n_hd_sec; // the number of hd sector in the wbfs partition + /* hdsectors, the size of the sector provided by the hosting hard drive */ + u32 hd_sec_sz; + u8 hd_sec_sz_s; // the power of two of the last number + u32 n_hd_sec; // the number of hd sector in the wbfs partition - /* standard wii sector (0x8000 bytes) */ - u32 wii_sec_sz; - u8 wii_sec_sz_s; - u32 n_wii_sec; - u32 n_wii_sec_per_disc; + /* standard wii sector (0x8000 bytes) */ + 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; - u16 n_wbfs_sec; // this must fit in 16 bit! - u16 n_wbfs_sec_per_disc; // size of the lookup table + /* The size of a wbfs sector */ + u32 wbfs_sec_sz; + 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 - u32 part_lba; - /* virtual methods to read write the partition */ - rw_sector_callback_t read_hdsector; - rw_sector_callback_t write_hdsector; - void *callback_data; + u32 part_lba; + /* virtual methods to read write the partition */ + rw_sector_callback_t read_hdsector; + rw_sector_callback_t write_hdsector; + void *callback_data; - u16 max_disc; - u32 freeblks_lba; - u32 *freeblks; - u16 disc_info_sz; + u16 max_disc; + u32 freeblks_lba; + u32 *freeblks; + u16 disc_info_sz; - u8 *tmp_buffer; // pre-allocated buffer for unaligned read + u8 *tmp_buffer; // pre-allocated buffer for unaligned read - u32 n_disc_open; + u32 n_disc_open; } wbfs_t; 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_t *p; + wbfs_disc_info_t *header; // pointer to wii header + int i; // disc index in the wbfs header (disc_table) } 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 ); + @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 ); - + @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* ); + 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 ); + @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 ); + 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* + @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 ); + // 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); /*! @return the number of discs inside the partition */ - u32 wbfs_count_discs( wbfs_t*p ); + 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 ); + 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 ); + 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 ******************/ /*! 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. + @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 ); - + 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 ); + u32 wbfs_rm_disc(wbfs_t*p, u8* discid); /*! rename a game */ - u32 wbfs_ren_disc( wbfs_t*p, u8* discid, u8* newname ); + 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 ); + 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 + This allows to use wbfs as a wiidisc container */ - u32 wbfs_trim( wbfs_t*p ); + 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. + 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 ); + 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 + 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 ); + int wbfs_extract_file(wbfs_disc_t*d, char *path, void **data); -// remove some sanity checks - void wbfs_set_force_mode( int force ); + // remove some sanity checks + 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 ); -// 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 ); + 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); - 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 ); - + 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 } diff --git a/source/libwbfs/libwbfs_os.h b/source/libwbfs/libwbfs_os.h index 32cfc2f7..87e692aa 100644 --- a/source/libwbfs/libwbfs_os.h +++ b/source/libwbfs/libwbfs_os.h @@ -29,5 +29,4 @@ #define wbfs_memcpy(x,y,z) memcpy(x,y,z) #define wbfs_memset(x,y,z) memset(x,y,z) - #endif diff --git a/source/libwbfs/rijndael.c b/source/libwbfs/rijndael.c index 18acd6f3..473023d9 100644 --- a/source/libwbfs/rijndael.c +++ b/source/libwbfs/rijndael.c @@ -1,13 +1,13 @@ /* Rijndael Block Cipher - rijndael.c - Written by Mike Scott 21st April 1999 - mike@compapp.dcu.ie + 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. -*/ + */ #include #include @@ -28,7 +28,7 @@ /* Fixed Data */ -static u8 InCo[4] = {0xB, 0xD, 0x9, 0xE}; /* Inverse Coefficients */ +static u8 InCo[4] = { 0xB, 0xD, 0x9, 0xE }; /* Inverse Coefficients */ static u8 fbsub[256]; static u8 rbsub[256]; @@ -44,83 +44,90 @@ u8 fi[24], ri[24]; u32 fkey[120]; u32 rkey[120]; -static u32 pack( u8 *b ) +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]; + return ((u32 ) b[3] << 24) | ((u32 ) b[2] << 16) | ((u32 ) b[1] << 8) | (u32 ) b[0]; } -static void unpack( u32 a, u8 *b ) +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 ); + 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; + if (a & 0x80) + b = 0x1B; + else b = 0; a <<= 1; a ^= b; return a; } -static u8 bmul( u8 x, u8 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]; + 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 ); + 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 ) +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 ); - return bmul( xb[0], yb[0] ) ^ bmul( xb[1], yb[1] ) ^ bmul( xb[2], yb[2] ) ^ bmul( xb[3], yb[3] ); + unpack(x, xb); + 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 ) +static u32 InvMixCol(u32 x) { /* matrix Multiplication */ u32 y, m; u8 b[4]; - m = pack( InCo ); - b[3] = product( m, x ); + m = pack(InCo); + b[3] = product(m, x); m = ROTL24( m ); - b[2] = product( m, x ); + b[2] = product(m, x); m = ROTL24( m ); - b[1] = product( m, x ); + b[1] = product(m, x); m = ROTL24( m ); - b[0] = product( m, x ); - y = pack( b ); + b[0] = product(m, x); + y = pack(b); 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; + 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; return y; } -void gentables( void ) +void gentables(void) { /* generate tables */ int i; u8 y, b[4]; @@ -128,11 +135,13 @@ void gentables( void ) /* 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] ); + ptab[i] = ptab[i - 1] ^ xtime(ptab[i - 1]); ltab[ptab[i]] = i; } @@ -140,34 +149,39 @@ void gentables( void ) 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; + y = ByteSub((u8 ) 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 ); + y = xtime(y); } /* calculate forward and reverse tables */ - for ( i = 0; i < 256; i++ ) + for (i = 0; i < 256; i++) { y = fbsub[i]; - b[3] = y ^ xtime( y ); b[2] = y; - b[1] = y; b[0] = xtime( y ); - ftable[i] = pack( b ); + 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 ); - rtable[i] = pack( b ); + 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 ) +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 */ @@ -176,230 +190,241 @@ void gkey( int nb, int nk, char *key ) int C1, C2, C3; u32 CipherKey[8]; - Nb = nb; Nk = nk; + Nb = nb; + Nk = nk; /* Nr is number of rounds */ - if ( Nb >= Nk ) Nr = 6 + Nb; - else Nr = 6 + Nk; + 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 < nb; j++, m += 3 ) + for (m = j = 0; j < nb; j++, m += 3) { - fi[m] = ( j + C1 ) % nb; - fi[m+1] = ( j + C2 ) % nb; - fi[m+2] = ( j + C3 ) % nb; - ri[m] = ( nb + j - C1 ) % nb; - ri[m+1] = ( nb + j - C2 ) % nb; - ri[m+2] = ( nb + j - C3 ) % nb; + fi[m] = (j + C1) % nb; + fi[m + 1] = (j + C2) % nb; + fi[m + 2] = (j + C3) % nb; + ri[m] = (nb + j - C1) % nb; + ri[m + 1] = (nb + j - C2) % nb; + ri[m + 2] = (nb + j - C3) % nb; } - N = Nb * ( Nr + 1 ); + N = Nb * (Nr + 1); - for ( i = j = 0; i < Nk; i++, j += 4 ) + for (i = j = 0; i < Nk; i++, j += 4) { - CipherKey[i] = pack( ( u8 * ) & key[j] ); + CipherKey[i] = pack((u8 *) &key[j]); } - for ( i = 0; i < Nk; i++ ) fkey[i] = CipherKey[i]; - for ( j = Nk, k = 0; j < N; j += Nk, k++ ) + for (i = 0; i < Nk; i++) + fkey[i] = CipherKey[i]; + for (j = Nk, k = 0; j < N; j += Nk, k++) { - fkey[j] = fkey[j-Nk] ^ SubByte( ROTL24( fkey[j-1] ) ) ^ rco[k]; - if ( Nk <= 6 ) + fkey[j] = fkey[j - Nk] ^ SubByte(ROTL24( fkey[j-1] )) ^ rco[k]; + if (Nk <= 6) { - for ( i = 1; i < Nk && ( i + j ) < N; i++ ) - fkey[i+j] = fkey[i+j-Nk] ^ fkey[i+j-1]; + for (i = 1; i < Nk && (i + j) < N; i++) + fkey[i + j] = fkey[i + j - Nk] ^ fkey[i + j - 1]; } else { - for ( i = 1; i < 4 && ( i + j ) < N; i++ ) - fkey[i+j] = fkey[i+j-Nk] ^ fkey[i+j-1]; - if ( ( j + 4 ) < N ) fkey[j+4] = fkey[j+4-Nk] ^ SubByte( fkey[j+3] ); - for ( i = 5; i < Nk && ( i + j ) < N; i++ ) - fkey[i+j] = fkey[i+j-Nk] ^ fkey[i+j-1]; + for (i = 1; i < 4 && (i + j) < N; i++) + fkey[i + j] = fkey[i + j - Nk] ^ fkey[i + j - 1]; + if ((j + 4) < N) fkey[j + 4] = fkey[j + 4 - Nk] ^ SubByte(fkey[j + 3]); + for (i = 5; i < Nk && (i + j) < N; i++) + fkey[i + j] = fkey[i + j - Nk] ^ fkey[i + j - 1]; } } /* now for the expanded decrypt key in reverse order */ - for ( j = 0; j < Nb; j++ ) rkey[j+N-Nb] = fkey[j]; - for ( i = Nb; i < N - Nb; i += Nb ) + for (j = 0; j < Nb; j++) + rkey[j + N - Nb] = fkey[j]; + for (i = Nb; i < N - Nb; i += Nb) { k = N - Nb - i; - for ( j = 0; j < Nb; j++ ) rkey[k+j] = InvMixCol( fkey[i+j] ); + for (j = 0; j < Nb; j++) + rkey[k + j] = InvMixCol(fkey[i + j]); } - for ( j = N - Nb; j < N; j++ ) rkey[j-N+Nb] = fkey[j]; + for (j = N - Nb; j < N; j++) + rkey[j - N + Nb] = fkey[j]; } - /* There is an obvious time/space trade-off possible here. * * Instead of just one ftable[], I could have 4, the other * * 3 pre-rotated to save the ROTL8, ROTL16 and ROTL24 overhead */ -void encrypt( char *buff ) +void encrypt(char *buff) { int i, j, k, m; u32 a[8], b[8], *x, *y, *t; - for ( i = j = 0; i < Nb; i++, j += 4 ) + for (i = j = 0; i < Nb; i++, j += 4) { - a[i] = pack( ( u8 * ) & buff[j] ); + a[i] = pack((u8 *) &buff[j]); a[i] ^= fkey[i]; } k = Nb; - x = a; y = b; + x = a; + y = b; /* State alternates between a and b */ - for ( i = 1; i < Nr; i++ ) + for (i = 1; i < Nr; i++) { /* Nr is number of rounds. May be odd. */ /* if Nb is fixed - unroll this next - loop and hard-code in the values of fi[] */ + loop and hard-code in the values of fi[] */ - for ( m = j = 0; j < Nb; j++, m += 3 ) + for (m = j = 0; j < Nb; j++, m += 3) { /* deal with each 32-bit element of the State */ /* This is the time-critical bit */ - y[j] = fkey[k++] ^ ftable[( u8 )x[j]] ^ - ROTL8( ftable[( u8 )( x[fi[m]] >> 8 )] ) ^ - ROTL16( ftable[( u8 )( x[fi[m+1]] >> 16 )] ) ^ - ROTL24( ftable[x[fi[m+2]] >> 24] ); + y[j] = fkey[k++] ^ ftable[(u8 ) x[j]] ^ ROTL8( ftable[( u8 )( x[fi[m]] >> 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 < Nb; j++, m += 3 ) + for (m = j = 0; j < Nb; j++, m += 3) { - y[j] = fkey[k++] ^ ( u32 )fbsub[( u8 )x[j]] ^ - ROTL8( ( u32 )fbsub[( u8 )( x[fi[m]] >> 8 )] ) ^ - ROTL16( ( u32 )fbsub[( u8 )( x[fi[m+1]] >> 16 )] ) ^ - ROTL24( ( u32 )fbsub[x[fi[m+2]] >> 24] ); + y[j] = fkey[k++] ^ (u32 ) fbsub[(u8 ) x[j]] ^ ROTL8( ( u32 )fbsub[( u8 )( x[fi[m]] >> 8 )] ) + ^ ROTL16( ( u32 )fbsub[( u8 )( x[fi[m+1]] >> 16 )] ) ^ ROTL24( ( u32 )fbsub[x[fi[m+2]] >> 24] ); } - for ( i = j = 0; i < Nb; i++, j += 4 ) + for (i = j = 0; i < Nb; i++, j += 4) { - unpack( y[i], ( u8 * )&buff[j] ); - x[i] = y[i] = 0; /* clean up stack */ + unpack(y[i], (u8 *) &buff[j]); + x[i] = y[i] = 0; /* clean up stack */ } return; } -void decrypt( char *buff ) +void decrypt(char *buff) { int i, j, k, m; u32 a[8], b[8], *x, *y, *t; - for ( i = j = 0; i < Nb; i++, j += 4 ) + for (i = j = 0; i < Nb; i++, j += 4) { - a[i] = pack( ( u8 * ) & buff[j] ); + a[i] = pack((u8 *) &buff[j]); a[i] ^= rkey[i]; } k = Nb; - x = a; y = b; + x = a; + y = b; /* State alternates between a and b */ - for ( i = 1; i < Nr; i++ ) + for (i = 1; i < Nr; i++) { /* Nr is number of rounds. May be odd. */ /* if Nb is fixed - unroll this next - loop and hard-code in the values of ri[] */ + loop and hard-code in the values of ri[] */ - for ( m = j = 0; j < Nb; j++, m += 3 ) + for (m = j = 0; j < Nb; j++, m += 3) { /* This is the time-critical bit */ - y[j] = rkey[k++] ^ rtable[( u8 )x[j]] ^ - ROTL8( rtable[( u8 )( x[ri[m]] >> 8 )] ) ^ - ROTL16( rtable[( u8 )( x[ri[m+1]] >> 16 )] ) ^ - ROTL24( rtable[x[ri[m+2]] >> 24] ); + y[j] = rkey[k++] ^ rtable[(u8 ) x[j]] ^ ROTL8( rtable[( u8 )( x[ri[m]] >> 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 < Nb; j++, m += 3 ) + for (m = j = 0; j < Nb; j++, m += 3) { - y[j] = rkey[k++] ^ ( u32 )rbsub[( u8 )x[j]] ^ - ROTL8( ( u32 )rbsub[( u8 )( x[ri[m]] >> 8 )] ) ^ - ROTL16( ( u32 )rbsub[( u8 )( x[ri[m+1]] >> 16 )] ) ^ - ROTL24( ( u32 )rbsub[x[ri[m+2]] >> 24] ); + y[j] = rkey[k++] ^ (u32 ) rbsub[(u8 ) x[j]] ^ ROTL8( ( u32 )rbsub[( u8 )( x[ri[m]] >> 8 )] ) + ^ ROTL16( ( u32 )rbsub[( u8 )( x[ri[m+1]] >> 16 )] ) ^ ROTL24( ( u32 )rbsub[x[ri[m+2]] >> 24] ); } - for ( i = j = 0; i < Nb; i++, j += 4 ) + for (i = j = 0; i < Nb; i++, j += 4) { - unpack( y[i], ( u8 * )&buff[j] ); - x[i] = y[i] = 0; /* clean up stack */ + unpack(y[i], (u8 *) &buff[j]); + x[i] = y[i] = 0; /* clean up stack */ } return; } -void aes_set_key( u8 *key ) +void aes_set_key(u8 *key) { gentables(); - gkey( 4, 4, ( char* ) key ); + gkey(4, 4, (char*) key); } // CBC mode decryption -void aes_decrypt( u8 *iv, u8 *inbuf, u8 *outbuf, unsigned long long len ) +void aes_decrypt(u8 *iv, u8 *inbuf, u8 *outbuf, unsigned long long len) { u8 block[16]; unsigned int blockno = 0, i; //printf("aes_decrypt(%p, %p, %p, %lld)\n", iv, inbuf, outbuf, len); - for ( blockno = 0; blockno <= ( len / sizeof( block ) ); blockno++ ) + for (blockno = 0; blockno <= (len / sizeof(block)); blockno++) { unsigned int fraction; - if ( blockno == ( len / sizeof( block ) ) ) // last block + if (blockno == (len / sizeof(block))) // last block { - fraction = len % sizeof( block ); - if ( fraction == 0 ) break; - memset( block, 0, sizeof( block ) ); + fraction = len % sizeof(block); + if (fraction == 0) break; + memset(block, 0, sizeof(block)); } else fraction = 16; // debug_printf("block %d: fraction = %d\n", blockno, fraction); - memcpy( block, inbuf + blockno * sizeof( block ), fraction ); - decrypt( ( char* )block ); + memcpy(block, inbuf + blockno * sizeof(block), fraction); + decrypt((char*) block); u8 *ctext_ptr; - if ( blockno == 0 ) ctext_ptr = iv; - else ctext_ptr = inbuf + ( blockno - 1 ) * sizeof( block ); + if (blockno == 0) + ctext_ptr = iv; + else ctext_ptr = inbuf + (blockno - 1) * sizeof(block); - for ( i = 0; i < fraction; i++ ) - outbuf[blockno * sizeof( block ) + i] = - ctext_ptr[i] ^ block[i]; + for (i = 0; i < fraction; i++) + outbuf[blockno * sizeof(block) + i] = ctext_ptr[i] ^ block[i]; // debug_printf("Block %d output: ", blockno); // hexdump(outbuf + blockno*sizeof(block), 16); } } // CBC mode encryption -void aes_encrypt( u8 *iv, u8 *inbuf, u8 *outbuf, unsigned long long len ) +void aes_encrypt(u8 *iv, u8 *inbuf, u8 *outbuf, unsigned long long len) { u8 block[16]; unsigned int blockno = 0, i; // debug_printf("aes_decrypt(%p, %p, %p, %lld)\n", iv, inbuf, outbuf, len); - for ( blockno = 0; blockno <= ( len / sizeof( block ) ); blockno++ ) + for (blockno = 0; blockno <= (len / sizeof(block)); blockno++) { unsigned int fraction; - if ( blockno == ( len / sizeof( block ) ) ) // last block + if (blockno == (len / sizeof(block))) // last block { - fraction = len % sizeof( block ); - if ( fraction == 0 ) break; - memset( block, 0, sizeof( block ) ); + fraction = len % sizeof(block); + if (fraction == 0) break; + memset(block, 0, sizeof(block)); } else fraction = 16; // debug_printf("block %d: fraction = %d\n", blockno, fraction); - memcpy( block, inbuf + blockno * sizeof( block ), fraction ); + memcpy(block, inbuf + blockno * sizeof(block), fraction); - for ( i = 0; i < fraction; i++ ) - block[i] = inbuf[blockno * sizeof( block ) + i] ^ iv[i]; + for (i = 0; i < fraction; i++) + block[i] = inbuf[blockno * sizeof(block) + i] ^ iv[i]; - encrypt( ( char* )block ); - memcpy( iv, block, sizeof( block ) ); - memcpy( outbuf + blockno * sizeof( block ), block, sizeof( block ) ); + encrypt((char*) block); + memcpy(iv, block, sizeof(block)); + memcpy(outbuf + blockno * sizeof(block), block, sizeof(block)); // debug_printf("Block %d output: ", blockno); // hexdump(outbuf + blockno*sizeof(block), 16); } diff --git a/source/libwbfs/wiidisc.c b/source/libwbfs/wiidisc.c index 19ecfecd..e4298793 100644 --- a/source/libwbfs/wiidisc.c +++ b/source/libwbfs/wiidisc.c @@ -5,147 +5,136 @@ #include "wiidisc.h" -void aes_set_key( u8 *key ); -void aes_decrypt( u8 *iv, u8 *inbuf, u8 *outbuf, unsigned long long len ); +void aes_set_key(u8 *key); +void aes_decrypt(u8 *iv, u8 *inbuf, u8 *outbuf, unsigned long long len); -static void _decrypt_title_key( u8 *tik, u8 *title_key ) +static void _decrypt_title_key(u8 *tik, u8 *title_key) { - u8 common_key[16] = - { - 0xeb, 0xe4, 0x2a, 0x22, 0x5e, 0x85, 0x93, 0xe4, 0x48, 0xd9, 0xc5, 0x45, - 0x73, 0x81, 0xaa, 0xf7 - };; + u8 common_key[16] = { 0xeb, 0xe4, 0x2a, 0x22, 0x5e, 0x85, 0x93, 0xe4, 0x48, 0xd9, 0xc5, 0x45, 0x73, 0x81, 0xaa, + 0xf7 }; + ; u8 iv[16]; wbfs_memset( iv, 0, sizeof iv ); wbfs_memcpy( iv, tik + 0x01dc, 8 ); - aes_set_key( common_key ); + aes_set_key(common_key); //_aes_cbc_dec(common_key, iv, tik + 0x01bf, 16, title_key); - aes_decrypt( iv, tik + 0x01bf, title_key, 16 ); + aes_decrypt(iv, tik + 0x01bf, title_key, 16); } -static u32 _be32( const u8 *p ) +static u32 _be32(const u8 *p) { - return ( p[0] << 24 ) | ( p[1] << 16 ) | ( p[2] << 8 ) | p[3]; + return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; } -static void disc_read( wiidisc_t *d, u32 offset, u8 *data, u32 len ) +static void disc_read(wiidisc_t *d, u32 offset, u8 *data, u32 len) { - if ( data ) + 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 (len == 0) return; + ret = d->read(d->fp, offset, len, data); + if (ret) + wbfs_fatal( "error reading disc" ); } - if ( d->sector_usage_table ) + 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 ); + if (len > 0x8000) len -= 0x8000; + } while (len > 0x8000); } } -static void partition_raw_read( wiidisc_t *d, u32 offset, u8 *data, u32 len ) +static void partition_raw_read(wiidisc_t *d, u32 offset, u8 *data, u32 len) { - disc_read( d, d->partition_raw_offset + offset, data, len ); + disc_read(d, d->partition_raw_offset + offset, data, len); } -static void partition_read_block( wiidisc_t *d, u32 blockno, u8 *block ) +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 ); + 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 ); + 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 ) +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; + if (fake && d->sector_usage_table == 0) return; - while ( len ) + 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 ) + 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 ); + 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; + 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 ) +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 ); + name = names + (_be32(fst + 12 * i) & 0x00ffffff); + size = _be32(fst + 12 * i + 8); - if ( i == 0 ) + if (i == 0) { - for ( j = 1; j < size && !d->extracted_buffer; ) + for (j = 1; j < size && !d->extracted_buffer;) { - j = do_fst( d, fst, names, j ); + j = do_fst(d, fst, names, j); } return size; } //printf("name %s\n",name); - if ( fst[12*i] ) + if (fst[12 * i]) { - for ( j = i + 1; j < size && !d->extracted_buffer; ) - j = do_fst( d, fst, names, j ); + 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 ) + 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 ); + partition_read(d, offset, d->extracted_buffer, size, 0); } - else - partition_read( d, offset, 0, size, 1 ); + else partition_read(d, offset, 0, size, 1); return i + 1; } } -static void do_files( wiidisc_t*d ) +static void do_files(wiidisc_t*d) { u8 *b = wbfs_ioalloc( 0x480 ); // XXX: determine actual header size u32 dol_offset; @@ -156,30 +145,28 @@ static void do_files( wiidisc_t*d ) u8 *apl_header = wbfs_ioalloc( 0x20 ); u8 *fst; u32 n_files; - partition_read( d, 0, b, 0x480, 0 ); + partition_read(d, 0, b, 0x480, 0); - dol_offset = _be32( b + 0x0420 ); - fst_offset = _be32( b + 0x0424 ); - fst_size = _be32( b + 0x0428 ) << 2; + 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 ); + 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 - if ( apl_size ) - partition_read( d, apl_offset, 0, apl_size, 1 ); - partition_read( d, dol_offset, 0, ( fst_offset - dol_offset ) << 2, 1 ); + if (apl_size) partition_read(d, apl_offset, 0, apl_size, 1); + partition_read(d, dol_offset, 0, (fst_offset - dol_offset) << 2, 1); - - if ( fst_size ) + if (fst_size) { 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 (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 (d->extract_pathname && *d->extract_pathname == 0) { // if empty pathname requested return fst d->extracted_buffer = fst; @@ -189,19 +176,18 @@ static void do_files( wiidisc_t*d ) n_files = 0; } - if ( 12*n_files <= fst_size ) + if (12 * n_files <= fst_size) { - if ( n_files > 1 ) - do_fst( d, fst, ( char * )fst + 12*n_files, 0 ); + if (n_files > 1) do_fst(d, fst, (char *) fst + 12 * n_files, 0); } + + if (fst != d->extracted_buffer) wbfs_iofree( fst ); } wbfs_iofree( b ); wbfs_iofree( apl_header ); - if ( fst != d->extracted_buffer ) - wbfs_iofree( fst ); } -static void do_partition( wiidisc_t*d ) +static void do_partition(wiidisc_t*d) { u8 *tik = wbfs_ioalloc( 0x2a4 ); u8 *b = wbfs_ioalloc( 0x1c ); @@ -214,53 +200,52 @@ static void do_partition( wiidisc_t*d ) 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 ); + 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_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 ); + 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 ); + if (cert == 0) + wbfs_fatal( "malloc cert" ); + partition_raw_read(d, cert_offset, cert, cert_size); + _decrypt_title_key(tik, d->disc_key); - _decrypt_title_key( tik, d->disc_key ); - - partition_raw_read( d, h3_offset, 0, 0x18000 ); + partition_raw_read(d, h3_offset, 0, 0x18000); wbfs_iofree( b ); wbfs_iofree( tik ); wbfs_iofree( cert ); wbfs_iofree( tmd ); - do_files( d ); + do_files(d); } -static int test_parition_skip( u32 partition_type, partition_selector_t part_sel ) +static int test_parition_skip(u32 partition_type, partition_selector_t part_sel) { - switch ( part_sel ) + switch (part_sel) { case ALL_PARTITIONS: return 0; case REMOVE_UPDATE_PARTITION: - return ( partition_type == 1 ); + return (partition_type == 1); case ONLY_GAME_PARTITION: - return ( partition_type != 0 ); + return (partition_type != 0); default: - return ( partition_type != part_sel ); + return (partition_type != part_sel); } } -static void do_disc( wiidisc_t*d ) +static void do_disc(wiidisc_t*d) { u8 *b = wbfs_ioalloc( 0x100 ); u64 partition_offset[32]; // XXX: don't know the real maximum @@ -268,35 +253,33 @@ static void do_disc( wiidisc_t*d ) u32 n_partitions; u32 magic; u32 i; - disc_read( d, 0, b, 0x100 ); - magic = _be32( b + 24 ); - if ( magic != 0x5D1C9EA3 ) + disc_read(d, 0, b, 0x100); + magic = _be32(b + 24); + if (magic != 0x5D1C9EA3) { wbfs_error( "not a wii disc" ); - return ; + 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++ ) + 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 ); + partition_offset[i] = _be32(b + 8 * i); + partition_type[i] = _be32(b + 8 * i + 4); } - for ( i = 0; i < n_partitions; i++ ) + 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 ); + 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 *wd_open_disc(read_wiidisc_callback_t read, void*fp) { wiidisc_t *d = wbfs_malloc( sizeof( wiidisc_t ) ); - if ( !d ) - return 0; + if (!d) return 0; wbfs_memset( d, 0, sizeof( wiidisc_t ) ); d->read = read; d->fp = fp; @@ -306,7 +289,7 @@ wiidisc_t *wd_open_disc( read_wiidisc_callback_t read, void*fp ) return d; } -void wd_close_disc( wiidisc_t *d ) +void wd_close_disc(wiidisc_t *d) { wbfs_iofree( d->tmp_buffer ); wbfs_free( d->tmp_buffer2 ); @@ -315,13 +298,13 @@ void wd_close_disc( wiidisc_t *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. // first file found with that name is returned. -u8 * wd_extract_file( wiidisc_t *d, partition_selector_t partition_type, char *pathname ) +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 ); + do_disc(d); d->extract_pathname = 0; d->part_sel = ALL_PARTITIONS; retval = d->extracted_buffer; @@ -329,44 +312,43 @@ u8 * wd_extract_file( wiidisc_t *d, partition_selector_t partition_type, char *p return retval; } -void wd_build_disc_usage( wiidisc_t *d, partition_selector_t selector, u8* usage_table ) +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 ); + 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 ) +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." ); + 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; + b += (_be32(b + 4) - (0x40000 >> 2)) * 4; j = 0; - for ( i = 0; i < n_partitions; i++ ) + 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 ) ) + 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 = (u32*) (b + 8 * j); b32[0] = wbfs_htonl( partition_offset ); b32[1] = wbfs_htonl( partition_type ); j++; } } - b32 = ( u32* )( partition_table ); + b32 = (u32*) (partition_table); *b32 = wbfs_htonl( j ); } diff --git a/source/libwbfs/wiidisc.h b/source/libwbfs/wiidisc.h index 2ea61724..ffb43395 100644 --- a/source/libwbfs/wiidisc.h +++ b/source/libwbfs/wiidisc.h @@ -2,7 +2,6 @@ #define WIIDISC_H #include #include "libwbfs_os.h" // this file is provided by the project wanting to compile libwbfs and wiidisc - #ifdef __cplusplus extern "C" { @@ -10,55 +9,53 @@ extern "C" #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 ); + // 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, -} partition_selector_t; + 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; -} wiidisc_t; + char *extract_pathname; + u8 *extracted_buffer; + int extracted_size; + } wiidisc_t; -wiidisc_t *wd_open_disc( read_wiidisc_callback_t read, void*fp ); -void wd_close_disc( wiidisc_t * ); -// returns a buffer allocated with wbfs_ioalloc() or NULL if not found of alloc error -u8 * wd_extract_file( wiidisc_t *d, partition_selector_t partition_type, char *pathname ); + wiidisc_t *wd_open_disc(read_wiidisc_callback_t read, void*fp); + void wd_close_disc(wiidisc_t *); + // returns a buffer allocated with wbfs_ioalloc() or NULL if not found of alloc error + u8 * wd_extract_file(wiidisc_t *d, partition_selector_t partition_type, char *pathname); -void wd_build_disc_usage( wiidisc_t *d, partition_selector_t selector, u8* usage_table ); + void wd_build_disc_usage(wiidisc_t *d, partition_selector_t selector, u8* usage_table); -// effectively remove not copied partition from the partition table. -void wd_fix_partition_table( wiidisc_t *d, partition_selector_t selector, u8* partition_table ); + // effectively remove not copied partition from the partition table. + void wd_fix_partition_table(wiidisc_t *d, partition_selector_t selector, u8* partition_table); #if 0 { diff --git a/source/libwiigui/Text.cpp b/source/libwiigui/Text.cpp index c942ccdd..04c9bab5 100644 --- a/source/libwiigui/Text.cpp +++ b/source/libwiigui/Text.cpp @@ -1,7 +1,7 @@ #include "Text.hpp" -Text::Text( const char * t, int s, GXColor c ) - : GuiText( t, s, c ) +Text::Text(const char * t, int s, GXColor c) : + GuiText(t, s, c) { maxWidth = 400; linestodraw = 9; @@ -9,30 +9,29 @@ Text::Text( const char * t, int s, GXColor c ) FirstLineOffset = 0; wText = NULL; - if ( !text ) - return; + if (!text) return; - wText = new ( std::nothrow ) wString( text ); - if ( !wText ) + wText = new (std::nothrow) wString(text); + if (!wText) { return; } - if ( wText->size() == 0 ) + if (wText->size() == 0) { - wText->push_back( L' ' ); - wText->push_back( 0 ); + wText->push_back(L' '); + wText->push_back(0); } - textWidth = ( font ? font : fontSystem )->getWidth( wText->data(), currentSize ); - delete [] text; + textWidth = (font ? font : fontSystem)->getWidth(wText->data(), currentSize); + delete[] text; text = NULL; - SetMaxWidth( maxWidth ); + SetMaxWidth(maxWidth); } -Text::Text( const wchar_t * t, int s, GXColor c ) - : GuiText( ( wchar_t * ) NULL, s, c ) +Text::Text(const wchar_t * t, int s, GXColor c) : + GuiText((wchar_t *) NULL, s, c) { maxWidth = 400; linestodraw = 9; @@ -40,113 +39,105 @@ Text::Text( const wchar_t * t, int s, GXColor c ) FirstLineOffset = 0; wText = NULL; - if ( !t ) - return; + if (!t) return; - wText = new ( std::nothrow ) wString( t ); - if ( !wText ) + wText = new (std::nothrow) wString(t); + if (!wText) { return; } - if ( wText->size() == 0 ) + if (wText->size() == 0) { - wText->push_back( L' ' ); - wText->push_back( 0 ); + wText->push_back(L' '); + wText->push_back(0); } - textWidth = ( font ? font : fontSystem )->getWidth( wText->data(), currentSize ); + textWidth = (font ? font : fontSystem)->getWidth(wText->data(), currentSize); - SetMaxWidth( maxWidth ); + SetMaxWidth(maxWidth); } Text::~Text() { - if ( wText ) - delete wText; + if (wText) delete wText; wText = NULL; TextLines.clear(); ClearDynamicText(); } -void Text::SetText( const char * t ) +void Text::SetText(const char * t) { - wchar_t * tmp = charToWideChar( t ); - if ( !tmp ) - return; + wchar_t * tmp = charToWideChar(t); + if (!tmp) return; - if ( wText ) - delete wText; + if (wText) delete wText; - wText = new ( std::nothrow ) wString( tmp ); - if ( !wText ) + wText = new (std::nothrow) wString(tmp); + if (!wText) { return; } - if ( wText->size() == 0 ) + if (wText->size() == 0) { - wText->push_back( L' ' ); - wText->push_back( 0 ); + wText->push_back(L' '); + wText->push_back(0); } - textWidth = ( font ? font : fontSystem )->getWidth( wText->data(), currentSize ); + textWidth = (font ? font : fontSystem)->getWidth(wText->data(), currentSize); - delete [] tmp; + delete[] tmp; ClearDynamicText(); CalcLineOffsets(); } -void Text::SetText( const wchar_t * t ) +void Text::SetText(const wchar_t * t) { - if ( !t ) - return; + if (!t) return; - if ( wText ) - delete wText; + if (wText) delete wText; - wText = new wString( t ); - textWidth = ( font ? font : fontSystem )->getWidth( wText->data(), currentSize ); + wText = new wString(t); + textWidth = (font ? font : fontSystem)->getWidth(wText->data(), currentSize); CalcLineOffsets(); } -void Text::SetMaxWidth( int w ) +void Text::SetMaxWidth(int w) { maxWidth = w; curLineStart = 0; Refresh(); } -void Text::SetTextLine( int line ) +void Text::SetTextLine(int line) { - if ( line < 0 ) + if (line < 0) line = 0; - else if ( line > ( int ) TextLines.size() - 1 ) - line = TextLines.size() - 1; + else if (line > (int) TextLines.size() - 1) line = TextLines.size() - 1; curLineStart = line; FillRows(); - while ( ( int ) textDyn.size() < linestodraw && curLineStart > 0 ) + while ((int) textDyn.size() < linestodraw && curLineStart > 0) { PreviousLine(); } } -void Text::SetTextPos( int pos ) +void Text::SetTextPos(int pos) { - if ( !wText ) - return; + if (!wText) return; int diff = 10000; - for ( u32 i = 0; i < TextLines.size(); i++ ) + for (u32 i = 0; i < TextLines.size(); i++) { - int curDiff = abs( TextLines[i].LineOffset - pos ); - if ( curDiff < diff ) + int curDiff = abs(TextLines[i].LineOffset - pos); + if (curDiff < diff) { diff = curDiff; curLineStart = i; @@ -155,7 +146,7 @@ void Text::SetTextPos( int pos ) FillRows(); - while ( ( int ) textDyn.size() < linestodraw && curLineStart > 0 ) + while ((int) textDyn.size() < linestodraw && curLineStart > 0) { PreviousLine(); } @@ -166,35 +157,29 @@ const wchar_t * Text::GetText() return wText->c_str(); } -std::string Text::GetUTF8String( void ) const +std::string Text::GetUTF8String(void) const { return wText->toUTF8(); } -int Text::GetLineOffset( int ind ) +int Text::GetLineOffset(int ind) { - if ( TextLines.size() == 0 ) - return 0; + if (TextLines.size() == 0) return 0; - if ( ind < 0 ) - return TextLines[0].LineOffset; + if (ind < 0) return TextLines[0].LineOffset; - if ( ind >= ( int ) TextLines.size() - 1 ) - return TextLines[TextLines.size()-1].LineOffset; + if (ind >= (int) TextLines.size() - 1) return TextLines[TextLines.size() - 1].LineOffset; return TextLines[ind].LineOffset; } -const wchar_t * Text::GetTextLine( int ind ) +const wchar_t * Text::GetTextLine(int ind) { - if ( filling || textDyn.size() == 0 ) - return NULL; + if (filling || textDyn.size() == 0) return NULL; - if ( ind < 0 ) - return textDyn[0]; + if (ind < 0) return textDyn[0]; - if ( ind >= ( int ) textDyn.size() ) - return textDyn[textDyn.size()-1]; + if (ind >= (int) textDyn.size()) return textDyn[textDyn.size() - 1]; return textDyn[ind]; } @@ -207,8 +192,7 @@ void Text::Refresh() void Text::NextLine() { - if ( !wText || ( curLineStart + 1 > ( ( int ) TextLines.size() - linestodraw ) ) ) - return; + if (!wText || (curLineStart + 1 > ((int) TextLines.size() - linestodraw))) return; ++curLineStart; @@ -217,8 +201,7 @@ void Text::NextLine() void Text::PreviousLine() { - if ( !wText || curLineStart - 1 < 0 ) - return; + if (!wText || curLineStart - 1 < 0) return; --curLineStart; @@ -227,25 +210,24 @@ void Text::PreviousLine() void Text::FillRows() { - if ( !wText ) - return; + if (!wText) return; filling = true; ClearDynamicText(); - for ( int i = 0; i < linestodraw && i < ( int ) TextLines.size(); i++ ) + for (int i = 0; i < linestodraw && i < (int) TextLines.size(); i++) { - if ( i >= ( int ) textDyn.size() ) + if (i >= (int) textDyn.size()) { - textDyn.resize( i + 1 ); + textDyn.resize(i + 1); textDyn[i] = new wchar_t[maxWidth]; } - int offset = TextLines[curLineStart+i].LineOffset; - int count = TextLines[curLineStart+i].CharCount + 1; + int offset = TextLines[curLineStart + i].LineOffset; + int count = TextLines[curLineStart + i].CharCount + 1; - for ( int n = 0; n < count && offset + n < ( int ) wText->size(); n++ ) - textDyn[i][n] = wText->at( offset + n ); + for (int n = 0; n < count && offset + n < (int) wText->size(); n++) + textDyn[i][n] = wText->at(offset + n); textDyn[i][count] = 0; } @@ -257,8 +239,7 @@ void Text::FillRows() void Text::CalcLineOffsets() { - if ( !wText ) - return; + if (!wText) return; TextLines.clear(); @@ -274,35 +255,35 @@ void Text::CalcLineOffsets() int currWidth = 0; int i = 0; - while ( origTxt[ch] ) + while (origTxt[ch]) { - currWidth += fontSystem->getCharWidth( origTxt[ch], currentSize, ch > 0 ? origTxt[ch-1] : 0x0000 ); + currWidth += fontSystem->getCharWidth(origTxt[ch], currentSize, ch > 0 ? origTxt[ch - 1] : 0x0000); - if ( currWidth >= maxWidth ) + if (currWidth >= maxWidth) { - if ( lastSpace > 0 ) + if (lastSpace > 0) { ch = lastSpace; } TmpLine.CharCount = ch - TmpLine.LineOffset; TmpLine.width = currWidth; - TextLines.push_back( TmpLine ); + TextLines.push_back(TmpLine); currWidth = 0; lastSpace = -1; i = -1; TmpLine.LineOffset = ch + 1; } - else if ( origTxt[ch] == '\n' ) + else if (origTxt[ch] == '\n') { TmpLine.CharCount = ch - TmpLine.LineOffset; TmpLine.width = currWidth; - TextLines.push_back( TmpLine ); + TextLines.push_back(TmpLine); currWidth = 0; lastSpace = -1; i = -1; TmpLine.LineOffset = ch + 1; } - else if ( origTxt[ch] == ' ' ) + else if (origTxt[ch] == ' ') { lastSpace = ch; lastSpaceIndex = i; @@ -315,36 +296,32 @@ void Text::CalcLineOffsets() TmpLine.CharCount = ch - TmpLine.LineOffset; TmpLine.width = currWidth; - if ( TmpLine.CharCount > 0 ) - TextLines.push_back( TmpLine ); + if (TmpLine.CharCount > 0) TextLines.push_back(TmpLine); } void Text::Draw() { - if ( textDyn.size() == 0 ) - return; + if (textDyn.size() == 0) return; - if ( !this->IsVisible() ) - return; + if (!this->IsVisible()) return; GXColor c = color; c.a = this->GetAlpha(); int newSize = size * GetScale(); - if ( newSize != currentSize ) + if (newSize != currentSize) { currentSize = newSize; - if ( wText ) - textWidth = ( font ? font : fontSystem )->getWidth( wText->data(), currentSize ); + if (wText) textWidth = (font ? font : fontSystem)->getWidth(wText->data(), currentSize); } u16 lineheight = newSize + 6; - for ( u32 i = 0; i < textDyn.size(); i++ ) + for (u32 i = 0; i < textDyn.size(); i++) { - if ( !filling ) - ( font ? font : fontSystem )->drawText( this->GetLeft(), this->GetTop() + i*lineheight, 0, textDyn[i], currentSize, c, style, 0, maxWidth ); + if (!filling) (font ? font : fontSystem)->drawText(this->GetLeft(), this->GetTop() + i * lineheight, 0, + textDyn[i], currentSize, c, style, 0, maxWidth); } } diff --git a/source/libwiigui/Text.hpp b/source/libwiigui/Text.hpp index 0db64dcb..8f7b101b 100644 --- a/source/libwiigui/Text.hpp +++ b/source/libwiigui/Text.hpp @@ -6,47 +6,63 @@ typedef struct { - int LineOffset; - int CharCount; - int width; + int LineOffset; + int CharCount; + int width; } TextLine; -class Text : public GuiText +class Text: public GuiText { public: - //!Constructor - //!\param t Text - //!\param s Font size - //!\param c Font color + //!Constructor + //!\param t Text + //!\param s Font size + //!\param c Font color Text(const char * t, int s, GXColor c); Text(const wchar_t * t, int s, GXColor c); ~Text(); - //!Sets the text of the GuiText element - //!\param t Text - void SetText(const char * t); - void SetText(const wchar_t * t); - //!Set the max texwidth + //!Sets the text of the GuiText element + //!\param t Text + void SetText(const char * t); + void SetText(const wchar_t * t); + //!Set the max texwidth void SetMaxWidth(int width); - //!Go to next line - void NextLine(); - //!Go to previous line - void PreviousLine(); - //!Refresh the rows to draw + //!Go to next line + void NextLine(); + //!Go to previous line + void PreviousLine(); + //!Refresh the rows to draw void Refresh(); - //!Set the text line + //!Set the text line void SetTextLine(int line); - //!Set to the char pos in text + //!Set to the char pos in text void SetTextPos(int pos); - //!Refresh the rows to draw - int GetCurrPos() { return curLineStart; }; - //!Get the count of loaded lines - int GetLinesCount() { return textDyn.size(); }; - //!Get the total count of lines - int GetTotalLinesCount() { return TextLines.size(); }; + //!Refresh the rows to draw + int GetCurrPos() + { + return curLineStart; + } + ; + //!Get the count of loaded lines + int GetLinesCount() + { + return textDyn.size(); + } + ; + //!Get the total count of lines + int GetTotalLinesCount() + { + return TextLines.size(); + } + ; //!Get the original full Text const wchar_t * GetText(); //!Get the original full Text as wString - wString * GetwString() { return wText; }; + wString * GetwString() + { + return wText; + } + ; //!Get the original Text as a UTF-8 text //!memory is allocated in this //!which needs to be deleted later @@ -55,17 +71,17 @@ class Text : public GuiText const wchar_t * GetTextLine(int ind); //!Get the offset in the text of a drawn Line int GetLineOffset(int ind); - //!Constantly called to draw the text - void Draw(); + //!Constantly called to draw the text + void Draw(); protected: void CalcLineOffsets(); void FillRows(); - wString * wText; - std::vector TextLines; - int curLineStart; - int FirstLineOffset; - bool filling; + wString * wText; + std::vector TextLines; + int curLineStart; + int FirstLineOffset; + bool filling; }; #endif diff --git a/source/libwiigui/gui.h b/source/libwiigui/gui.h index 96bafcf6..e693493d 100644 --- a/source/libwiigui/gui.h +++ b/source/libwiigui/gui.h @@ -26,7 +26,7 @@ * authors of PNGU and FreeTypeGX, of which this library makes use. Thanks * also to the authors of GRRLIB and libwiisprite for laying the foundations. * -*/ + */ #ifndef LIBWIIGUI_H #define LIBWIIGUI_H @@ -54,62 +54,44 @@ extern FreeTypeGX *fontSystem; #define FILEBROWSERSIZE 8 #define MAX_OPTIONS 170 -typedef void ( *UpdateCallback )( void * e ); +typedef void (*UpdateCallback)(void * e); enum { - ALIGN_LEFT, - ALIGN_RIGHT, - ALIGN_CENTRE, - ALIGN_TOP, - ALIGN_BOTTOM, - ALIGN_MIDDLE + 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 + STATE_DEFAULT, STATE_SELECTED, STATE_CLICKED, STATE_HELD, STATE_DISABLED }; enum { - IMAGE_TEXTURE, - IMAGE_COLOR, - IMAGE_DATA, - IMAGE_COPY + IMAGE_TEXTURE, IMAGE_COLOR, IMAGE_DATA, IMAGE_COPY }; enum { - TRIGGER_SIMPLE, - TRIGGER_HELD, - TRIGGER_BUTTON_ONLY, - TRIGGER_BUTTON_ONLY_IN_FOCUS + TRIGGER_SIMPLE, TRIGGER_HELD, TRIGGER_BUTTON_ONLY, TRIGGER_BUTTON_ONLY_IN_FOCUS }; enum { - WRAP, - DOTTED, - SCROLL_HORIZONTAL, - SCROLL_NONE + WRAP, DOTTED, SCROLL_HORIZONTAL, SCROLL_NONE }; 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 @@ -139,18 +121,18 @@ class GuiSound //!\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 ); + 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 ); + 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 ); + bool Load(const u8 *s, int l, bool r = false, bool a = false); + bool Load(const char *p); //!Destructor ~GuiSound(); @@ -167,26 +149,26 @@ class GuiSound bool IsPlaying(); //!Set sound volume //!\param v Sound volume (0-100) - void SetVolume( int v ); + void SetVolume(int v); //!Set the sound to loop playback (only applies to OGG) //!\param l Loop (true to loop) - void SetLoop( bool l ); + 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 + 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 ); + 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. @@ -201,27 +183,27 @@ class GuiTrigger //!\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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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(); @@ -253,7 +235,7 @@ class GuiElement ~GuiElement(); //!Set the element's parent //!\param e Pointer to parent element - void SetParent( GuiElement * e ); + void SetParent(GuiElement * e); //!Gets the element's parent //!\return Pointer to parent element GuiElement * GetParent(); @@ -267,25 +249,25 @@ class GuiElement int GetTop(); //!Sets the minimum y offset of the element //!\param y Y offset - void SetMinY( int y ); + 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 ); + 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 ); + 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 ); + void SetMaxX(int x); //!Gets the maximum x offset of the element //!\return Maximum X offset int GetMaxX(); @@ -298,7 +280,7 @@ class GuiElement //!Sets the size (width/height) of the element //!\param w Width of element //!\param h Height of element - void SetSize( int w, int h ); + void SetSize(int w, int h); //!Checks whether or not the element is visible //!\return true if visible, false otherwise bool IsVisible(); @@ -313,13 +295,13 @@ class GuiElement bool IsHoldable(); //!Sets whether or not the element is selectable //!\param s Selectable - void SetSelectable( bool s ); + void SetSelectable(bool s); //!Sets whether or not the element is clickable //!\param c Clickable - void SetClickable( bool c ); + void SetClickable(bool c); //!Sets whether or not the element is holdable //!\param c Holdable - void SetHoldable( bool d ); + void SetHoldable(bool d); //!Gets the element's current state //!\return state int GetState(); @@ -328,7 +310,7 @@ class GuiElement int GetStateChan(); //!Sets the element's alpha value //!\param a alpha value - void SetAlpha( int a ); + void SetAlpha(int a); //!Gets the element's alpha value //!Considers alpha, alphaDyn, and the parent element's GetAlpha() value //!\return alpha @@ -338,31 +320,31 @@ class GuiElement float GetAngleDyn(); //!Sets the element's scale //!\param s scale (1 is 100%) - void SetScale( float s ); + 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 ); + void SetTrigger(GuiTrigger * t); //!\overload //!\param i Index of trigger array to set //!\param t Pointer to GuiTrigger - void SetTrigger( u8 i, GuiTrigger * t ); + void SetTrigger(u8 i, GuiTrigger * t); //!Remove GuiTrigger for the element //!\param i Index of trigger array to set - void RemoveTrigger( u8 i ); + 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 ); + 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 ); + 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 @@ -373,7 +355,8 @@ class GuiElement //! 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 ); + 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(); @@ -381,7 +364,7 @@ class GuiElement //!\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 ); + void SetEffectOnOver(int e, int a, int t = 0); //!Shortcut to SetEffectOnOver(EFFECT_SCALE, 4, 110) void SetEffectGrow(); //!Stops the current element effect @@ -396,30 +379,30 @@ class GuiElement //!\param x X coordinate //!\param y Y coordinate //!\return true if contained within, false otherwise - bool IsInside( int x, int y ); + 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 ); + 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 ); + 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 ); + virtual void SetVisible(bool v); //!Sets the element's focus //!\param f Focus (true = in focus) - virtual void SetFocus( int f ); + 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 ); + 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 @@ -428,21 +411,21 @@ class GuiElement //!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 ); + 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 ); + 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; + // static mutex_t mutex; + static mutex_t _lock_mutex; + lwp_t _lock_thread; + u16 _lock_count; + lwpq_t _lock_queue; friend class SimpleLock; //int position2; //! B Scrollbariable @@ -496,7 +479,7 @@ class GuiElement class SimpleLock { public: - SimpleLock( GuiElement *e ); + SimpleLock(GuiElement *e); ~SimpleLock(); private: GuiElement *element; @@ -504,7 +487,7 @@ class SimpleLock #define LOCK(e) SimpleLock LOCK(e) //!Allows GuiElements to be grouped together into a "window" -class GuiWindow : public GuiElement +class GuiWindow: public GuiElement { public: //!Constructor @@ -512,65 +495,65 @@ class GuiWindow : public GuiElement //!\overload //!\param w Width of window //!\param h Height of window - GuiWindow( int w, int h ); + 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 ); + 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 ); + void Insert(GuiElement* e, u32 i); //!Removes the specified GuiElement from the GuiWindow //!\param e GuiElement to be removed - void Remove( GuiElement* e ); + 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; + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + void Update(GuiTrigger * t); protected: std::vector _elements; //!< Contains all elements within the GuiWindow }; @@ -582,10 +565,11 @@ class GuiImageData //!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 ); + 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 @@ -598,11 +582,11 @@ class GuiImageData //!\return image height int GetHeight(); //!LoadJpeg file - void LoadJpeg( const u8 *img, int imgSize ); + void LoadJpeg(const u8 *img, int imgSize); //!RawTo4x4RGBA - void RawTo4x4RGBA( const unsigned char *src, void *dst, const unsigned int width, const unsigned int height ); + void RawTo4x4RGBA(const unsigned char *src, void *dst, const unsigned int width, const unsigned int height); //!Sets the image to grayscale - void SetGrayscale( void ); + void SetGrayscale(void); protected: u8 * data; //!< Image data int height; //!< Height of image @@ -610,43 +594,43 @@ class GuiImageData }; //!Display, manage, and manipulate images in the GUI -class GuiImage : public GuiElement +class GuiImage: public GuiElement { public: //!Constructor GuiImage(); //!\overload //!\param img Pointer to GuiImageData element - GuiImage( GuiImageData * img ); + 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 ); + 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 ); + GuiImage(int w, int h, GXColor c); //! Copy Constructor - GuiImage( GuiImage &srcimage ); - GuiImage( GuiImage *srcimage ); + GuiImage(GuiImage &srcimage); + GuiImage(GuiImage *srcimage); //! = operator for copying images - GuiImage &operator=( GuiImage &srcimage ); + GuiImage &operator=(GuiImage &srcimage); //!Destructor ~GuiImage(); //!Sets the image rotation angle for drawing //!\param a Angle (in degrees) - void SetAngle( float a ); + 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 ); + void SetTile(int t); // true set horizontal scale to 0.8 //added - void SetWidescreen( bool w ); + void SetWidescreen(bool w); //!Constantly called to draw the image void Draw(); //!Gets the image data @@ -654,36 +638,36 @@ class GuiImage : public GuiElement u8 * GetImage(); //!Sets up a new image using the GuiImageData object specified //!\param img Pointer to GuiImageData object - void SetImage( GuiImageData * img ); + 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 ); + 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 ); + 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 ); + void SetPixel(int x, int y, GXColor color); //!Sets the image to grayscale - void SetGrayscale( void ); + void SetGrayscale(void); //!Set/disable the use of parentelement angle (default true) - void SetParentAngle( bool a ); + 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 ); + 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 ); + 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] */ ); + 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; @@ -710,30 +694,30 @@ class GuiImage : public GuiElement bool parentangle; }; //!Display, manage, and manipulate text in the GUI -class GuiText : public GuiElement +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 ); + GuiText(const char * t, int s, GXColor c); //!\overload //!\param t Text //!\param s Font size //!\param c Font color - GuiText( const wchar_t * t, int s, GXColor c ); + GuiText(const wchar_t * t, int s, GXColor c); //!\overload //!\Assumes SetPresets() has been called to setup preferred text attributes //!\param t Text - GuiText( const char * t ); + GuiText(const char * t); //!Destructor ~GuiText(); //!Sets the text of the GuiText element //!\param t Text - virtual void SetText( const char * t ); - virtual void SetText( const wchar_t * t ); - virtual void SetTextf( const char *format, ... ) __attribute__( ( format( printf, 2, 3 ) ) ); + virtual void SetText(const char * t); + virtual void SetText(const wchar_t * t); + virtual void SetTextf(const char *format, ...) __attribute__( ( format( printf, 2, 3 ) ) ); //!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 @@ -743,52 +727,68 @@ class GuiText : public GuiElement //!\param s Font style //!\param h Text alignment (horizontal) //!\param v Text alignment (vertical) - static void SetPresets( int sz, GXColor c, int w, u16 s, int h, int v ); + static void SetPresets(int sz, GXColor c, int w, u16 s, int h, int v); //!Sets the font size //!\param s Font size - void SetFontSize( int s ); + 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 - void SetMaxWidth( int w = 0, int m = WRAP ); + void SetMaxWidth(int w = 0, int m = WRAP); //!Sets the font color //!\param c Font color - void SetColor( GXColor c ); + void SetColor(GXColor c); //!Sets the FreeTypeGX style attributes //!\param s Style attributes //!\param m Style-Mask attributes - void SetStyle( u16 s ); + void SetStyle(u16 s); //!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 ); + void SetAlignment(int hor, int vert); //!Set PassChar - void SetPassChar( wchar_t p ); + void SetPassChar(wchar_t p); //!Sets the font //!\param f Font - void SetFont( FreeTypeGX *f ); + void SetFont(FreeTypeGX *f); //!Get the original text as char virtual const wchar_t * GetText(); //!Get the Horizontal Size of Text int GetTextWidth(); - int GetTextWidth( int ind ); + int GetTextWidth(int ind); //!Get the max textwidth int GetTextMaxWidth(); //!Gets the total line number - virtual int GetLinesCount() { return 1; }; + virtual int GetLinesCount() + { + return 1; + } + ; //!Get fontsize - int GetFontSize() { return size; }; + int GetFontSize() + { + return size; + } + ; //!Set max lines to draw - void SetLinesToDraw( int l ); - void SetWidescreen( bool b ) { widescreen = b; }; + void SetLinesToDraw(int l); + void SetWidescreen(bool b) + { + widescreen = b; + } + ; //!Get current Textline (for position calculation) - const wchar_t * GetDynText( int ind = 0 ); - virtual const wchar_t * GetTextLine( int ind ) { return GetDynText( ind ); }; + const wchar_t * GetDynText(int ind = 0); + virtual const wchar_t * GetTextLine(int ind) + { + return GetDynText(ind); + } + ; //!Change the font //!\param font bufferblock //!\param font filesize - bool SetFont( const u8 *font, const u32 filesize ); + bool SetFont(const u8 *font, const u32 filesize); //!Constantly called to draw the text void Draw(); protected: @@ -820,12 +820,12 @@ class GuiText : public GuiElement }; //!Display, manage, and manipulate tooltips in the GUI. -class GuiTooltip : public GuiElement +class GuiTooltip: public GuiElement { public: //!Constructor //!\param t Text - GuiTooltip( const char *t, int Alpha = 255 ); + GuiTooltip(const char *t, int Alpha = 255); //!Destructor ~ GuiTooltip(); @@ -835,8 +835,8 @@ class GuiTooltip : public GuiElement float GetScale(); //!Sets the text of the GuiTooltip element //!\param t Text - void SetText( const char * t ); - void SetWidescreen( bool w ); // timely a dummy + void SetText(const char * t); + void SetWidescreen(bool w); // timely a dummy //!Constantly called to draw the GuiButton void Draw(); @@ -847,15 +847,14 @@ class GuiTooltip : public GuiElement 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 +class GuiButton: public GuiElement { public: //!Constructor //!\param w Width //!\param h Height - GuiButton( int w, int h ); + 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 @@ -866,64 +865,67 @@ class GuiButton : public GuiElement //!\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 ); + 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 ); + 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 ); + void SetImage(GuiImage* i); //!Sets the button's image on over //!\param i Pointer to GuiImage object - void SetImageOver( GuiImage* i ); + 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 ); + 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 ); + void SetImageClick(GuiImage* i); //!Sets the button's icon //!\param i Pointer to GuiImage object - void SetIcon( GuiImage* i ); + void SetIcon(GuiImage* i); //!Sets the button's icon on over //!\param i Pointer to GuiImage object - void SetIconOver( GuiImage* i ); + void SetIconOver(GuiImage* i); //!Sets the button's icon on hold //!\param i Pointer to GuiImage object - void SetIconHold( GuiImage* i ); + void SetIconHold(GuiImage* i); //!Sets the button's icon on click //!\param i Pointer to GuiImage object - void SetIconClick( GuiImage* i ); + 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 ); + 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 ); + 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 ); + 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 ); + void SetLabelClick(GuiText* t, int n = 0); //!Sets the sound to play on over //!\param s Pointer to GuiSound object - void SetSoundOver( GuiSound * s ); + void SetSoundOver(GuiSound * s); //!Sets the sound to play on hold //!\param s Pointer to GuiSound object - void SetSoundHold( GuiSound * s ); + void SetSoundHold(GuiSound * s); //!Sets the sound to play on click //!\param s Pointer to GuiSound object - void SetSoundClick( GuiSound * s ); + void SetSoundClick(GuiSound * s); //!\param reset the soundover to NULL void RemoveSoundOver(); //!\param reset the soundclick to NULL @@ -931,7 +933,7 @@ class GuiButton : public GuiElement //!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 SetToolTip(GuiTooltip* tt, int x, int y, int h = ALIGN_RIGHT, int v = ALIGN_TOP); void RemoveToolTip(); //!Constantly called to draw the GuiButton @@ -939,11 +941,11 @@ class GuiButton : public GuiElement 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 ); + 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] */ ); + 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 @@ -966,16 +968,16 @@ class GuiButton : public GuiElement typedef struct _keytype { - char ch, chShift, chalt, chalt2; + char ch, chShift, chalt, chalt2; } Key; //!On-screen keyboard -class GuiKeyboard : public GuiWindow +class GuiKeyboard: public GuiWindow { public: - GuiKeyboard( char * t, u32 m, int min, int lang ); + GuiKeyboard(char * t, u32 m, int min, int lang); ~GuiKeyboard(); - void Update( GuiTrigger * t ); + void Update(GuiTrigger * t); char kbtextstr[256]; protected: u32 kbtextmaxlen; @@ -1031,12 +1033,12 @@ class GuiKeyboard : public GuiWindow }; //!On-screen keyboard -class GuiNumpad : public GuiWindow +class GuiNumpad: public GuiWindow { public: - GuiNumpad( char * t, u32 max ); + GuiNumpad(char * t, u32 max); ~GuiNumpad(); - void Update( GuiTrigger * t ); + void Update(GuiTrigger * t); char kbtextstr[256]; protected: u32 kbtextmaxlen; @@ -1067,27 +1069,28 @@ class GuiNumpad : public GuiWindow 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 +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(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 ); + void SetCol2Position(int x); + int FindMenuItem(int c, int d); int GetClickedOption(); int GetSelectedOption(); void ResetState(); - void SetFocus( int f ); + void SetFocus(int f); void Draw(); void TriggerUpdate(); - void Update( GuiTrigger * t ); + void Update(GuiTrigger * t); GuiText * optionVal[PAGESIZE]; protected: int selectedItem; @@ -1132,17 +1135,17 @@ class GuiOptionBrowser : public GuiElement }; //!Display a list of files -class GuiFileBrowser : public GuiElement +class GuiFileBrowser: public GuiElement { public: - GuiFileBrowser( int w, int h ); + GuiFileBrowser(int w, int h); ~GuiFileBrowser(); - void DisableTriggerUpdate( bool set ); + void DisableTriggerUpdate(bool set); void ResetState(); - void SetFocus( int f ); + void SetFocus(int f); void Draw(); void TriggerUpdate(); - void Update( GuiTrigger * t ); + void Update(GuiTrigger * t); GuiButton * fileList[PAGESIZE]; protected: int selectedItem; diff --git a/source/libwiigui/gui_bgm.cpp b/source/libwiigui/gui_bgm.cpp index d5547f4c..98c89533 100644 --- a/source/libwiigui/gui_bgm.cpp +++ b/source/libwiigui/gui_bgm.cpp @@ -8,8 +8,8 @@ #include "gui_bgm.h" #include "menu.h" -GuiBGM::GuiBGM( const u8 *s, int l, int v ) - : GuiSound( s, l, v ) +GuiBGM::GuiBGM(const u8 *s, int l, int v) : + GuiSound(s, l, v) { loop = 0; loopMode = ONCE; @@ -18,153 +18,148 @@ GuiBGM::GuiBGM( const u8 *s, int l, int v ) //shouldn't be needed but //fixes some kind of weird bug in ogg system - GuiSound::Load( s, l, v ); + GuiSound::Load(s, l, v); } GuiBGM::~GuiBGM() { - if ( currentPath ) - delete [] currentPath; + if (currentPath) delete[] currentPath; ClearList(); -}; +} +; -void GuiBGM::SetLoop( bool l ) +void GuiBGM::SetLoop(bool l) { } -void GuiBGM::SetLoop( int l ) +void GuiBGM::SetLoop(int l) { loop = false; loopMode = ONCE; - if ( l == LOOP ) + if (l == LOOP) { loop = true; } - else - loopMode = l; + else loopMode = l; } -bool GuiBGM::Load( const char *path ) +bool GuiBGM::Load(const char *path) { - if ( !path ) + if (!path) { LoadStandard(); return false; } - if ( strcmp( path, "" ) == 0 ) + if (strcmp(path, "") == 0) { LoadStandard(); return false; } - if ( !GuiSound::Load( path ) ) + if (!GuiSound::Load(path)) { LoadStandard(); return false; } - return ParsePath( path ); + return ParsePath(path); } bool GuiBGM::LoadStandard() { ClearList(); - if ( currentPath ) + if (currentPath) { - delete [] currentPath; + delete[] currentPath; currentPath = NULL; } - strcpy( Settings.ogg_path, "" ); + strcpy(Settings.ogg_path, ""); - bool ret = GuiSound::Load( bg_music_ogg, bg_music_ogg_size, true ); + bool ret = GuiSound::Load(bg_music_ogg, bg_music_ogg_size, true); - if ( ret ) - Play(); + if (ret) Play(); return ret; } -bool GuiBGM::ParsePath( const char * folderpath ) +bool GuiBGM::ParsePath(const char * folderpath) { ClearList(); - if ( currentPath ) - delete [] currentPath; + if (currentPath) delete[] currentPath; - currentPath = new char[strlen( folderpath )+1]; - sprintf( currentPath, "%s", folderpath ); + currentPath = new char[strlen(folderpath) + 1]; + sprintf(currentPath, "%s", folderpath); - char * isdirpath = strrchr( folderpath, '.' ); - if ( isdirpath ) + char * isdirpath = strrchr(folderpath, '.'); + if (isdirpath) { - char * pathptr = strrchr( currentPath, '/' ); - if ( pathptr ) + char * pathptr = strrchr(currentPath, '/'); + if (pathptr) { pathptr++; pathptr[0] = 0; } } - char * LoadedFilename = strrchr( folderpath, '/' ) + 1; + char * LoadedFilename = strrchr(folderpath, '/') + 1; char filename[1024]; struct stat st; - DIR_ITER * dir = diropen( currentPath ); - if ( dir == NULL ) + DIR_ITER * dir = diropen(currentPath); + if (dir == NULL) { LoadStandard(); return false; } u32 counter = 0; - while ( dirnext( dir, filename, &st ) == 0 ) + while (dirnext(dir, filename, &st) == 0) { - char * fileext = strrchr( filename, '.' ); - if ( fileext ) + char * fileext = strrchr(filename, '.'); + if (fileext) { - if ( strcasecmp( fileext, ".mp3" ) == 0 || strcasecmp( fileext, ".ogg" ) == 0 - || strcasecmp( fileext, ".wav" ) == 0 ) + if (strcasecmp(fileext, ".mp3") == 0 || strcasecmp(fileext, ".ogg") == 0 || strcasecmp(fileext, ".wav") + == 0) { - AddEntrie( filename ); + AddEntrie(filename); - if ( strcmp( LoadedFilename, filename ) == 0 ) - currentPlaying = counter; + if (strcmp(LoadedFilename, filename) == 0) currentPlaying = counter; counter++; } } } - dirclose( dir ); + dirclose(dir); - snprintf( Settings.ogg_path, sizeof( Settings.ogg_path ), "%s", folderpath ); + snprintf(Settings.ogg_path, sizeof(Settings.ogg_path), "%s", folderpath); return true; } -void GuiBGM::AddEntrie( const char * filename ) +void GuiBGM::AddEntrie(const char * filename) { - if ( !filename ) - return; + if (!filename) return; - char * NewEntrie = new char[strlen( filename )+1]; - sprintf( NewEntrie, "%s", filename ); + char * NewEntrie = new char[strlen(filename) + 1]; + sprintf(NewEntrie, "%s", filename); - PlayList.push_back( NewEntrie ); + PlayList.push_back(NewEntrie); } void GuiBGM::ClearList() { - for ( u32 i = 0; i < PlayList.size(); i++ ) + for (u32 i = 0; i < PlayList.size(); i++) { - if ( PlayList.at( i ) != NULL ) + if (PlayList.at(i) != NULL) { - delete [] PlayList.at( i ); - PlayList.at( i ) = NULL; + delete[] PlayList.at(i); + PlayList.at(i) = NULL; } } @@ -173,17 +168,14 @@ void GuiBGM::ClearList() bool GuiBGM::PlayNext() { - if ( !currentPath ) - return false; + if (!currentPath) return false; currentPlaying++; - if ( currentPlaying >= ( int ) PlayList.size() ) - currentPlaying = 0; + if (currentPlaying >= (int) PlayList.size()) currentPlaying = 0; - snprintf( Settings.ogg_path, sizeof( Settings.ogg_path ), "%s%s", currentPath, PlayList.at( currentPlaying ) ); + snprintf(Settings.ogg_path, sizeof(Settings.ogg_path), "%s%s", currentPath, PlayList.at(currentPlaying)); - if ( !GuiSound::Load( Settings.ogg_path ) ) - return false; + if (!GuiSound::Load(Settings.ogg_path)) return false; Play(); @@ -192,17 +184,14 @@ bool GuiBGM::PlayNext() bool GuiBGM::PlayPrevious() { - if ( !currentPath ) - return false; + if (!currentPath) return false; currentPlaying--; - if ( currentPlaying < 0 ) - currentPlaying = PlayList.size() - 1; + if (currentPlaying < 0) currentPlaying = PlayList.size() - 1; - snprintf( Settings.ogg_path, sizeof( Settings.ogg_path ), "%s%s", currentPath, PlayList.at( currentPlaying ) ); + snprintf(Settings.ogg_path, sizeof(Settings.ogg_path), "%s%s", currentPath, PlayList.at(currentPlaying)); - if ( !GuiSound::Load( Settings.ogg_path ) ) - return false; + if (!GuiSound::Load(Settings.ogg_path)) return false; Play(); @@ -211,23 +200,20 @@ bool GuiBGM::PlayPrevious() bool GuiBGM::PlayRandom() { - if ( !currentPath ) - return false; + if (!currentPath) return false; - srand ( time( NULL ) ); + srand(time(NULL)); currentPlaying = rand() % PlayList.size(); //just in case - if ( currentPlaying < 0 ) + if (currentPlaying < 0) currentPlaying = PlayList.size() - 1; - else if ( currentPlaying >= ( int ) PlayList.size() ) - currentPlaying = 0; + else if (currentPlaying >= (int) PlayList.size()) currentPlaying = 0; - snprintf( Settings.ogg_path, sizeof( Settings.ogg_path ), "%s%s", currentPath, PlayList.at( currentPlaying ) ); + snprintf(Settings.ogg_path, sizeof(Settings.ogg_path), "%s%s", currentPath, PlayList.at(currentPlaying)); - if ( !GuiSound::Load( Settings.ogg_path ) ) - return false; + if (!GuiSound::Load(Settings.ogg_path)) return false; Play(); @@ -236,13 +222,13 @@ bool GuiBGM::PlayRandom() void GuiBGM::UpdateState() { - if ( !IsPlaying() ) + if (!IsPlaying()) { - if ( loopMode == DIR_LOOP ) + if (loopMode == DIR_LOOP) { PlayNext(); } - else if ( loopMode == RANDOM_BGM ) + else if (loopMode == RANDOM_BGM) { PlayRandom(); } diff --git a/source/libwiigui/gui_bgm.h b/source/libwiigui/gui_bgm.h index 5a458d3a..8fe076d1 100644 --- a/source/libwiigui/gui_bgm.h +++ b/source/libwiigui/gui_bgm.h @@ -12,28 +12,25 @@ enum { - ONCE = 0, - LOOP, - RANDOM_BGM, - DIR_LOOP + ONCE = 0, LOOP, RANDOM_BGM, DIR_LOOP }; -class GuiBGM : public GuiSound +class GuiBGM: public GuiSound { public: - GuiBGM( const u8 *s, int l, int v ); + GuiBGM(const u8 *s, int l, int v); ~GuiBGM(); - bool Load( const char *path ); + bool Load(const char *path); bool LoadStandard(); - bool ParsePath( const char * folderpath ); + bool ParsePath(const char * folderpath); bool PlayNext(); bool PlayPrevious(); bool PlayRandom(); - void SetLoop( bool l ); - void SetLoop( int l ); + void SetLoop(bool l); + void SetLoop(int l); void UpdateState(); protected: - void AddEntrie( const char * filename ); + void AddEntrie(const char * filename); void ClearList(); int currentPlaying; diff --git a/source/libwiigui/gui_button.cpp b/source/libwiigui/gui_button.cpp index 70f9a1c9..59bccea8 100644 --- a/source/libwiigui/gui_button.cpp +++ b/source/libwiigui/gui_button.cpp @@ -16,7 +16,7 @@ static int scrollison; * Constructor for the GuiButton class. */ -GuiButton::GuiButton( int w, int h ) +GuiButton::GuiButton(int w, int h) { width = w; height = h; @@ -30,7 +30,7 @@ GuiButton::GuiButton( int w, int h ) iconClick = NULL; toolTip = NULL; - for ( int i = 0; i < 3; i++ ) + for (int i = 0; i < 3; i++) { label[i] = NULL; labelOver[i] = NULL; @@ -48,14 +48,15 @@ GuiButton::GuiButton( int w, int h ) 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 ) +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 ); + image->SetParent(this); imageOver = imgOver; - if ( imageOver ) imageOver->SetParent( this ); + if (imageOver) imageOver->SetParent(this); imageHold = NULL; imageClick = NULL; icon = NULL; @@ -69,7 +70,7 @@ GuiButton::GuiButton( GuiImage* img, GuiImage* imgOver, int hor, int vert, int x yoffset = y; trigger[0] = trig; - for ( int i = 0; i < 3; i++ ) + for (int i = 0; i < 3; i++) { label[i] = NULL; labelOver[i] = NULL; @@ -84,7 +85,7 @@ GuiButton::GuiButton( GuiImage* img, GuiImage* imgOver, int hor, int vert, int x holdable = false; clickable = true; - if ( grow == 1 ) + if (grow == 1) { effectsOver |= EFFECT_SCALE; effectAmountOver = 4; @@ -93,14 +94,15 @@ GuiButton::GuiButton( GuiImage* img, GuiImage* imgOver, int hor, int vert, int x 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 ) +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 ); + image->SetParent(this); imageOver = imgOver; - if ( imageOver ) imageOver->SetParent( this ); + if (imageOver) imageOver->SetParent(this); imageHold = NULL; imageClick = NULL; icon = NULL; @@ -114,7 +116,7 @@ GuiButton::GuiButton( GuiImage* img, GuiImage* imgOver, int hor, int vert, int x yoffset = y; trigger[0] = trig; - for ( int i = 0; i < 3; i++ ) + for (int i = 0; i < 3; i++) { label[i] = NULL; labelOver[i] = NULL; @@ -129,7 +131,7 @@ GuiButton::GuiButton( GuiImage* img, GuiImage* imgOver, int hor, int vert, int x holdable = false; clickable = true; - if ( grow == 1 ) + if (grow == 1) { effectsOver |= EFFECT_SCALE; effectAmountOver = 4; @@ -137,9 +139,9 @@ GuiButton::GuiButton( GuiImage* img, GuiImage* imgOver, int hor, int vert, int x } toolTip = tt; - toolTip->SetParent( this ); - toolTip->SetAlignment( h_align, v_align ); - toolTip->SetPosition( ttx, tty ); + toolTip->SetParent(this); + toolTip->SetAlignment(h_align, v_align); + toolTip->SetPosition(ttx, tty); time1 = time2 = 0; } @@ -151,103 +153,103 @@ GuiButton::~GuiButton() { } -void GuiButton::SetImage( GuiImage* img ) +void GuiButton::SetImage(GuiImage* img) { LOCK( this ); image = img; - if ( img ) img->SetParent( this ); + if (img) img->SetParent(this); } -void GuiButton::SetImageOver( GuiImage* img ) +void GuiButton::SetImageOver(GuiImage* img) { LOCK( this ); imageOver = img; - if ( img ) img->SetParent( this ); + if (img) img->SetParent(this); } -void GuiButton::SetImageHold( GuiImage* img ) +void GuiButton::SetImageHold(GuiImage* img) { LOCK( this ); imageHold = img; - if ( img ) img->SetParent( this ); + if (img) img->SetParent(this); } -void GuiButton::SetImageClick( GuiImage* img ) +void GuiButton::SetImageClick(GuiImage* img) { LOCK( this ); imageClick = img; - if ( img ) img->SetParent( this ); + if (img) img->SetParent(this); } -void GuiButton::SetIcon( GuiImage* img ) +void GuiButton::SetIcon(GuiImage* img) { LOCK( this ); icon = img; - if ( img ) img->SetParent( this ); + if (img) img->SetParent(this); } -void GuiButton::SetIconOver( GuiImage* img ) +void GuiButton::SetIconOver(GuiImage* img) { LOCK( this ); iconOver = img; - if ( img ) img->SetParent( this ); + if (img) img->SetParent(this); } -void GuiButton::SetIconHold( GuiImage* img ) +void GuiButton::SetIconHold(GuiImage* img) { LOCK( this ); iconHold = img; - if ( img ) img->SetParent( this ); + if (img) img->SetParent(this); } -void GuiButton::SetIconClick( GuiImage* img ) +void GuiButton::SetIconClick(GuiImage* img) { LOCK( this ); iconClick = img; - if ( img ) img->SetParent( this ); + if (img) img->SetParent(this); } -void GuiButton::SetLabel( GuiText* txt, int n ) +void GuiButton::SetLabel(GuiText* txt, int n) { LOCK( this ); label[n] = txt; - if ( txt ) txt->SetParent( this ); + if (txt) txt->SetParent(this); } -void GuiButton::SetLabelOver( GuiText* txt, int n ) +void GuiButton::SetLabelOver(GuiText* txt, int n) { LOCK( this ); labelOver[n] = txt; - if ( txt ) txt->SetParent( this ); + if (txt) txt->SetParent(this); } -void GuiButton::SetLabelHold( GuiText* txt, int n ) +void GuiButton::SetLabelHold(GuiText* txt, int n) { LOCK( this ); labelHold[n] = txt; - if ( txt ) txt->SetParent( this ); + if (txt) txt->SetParent(this); } -void GuiButton::SetLabelClick( GuiText* txt, int n ) +void GuiButton::SetLabelClick(GuiText* txt, int n) { LOCK( this ); labelClick[n] = txt; - if ( txt ) txt->SetParent( this ); + if (txt) txt->SetParent(this); } -void GuiButton::SetSoundOver( GuiSound * snd ) +void GuiButton::SetSoundOver(GuiSound * snd) { LOCK( this ); soundOver = snd; } -void GuiButton::SetSoundHold( GuiSound * snd ) +void GuiButton::SetSoundHold(GuiSound * snd) { LOCK( this ); soundHold = snd; } -void GuiButton::SetSoundClick( GuiSound * 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 ) +void GuiButton::SetToolTip(GuiTooltip* tt, int x, int y, int h_align, int v_align) { LOCK( this ); - if ( tt ) + if (tt) { toolTip = tt; - toolTip->SetParent( this ); - toolTip->SetAlignment( h_align, v_align ); - toolTip->SetPosition( x, y ); + toolTip->SetParent(this); + toolTip->SetAlignment(h_align, v_align); + toolTip->SetPosition(x, y); } } @@ -268,9 +270,9 @@ 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 ) +void GuiButton::SetSkew(int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, int XX4, int YY4) { - if ( image ) + if (image) { image->xx1 = XX1; image->yy1 = YY1; @@ -283,39 +285,33 @@ void GuiButton::SetSkew( int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, i } } -void GuiButton::SetSkew( int *skew ) +void GuiButton::SetSkew(int *skew) { - if ( image ) - image->SetSkew( skew ); + if (image) image->SetSkew(skew); } - /** * Draw the button on screen */ void GuiButton::Draw() { LOCK( this ); - if ( !this->IsVisible() ) - return; + if (!this->IsVisible()) return; // draw image - if ( ( state == STATE_SELECTED || state == STATE_HELD ) && imageOver ) + if ((state == STATE_SELECTED || state == STATE_HELD) && imageOver) imageOver->Draw(); - else if ( image ) - image->Draw(); + else if (image) image->Draw(); // draw icon - if ( ( state == STATE_SELECTED || state == STATE_HELD ) && iconOver ) + if ((state == STATE_SELECTED || state == STATE_HELD) && iconOver) iconOver->Draw(); - else if ( icon ) - icon->Draw(); + else if (icon) icon->Draw(); // draw text - for ( int i = 0; i < 3; i++ ) + for (int i = 0; i < 3; i++) { - if ( ( state == STATE_SELECTED || state == STATE_HELD ) && labelOver[i] ) + if ((state == STATE_SELECTED || state == STATE_HELD) && labelOver[i]) labelOver[i]->Draw(); - else if ( label[i] ) - label[i]->Draw(); + else if (label[i]) label[i]->Draw(); } this->UpdateEffects(); @@ -323,20 +319,20 @@ void GuiButton::Draw() void GuiButton::DrawTooltip() { LOCK( this ); - if ( this->IsVisible() && state == STATE_SELECTED && toolTip ) + if (this->IsVisible() && state == STATE_SELECTED && toolTip) { - if ( time2 == 0 ) + if (time2 == 0) { - time( &time1 ); + time(&time1); time2 = time1; } - if ( time1 != 0 ) // timer läuft - time( &time1 ); + if (time1 != 0) // timer läuft + time(&time1); - if ( time1 == 0 || difftime( time1, time2 ) >= 2 ) + if (time1 == 0 || difftime(time1, time2) >= 2) { - if ( time1 != 0 ) // timer gerade abgelaufen - toolTip->SetEffect( EFFECT_FADE, 20 ); + if (time1 != 0) // timer gerade abgelaufen + toolTip->SetEffect(EFFECT_FADE, 20); time1 = 0; toolTip->Draw(); return; @@ -344,25 +340,23 @@ void GuiButton::DrawTooltip() } else { - if ( time2 != 0 && time1 == 0 ) // timer abgelaufen, gerade DESELECT - if ( toolTip ) toolTip->SetEffect( EFFECT_FADE, -20 ); + if (time2 != 0 && time1 == 0) // timer abgelaufen, gerade DESELECT + if (toolTip) toolTip->SetEffect(EFFECT_FADE, -20); time2 = 0; } - if ( toolTip && toolTip->GetEffect() ) - toolTip->Draw(); + if (toolTip && toolTip->GetEffect()) toolTip->Draw(); } -void GuiButton::ScrollIsOn( int f ) +void GuiButton::ScrollIsOn(int f) { LOCK( this ); scrollison = f; } -void GuiButton::Update( GuiTrigger * t ) +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 ) + if (!this->IsVisible() || state == STATE_CLICKED || state == STATE_DISABLED || !t) return; + else if (parentElement && parentElement->GetState() == STATE_DISABLED) return; #ifdef HW_RVL // cursor @@ -371,6 +365,7 @@ void GuiButton::Update( GuiTrigger * t ) 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 ) { @@ -378,10 +373,10 @@ void GuiButton::Update( GuiTrigger * t ) } if ( this->Rumble() && scrollison == 0 ) - rumbleRequest[t->chan] = 1; + rumbleRequest[t->chan] = 1; if ( soundOver && scrollison == 0 ) - soundOver->Play(); + soundOver->Play(); if ( effectsOver && !effects && scrollison == 0 ) { @@ -395,7 +390,7 @@ void GuiButton::Update( GuiTrigger * t ) else { if ( state == STATE_SELECTED && ( stateChan == t->chan || stateChan == -1 ) ) - this->ResetState(); + this->ResetState(); if ( effectTarget == effectTargetOver && effectAmount == effectAmountOver ) { @@ -408,10 +403,9 @@ void GuiButton::Update( GuiTrigger * t ) } #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 ) + if (effectTarget == effectTargetOver && effectAmount == effectAmountOver) { // initiate effects (in reverse) effects = effectsOver; @@ -419,16 +413,15 @@ void GuiButton::Update( GuiTrigger * t ) effectTarget = 100; } - #endif // button triggers - if ( this->IsClickable() && scrollison == 0 ) + if (this->IsClickable() && scrollison == 0) { s32 wm_btns, wm_btns_trig, cc_btns, cc_btns_trig; - for ( int i = 0; i < 6; i++ ) + for (int i = 0; i < 6; i++) { - if ( trigger[i] && ( trigger[i]->chan == -1 || trigger[i]->chan == t->chan ) ) + if (trigger[i] && (trigger[i]->chan == -1 || trigger[i]->chan == t->chan)) { // higher 16 bits only (wiimote) wm_btns = t->wpad.btns_d << 16; @@ -438,33 +431,26 @@ void GuiButton::Update( GuiTrigger * t ) cc_btns = t->wpad.btns_d >> 16; cc_btns_trig = trigger[i]->wpad.btns_d >> 16; - 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->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 (t->chan == stateChan || stateChan == -1) { - if ( state == STATE_SELECTED ) + if (state == STATE_SELECTED) { - this->SetState( STATE_CLICKED, t->chan ); + this->SetState(STATE_CLICKED, t->chan); - if ( soundClick ) - soundClick->Play(); + if (soundClick) soundClick->Play(); } - else if ( trigger[i]->type == TRIGGER_BUTTON_ONLY ) + else if (trigger[i]->type == TRIGGER_BUTTON_ONLY) { - this->SetState( STATE_CLICKED, t->chan ); - if ( soundClick ) - soundClick->Play(); + this->SetState(STATE_CLICKED, t->chan); + if (soundClick) soundClick->Play(); } - else if ( trigger[i]->type == TRIGGER_BUTTON_ONLY_IN_FOCUS && - parentElement->IsFocused() ) + else if (trigger[i]->type == TRIGGER_BUTTON_ONLY_IN_FOCUS && parentElement->IsFocused()) { - this->SetState( STATE_CLICKED, t->chan ); - if ( soundClick ) - soundClick->Play(); + this->SetState(STATE_CLICKED, t->chan); + if (soundClick) soundClick->Play(); } } } @@ -472,14 +458,14 @@ void GuiButton::Update( GuiTrigger * t ) } } - if ( this->IsHoldable() ) + if (this->IsHoldable()) { bool held = false; s32 wm_btns, wm_btns_h, wm_btns_trig, cc_btns, cc_btns_h, cc_btns_trig; - for ( int i = 0; i < 6; i++ ) + for (int i = 0; i < 6; i++) { - if ( trigger[i] && ( trigger[i]->chan == -1 || trigger[i]->chan == t->chan ) ) + if (trigger[i] && (trigger[i]->chan == -1 || trigger[i]->chan == t->chan)) { // higher 16 bits only (wiimote) wm_btns = t->wpad.btns_d << 16; @@ -491,40 +477,32 @@ void GuiButton::Update( GuiTrigger * t ) cc_btns_h = t->wpad.btns_h >> 16; cc_btns_trig = trigger[i]->wpad.btns_h >> 16; - 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 (((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 (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 (((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 (trigger[i]->type == TRIGGER_HELD) held = true; } - if ( !held && state == STATE_HELD && stateChan == t->chan ) + if (!held && state == STATE_HELD && stateChan == t->chan) { this->ResetState(); } - else if ( held && state == STATE_CLICKED && stateChan == t->chan ) + else if (held && state == STATE_CLICKED && stateChan == t->chan) { - this->SetState( STATE_HELD, 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 ab80c11f..2a1cabfb 100644 --- a/source/libwiigui/gui_customoptionbrowser.cpp +++ b/source/libwiigui/gui_customoptionbrowser.cpp @@ -15,108 +15,106 @@ #include - #define GAMESELECTSIZE 30 #define OPTION_LIST_PADDING PAGESIZE -customOptionList::customOptionList( int Size ) +customOptionList::customOptionList(int Size) { - name = value = NULL; + name = value = NULL; size = 0; - SetSize( Size == 0 ? PAGESIZE : Size ); - length = Size; + SetSize(Size == 0 ? PAGESIZE : Size); + length = Size; changed = false; } customOptionList::~customOptionList() { - for ( int i = 0; i < size; i++ ) + for (int i = 0; i < size; i++) { - free( name[i] ); - free( value[i] ); + free(name[i]); + free(value[i]); } - delete [] name; - delete [] value; + delete[] name; + delete[] value; } -void customOptionList::SetLength( int Length ) //set number of lines +void customOptionList::SetLength(int Length) //set number of lines { - if ( Length < 0 || Length == length ) return; + if (Length < 0 || Length == length) return; - if ( Length > size ) - SetSize( Length + OPTION_LIST_PADDING ); - if ( Length < length ) + if (Length > size) SetSize(Length + OPTION_LIST_PADDING); + if (Length < length) { - for ( int i = Length; i < length; i++ ) + for (int i = Length; i < length; i++) { - free( name[i] ); // clear unused + free(name[i]); // clear unused name[i] = NULL; - free( value[i] ); + free(value[i]); value[i] = NULL; } } - length = Length; + length = Length; changed = true; } -void customOptionList::SetSize( int Size ) //set number of lines +void customOptionList::SetSize(int Size) //set number of lines { - if ( Size < 0 || Size == size ) return; + if (Size < 0 || Size == size) return; - if ( Size > size ) + if (Size > size) { - char **newName = new char *[Size]; + char **newName = new char *[Size]; char **newValue = new char *[Size]; int i; - for ( i = 0; i < size; i++ ) + for (i = 0; i < size; i++) { - newName[i] = name[i]; // copy + newName[i] = name[i]; // copy newValue[i] = value[i]; } - for ( ; i < Size; i++ ) + for (; i < Size; i++) { - newName[i] = NULL; // fill rest with NULL + newName[i] = NULL; // fill rest with NULL newValue[i] = NULL; } - delete [] name; - name = newName; // set new - delete [] value; - value = newValue; - size = Size; + delete[] name; + name = newName; // set new + delete[] value; + value = newValue; + size = Size; } } -void customOptionList::SetName( int i, const char *format, ... ) +void customOptionList::SetName(int i, const char *format, ...) { - if ( i >= length ) SetLength( i + 1 ); + if (i >= length) SetLength(i + 1); - if ( i >= 0 && i < length ) + if (i >= 0 && i < length) { - if ( name[i] ) free( name[i] ); + if (name[i]) free(name[i]); name[i] = 0; va_list va; va_start( va, format ); - vasprintf( &name[i], format, va ); + vasprintf(&name[i], format, va); va_end( va ); changed = true; } //gprintf("customOptionList::SetName( %d, %s )\n", i, name[i] ); } -void customOptionList::SetValue( int i, const char *format, ... ) +void customOptionList::SetValue(int i, const char *format, ...) { - if ( i >= length ) SetLength( i + 1 ); + if (i >= length) SetLength(i + 1); - if ( i >= 0 && i < length ) + if (i >= 0 && i < length) { - char *tmp = 0; + char *tmp = 0; va_list va; va_start( va, format ); - vasprintf( &tmp, format, va ); + vasprintf(&tmp, format, va); va_end( va ); - if ( tmp ) + if (tmp) { - if ( value[i] && !strcmp( tmp, value[i] ) ) - free( tmp ); + if (value[i] && !strcmp(tmp, value[i])) + free(tmp); else { - free( value[i] ); + free(value[i]); value[i] = tmp; changed = true; } @@ -124,16 +122,16 @@ void customOptionList::SetValue( int i, const char *format, ... ) } //gprintf("customOptionList::SetValue( %d, %s )\n", i, value[i] ); } -void customOptionList::Clear( bool OnlyValue/*=false*/ ) +void customOptionList::Clear(bool OnlyValue/*=false*/) { - for ( int i = 0; i < size; i++ ) + for (int i = 0; i < size; i++) { - if ( !OnlyValue ) + if (!OnlyValue) { - free( name[i] ); + free(name[i]); name[i] = NULL; } - free( value[i] ); + free(value[i]); value[i] = NULL; } changed = true; @@ -142,7 +140,8 @@ void customOptionList::Clear( bool OnlyValue/*=false*/ ) /** * 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 ) +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; @@ -150,120 +149,120 @@ GuiCustomOptionBrowser::GuiCustomOptionBrowser( int w, int h, customOptionList * size = PAGESIZE; scrollbaron = scrollon; selectable = true; - listOffset = this->FindMenuItem( -1, 1 ); + 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 ); + 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 ), "%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]; + 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++ ) + 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 ), DOTTED ); + 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), DOTTED); - optionBg[i] = new GuiImage( bgOptionsEntry ); + optionBg[i] = new GuiImage(bgOptionsEntry); - optionVal[i] = new GuiText( ( char * ) NULL, 20, THEME.settingstext ); - optionVal[i]->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + optionVal[i] = new GuiText((char *) NULL, 20, THEME.settingstext); + optionVal[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - optionValOver[i] = new GuiText( ( char * ) NULL, 20, THEME.settingstext ); - optionValOver[i]->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + optionValOver[i] = new GuiText((char *) 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(); @@ -300,7 +299,7 @@ GuiCustomOptionBrowser::~GuiCustomOptionBrowser() delete trigHeldA; delete btnSoundClick; - for ( int i = 0; i < size; i++ ) + for (int i = 0; i < size; i++) { delete optionTxt[i]; delete optionVal[i]; @@ -308,36 +307,35 @@ GuiCustomOptionBrowser::~GuiCustomOptionBrowser() delete optionBg[i]; delete optionBtn[i]; } - delete [] optionIndex; - delete [] optionVal; - delete [] optionValOver; - delete [] optionBtn; - delete [] optionTxt; - delete [] optionBg; + delete[] optionIndex; + delete[] optionVal; + delete[] optionValOver; + delete[] optionBtn; + delete[] optionTxt; + delete[] optionBg; } -void GuiCustomOptionBrowser::SetFocus( int f ) +void GuiCustomOptionBrowser::SetFocus(int f) { LOCK( this ); focus = f; - for ( int i = 0; i < size; i++ ) + 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 ) + if (state != STATE_DISABLED) { state = STATE_DEFAULT; stateChan = -1; } - for ( int i = 0; i < size; i++ ) + for (int i = 0; i < size; i++) { optionBtn[i]->ResetState(); } @@ -346,11 +344,11 @@ void GuiCustomOptionBrowser::ResetState() int GuiCustomOptionBrowser::GetClickedOption() { int found = -1; - for ( int i = 0; i < size; i++ ) + for (int i = 0; i < size; i++) { - if ( optionBtn[i]->GetState() == STATE_CLICKED ) + if (optionBtn[i]->GetState() == STATE_CLICKED) { - optionBtn[i]->SetState( STATE_SELECTED ); + optionBtn[i]->SetState(STATE_SELECTED); found = optionIndex[i]; break; } @@ -361,9 +359,9 @@ int GuiCustomOptionBrowser::GetClickedOption() int GuiCustomOptionBrowser::GetSelectedOption() { int found = -1; - for ( int i = 0; i < size; i++ ) + for (int i = 0; i < size; i++) { - if ( optionBtn[i]->GetState() == STATE_SELECTED ) + if (optionBtn[i]->GetState() == STATE_SELECTED) { found = optionIndex[i]; break; @@ -372,20 +370,20 @@ int GuiCustomOptionBrowser::GetSelectedOption() return found; } -void GuiCustomOptionBrowser::SetClickable( bool enable ) +void GuiCustomOptionBrowser::SetClickable(bool enable) { - for ( int i = 0; i < size; i++ ) + for (int i = 0; i < size; i++) { - optionBtn[i]->SetClickable( enable ); + optionBtn[i]->SetClickable(enable); } } -void GuiCustomOptionBrowser::SetScrollbar( int enable ) +void GuiCustomOptionBrowser::SetScrollbar(int enable) { scrollbaron = enable; } -void GuiCustomOptionBrowser::SetOffset( int optionnumber ) +void GuiCustomOptionBrowser::SetOffset(int optionnumber) { listOffset = optionnumber; selectedItem = optionnumber; @@ -397,17 +395,15 @@ 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 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 ) + if (strlen(options->GetName(nextItem)) > 0) return nextItem; - else - return FindMenuItem( nextItem, direction ); + else return FindMenuItem(nextItem, direction); } /** @@ -416,25 +412,23 @@ int GuiCustomOptionBrowser::FindMenuItem( int currentItem, int direction ) void GuiCustomOptionBrowser::Draw() { LOCK( this ); - if ( !this->IsVisible() ) - return; + if (!this->IsVisible()) return; bgOptionsImg->Draw(); int next = listOffset; - for ( int i = 0; i < size; i++ ) + for (int i = 0; i < size; i++) { - if ( next >= 0 ) + if (next >= 0) { optionBtn[i]->Draw(); - next = this->FindMenuItem( next, 1 ); + next = this->FindMenuItem(next, 1); } - else - break; + else break; } - if ( scrollbaron == 1 ) + if (scrollbaron == 1) { scrollbarImg->Draw(); arrowUpBtn->Draw(); @@ -447,100 +441,95 @@ void GuiCustomOptionBrowser::Draw() void GuiCustomOptionBrowser::UpdateListEntries() { scrollbaron = options->GetLength() > size; - if ( listOffset < 0 ) listOffset = this->FindMenuItem( -1, 1 ); + if (listOffset < 0) listOffset = this->FindMenuItem(-1, 1); int next = listOffset; int maxNameWidth = 0; - for ( int i = 0; i < size; i++ ) + for (int i = 0; i < size; i++) { - if ( next >= 0 ) + if (next >= 0) { - if ( optionBtn[i]->GetState() == STATE_DISABLED ) + if (optionBtn[i]->GetState() == STATE_DISABLED) { - optionBtn[i]->SetVisible( true ); - optionBtn[i]->SetState( STATE_DEFAULT ); + 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 ); + next = this->FindMenuItem(next, 1); } else { - optionBtn[i]->SetVisible( false ); - optionBtn[i]->SetState( STATE_DISABLED ); + 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 (coL2 < (24 + maxNameWidth + 16)) coL2 = 24 + maxNameWidth + 16; + for (int i = 0; i < size; i++) { - if ( optionBtn[i]->GetState() != STATE_DISABLED ) + if (optionBtn[i]->GetState() != STATE_DISABLED) { - optionVal[i]->SetPosition( coL2, 0 ); - optionVal[i]->SetMaxWidth( bgOptionsImg->GetWidth() - ( coL2 + 24 ), DOTTED ); + optionVal[i]->SetPosition(coL2, 0); + optionVal[i]->SetMaxWidth(bgOptionsImg->GetWidth() - (coL2 + 24), DOTTED); - optionValOver[i]->SetPosition( coL2, 0 ); - optionValOver[i]->SetMaxWidth( bgOptionsImg->GetWidth() - ( coL2 + 24 ), SCROLL_HORIZONTAL ); + optionValOver[i]->SetPosition(coL2, 0); + optionValOver[i]->SetMaxWidth(bgOptionsImg->GetWidth() - (coL2 + 24), SCROLL_HORIZONTAL); } } } -void GuiCustomOptionBrowser::Update( GuiTrigger * t ) +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() ) + if (options->IsChanged()) { coL2 = 0; UpdateListEntries(); } int old_listOffset = listOffset; - if ( scrollbaron == 1 ) + 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 ); + arrowUpBtn->Update(t); + arrowDownBtn->Update(t); + scrollbarBoxBtn->Update(t); } 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 < size; i++ ) + for (int i = 0; i < size; i++) { - if ( next >= 0 ) - next = this->FindMenuItem( next, 1 ); + if (next >= 0) next = this->FindMenuItem(next, 1); - if ( focus ) + if (focus) { - if ( i != selectedItem && optionBtn[i]->GetState() == STATE_SELECTED ) + if (i != selectedItem && optionBtn[i]->GetState() == STATE_SELECTED) { optionBtn[i]->ResetState(); } - else if ( i == selectedItem && optionBtn[i]->GetState() == STATE_DEFAULT ) + else if (i == selectedItem && optionBtn[i]->GetState() == STATE_DEFAULT) { - optionBtn[selectedItem]->SetState( STATE_SELECTED ); + optionBtn[selectedItem]->SetState(STATE_SELECTED); } } + optionBtn[i]->Update(t); - optionBtn[i]->Update( t ); - - if ( optionBtn[i]->GetState() == STATE_SELECTED ) + if (optionBtn[i]->GetState() == STATE_SELECTED) { selectedItem = i; } @@ -548,35 +537,34 @@ void GuiCustomOptionBrowser::Update( GuiTrigger * t ) } // pad/joystick navigation - if ( !focus ) - return; // skip navigation + if (!focus) return; // skip navigation - if ( t->Down() ) + if (t->Down()) { - next = this->FindMenuItem( optionIndex[selectedItem], 1 ); + next = this->FindMenuItem(optionIndex[selectedItem], 1); - if ( next >= 0 ) + if (next >= 0) { - if ( selectedItem == size - 1 ) + if (selectedItem == size - 1) { // move list down by 1 - listOffset = this->FindMenuItem( listOffset, 1 ); + listOffset = this->FindMenuItem(listOffset, 1); } - else if ( optionBtn[selectedItem+1]->IsVisible() ) + else if (optionBtn[selectedItem + 1]->IsVisible()) { optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + optionBtn[selectedItem + 1]->SetState(STATE_SELECTED, t->chan); selectedItem++; } } } - else if ( t->Up() ) + else if (t->Up()) { - prev = this->FindMenuItem( optionIndex[selectedItem], -1 ); + prev = this->FindMenuItem(optionIndex[selectedItem], -1); - if ( prev >= 0 ) + if (prev >= 0) { - if ( selectedItem == 0 ) + if (selectedItem == 0) { // move list up by 1 listOffset = prev; @@ -584,49 +572,47 @@ void GuiCustomOptionBrowser::Update( GuiTrigger * t ) else { optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + optionBtn[selectedItem - 1]->SetState(STATE_SELECTED, t->chan); selectedItem--; } } } - if ( scrollbaron == 1 ) + if (scrollbaron == 1) { - if ( arrowDownBtn->GetState() == STATE_CLICKED || - arrowDownBtn->GetState() == STATE_HELD ) + 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 (next >= 0) { - if ( selectedItem == size - 1 ) + if (selectedItem == size - 1) { // move list down by 1 - listOffset = this->FindMenuItem( listOffset, 1 ); + listOffset = this->FindMenuItem(listOffset, 1); } - else if ( optionBtn[selectedItem+1]->IsVisible() ) + else if (optionBtn[selectedItem + 1]->IsVisible()) { optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + optionBtn[selectedItem + 1]->SetState(STATE_SELECTED, t->chan); selectedItem++; } scrollbarBoxBtn->Draw(); - usleep( 35000 ); + usleep(35000); } - if ( buttonshold != WPAD_BUTTON_A ) + if (buttonshold != WPAD_BUTTON_A) { arrowDownBtn->ResetState(); } } - else if ( arrowUpBtn->GetState() == STATE_CLICKED || - arrowUpBtn->GetState() == STATE_HELD ) + else if (arrowUpBtn->GetState() == STATE_CLICKED || arrowUpBtn->GetState() == STATE_HELD) { - prev = this->FindMenuItem( optionIndex[selectedItem], -1 ); + prev = this->FindMenuItem(optionIndex[selectedItem], -1); - if ( prev >= 0 ) + if (prev >= 0) { - if ( selectedItem == 0 ) + if (selectedItem == 0) { // move list up by 1 listOffset = prev; @@ -634,68 +620,62 @@ void GuiCustomOptionBrowser::Update( GuiTrigger * t ) else { optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + optionBtn[selectedItem - 1]->SetState(STATE_SELECTED, t->chan); selectedItem--; } scrollbarBoxBtn->Draw(); - usleep( 35000 ); + usleep(35000); } - if ( buttonshold != WPAD_BUTTON_A ) + if (buttonshold != WPAD_BUTTON_A) { arrowUpBtn->ResetState(); } } - if ( scrollbarBoxBtn->GetState() == STATE_HELD && - scrollbarBoxBtn->GetStateChan() == t->chan && - t->wpad.ir.valid && options->GetLength() > size ) + if (scrollbarBoxBtn->GetState() == STATE_HELD && scrollbarBoxBtn->GetStateChan() == t->chan && t->wpad.ir.valid + && options->GetLength() > size) { - scrollbarBoxBtn->SetPosition( width / 2 - 18 + 7, 0 ); + scrollbarBoxBtn->SetPosition(width / 2 - 18 + 7, 0); int position = t->wpad.ir.y - 50 - scrollbarBoxBtn->GetTop(); - listOffset = ( position * lang ) / 180 - selectedItem; + listOffset = (position * lang) / 180 - selectedItem; - if ( listOffset <= 0 ) + if (listOffset <= 0) { listOffset = 0; selectedItem = 0; } - else if ( listOffset + size >= lang ) + else if (listOffset + size >= lang) { listOffset = lang - size; selectedItem = size - 1; } } - int positionbar = 237 * ( listOffset + selectedItem ) / lang; + 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 (t->Right()) { - if ( listOffset < lang && lang > size ) + if (listOffset < lang && lang > size) { listOffset = listOffset + size; - if ( listOffset + size >= lang ) - listOffset = lang - size; + if (listOffset + size >= lang) listOffset = lang - size; } } - else if ( t->Left() ) + else if (t->Left()) { - if ( listOffset > 0 ) + if (listOffset > 0) { listOffset = listOffset - size; - if ( listOffset < 0 ) - listOffset = 0; + 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 8bab4d77..1c4bf32a 100644 --- a/source/libwiigui/gui_customoptionbrowser.h +++ b/source/libwiigui/gui_customoptionbrowser.h @@ -3,30 +3,36 @@ class customOptionList { public: - customOptionList( int Size ); + 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 ) + 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] ) + if (i >= 0 && i < length && name[i]) return name[i]; - else - return ""; + else return ""; } - void SetValue( int i, const char *format, ... ) __attribute__( ( format ( printf, 3, 4 ) ) ); - const char *GetValue( int i ) + void SetValue(int i, const char *format, ...) __attribute__( ( format ( printf, 3, 4 ) ) ); + const char *GetValue(int i) { - if ( i >= 0 && i < length && value[i] ) + if (i >= 0 && i < length && value[i]) return value[i]; - else - return ""; + else return ""; + } + void Clear(bool OnlyValue = false); + int GetLength() + { + return length; + } + bool IsChanged() + { + bool ret = changed; + changed = false; + return ret; } - void Clear( bool OnlyValue = false ); - int GetLength() { return length; } - bool IsChanged() { bool ret = changed; changed = false; return ret;} private: - void SetSize( int Size ); + void SetSize(int Size); int size; char ** name; char ** value; @@ -35,21 +41,22 @@ class customOptionList }; //!Display a list of menu options -class GuiCustomOptionBrowser : public GuiElement +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 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 FindMenuItem(int c, int d); int GetClickedOption(); int GetSelectedOption(); - void SetClickable( bool enable ); - void SetScrollbar( int enable ); - void SetOffset( int optionnumber ); + void SetClickable(bool enable); + void SetScrollbar(int enable); + void SetOffset(int optionnumber); void ResetState(); - void SetFocus( int f ); + void SetFocus(int f); void Draw(); - void Update( GuiTrigger * t ); + void Update(GuiTrigger * t); protected: void UpdateListEntries(); int selectedItem; diff --git a/source/libwiigui/gui_diskcover.cpp b/source/libwiigui/gui_diskcover.cpp index dbc916a4..bf11bd18 100644 --- a/source/libwiigui/gui_diskcover.cpp +++ b/source/libwiigui/gui_diskcover.cpp @@ -1,19 +1,19 @@ #include "gui_diskcover.h" - GuiDiskCover::GuiDiskCover() { deg_beta = 0.0; eff_step = 0; -// spin_angle = 0; + // spin_angle = 0; spin_speedup = 1.0; spin_up = false; } -GuiDiskCover::GuiDiskCover( GuiImageData *Disk ) : GuiImage( Disk ) +GuiDiskCover::GuiDiskCover(GuiImageData *Disk) : + GuiImage(Disk) { deg_beta = 0.0; eff_step = 0; -// spin_angle = 0; + // spin_angle = 0; spin_speedup = 1.0; spin_up = false; } @@ -21,13 +21,13 @@ GuiDiskCover::~GuiDiskCover() { } -void GuiDiskCover::SetBeta( f32 beta ) +void GuiDiskCover::SetBeta(f32 beta) { deg_beta = beta; } -void GuiDiskCover::SetBetaRotateEffect( f32 beta, u16 step ) +void GuiDiskCover::SetBetaRotateEffect(f32 beta, u16 step) { - eff_beta = beta / ( f32 )step; + eff_beta = beta / (f32) step; eff_step = step; } bool GuiDiskCover::GetBetaRotateEffect() @@ -35,43 +35,44 @@ bool GuiDiskCover::GetBetaRotateEffect() return eff_step != 0; } -void GuiDiskCover::SetSpin( bool 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 ); -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 ); +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); +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); void GuiDiskCover::Draw() { LOCK( this ); - if ( !image || !this->IsVisible() ) - return; + 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_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); - if ( eff_step ) + if (eff_step) { deg_beta += eff_beta; eff_step--; } GuiImage::imageangle += spin_speedup; - while ( GuiImage::imageangle >= 360.0 ) GuiImage::imageangle -= 360.0; + while (GuiImage::imageangle >= 360.0) + GuiImage::imageangle -= 360.0; - if ( spin_up ) + if (spin_up) { - if ( spin_speedup < 11 ) // speed up - spin_speedup += 0.20; + if (spin_speedup < 11) // speed up + spin_speedup += 0.20; } else { - if ( spin_speedup > 1 ) - spin_speedup -= 0.05; //slow down + 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 426007e4..5f91ac03 100644 --- a/source/libwiigui/gui_diskcover.h +++ b/source/libwiigui/gui_diskcover.h @@ -3,40 +3,26 @@ #include "gui.h" - -class GuiDiskCover : public GuiImage +class GuiDiskCover: public GuiImage { public: GuiDiskCover(); - GuiDiskCover( GuiImageData * img ); + GuiDiskCover(GuiImageData * img); ~GuiDiskCover(); - void SetBeta( f32 beta ); - void SetBetaRotateEffect( f32 beta, u16 Step ); + void SetBeta(f32 beta); + void SetBetaRotateEffect(f32 beta, u16 Step); bool GetBetaRotateEffect(); - void SetSpin( bool Up ); + void SetSpin(bool Up); void Draw(); private: f32 deg_beta; f32 eff_beta; u16 eff_step; -// f32 spin_angle; + // f32 spin_angle; f32 spin_speedup; bool spin_up; }; - - - - - - - - - - - - - #endif /* _GUIDISCCOVER_H_ */ diff --git a/source/libwiigui/gui_element.cpp b/source/libwiigui/gui_element.cpp index 0056409d..f91337fb 100644 --- a/source/libwiigui/gui_element.cpp +++ b/source/libwiigui/gui_element.cpp @@ -66,11 +66,11 @@ GuiElement::GuiElement() // 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(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; } @@ -79,10 +79,10 @@ GuiElement::GuiElement() */ GuiElement::~GuiElement() { -// LWP_MutexDestroy(mutex); + // LWP_MutexDestroy(mutex); } -void GuiElement::SetParent( GuiElement * e ) +void GuiElement::SetParent(GuiElement * e) { LOCK( this ); parentElement = e; @@ -103,22 +103,21 @@ int GuiElement::GetLeft() int pWidth = 0; int pLeft = 0; - if ( parentElement ) + 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 ) + switch (alignmentHor) { case ALIGN_LEFT: x = pLeft; break; case ALIGN_CENTRE: - x = pLeft + ( pWidth / 2 ) - ( width / 2 ); + x = pLeft + (pWidth / 2) - (width / 2); break; case ALIGN_RIGHT: x = pLeft + pWidth - width; @@ -138,23 +137,21 @@ int GuiElement::GetTop() int pHeight = 0; int pTop = 0; - if ( parentElement ) + 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 ) + switch (alignmentVert) { case ALIGN_TOP: y = pTop; break; case ALIGN_MIDDLE: - y = pTop + ( pHeight / 2 ) - ( height / 2 ); + y = pTop + (pHeight / 2) - (height / 2); break; case ALIGN_BOTTOM: y = pTop + pHeight - height; @@ -163,7 +160,7 @@ int GuiElement::GetTop() return y + yoffset; } -void GuiElement::SetMinX( int x ) +void GuiElement::SetMinX(int x) { LOCK( this ); xmin = x; @@ -174,7 +171,7 @@ int GuiElement::GetMinX() return xmin; } -void GuiElement::SetMaxX( int x ) +void GuiElement::SetMaxX(int x) { LOCK( this ); xmax = x; @@ -185,7 +182,7 @@ int GuiElement::GetMaxX() return xmax; } -void GuiElement::SetMinY( int y ) +void GuiElement::SetMinY(int y) { LOCK( this ); ymin = y; @@ -196,7 +193,7 @@ int GuiElement::GetMinY() return ymin; } -void GuiElement::SetMaxY( int y ) +void GuiElement::SetMaxY(int y) { LOCK( this ); ymax = y; @@ -234,7 +231,7 @@ int GuiElement::GetHeight() * @see SetWidth() * @see SetHeight() */ -void GuiElement::SetSize( int w, int h ) +void GuiElement::SetSize(int w, int h) { LOCK( this ); @@ -257,13 +254,13 @@ bool GuiElement::IsVisible() * @param[in] Visible Set to true to show GuiElement. * @see IsVisible() */ -void GuiElement::SetVisible( bool v ) +void GuiElement::SetVisible(bool v) { LOCK( this ); visible = v; } -void GuiElement::SetAlpha( int a ) +void GuiElement::SetAlpha(int a) { LOCK( this ); alpha = a; @@ -273,13 +270,11 @@ int GuiElement::GetAlpha() { int a; - if ( alphaDyn >= 0 ) + if (alphaDyn >= 0) a = alphaDyn; - else - a = alpha; + else a = alpha; - if ( parentElement ) - a *= parentElement->GetAlpha() / 255.0; + if (parentElement) a *= parentElement->GetAlpha() / 255.0; return a; } @@ -288,16 +283,14 @@ 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 ) +void GuiElement::SetScale(float s) { LOCK( this ); scale = s; @@ -307,8 +300,7 @@ float GuiElement::GetScale() { float s = scale * scaleDyn; - if ( parentElement ) - s *= parentElement->GetScale(); + if (parentElement) s *= parentElement->GetScale(); return s; } @@ -323,7 +315,7 @@ int GuiElement::GetStateChan() return stateChan; } -void GuiElement::SetState( int s, int c ) +void GuiElement::SetState(int s, int c) { LOCK( this ); state = s; @@ -333,26 +325,26 @@ void GuiElement::SetState( int s, int c ) void GuiElement::ResetState() { LOCK( this ); - if ( state != STATE_DISABLED ) + if (state != STATE_DISABLED) { state = STATE_DEFAULT; stateChan = -1; } } -void GuiElement::SetClickable( bool c ) +void GuiElement::SetClickable(bool c) { LOCK( this ); clickable = c; } -void GuiElement::SetSelectable( bool s ) +void GuiElement::SetSelectable(bool s) { LOCK( this ); selectable = s; } -void GuiElement::SetHoldable( bool d ) +void GuiElement::SetHoldable(bool d) { LOCK( this ); holdable = d; @@ -360,31 +352,26 @@ void GuiElement::SetHoldable( bool d ) bool GuiElement::IsSelectable() { - if ( state == STATE_DISABLED || state == STATE_CLICKED ) + if (state == STATE_DISABLED || state == STATE_CLICKED) return false; - else - return selectable; + else return selectable; } bool GuiElement::IsClickable() { - if ( state == STATE_DISABLED || - state == STATE_CLICKED || - state == STATE_HELD ) + if (state == STATE_DISABLED || state == STATE_CLICKED || state == STATE_HELD) return false; - else - return clickable; + else return clickable; } bool GuiElement::IsHoldable() { - if ( state == STATE_DISABLED ) + if (state == STATE_DISABLED) return false; - else - return holdable; + else return holdable; } -void GuiElement::SetFocus( int f ) +void GuiElement::SetFocus(int f) { LOCK( this ); focus = f; @@ -395,32 +382,32 @@ int GuiElement::IsFocused() return focus; } -void GuiElement::SetTrigger( GuiTrigger * t ) +void GuiElement::SetTrigger(GuiTrigger * t) { LOCK( this ); - if ( !trigger[0] ) + if (!trigger[0]) trigger[0] = t; - else if ( !trigger[1] ) + else if (!trigger[1]) trigger[1] = t; - else if ( !trigger[2] ) + else if (!trigger[2]) trigger[2] = t; - else if ( !trigger[3] ) + else if (!trigger[3]) trigger[3] = t; - else if ( !trigger[4] ) + else if (!trigger[4]) trigger[4] = t; - else if ( !trigger[5] ) + else if (!trigger[5]) trigger[5] = t; else // both were assigned, so we'll just overwrite the first one - trigger[0] = t; + trigger[0] = t; } -void GuiElement::SetTrigger( u8 i, GuiTrigger * t ) +void GuiElement::SetTrigger(u8 i, GuiTrigger * t) { LOCK( this ); trigger[i] = t; } -void GuiElement::RemoveTrigger( u8 i ) +void GuiElement::RemoveTrigger(u8 i) { LOCK( this ); trigger[i] = NULL; @@ -431,7 +418,7 @@ bool GuiElement::Rumble() return rumble; } -void GuiElement::SetRumble( bool r ) +void GuiElement::SetRumble(bool r) { LOCK( this ); rumble = r; @@ -455,51 +442,51 @@ float GuiElement::GetFrequency() return frequency; } -void GuiElement::SetEffect( int eff, int speed, f32 circles, int r, f32 startdegree, f32 anglespeedset, int center_x, int center_y ) +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 + 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 + temp_xoffset = center_x; //!position of center in x + temp_yoffset = center_y; //!position of center in y } effects |= eff; - effectAmount = speed; //!Circlespeed + effectAmount = speed; //!Circlespeed } -void GuiElement::SetEffect( int eff, int amount, int target ) +void GuiElement::SetEffect(int eff, int amount, int target) { LOCK( this ); - if ( eff & EFFECT_SLIDE_IN ) + if (eff & EFFECT_SLIDE_IN) { // these calculations overcompensate a little - if ( eff & EFFECT_SLIDE_TOP ) + if (eff & EFFECT_SLIDE_TOP) yoffsetDyn = -screenheight; - else if ( eff & EFFECT_SLIDE_LEFT ) + else if (eff & EFFECT_SLIDE_LEFT) xoffsetDyn = -screenwidth; - else if ( eff & EFFECT_SLIDE_BOTTOM ) + else if (eff & EFFECT_SLIDE_BOTTOM) yoffsetDyn = screenheight; - else if ( eff & EFFECT_SLIDE_RIGHT ) - xoffsetDyn = screenwidth; + else if (eff & EFFECT_SLIDE_RIGHT) xoffsetDyn = screenwidth; } - if ( eff & EFFECT_FADE && amount > 0 ) + if (eff & EFFECT_FADE && amount > 0) { alphaDyn = 0; } - else if ( eff & EFFECT_FADE && amount < 0 ) + else if (eff & EFFECT_FADE && amount < 0) { alphaDyn = alpha; } - else if ( eff & EFFECT_ROCK_VERTICLE ) + else if (eff & EFFECT_ROCK_VERTICLE) { changervar = 0; yoffsetDyn = 0; @@ -511,7 +498,7 @@ void GuiElement::SetEffect( int eff, int amount, int target ) effectTarget = target; } -void GuiElement::SetEffectOnOver( int eff, int amount, int target ) +void GuiElement::SetEffectOnOver(int eff, int amount, int target) { LOCK( this ); effectsOver |= eff; @@ -521,7 +508,7 @@ void GuiElement::SetEffectOnOver( int eff, int amount, int target ) void GuiElement::SetEffectGrow() { - SetEffectOnOver( EFFECT_SCALE, 4, 110 ); + SetEffectOnOver(EFFECT_SCALE, 4, 110); } void GuiElement::StopEffect() @@ -545,45 +532,45 @@ void GuiElement::UpdateEffects() { LOCK( this ); - if ( effects & ( EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND ) ) + if (effects & (EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND)) { - if ( effects & EFFECT_SLIDE_IN ) + if (effects & EFFECT_SLIDE_IN) { - if ( effects & EFFECT_SLIDE_LEFT ) + if (effects & EFFECT_SLIDE_LEFT) { xoffsetDyn += effectAmount; - if ( xoffsetDyn >= 0 ) + if (xoffsetDyn >= 0) { xoffsetDyn = 0; effects = 0; } } - else if ( effects & EFFECT_SLIDE_RIGHT ) + else if (effects & EFFECT_SLIDE_RIGHT) { xoffsetDyn -= effectAmount; - if ( xoffsetDyn <= 0 ) + if (xoffsetDyn <= 0) { xoffsetDyn = 0; effects = 0; } } - else if ( effects & EFFECT_SLIDE_TOP ) + else if (effects & EFFECT_SLIDE_TOP) { yoffsetDyn += effectAmount; - if ( yoffsetDyn >= 0 ) + if (yoffsetDyn >= 0) { yoffsetDyn = 0; effects = 0; } } - else if ( effects & EFFECT_SLIDE_BOTTOM ) + else if (effects & EFFECT_SLIDE_BOTTOM) { yoffsetDyn -= effectAmount; - if ( yoffsetDyn <= 0 ) + if (yoffsetDyn <= 0) { yoffsetDyn = 0; effects = 0; @@ -592,55 +579,51 @@ void GuiElement::UpdateEffects() } else { - if ( effects & EFFECT_SLIDE_LEFT ) + if (effects & EFFECT_SLIDE_LEFT) { xoffsetDyn -= effectAmount; - if ( xoffsetDyn <= -screenwidth ) - effects = 0; // shut off effect + if (xoffsetDyn <= -screenwidth) effects = 0; // shut off effect } - else if ( effects & EFFECT_SLIDE_RIGHT ) + else if (effects & EFFECT_SLIDE_RIGHT) { xoffsetDyn += effectAmount; - if ( xoffsetDyn >= screenwidth ) - effects = 0; // shut off effect + if (xoffsetDyn >= screenwidth) effects = 0; // shut off effect } - else if ( effects & EFFECT_SLIDE_TOP ) + else if (effects & EFFECT_SLIDE_TOP) { yoffsetDyn -= effectAmount; - if ( yoffsetDyn <= -screenheight ) - effects = 0; // shut off effect + if (yoffsetDyn <= -screenheight) effects = 0; // shut off effect } - else if ( effects & EFFECT_SLIDE_BOTTOM ) + else if (effects & EFFECT_SLIDE_BOTTOM) { yoffsetDyn += effectAmount; - if ( yoffsetDyn >= screenheight ) - effects = 0; // shut off effect + if (yoffsetDyn >= screenheight) effects = 0; // shut off effect } } } - if ( effects & EFFECT_GOROUND ) + if (effects & EFFECT_GOROUND) { //!< check out gui.h for info xoffset = temp_xoffset; yoffset = temp_yoffset; - if ( fabs( frequency ) < circleamount ) + 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; + 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 ) ); + 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; @@ -648,92 +631,91 @@ void GuiElement::UpdateEffects() } } - 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 ); + 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 ); + yoffsetDynFloat -= (effectAmount * 0.01); } - else if ( yoffsetDynFloat < -10.0 ) + else if (yoffsetDynFloat < -10.0) { changervar = 0; } - yoffsetDyn = ( int )( yoffsetDynFloat ); + yoffsetDyn = (int) (yoffsetDynFloat); } - if ( effects & EFFECT_FADE ) + if (effects & EFFECT_FADE) { alphaDyn += effectAmount; - if ( effectAmount < 0 && alphaDyn <= 0 ) + if (effectAmount < 0 && alphaDyn <= 0) { alphaDyn = 0; effects = 0; // shut off effect } - else if ( effectAmount > 0 && alphaDyn >= alpha ) + else if (effectAmount > 0 && alphaDyn >= alpha) { alphaDyn = alpha; effects = 0; // shut off effect } } - if ( effects & EFFECT_SCALE ) + if (effects & EFFECT_SCALE) { scaleDyn += effectAmount / 100.0; - if ( ( effectAmount < 0 && scaleDyn <= effectTarget / 100.0 ) - || ( effectAmount > 0 && scaleDyn >= effectTarget / 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 ) + 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 ); + 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 ); + 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 ) +void GuiElement::Update(GuiTrigger * t) { LOCK( this ); - if ( updateCB ) - updateCB( this ); + if (updateCB) updateCB(this); } -void GuiElement::SetUpdateCallback( UpdateCallback u ) +void GuiElement::SetUpdateCallback(UpdateCallback u) { LOCK( this ); updateCB = u; } -void GuiElement::SetPosition( int xoff, int yoff, int zoff ) +void GuiElement::SetPosition(int xoff, int yoff, int zoff) { LOCK( this ); xoffset = xoff; @@ -741,7 +723,7 @@ void GuiElement::SetPosition( int xoff, int yoff, int zoff ) zoffset = zoff; } -void GuiElement::SetAlignment( int hor, int vert ) +void GuiElement::SetAlignment(int hor, int vert) { LOCK( this ); alignmentHor = hor; @@ -772,65 +754,63 @@ void GuiElement::DrawTooltip() * @param[in] x X position in pixel. * @param[in] y Y position in pixel. */ -bool GuiElement::IsInside( int x, int y ) +bool GuiElement::IsInside(int x, int y) { - if ( x > this->GetLeft() && x < ( this->GetLeft() + width ) - && y > this->GetTop() && y < ( this->GetTop() + height ) ) - return true; + if (x > this->GetLeft() && x < (this->GetLeft() + width) && y > this->GetTop() && y < (this->GetTop() + height)) return true; return false; } void GuiElement::Lock() { -// LWP_MutexLock(mutex); - for ( ;; ) // loop while element is locked by self + // LWP_MutexLock(mutex); + for (;;) // loop while element is locked by self { - LWP_MutexLock( _lock_mutex ); + LWP_MutexLock(_lock_mutex); - if ( _lock_thread == LWP_THREAD_NULL ) // element is not locked + 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 ); + _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 + else if (_lock_thread == LWP_GetSelf()) // thread is locked by my self { - _lock_count++; // inc count of locks; - LWP_MutexUnlock( _lock_mutex ); + _lock_count++; // inc count of locks; + LWP_MutexUnlock(_lock_mutex); return; } - else // otherwise the element is locked by an other thread + 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 + 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() { -// LWP_MutexUnlock(mutex); - LWP_MutexLock( _lock_mutex ); + // 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_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; + 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 + _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 + LWP_CloseQueue(_lock_queue); // close the queue and wake all waited threads _lock_queue = LWP_TQUEUE_NULL; } } } - LWP_MutexUnlock( _lock_mutex ); + LWP_MutexUnlock(_lock_mutex); } - -SimpleLock::SimpleLock( GuiElement *e ) : element( e ) +SimpleLock::SimpleLock(GuiElement *e) : + element(e) { element->Lock(); } diff --git a/source/libwiigui/gui_filebrowser.cpp b/source/libwiigui/gui_filebrowser.cpp index e8178106..1a226729 100644 --- a/source/libwiigui/gui_filebrowser.cpp +++ b/source/libwiigui/gui_filebrowser.cpp @@ -15,7 +15,7 @@ /** * Constructor for the GuiFileBrowser class. */ -GuiFileBrowser::GuiFileBrowser( int w, int h ) +GuiFileBrowser::GuiFileBrowser(int w, int h) { width = w; height = h; @@ -26,116 +26,119 @@ GuiFileBrowser::GuiFileBrowser( int w, int h ) focus = 0; // allow focus trigA = new GuiTrigger; - trigA->SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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->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", Settings.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.png", Settings.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", Settings.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 ); -// 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), "%sbg_browser_selection.png", Settings.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); + // 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", Settings.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", Settings.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", Settings.theme_path ); - arrowDown = new GuiImageData( imgPath, scrollbar_arrowdown_png ); - arrowDownImg = new GuiImage( arrowDown ); - snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_arrowup.png", Settings.theme_path ); - arrowUp = new GuiImageData( imgPath, scrollbar_arrowup_png ); - arrowUpImg = new GuiImage( arrowUp ); - snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_box.png", Settings.theme_path ); - scrollbarBox = new GuiImageData( imgPath, scrollbar_box_png ); - scrollbarBoxImg = new GuiImage( scrollbarBox ); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowdown.png", Settings.theme_path); + arrowDown = new GuiImageData(imgPath, scrollbar_arrowdown_png); + arrowDownImg = new GuiImage(arrowDown); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", Settings.theme_path); + arrowUp = new GuiImageData(imgPath, scrollbar_arrowup_png); + arrowUpImg = new GuiImage(arrowUp); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_box.png", Settings.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; i < FILEBROWSERSIZE; i++ ) + for (int i = 0; i < FILEBROWSERSIZE; i++) { - fileListText[i] = new GuiText( ( char * ) NULL, 20, ( GXColor ) {0, 0, 0, 0xff} ); - fileListText[i]->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - fileListText[i]->SetPosition( 5, 0 ); - fileListText[i]->SetMaxWidth( bgFileSelectionImg->GetWidth() - ( arrowDownImg->GetWidth() + 20 ), DOTTED ); + fileListText[i] = new GuiText((char *) NULL, 20, ( GXColor ) + { 0, 0, 0, 0xff}); + fileListText[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + fileListText[i]->SetPosition(5, 0); + fileListText[i]->SetMaxWidth(bgFileSelectionImg->GetWidth() - (arrowDownImg->GetWidth() + 20), DOTTED); - fileListTextOver[i] = new GuiText( ( char * ) 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 ), SCROLL_HORIZONTAL ); + fileListTextOver[i] = new GuiText((char *) 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), + SCROLL_HORIZONTAL); - fileListBg[i] = new GuiImage( bgFileSelectionEntry ); + fileListBg[i] = new GuiImage(bgFileSelectionEntry); //fileListArchives[i] = new GuiImage(fileArchives); //fileListDefault[i] = new GuiImage(fileDefault); - fileListFolder[i] = new GuiImage( fileFolder ); + 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 ); + 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); } } @@ -174,7 +177,7 @@ GuiFileBrowser::~GuiFileBrowser() delete trigHeldA; delete trigA; - for ( int i = 0; i < FILEBROWSERSIZE; i++ ) + for (int i = 0; i < FILEBROWSERSIZE; i++) { delete fileListText[i]; delete fileListTextOver[i]; @@ -191,19 +194,18 @@ GuiFileBrowser::~GuiFileBrowser() } } -void GuiFileBrowser::SetFocus( int f ) +void GuiFileBrowser::SetFocus(int f) { LOCK( this ); focus = f; - for ( int i = 0; i < FILEBROWSERSIZE; i++ ) + for (int i = 0; i < FILEBROWSERSIZE; i++) fileList[i]->ResetState(); - if ( f == 1 ) - fileList[selectedItem]->SetState( STATE_SELECTED ); + if (f == 1) fileList[selectedItem]->SetState(STATE_SELECTED); } -void GuiFileBrowser::DisableTriggerUpdate( bool set ) +void GuiFileBrowser::DisableTriggerUpdate(bool set) { LOCK( this ); triggerdisabled = set; @@ -216,7 +218,7 @@ void GuiFileBrowser::ResetState() stateChan = -1; selectedItem = 0; - for ( int i = 0; i < FILEBROWSERSIZE; i++ ) + for (int i = 0; i < FILEBROWSERSIZE; i++) { fileList[i]->ResetState(); } @@ -234,12 +236,11 @@ void GuiFileBrowser::TriggerUpdate() void GuiFileBrowser::Draw() { LOCK( this ); - if ( !this->IsVisible() ) - return; + if (!this->IsVisible()) return; bgFileSelectionImg->Draw(); - for ( int i = 0; i < FILEBROWSERSIZE; i++ ) + for (int i = 0; i < FILEBROWSERSIZE; i++) { fileList[i]->Draw(); } @@ -252,234 +253,221 @@ void GuiFileBrowser::Draw() this->UpdateEffects(); } -void GuiFileBrowser::Update( GuiTrigger * t ) +void GuiFileBrowser::Update(GuiTrigger * t) { LOCK( this ); - if ( state == STATE_DISABLED || !t || triggerdisabled ) - return; + if (state == STATE_DISABLED || !t || triggerdisabled) return; 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 - ) + if (scrollbarBoxBtn->GetState() == STATE_HELD && scrollbarBoxBtn->GetStateChan() == t->chan && t->wpad.ir.valid + && browser->browserList.size() > FILEBROWSERSIZE) { - scrollbarBoxBtn->SetPosition( 20, -10 ); + scrollbarBoxBtn->SetPosition(20, -10); positionWiimote = t->wpad.ir.y - 60 - scrollbarBoxBtn->GetTop(); - if ( positionWiimote < scrollbarBoxBtn->GetMinY() ) + if (positionWiimote < scrollbarBoxBtn->GetMinY()) positionWiimote = scrollbarBoxBtn->GetMinY(); - else if ( positionWiimote > scrollbarBoxBtn->GetMaxY() ) - positionWiimote = scrollbarBoxBtn->GetMaxY(); + 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 ) + if (browser->pageIndex <= 0) { browser->pageIndex = 0; } - else if ( browser->pageIndex + FILEBROWSERSIZE >= ( int )browser->browserList.size() ) + 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 ) + if (arrowDownBtn->GetState() == STATE_HELD && arrowDownBtn->GetStateChan() == t->chan) { t->wpad.btns_h |= WPAD_BUTTON_DOWN; - if ( !this->IsFocused() ) - ( ( GuiWindow * )this->GetParent() )->ChangeFocus( this ); + if (!this->IsFocused()) ((GuiWindow *) this->GetParent())->ChangeFocus(this); } - else if ( arrowUpBtn->GetState() == STATE_HELD && arrowUpBtn->GetStateChan() == 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 ); + if (!this->IsFocused()) ((GuiWindow *) this->GetParent())->ChangeFocus(this); } /* // pad/joystick navigation - if(!focus) - { - goto endNavigation; // skip navigation - listChanged = false; - } - */ - if ( t->Right() ) + if(!focus) + { + goto endNavigation; // skip navigation + listChanged = false; + } + */ + if (t->Right()) { - if ( browser->pageIndex < ( int )browser->browserList.size() && browser->browserList.size() > FILEBROWSERSIZE ) + 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; + if (browser->pageIndex + FILEBROWSERSIZE >= (int) browser->browserList.size()) browser->pageIndex + = browser->browserList.size() - FILEBROWSERSIZE; listChanged = true; } } - else if ( t->Left() ) + else if (t->Left()) { - if ( browser->pageIndex > 0 ) + if (browser->pageIndex > 0) { browser->pageIndex -= FILEBROWSERSIZE; - if ( browser->pageIndex < 0 ) - browser->pageIndex = 0; + if (browser->pageIndex < 0) browser->pageIndex = 0; listChanged = true; } } - else if ( t->Down() ) + else if (t->Down()) { - if ( browser->pageIndex + selectedItem + 1 < ( int )browser->browserList.size() ) + if (browser->pageIndex + selectedItem + 1 < (int) browser->browserList.size()) { - if ( selectedItem == FILEBROWSERSIZE - 1 ) + if (selectedItem == FILEBROWSERSIZE - 1) { // move list down by 1 browser->pageIndex++; listChanged = true; } - else if ( fileList[selectedItem+1]->IsVisible() ) + else if (fileList[selectedItem + 1]->IsVisible()) { fileList[selectedItem]->ResetState(); - fileList[++selectedItem]->SetState( STATE_SELECTED, t->chan ); + fileList[++selectedItem]->SetState(STATE_SELECTED, t->chan); } } } - else if ( t->Up() ) + else if (t->Up()) { - if ( selectedItem == 0 && browser->pageIndex + selectedItem > 0 ) + if (selectedItem == 0 && browser->pageIndex + selectedItem > 0) { // move list up by 1 browser->pageIndex--; listChanged = true; } - else if ( selectedItem > 0 ) + else if (selectedItem > 0) { fileList[selectedItem]->ResetState(); - fileList[--selectedItem]->SetState( STATE_SELECTED, t->chan ); + fileList[--selectedItem]->SetState(STATE_SELECTED, t->chan); } } //endNavigation: - for ( int i = 0; i < FILEBROWSERSIZE; i++ ) + for (int i = 0; i < FILEBROWSERSIZE; i++) { - if ( listChanged ) + if (listChanged) { bool haveselected = false; - if ( browser->pageIndex + i < ( int )browser->browserList.size() ) + if (browser->pageIndex + i < (int) browser->browserList.size()) { - if ( fileList[i]->GetState() == STATE_DISABLED ) - fileList[i]->SetState( STATE_DEFAULT ); + if (fileList[i]->GetState() == STATE_DISABLED) fileList[i]->SetState(STATE_DEFAULT); - if ( fileList[i]->GetState() == STATE_SELECTED ) - haveselected = true; + if (fileList[i]->GetState() == STATE_SELECTED) haveselected = true; - fileList[i]->SetVisible( true ); + fileList[i]->SetVisible(true); - fileListText[i]->SetText( browser->browserList[browser->pageIndex+i].displayname ); - fileListTextOver[i]->SetText( browser->browserList[browser->pageIndex+i].displayname ); + 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 + if (browser->browserList[browser->pageIndex + i].isdir) // directory { - fileList[i]->SetIcon( fileListFolder[i] ); - fileListText[i]->SetPosition( 30, 0 ); - fileListTextOver[i]->SetPosition( 30, 0 ); + 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")) { - 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")) { - fileList[i]->SetIcon(fileListSFX[i]); - } else if(!strcasecmp(fileext, ".pls") || !strcasecmp(fileext, ".m3u")) { - fileList[i]->SetIcon(fileListPLS[i]); - } else if(!strcasecmp(fileext, ".txt")) { - fileList[i]->SetIcon(fileListTXT[i]); - } else if(!strcasecmp(fileext, ".xml")) { - fileList[i]->SetIcon(fileListXML[i]); - } else if(!strcasecmp(fileext, ".rar") || !strcasecmp(fileext, ".zip") || - !strcasecmp(fileext, ".gz") || !strcasecmp(fileext, ".7z")) { - fileList[i]->SetIcon(fileListArchives[i]); - } else { - fileList[i]->SetIcon(fileListDefault[i]); - } - } else { - fileList[i]->SetIcon(fileListDefault[i]); - } - */ - fileList[i]->SetIcon( NULL ); - fileListText[i]->SetPosition( 10, 0 ); - fileListTextOver[i]->SetPosition( 10, 0 ); + 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")) { + 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")) { + fileList[i]->SetIcon(fileListSFX[i]); + } else if(!strcasecmp(fileext, ".pls") || !strcasecmp(fileext, ".m3u")) { + fileList[i]->SetIcon(fileListPLS[i]); + } else if(!strcasecmp(fileext, ".txt")) { + fileList[i]->SetIcon(fileListTXT[i]); + } else if(!strcasecmp(fileext, ".xml")) { + fileList[i]->SetIcon(fileListXML[i]); + } else if(!strcasecmp(fileext, ".rar") || !strcasecmp(fileext, ".zip") || + !strcasecmp(fileext, ".gz") || !strcasecmp(fileext, ".7z")) { + fileList[i]->SetIcon(fileListArchives[i]); + } else { + fileList[i]->SetIcon(fileListDefault[i]); + } + } 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 ); + 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 (!haveselected && browser->pageIndex < (int) browser->browserList.size()) fileList[i]->SetState( + STATE_SELECTED, t->chan); } - if ( i != selectedItem && fileList[i]->GetState() == STATE_SELECTED ) + 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 ); + else if (focus && i == selectedItem && fileList[i]->GetState() == STATE_DEFAULT) fileList[selectedItem]->SetState( + STATE_SELECTED, 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 ); + fileList[i]->Update(t); t->chan = currChan; - if ( fileList[i]->GetState() == STATE_SELECTED ) + 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 ) + if (positionWiimote > 0) { position = positionWiimote; // follow wiimote cursor } else { - position = 136 * ( browser->pageIndex + FILEBROWSERSIZE / 2.0 ) / ( browser->browserList.size() * 1.0 ); + position = 136 * (browser->pageIndex + FILEBROWSERSIZE / 2.0) / (browser->browserList.size() * 1.0); - if ( browser->pageIndex / ( FILEBROWSERSIZE / 2.0 ) < 1 ) + 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; + 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; - if ( updateCB ) - updateCB( this ); + if (updateCB) updateCB(this); } diff --git a/source/libwiigui/gui_gamebrowser.cpp b/source/libwiigui/gui_gamebrowser.cpp index 56b88317..44066c87 100644 --- a/source/libwiigui/gui_gamebrowser.cpp +++ b/source/libwiigui/gui_gamebrowser.cpp @@ -24,12 +24,12 @@ int txtscroll = 0; /** * Constructor for the GuiGameBrowser class. */ -GuiGameBrowser::GuiGameBrowser( int w, int h, const char *themePath, const u8 *imagebg, int selected, int offset ) +GuiGameBrowser::GuiGameBrowser(int w, int h, const char *themePath, const u8 *imagebg, int selected, int offset) { width = w; height = h; pagesize = THEME.pagesize; - scrollbaron = ( gameList.size() > pagesize ) ? 1 : 0; + scrollbaron = (gameList.size() > pagesize) ? 1 : 0; selectable = true; listOffset = MAX( 0, MIN( offset, ( gameList.size() - pagesize ) ) ); selectedItem = selected - offset; @@ -37,124 +37,123 @@ GuiGameBrowser::GuiGameBrowser( int w, int h, const char *themePath, const u8 *i char imgPath[100]; trigA = new GuiTrigger; - trigA->SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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; - 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; - 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]; + 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++ ) + 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, DOTTED ); + 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, 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, SCROLL_HORIZONTAL); - 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, SCROLL_HORIZONTAL ); + 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; } @@ -192,7 +191,7 @@ GuiGameBrowser::~GuiGameBrowser() delete trigHeldA; delete btnSoundClick; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { delete gameTxt[i]; delete gameTxtOver[i]; @@ -200,38 +199,36 @@ GuiGameBrowser::~GuiGameBrowser() delete game[i]; delete newImg[i]; } - delete [] gameIndex; - delete [] game; - delete [] gameTxt; - delete [] gameTxtOver; - delete [] gameBg; + delete[] gameIndex; + delete[] game; + delete[] gameTxt; + delete[] gameTxtOver; + delete[] gameBg; } -void GuiGameBrowser::SetFocus( int f ) +void GuiGameBrowser::SetFocus(int f) { LOCK( this ); - if ( !gameList.size() ) - return; + if (!gameList.size()) return; focus = f; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) game[i]->ResetState(); - 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 ) + if (state != STATE_DISABLED) { state = STATE_DEFAULT; stateChan = -1; } - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { game[i]->ResetState(); } @@ -244,11 +241,11 @@ int GuiGameBrowser::GetOffset() int GuiGameBrowser::GetClickedOption() { int found = -1; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { - if ( game[i]->GetState() == STATE_CLICKED ) + if (game[i]->GetState() == STATE_CLICKED) { - game[i]->SetState( STATE_SELECTED ); + game[i]->SetState(STATE_SELECTED); found = gameIndex[i]; break; } @@ -259,11 +256,11 @@ int GuiGameBrowser::GetClickedOption() int GuiGameBrowser::GetSelectedOption() { int found = -1; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { - if ( game[i]->GetState() == STATE_SELECTED ) + if (game[i]->GetState() == STATE_SELECTED) { - game[i]->SetState( STATE_SELECTED ); + game[i]->SetState(STATE_SELECTED); found = gameIndex[i]; break; } @@ -277,17 +274,15 @@ int GuiGameBrowser::GetSelectedOption() * Help function to find the next visible menu item on the list ***************************************************************************/ -int GuiGameBrowser::FindMenuItem( int currentItem, int direction ) +int GuiGameBrowser::FindMenuItem(int currentItem, int direction) { int nextItem = currentItem + direction; - if ( nextItem < 0 || nextItem >= gameList.size() ) - return -1; + if (nextItem < 0 || nextItem >= gameList.size()) return -1; - if ( strlen( get_title( gameList[nextItem] ) ) > 0 ) + if (strlen(get_title(gameList[nextItem])) > 0) return nextItem; - else - return FindMenuItem( nextItem, direction ); + else return FindMenuItem(nextItem, direction); } /** @@ -296,25 +291,23 @@ int GuiGameBrowser::FindMenuItem( int currentItem, int direction ) void GuiGameBrowser::Draw() { LOCK( this ); - if ( !this->IsVisible() || !gameList.size() ) - return; + if (!this->IsVisible() || !gameList.size()) return; bgGameImg->Draw(); int next = listOffset; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { - if ( next >= 0 ) + if (next >= 0) { game[i]->Draw(); - next = this->FindMenuItem( next, 1 ); + next = this->FindMenuItem(next, 1); } - else - break; + else break; } - if ( scrollbaron == 1 ) + if (scrollbaron == 1) { scrollbarImg->Draw(); arrowUpBtn->Draw(); @@ -327,52 +320,51 @@ void GuiGameBrowser::Draw() void GuiGameBrowser::UpdateListEntries() { int next = listOffset; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { - if ( next >= 0 ) + if (next >= 0) { - if ( game[i]->GetState() == STATE_DISABLED ) + if (game[i]->GetState() == STATE_DISABLED) { - game[i]->SetVisible( true ); - game[i]->SetState( STATE_DEFAULT ); + 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 ); + 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 ) + if (Settings.marknewtitles) { - bool isNew = NewTitles::Instance()->IsNew( gameList[next]->id ); - if ( isNew ) + bool isNew = NewTitles::Instance()->IsNew(gameList[next]->id); + if (isNew) { - gameTxt[i]->SetMaxWidth( maxTextWidth - ( newGames->GetWidth() + 1 ), DOTTED ); - gameTxtOver[i]->SetMaxWidth( maxTextWidth - ( newGames->GetWidth() + 1 ), SCROLL_HORIZONTAL ); + gameTxt[i]->SetMaxWidth(maxTextWidth - (newGames->GetWidth() + 1), DOTTED); + gameTxtOver[i]->SetMaxWidth(maxTextWidth - (newGames->GetWidth() + 1), SCROLL_HORIZONTAL); } else { - gameTxt[i]->SetMaxWidth( maxTextWidth, DOTTED ); - gameTxtOver[i]->SetMaxWidth( maxTextWidth, SCROLL_HORIZONTAL ); + gameTxt[i]->SetMaxWidth(maxTextWidth, DOTTED); + gameTxtOver[i]->SetMaxWidth(maxTextWidth, SCROLL_HORIZONTAL); } - newImg[i]->SetVisible( isNew ); + newImg[i]->SetVisible(isNew); } gameIndex[i] = next; - next = this->FindMenuItem( next, 1 ); + next = this->FindMenuItem(next, 1); } else { - game[i]->SetVisible( false ); - game[i]->SetState( STATE_DISABLED ); + game[i]->SetVisible(false); + game[i]->SetState(STATE_DISABLED); } } } -void GuiGameBrowser::Update( GuiTrigger * t ) +void GuiGameBrowser::Update(GuiTrigger * t) { LOCK( this ); - if ( state == STATE_DISABLED || !t || !gameList.size() ) - return; + if (state == STATE_DISABLED || !t || !gameList.size()) return; int next, prev; int old_listOffset = listOffset; @@ -381,37 +373,36 @@ void GuiGameBrowser::Update( GuiTrigger * t ) // when the arrows are clicked float scrolldelay = 3.5; - if ( scrollbaron == 1 ) + 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 ); + arrowUpBtn->Update(t); + arrowDownBtn->Update(t); + scrollbarBoxBtn->Update(t); } 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 < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { - if ( next >= 0 ) - next = this->FindMenuItem( next, 1 ); + if (next >= 0) next = this->FindMenuItem(next, 1); - if ( focus ) + if (focus) { - if ( i != selectedItem && game[i]->GetState() == STATE_SELECTED ) + if (i != selectedItem && game[i]->GetState() == STATE_SELECTED) game[i]->ResetState(); - else if ( i == selectedItem && game[i]->GetState() == STATE_DEFAULT ) - game[selectedItem]->SetState( STATE_SELECTED, t->chan ); + else if (i == selectedItem && game[i]->GetState() == STATE_DEFAULT) game[selectedItem]->SetState( + STATE_SELECTED, t->chan); } - game[i]->Update( t ); + game[i]->Update(t); - if ( game[i]->GetState() == STATE_SELECTED ) + if (game[i]->GetState() == STATE_SELECTED) { selectedItem = i; } @@ -419,43 +410,41 @@ void GuiGameBrowser::Update( GuiTrigger * t ) } // pad and joystick navigation - if ( !focus || !gameList.size() ) - return; // skip navigation + if (!focus || !gameList.size()) 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 (next >= 0) { - if ( selectedItem == pagesize - 1 ) + if (selectedItem == pagesize - 1) { // move list down by 1 - listOffset = this->FindMenuItem( listOffset, 1 ); + listOffset = this->FindMenuItem(listOffset, 1); } - else if ( game[selectedItem+1]->IsVisible() ) + else if (game[selectedItem + 1]->IsVisible()) { game[selectedItem]->ResetState(); - game[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + game[selectedItem + 1]->SetState(STATE_SELECTED, t->chan); selectedItem++; } -// scrollbarBoxBtn->Draw(); - usleep( 10000 * scrolldelay ); + // scrollbarBoxBtn->Draw(); + usleep(10000 * scrolldelay); } - if ( !( ButtonsHold() & WPAD_BUTTON_A ) ) - arrowDownBtn->ResetState(); + if (!(ButtonsHold() & WPAD_BUTTON_A)) arrowDownBtn->ResetState(); } - else if ( t->Up() || arrowUpBtn->GetState() == STATE_CLICKED || arrowUpBtn->GetState() == STATE_HELD ) //up + else if (t->Up() || arrowUpBtn->GetState() == STATE_CLICKED || arrowUpBtn->GetState() == STATE_HELD) //up { - prev = this->FindMenuItem( gameIndex[selectedItem], -1 ); + prev = this->FindMenuItem(gameIndex[selectedItem], -1); - if ( prev >= 0 ) + if (prev >= 0) { - if ( selectedItem == 0 ) + if (selectedItem == 0) { // move list up by 1 listOffset = prev; @@ -463,33 +452,32 @@ void GuiGameBrowser::Update( GuiTrigger * t ) else { game[selectedItem]->ResetState(); - game[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + game[selectedItem - 1]->SetState(STATE_SELECTED, t->chan); selectedItem--; } -// scrollbarBoxBtn->Draw(); - usleep( 10000 * scrolldelay ); + // scrollbarBoxBtn->Draw(); + usleep(10000 * scrolldelay); } - if ( !( ButtonsHold() & WPAD_BUTTON_A ) ) - arrowUpBtn->ResetState(); + if (!(ButtonsHold() & WPAD_BUTTON_A)) arrowUpBtn->ResetState(); } int position1 = t->wpad.ir.y; - if ( position2 == 0 && position1 > 0 ) + if (position2 == 0 && position1 > 0) { position2 = position1; } - if ( ( buttonshold & WPAD_BUTTON_B ) && position1 > 0 ) + if ((buttonshold & WPAD_BUTTON_B) && position1 > 0) { - scrollbarBoxBtn->ScrollIsOn( 1 ); - if ( position2 > position1 ) + scrollbarBoxBtn->ScrollIsOn(1); + if (position2 > position1) { - prev = this->FindMenuItem( gameIndex[selectedItem], -1 ); + prev = this->FindMenuItem(gameIndex[selectedItem], -1); - if ( prev >= 0 ) + if (prev >= 0) { - if ( selectedItem == 0 ) + if (selectedItem == 0) { // move list up by 1 listOffset = prev; @@ -497,117 +485,114 @@ void GuiGameBrowser::Update( GuiTrigger * t ) else { game[selectedItem]->ResetState(); - game[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + game[selectedItem - 1]->SetState(STATE_SELECTED, t->chan); selectedItem--; } -// scrollbarBoxBtn->Draw(); - usleep( 10000 * scrolldelay ); + // scrollbarBoxBtn->Draw(); + usleep(10000 * scrolldelay); } } - else if ( position2 < position1 ) + else if (position2 < position1) { - next = this->FindMenuItem( gameIndex[selectedItem], 1 ); + next = this->FindMenuItem(gameIndex[selectedItem], 1); - if ( next >= 0 ) + if (next >= 0) { - if ( selectedItem == pagesize - 1 ) + if (selectedItem == pagesize - 1) { // move list down by 1 - listOffset = this->FindMenuItem( listOffset, 1 ); + listOffset = this->FindMenuItem(listOffset, 1); } - else if ( game[selectedItem+1]->IsVisible() ) + else if (game[selectedItem + 1]->IsVisible()) { game[selectedItem]->ResetState(); - game[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + game[selectedItem + 1]->SetState(STATE_SELECTED, t->chan); selectedItem++; } -// scrollbarBoxBtn->Draw(); - usleep( 10000 * scrolldelay ); + // scrollbarBoxBtn->Draw(); + usleep(10000 * scrolldelay); } } } - else if ( !( buttonshold & WPAD_BUTTON_B ) ) + else if (!(buttonshold & WPAD_BUTTON_B)) { - scrollbarBoxBtn->ScrollIsOn( 0 ); + scrollbarBoxBtn->ScrollIsOn(0); position2 = 0; } - if ( scrollbarBoxBtn->GetState() == STATE_HELD && scrollbarBoxBtn->GetStateChan() == t->chan && t->wpad.ir.valid && gameList.size() > pagesize ) + if (scrollbarBoxBtn->GetState() == STATE_HELD && scrollbarBoxBtn->GetStateChan() == t->chan && t->wpad.ir.valid + && gameList.size() > pagesize) { // allow dragging of scrollbar box - scrollbarBoxBtn->SetPosition( width / 2 - 18 + 7, 0 ); + scrollbarBoxBtn->SetPosition(width / 2 - 18 + 7, 0); int position = t->wpad.ir.y - 32 - scrollbarBoxBtn->GetTop(); - listOffset = ( position * gameList.size() ) / ( 25.2 * pagesize ) - selectedItem; + listOffset = (position * gameList.size()) / (25.2 * pagesize) - selectedItem; - if ( listOffset <= 0 ) + if (listOffset <= 0) { listOffset = 0; selectedItem = 0; } - else if ( listOffset + pagesize >= gameList.size() ) + else if (listOffset + pagesize >= gameList.size()) { listOffset = gameList.size() - pagesize; selectedItem = pagesize - 1; } } - int positionbar = ( 25.2 * pagesize ) * ( listOffset + selectedItem ) / gameList.size(); + int positionbar = (25.2 * pagesize) * (listOffset + selectedItem) / gameList.size(); - 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 (t->Right()) //skip pagesize # of games if right is pressed { - if ( listOffset < gameList.size() && gameList.size() > pagesize ) + if (listOffset < gameList.size() && gameList.size() > pagesize) { listOffset = listOffset + pagesize; - if ( listOffset + pagesize >= gameList.size() ) - listOffset = gameList.size() - pagesize; + if (listOffset + pagesize >= gameList.size()) listOffset = gameList.size() - pagesize; } } - else if ( t->Left() ) + else if (t->Left()) { - if ( listOffset > 0 ) + if (listOffset > 0) { listOffset = listOffset - pagesize; - if ( listOffset < 0 ) - listOffset = 0; + if (listOffset < 0) listOffset = 0; } } } else { - if ( t->Down() ) //if there isn't a scrollbar and down is pressed + if (t->Down()) //if there isn't a scrollbar and down is pressed { - next = this->FindMenuItem( gameIndex[selectedItem], 1 ); + next = this->FindMenuItem(gameIndex[selectedItem], 1); - if ( next >= 0 ) + if (next >= 0) { - if ( selectedItem == pagesize - 1 ) + if (selectedItem == pagesize - 1) { // move list down by 1 - listOffset = this->FindMenuItem( listOffset, 1 ); + listOffset = this->FindMenuItem(listOffset, 1); } - else if ( game[selectedItem+1]->IsVisible() ) + else if (game[selectedItem + 1]->IsVisible()) { game[selectedItem]->ResetState(); - game[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + game[selectedItem + 1]->SetState(STATE_SELECTED, t->chan); selectedItem++; } } } - else if ( t->Up() ) //up + else if (t->Up()) //up { - prev = this->FindMenuItem( gameIndex[selectedItem], -1 ); + prev = this->FindMenuItem(gameIndex[selectedItem], -1); - if ( prev >= 0 ) + if (prev >= 0) { - if ( selectedItem == 0 ) + if (selectedItem == 0) { // move list up by 1 listOffset = prev; @@ -615,29 +600,27 @@ void GuiGameBrowser::Update( GuiTrigger * t ) else { game[selectedItem]->ResetState(); - game[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + 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() { LOCK( this ); - scrollbaron = ( gameList.size() > pagesize ) ? 1 : 0; + scrollbaron = (gameList.size() > pagesize) ? 1 : 0; selectedItem = 0; listOffset = 0; focus = 1; UpdateListEntries(); - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) game[i]->ResetState(); } diff --git a/source/libwiigui/gui_gamebrowser.h b/source/libwiigui/gui_gamebrowser.h index ee7b9f6e..e7f9768e 100644 --- a/source/libwiigui/gui_gamebrowser.h +++ b/source/libwiigui/gui_gamebrowser.h @@ -4,18 +4,18 @@ #include "gui.h" #include "../usbloader/disc.h" -class GuiGameBrowser : public GuiElement +class GuiGameBrowser: public GuiElement { public: - GuiGameBrowser( int w, int h, const char *themePath, const u8 *imagebg, int selected = 0, int offset = 0 ); + GuiGameBrowser(int w, int h, const char *themePath, const u8 *imagebg, int selected = 0, int offset = 0); ~GuiGameBrowser(); - int FindMenuItem( int c, int d ); + int FindMenuItem(int c, int d); int GetClickedOption(); int GetSelectedOption(); void ResetState(); - void SetFocus( int f ); + void SetFocus(int f); void Draw(); - void Update( GuiTrigger * t ); + void Update(GuiTrigger * t); int GetOffset(); void Reload(); //GuiText * optionVal[PAGESIZE]; diff --git a/source/libwiigui/gui_gamecarousel.cpp b/source/libwiigui/gui_gamecarousel.cpp index 9a0aa1ca..a21050a5 100644 --- a/source/libwiigui/gui_gamecarousel.cpp +++ b/source/libwiigui/gui_gamecarousel.cpp @@ -29,94 +29,93 @@ #define SPEED_STEP 4 #define SPEED_LIMIT 250 -static inline int OFFSETLIMIT( int Offset, int gameCnt ) +static inline int OFFSETLIMIT(int Offset, int gameCnt) { - while ( Offset < 0 ) Offset += gameCnt; + while (Offset < 0) + Offset += gameCnt; return Offset % gameCnt; } #define GetGameIndex(pageEntry, listOffset, gameCnt) OFFSETLIMIT(listOffset+pageEntry, gameCnt) -static GuiImageData *GameCarouselLoadCoverImage( void * Arg ) +static GuiImageData *GameCarouselLoadCoverImage(void * Arg) { - return LoadCoverImage( ( struct discHdr * )Arg, true, false ); + return LoadCoverImage((struct discHdr *) Arg, true, false); } /** * Constructor for the GuiGameCarousel class. */ -GuiGameCarousel::GuiGameCarousel( int w, int h, const char *themePath, const u8 *imagebg, int selected, int offset ) : - noCover( nocover_png ) +GuiGameCarousel::GuiGameCarousel(int w, int h, const char *themePath, const u8 *imagebg, int selected, int offset) : + noCover(nocover_png) { width = w; height = h; - pagesize = ( gameList.size() < 11 ) ? gameList.size() : 11; + pagesize = (gameList.size() < 11) ? gameList.size() : 11; listOffset = 0; selectable = true; selectedItem = -1; - focus = 1; // allow focus + focus = 1; // allow focus clickedItem = -1; speed = 0; char imgPath[100]; trigA = new GuiTrigger; - trigA->SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + 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 ); + 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 ); + 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 ); + 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", Settings.theme_path ); - imgLeft = new GuiImageData( imgPath, startgame_arrow_left_png ); - snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_right.png", Settings.theme_path ); - imgRight = new GuiImageData( imgPath, startgame_arrow_right_png ); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", Settings.theme_path); + imgLeft = new GuiImageData(imgPath, startgame_arrow_left_png); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", Settings.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( Settings.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 ); + btnLeftImg = new GuiImage(imgLeft); + if (Settings.wsprompt == yes) btnLeftImg->SetWidescreen(Settings.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( Settings.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 ); + btnRightImg = new GuiImage(imgRight); + if (Settings.wsprompt == yes) btnRightImg->SetWidescreen(Settings.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, DOTTED ); + gamename = new GuiText(" ", 18, THEME.info); + gamename->SetParent(this); + gamename->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + gamename->SetPosition(0, 330); + gamename->SetMaxWidth(280, DOTTED); - gameIndex = new int[pagesize]; - game = new GuiButton * [pagesize]; - coverImg = new GuiImageAsync * [pagesize]; + gameIndex = new int[pagesize]; + game = new GuiButton *[pagesize]; + coverImg = new GuiImageAsync *[pagesize]; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { //------------------------ // Index @@ -126,29 +125,29 @@ GuiGameCarousel::GuiGameCarousel( int w, int h, const char *themePath, const u8 //------------------------ // Image //------------------------ - coverImg[i] = new( std::nothrow ) GuiImageAsync( GameCarouselLoadCoverImage, gameList[gameIndex[i]], sizeof( struct discHdr ), &noCover ); - if ( coverImg[i] ) - coverImg[i]->SetWidescreen( Settings.widescreen ); + coverImg[i] = new (std::nothrow) GuiImageAsync(GameCarouselLoadCoverImage, gameList[gameIndex[i]], + sizeof(struct discHdr), &noCover); + if (coverImg[i]) coverImg[i]->SetWidescreen(Settings.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]->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] = 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); } } - /** * Destructor for the GuiGameCarousel class. */ @@ -170,80 +169,73 @@ GuiGameCarousel::~GuiGameCarousel() delete btnSoundOver; delete gamename; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { delete coverImg[i]; delete game[i]; } - delete [] gameIndex; - delete [] coverImg; - delete [] game; - + delete[] gameIndex; + delete[] coverImg; + delete[] game; } - -void GuiGameCarousel::SetFocus( int f ) +void GuiGameCarousel::SetFocus(int f) { LOCK( this ); - if ( !gameList.size() ) return; + if (!gameList.size()) return; focus = f; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) game[i]->ResetState(); - 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 ) + if (state != STATE_DISABLED) { state = STATE_DEFAULT; stateChan = -1; } - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { game[i]->ResetState(); } } - int GuiGameCarousel::GetOffset() { LOCK( this ); return listOffset; } - int GuiGameCarousel::GetClickedOption() { LOCK( this ); int found = -1; - if ( clickedItem >= 0 ) + if (clickedItem >= 0) { - game[clickedItem]->SetState( STATE_SELECTED ); + game[clickedItem]->SetState(STATE_SELECTED); found = gameIndex[clickedItem]; clickedItem = -1; } return found; } - int GuiGameCarousel::GetSelectedOption() { LOCK( this ); int found = -1; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { - if ( game[i]->GetState() == STATE_SELECTED ) + if (game[i]->GetState() == STATE_SELECTED) { - game[i]->SetState( STATE_SELECTED ); + game[i]->SetState(STATE_SELECTED); found = gameIndex[i]; break; } @@ -257,40 +249,35 @@ int GuiGameCarousel::GetSelectedOption() void GuiGameCarousel::Draw() { LOCK( this ); - if ( !this->IsVisible() || !gameList.size() ) - return; + if (!this->IsVisible() || !gameList.size()) return; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) game[i]->Draw(); - gamename->Draw(); - if ( gameList.size() > 6 ) + if (gameList.size() > 6) { btnRight->Draw(); btnLeft->Draw(); } //!Draw tooltip after the Images to have it on top - if ( focus && Settings.tooltips == TooltipsOn ) - for ( int i = 0; i < pagesize; i++ ) - game[i]->DrawTooltip(); + if (focus && Settings.tooltips == TooltipsOn) for (int i = 0; i < pagesize; i++) + game[i]->DrawTooltip(); this->UpdateEffects(); } - -void GuiGameCarousel::Update( GuiTrigger * t ) +void GuiGameCarousel::Update(GuiTrigger * t) { LOCK( this ); - if ( state == STATE_DISABLED || !t || !gameList.size() ) - return; + if (state == STATE_DISABLED || !t || !gameList.size()) 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 ) + if (game[0]->GetEffect() & EFFECT_GOROUND || game[pagesize - 1]->GetEffect() & EFFECT_GOROUND) { return; // skip when rotate } @@ -299,14 +286,14 @@ void GuiGameCarousel::Update( GuiTrigger * t ) int selectedItem_old = selectedItem; selectedItem = -1; clickedItem = -1; - for ( int i = pagesize - 1; i >= 0; i-- ) + for (int i = pagesize - 1; i >= 0; i--) { - game[i]->Update( t ); - if ( game[i]->GetState() == STATE_SELECTED ) + game[i]->Update(t); + if (game[i]->GetState() == STATE_SELECTED) { selectedItem = i; } - if ( game[i]->GetState() == STATE_CLICKED ) + if (game[i]->GetState() == STATE_CLICKED) { clickedItem = i; } @@ -314,146 +301,142 @@ void GuiGameCarousel::Update( GuiTrigger * t ) } /// OnOver-Effect + GameText + Tooltop - if ( selectedItem_old != selectedItem ) + if (selectedItem_old != selectedItem) { - if ( selectedItem >= 0 ) + if (selectedItem >= 0) { - game[selectedItem]->SetEffect( EFFECT_SCALE, 1, 130 ); - char *gameTitle = get_title( gameList[gameIndex[selectedItem]] ); - gamename->SetText( gameTitle ); + 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 ); + else gamename->SetText((char*) NULL); + if (selectedItem_old >= 0) game[selectedItem_old]->SetEffect(EFFECT_SCALE, -1, 100); } // navigation - if ( focus && gameList.size() > 6 ) + if (focus && gameList.size() > 6) { int newspeed = 0; // Left/Right Navigation - if ( btnLeft->GetState() == STATE_CLICKED ) + 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() ) ) + 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; + if (Settings.xflip == sysmenu || Settings.xflip == yes || Settings.xflip == disk3d) + newspeed = SHIFT_SPEED; + else newspeed = -SHIFT_SPEED; } - else if ( btnRight->GetState() == STATE_CLICKED ) + 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() ) ) + 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 (Settings.xflip == sysmenu || Settings.xflip == yes || Settings.xflip == disk3d) + newspeed = -SHIFT_SPEED; + else newspeed = SHIFT_SPEED; } - if ( newspeed ) + if (newspeed) { - if ( speed == 0 ) + if (speed == 0) speed = newspeed; - else if ( speed > 0 ) + else if (speed > 0) { - if ( ( speed += SPEED_STEP ) > SPEED_LIMIT ) - speed = SPEED_LIMIT; + if ((speed += SPEED_STEP) > SPEED_LIMIT) speed = SPEED_LIMIT; } else { - if ( ( speed -= SPEED_STEP ) < -SPEED_LIMIT ) - speed = -SPEED_LIMIT; + if ((speed -= SPEED_STEP) < -SPEED_LIMIT) speed = -SPEED_LIMIT; } } - else - speed = 0; + else speed = 0; - - if ( speed > 0 ) // rotate right + if (speed > 0) // rotate right { GuiButton *tmpButton; - listOffset = OFFSETLIMIT( listOffset - 1, gameList.size() ); // set the new listOffset + listOffset = OFFSETLIMIT(listOffset - 1, gameList.size()); // 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]; + 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-- ) + for (int i = pagesize - 1; i >= 1; i--) { - coverImg[i] = coverImg[i-1]; - game[i] = game[i-1]; - gameIndex[i] = gameIndex[i-1]; + 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( Settings.widescreen ); + gameIndex[0] = listOffset; + coverImg[0] = new GuiImageAsync(GameCarouselLoadCoverImage, gameList[gameIndex[0]], sizeof(struct discHdr), + &noCover); + coverImg[0] ->SetWidescreen(Settings.widescreen); - game[0] = tmpButton; - game[0] ->SetImage( coverImg[0] ); + game[0] = tmpButton; + game[0] ->SetImage(coverImg[0]); - - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { game[i]->StopEffect(); 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]->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 + else if (speed < 0) // rotate left { GuiButton *tmpButton; - listOffset = OFFSETLIMIT( listOffset + 1, gameList.size() ); // set the new listOffset + listOffset = OFFSETLIMIT(listOffset + 1, gameList.size()); // 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]; + 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++ ) + for (int i = 0; i < (pagesize - 1); i++) { - coverImg[i] = coverImg[i+1]; - game[i] = game[i+1]; - gameIndex[i] = gameIndex[i+1]; + 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, gameList.size() ); - coverImg[ii] = new GuiImageAsync( GameCarouselLoadCoverImage, gameList[gameIndex[ii]], sizeof( struct discHdr ), &noCover ); - coverImg[ii] ->SetWidescreen( Settings.widescreen ); + gameIndex[ii] = OFFSETLIMIT(listOffset + ii, gameList.size()); + coverImg[ii] = new GuiImageAsync(GameCarouselLoadCoverImage, gameList[gameIndex[ii]], + sizeof(struct discHdr), &noCover); + coverImg[ii] ->SetWidescreen(Settings.widescreen); - game[ii] = tmpButton; - game[ii] ->SetImage( coverImg[ii] ); + game[ii] = tmpButton; + game[ii] ->SetImage(coverImg[ii]); - - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { game[i]->StopEffect(); 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]->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 816a3759..a45fb9b0 100644 --- a/source/libwiigui/gui_gamecarousel.h +++ b/source/libwiigui/gui_gamecarousel.h @@ -4,23 +4,23 @@ #include "gui.h" #include "../usbloader/disc.h" class GuiImageAsync; -class GuiGameCarousel : public GuiElement +class GuiGameCarousel: public GuiElement { public: - GuiGameCarousel( int w, int h, const char *themePath, const u8 *imagebg, int selected = 0, int offset = 0 ); + GuiGameCarousel(int w, int h, const char *themePath, const u8 *imagebg, int selected = 0, int offset = 0); ~GuiGameCarousel(); - int FindMenuItem( int c, int d ); + int FindMenuItem(int c, int d); int GetClickedOption(); int GetSelectedOption(); void ResetState(); - void SetFocus( int f ); + void SetFocus(int f); void Draw(); - void Update( GuiTrigger * t ); + void Update(GuiTrigger * t); int GetOffset(); void Reload(); //GuiText * optionVal[PAGESIZE]; protected: - GuiImageData noCover; + GuiImageData noCover; int selectedItem; int listOffset; int scrollbaron; diff --git a/source/libwiigui/gui_gamegrid.cpp b/source/libwiigui/gui_gamegrid.cpp index b0ba8fd0..fb4c30b2 100644 --- a/source/libwiigui/gui_gamegrid.cpp +++ b/source/libwiigui/gui_gamegrid.cpp @@ -33,345 +33,256 @@ #define goSteps 10 #include "../main.h" - - - 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} -}; -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}} -}; -static int Skew2[18][8] = -{ - { -5, -49, 5, -27, 5, 0, -5, 0}, - { -5, 0, 5, 0, 5, 27, -5, 49}, +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 } }; +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 } } }; +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}, +{ -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}, +{ -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, -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, 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}, +{ 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}, +{ -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, -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}}, +{ -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}}, + { { 3, 50 }, { -54, 50 } }, { { 3, 193 }, { -54, 193 } }, - {{97, 50}, {58, 50}}, - {{97, 193}, {58, 193}}, + { { 97, 50 }, { 58, 50 } }, { { 97, 193 }, { 58, 193 } }, - {{187, 50}, {166, 50}}, - {{187, 193}, {166, 193}}, + { { 187, 50 }, { 166, 50 } }, { { 187, 193 }, { 166, 193 } }, - {{272, 50}, {272, 50}}, - {{272, 193}, {272, 193}}, + { { 272, 50 }, { 272, 50 } }, { { 272, 193 }, { 272, 193 } }, - {{358, 50}, {378, 50}}, - {{358, 193}, {378, 193}}, + { { 358, 50 }, { 378, 50 } }, { { 358, 193 }, { 378, 193 } }, - {{449, 50}, {487, 50}}, - {{449, 193}, {487, 193}}, + { { 449, 50 }, { 487, 50 } }, { { 449, 193 }, { 487, 193 } }, - {{545, 50}, {599, 50}}, - {{545, 193}, {599, 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}, + { { 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, -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} -}; -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}}, + { -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}}, + { { 13, 58 }, { -29, 58 } }, { { 13, 153 }, { -29, 153 } }, { { 13, 250 }, { -29, 250 } }, - {{68, 67}, {33, 67}}, - {{68, 153}, {33, 153}}, - {{68, 239}, {33, 239}}, + { { 68, 67 }, { 33, 67 } }, { { 68, 153 }, { 33, 153 } }, { { 68, 239 }, { 33, 239 } }, - {{120, 74}, {92, 74}}, - {{120, 153}, {92, 153}}, - {{120, 232}, {92, 232}}, + { { 120, 74 }, { 92, 74 } }, { { 120, 153 }, { 92, 153 } }, { { 120, 232 }, { 92, 232 } }, - {{170, 78}, {149, 78}}, - {{170, 153}, {149, 153}}, - {{170, 228}, {149, 228}}, + { { 170, 78 }, { 149, 78 } }, { { 170, 153 }, { 149, 153 } }, { { 170, 228 }, { 149, 228 } }, - {{214, 80}, {200, 80}}, - {{214, 153}, {200, 153}}, - {{214, 226}, {200, 226}}, + { { 214, 80 }, { 200, 80 } }, { { 214, 153 }, { 200, 153 } }, { { 214, 226 }, { 200, 226 } }, - {{258, 81}, {251, 81}}, - {{258, 153}, {251, 153}}, - {{258, 224}, {251, 224}}, + { { 258, 81 }, { 251, 81 } }, { { 258, 153 }, { 251, 153 } }, { { 258, 224 }, { 251, 224 } }, - {{302, 81}, {302, 81}}, - {{302, 153}, {302, 153}}, - {{302, 223}, {302, 223}}, + { { 302, 81 }, { 302, 81 } }, { { 302, 153 }, { 302, 153 } }, { { 302, 223 }, { 302, 223 } }, - {{346, 81}, {353, 81}}, - {{346, 153}, {353, 153}}, - {{346, 223}, {353, 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}}, + { { 390, 80 }, { 404, 80 } }, { { 390, 153 }, { 404, 153 } }, { { 390, 225 }, { 404, 225 } }, - {{434, 77}, {457, 77}}, - {{434, 153}, {457, 153}}, - {{434, 227}, {457, 227}}, + { { 434, 77 }, { 457, 77 } }, { { 434, 153 }, { 457, 153 } }, { { 434, 227 }, { 457, 227 } }, - {{484, 73}, {512, 73}}, - {{484, 153}, {512, 153}}, - {{484, 231}, {512, 231}}, + { { 484, 73 }, { 512, 73 } }, { { 484, 153 }, { 512, 153 } }, { { 484, 231 }, { 512, 231 } }, - {{537, 67}, {572, 67}}, - {{537, 153}, {572, 153}}, - {{537, 239}, {572, 239}}, + { { 537, 67 }, { 572, 67 } }, { { 537, 153 }, { 572, 153 } }, { { 537, 239 }, { 572, 239 } }, - {{591, 58}, {633, 58}}, - {{591, 153}, {633, 153}}, - {{591, 250}, {633, 250}}, + { { 591, 58 }, { 633, 58 } }, { { 591, 153 }, { 633, 153 } }, { { 591, 250 }, { 633, 250 } }, - {{660, 58}, {660, 58}}, - {{660, 153}, {660, 153}}, - {{660, 250}, {660, 250}} + { { 660, 58 }, { 660, 58 } }, { { 660, 153 }, { 660, 153 } }, { { 660, 250 }, { 660, 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 ) +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; + 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 ) +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 skip = (rows - (gameCnt % rows)) % rows; // count of skiped Entries at end if List int pagesize = ROWS2PAGESIZE( rows ); - if ( gameCnt < ( pagesize - 2*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; + 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; + 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 ) +static GuiImageData *GameGridLoadCoverImage(void * Arg) { - return LoadCoverImage( ( struct discHdr * )Arg, false, false ); + return LoadCoverImage((struct discHdr *) Arg, false, false); } /** * Constructor for the GuiGamegrid class. */ -GuiGameGrid::GuiGameGrid( int w, int h, const char *themePath, const u8 *imagebg, int selected, int offset ) : - noCover( nocoverFlat_png ) +GuiGameGrid::GuiGameGrid(int w, int h, const char *themePath, const u8 *imagebg, int selected, int offset) : + 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 + // 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 -// selectedItem = -1; will be set later in Reload -// clickedItem = -1; will be set later in Reload + 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; + rows = Settings.gridRows; + if ((count<45)&&(rows==3))rows=2; + if ((count<18)&&(rows==2))rows=1; - pagesize = ROWS2PAGESIZE(rows); - */ + pagesize = ROWS2PAGESIZE(rows); + */ trigA = new GuiTrigger; - trigA->SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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; -// cover = NULL; - coverImg = NULL; - game = NULL; + gameIndex = NULL; + titleTT = NULL; + // cover = NULL; + coverImg = NULL; + game = NULL; - Reload( Settings.gridRows, 0 ); + Reload(Settings.gridRows, 0); } - /** * Destructor for the GuiGameGrid class. */ @@ -393,82 +304,75 @@ GuiGameGrid::~GuiGameGrid() delete btnSoundClick; delete btnSoundOver; - for ( int i = pagesize - 1; i >= 0; 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 ) +void GuiGameGrid::SetFocus(int f) { LOCK( this ); - if ( !gameList.size() ) - return; + if (!gameList.size()) return; focus = f; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) game[i]->ResetState(); - 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 ) + if (state != STATE_DISABLED) { state = STATE_DEFAULT; stateChan = -1; } - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { game[i]->ResetState(); } } - int GuiGameGrid::GetOffset() { LOCK( this ); return listOffset; } - int GuiGameGrid::GetClickedOption() { LOCK( this ); int found = -1; - if ( clickedItem >= 0 ) + if (clickedItem >= 0) { - game[clickedItem]->SetState( STATE_SELECTED ); + game[clickedItem]->SetState(STATE_SELECTED); found = gameIndex[clickedItem]; clickedItem = -1; } return found; } - int GuiGameGrid::GetSelectedOption() { LOCK( this ); int found = -1; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { - if ( game[i]->GetState() == STATE_SELECTED ) + if (game[i]->GetState() == STATE_SELECTED) { - game[i]->SetState( STATE_SELECTED ); + game[i]->SetState(STATE_SELECTED); found = gameIndex[i]; break; } @@ -482,60 +386,51 @@ int GuiGameGrid::GetSelectedOption() void GuiGameGrid::Draw() { LOCK( this ); - if ( !this->IsVisible() || !gameList.size() ) - return; + if (!this->IsVisible() || !gameList.size()) return; - if ( goLeft > 0 ) + if (goLeft > 0) { goLeft--; int wsi = Settings.widescreen ? 0 : 1; - float f2 = ( ( float )goLeft ) / goSteps; + 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 ); + int (*Pos)[2][2] = VALUE4ROWS( rows, Pos1, Pos2, Pos3 ); + int (*Skew)[8] = VALUE4ROWS( rows, Skew1, Skew2, Skew3 ); - for ( int i = 0; i < pagesize - rows; i++ ) + for (int i = 0; i < pagesize - rows; i++) { - game[i]->SetPosition( 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]->SetPosition(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 ) + else if (goRight > 0) { goRight--; int wsi = Settings.widescreen ? 0 : 1; - float f2 = ( ( float )goRight ) / goSteps; + 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; i < pagesize; i++ ) + int (*Pos)[2][2] = VALUE4ROWS( rows, Pos1, Pos2, Pos3 ); + int (*Skew)[8] = VALUE4ROWS( rows, Skew1, Skew2, Skew3 ); + for (int i = rows; i < pagesize; i++) { - game[i]->SetPosition( 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]->SetPosition(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); } } - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) game[i]->Draw(); - if ( gameList.size() > pagesize - 2*rows ) + if (gameList.size() > pagesize - 2 * rows) { btnRight->Draw(); btnLeft->Draw(); @@ -544,260 +439,258 @@ void GuiGameGrid::Draw() btnRowUp->Draw(); btnRowDown->Draw(); - if ( focus && Settings.tooltips == TooltipsOn ) - for ( int i = 0; i < pagesize; i++ ) - game[i]->DrawTooltip(); + if (focus && Settings.tooltips == TooltipsOn) for (int i = 0; i < pagesize; i++) + game[i]->DrawTooltip(); this->UpdateEffects(); } - - /** * Change the number of rows */ -void GuiGameGrid::ChangeRows( int n ) +void GuiGameGrid::ChangeRows(int n) { LOCK( this ); - if ( n != rows ) - Reload( n, -1 ); + if (n != rows) Reload(n, -1); } - -void GuiGameGrid::Update( GuiTrigger * t ) +void GuiGameGrid::Update(GuiTrigger * t) { LOCK( this ); - if ( state == STATE_DISABLED || !t || !gameList.size() ) - return; + if (state == STATE_DISABLED || !t || !gameList.size()) return; - if ( !( game[0]->GetEffect() || game[0]->GetEffectOnOver() ) ) + if (!(game[0]->GetEffect() || game[0]->GetEffectOnOver())) { - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) game[i]->SetEffectGrow(); } - btnRight->Update( t ); - btnLeft->Update( t ); - btnRowUp->Update( t ); - btnRowDown->Update( t ); + btnRight->Update(t); + btnLeft->Update(t); + btnRowUp->Update(t); + btnRowDown->Update(t); selectedItem = -1; clickedItem = -1; - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { - game[i]->Update( t ); - if ( game[i]->GetState() == STATE_SELECTED ) + game[i]->Update(t); + if (game[i]->GetState() == STATE_SELECTED) { selectedItem = i; } - if ( game[i]->GetState() == STATE_CLICKED ) + if (game[i]->GetState() == STATE_CLICKED) { clickedItem = i; } } // navigation - if ( focus && gameList.size() >= ( pagesize - 2*rows ) && goLeft == 0 && goRight == 0 ) + if (focus && gameList.size() >= (pagesize - 2 * rows) && goLeft == 0 && goRight == 0) { // Left/Right Navigation - if ( btnLeft->GetState() == STATE_CLICKED ) + 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() ) ) + 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 ) + if (Settings.xflip == sysmenu || Settings.xflip == yes || Settings.xflip == disk3d) goRight = goSteps; - else - goLeft = goSteps; + else goLeft = goSteps; } - else if ( btnRight->GetState() == STATE_CLICKED ) + 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() ) ) + 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 (Settings.xflip == sysmenu || Settings.xflip == yes || Settings.xflip == disk3d) + goLeft = goSteps; + else goRight = goSteps; } - if ( goLeft == goSteps ) + if (goLeft == goSteps) { GuiButton *tmpButton[rows]; GuiTooltip *tmpTooltip[rows]; - listOffset = OFFSETLIMIT( listOffset + rows, rows, gameList.size() ); // set the new listOffset + listOffset = OFFSETLIMIT(listOffset + rows, rows, gameList.size()); // set the new listOffset // Save left Tooltip & Button and destroy left Image + Image-Data - for ( int i = 0; i < rows; i++ ) + for (int i = 0; i < rows; i++) { - delete coverImg[i]; coverImg[i] = NULL; game[i]->SetImage( NULL ); - tmpTooltip[i] = titleTT[i]; - tmpButton[i] = game[i]; + delete coverImg[i]; + coverImg[i] = NULL; + game[i]->SetImage(NULL); + tmpTooltip[i] = titleTT[i]; + tmpButton[i] = game[i]; } // Move all Page-Entries one step left - for ( int i = 0; i < ( pagesize - rows ); i++ ) + 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]; + 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 = Settings.widescreen ? 0 : 1; - int ( *Pos )[2][2] = VALUE4ROWS( rows, Pos1, Pos2, Pos3 ); - int ( *Skew )[8] = VALUE4ROWS( rows, Skew1, Skew2, Skew3 ); + int (*Pos)[2][2] = VALUE4ROWS( rows, Pos1, Pos2, Pos3 ); + int (*Skew)[8] = VALUE4ROWS( rows, Skew1, Skew2, Skew3 ); - for ( int i = 0; i < rows; i++ ) + for (int i = 0; i < rows; i++) { int ii = i + pagesize - rows; - gameIndex[ii] = GetGameIndex( ii, rows, listOffset, gameList.size() ); - titleTT[ii] = tmpTooltip[i]; - coverImg[ii] = NULL; - if ( gameIndex[ii] != -1 ) + gameIndex[ii] = GetGameIndex(ii, rows, listOffset, gameList.size()); + titleTT[ii] = tmpTooltip[i]; + coverImg[ii] = NULL; + if (gameIndex[ii] != -1) { - coverImg[ii] = new GuiImageAsync( GameGridLoadCoverImage, gameList[gameIndex[ii]], sizeof( struct discHdr ), &noCover ); - if ( coverImg[ii] ) + coverImg[ii] = new GuiImageAsync(GameGridLoadCoverImage, gameList[gameIndex[ii]], + sizeof(struct discHdr), &noCover); + if (coverImg[ii]) { - coverImg[ii] ->SetWidescreen( Settings.widescreen ); - coverImg[ii] ->SetScale( VALUE4ROWS( rows, 1.0, 0.6, 0.26 ) ); - coverImg[ii] ->SetPosition( 0, VALUE4ROWS( rows, 0, -50, -80 ) ); + coverImg[ii] ->SetWidescreen(Settings.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]] ) ); + titleTT[ii] ->SetText(get_title(gameList[gameIndex[ii]])); } else { - titleTT[ii] ->SetText( NULL ); + titleTT[ii] ->SetText(NULL); } - 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] = 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 ); + game[ii] ->SetClickable(true); + game[ii] ->SetVisible(true); } else { - game[ii] ->SetVisible( false ); - game[ii] ->SetClickable( false ); - game[ii] ->RemoveSoundOver(); + game[ii] ->SetVisible(false); + game[ii] ->SetClickable(false); + game[ii] ->RemoveSoundOver(); } } // Set Tooltip-Position int ttoffset_x = Settings.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++ ) + for (int i = 0; i < pagesize; i++) { - switch ( ( i*3 ) / pagesize ) + switch ((i * 3) / pagesize) { case 0: - game[i]->SetToolTip( titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE ); + 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 ); + 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 ); + game[i]->SetToolTip(titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE); break; default: break; } } } - else if ( goRight == goSteps ) + else if (goRight == goSteps) { GuiButton *tmpButton[rows]; GuiTooltip *tmpTooltip[rows]; - listOffset = OFFSETLIMIT( listOffset - rows, rows, gameList.size() ); // set the new listOffset + listOffset = OFFSETLIMIT(listOffset - rows, rows, gameList.size()); // set the new listOffset // Save right Button & Tooltip and destroy right Image-Data - for ( int i = 0; i < rows; i++ ) + for (int i = 0; i < rows; i++) { int ii = i + pagesize - rows; - delete coverImg[ii]; coverImg[ii] = NULL; game[ii]->SetImage( NULL ); - tmpTooltip[i] = titleTT[ii]; - tmpButton[i] = game[ii]; + delete coverImg[ii]; + coverImg[ii] = NULL; + game[ii]->SetImage(NULL); + tmpTooltip[i] = titleTT[ii]; + tmpButton[i] = game[ii]; } // Move all Page-Entries one step right - for ( int i = pagesize - 1; i >= rows; i-- ) + 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]; + 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 = Settings.widescreen ? 0 : 1; - int ( *Pos )[2][2] = VALUE4ROWS( rows, Pos1, Pos2, Pos3 ); - int ( *Skew )[8] = VALUE4ROWS( rows, Skew1, Skew2, Skew3 ); + int (*Pos)[2][2] = VALUE4ROWS( rows, Pos1, Pos2, Pos3 ); + int (*Skew)[8] = VALUE4ROWS( rows, Skew1, Skew2, Skew3 ); - for ( int i = 0; i < rows; i++ ) + for (int i = 0; i < rows; i++) { - gameIndex[i] = GetGameIndex( i, rows, listOffset, gameList.size() ); - titleTT[i] = tmpTooltip[i]; - coverImg[i] = NULL; - if ( gameIndex[i] != -1 ) + gameIndex[i] = GetGameIndex(i, rows, listOffset, gameList.size()); + titleTT[i] = tmpTooltip[i]; + coverImg[i] = NULL; + if (gameIndex[i] != -1) { - coverImg[i] = new GuiImageAsync( GameGridLoadCoverImage, gameList[gameIndex[i]], sizeof( struct discHdr ), &noCover ); - if ( coverImg[i] ) + coverImg[i] = new GuiImageAsync(GameGridLoadCoverImage, gameList[gameIndex[i]], + sizeof(struct discHdr), &noCover); + if (coverImg[i]) { - coverImg[i] ->SetWidescreen( Settings.widescreen ); - coverImg[i] ->SetScale( VALUE4ROWS( rows, 1.0, 0.6, 0.26 ) ); - coverImg[i] ->SetPosition( 0, VALUE4ROWS( rows, 0, -50, -80 ) ); + coverImg[i] ->SetWidescreen(Settings.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]] ) ); + titleTT[i] ->SetText(get_title(gameList[gameIndex[i]])); } else { - titleTT[i] ->SetText( NULL ); + 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] = 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 ); + game[i] ->SetClickable(true); + game[i] ->SetVisible(true); } else { - game[i] ->SetVisible( false ); - game[i] ->SetClickable( false ); - game[i] ->RemoveSoundOver(); + game[i] ->SetVisible(false); + game[i] ->SetClickable(false); + game[i] ->RemoveSoundOver(); } } // Set Tooltip-Position int ttoffset_x = Settings.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++ ) + for (int i = 0; i < pagesize; i++) { - switch ( ( i*3 ) / pagesize ) + switch ((i * 3) / pagesize) { case 0: - game[i]->SetToolTip( titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE ); + 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 ); + 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 ); + game[i]->SetToolTip(titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE); break; default: break; @@ -806,64 +699,61 @@ void GuiGameGrid::Update( GuiTrigger * t ) } } - if ( ( btnRowUp->GetState() == STATE_CLICKED ) ) + if ((btnRowUp->GetState() == STATE_CLICKED)) { - if ( ( rows == 1 ) && ( gameList.size() >= 18 ) )this->ChangeRows( 2 ); - else if ( ( rows == 2 ) && ( gameList.size() >= 45 ) )this->ChangeRows( 3 ); + if ((rows == 1) && (gameList.size() >= 18)) + this->ChangeRows(2); + else if ((rows == 2) && (gameList.size() >= 45)) this->ChangeRows(3); btnRowUp->ResetState(); return; } - if ( ( btnRowDown->GetState() == STATE_CLICKED ) ) + if ((btnRowDown->GetState() == STATE_CLICKED)) { - if ( rows == 3 )this->ChangeRows( 2 ); - else if ( rows == 2 )this->ChangeRows( 1 ); + 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( int Rows, int ListOffset ) +void GuiGameGrid::Reload(int Rows, int ListOffset) { LOCK( this ); // CleanUp - if ( game ) - for ( int i = pagesize - 1; i >= 0; i-- ) - delete game[i]; + 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(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 [] cover; - delete [] titleTT; + delete[] gameIndex; + delete[] game; + delete[] coverImg; + // delete [] cover; + delete[] titleTT; goLeft = 0; goRight = 0; - rows = Rows > 3 ? 3 : ( Rows < 1 ? 1 : Rows ); - if ( ( gameList.size() < 45 ) && ( rows == 3 ) )rows = 2; - if ( ( gameList.size() < 18 ) && ( rows == 2 ) )rows = 1; + rows = Rows > 3 ? 3 : (Rows < 1 ? 1 : Rows); + if ((gameList.size() < 45) && (rows == 3)) rows = 2; + if ((gameList.size() < 18) && (rows == 2)) rows = 1; - if ( ListOffset >= 0 ) // if ListOffset < 0 then no change - listOffset = ListOffset; - listOffset = OFFSETLIMIT( listOffset, rows, gameList.size() ); + if (ListOffset >= 0) // if ListOffset < 0 then no change + listOffset = ListOffset; + listOffset = OFFSETLIMIT(listOffset, rows, gameList.size()); selectedItem = -1; clickedItem = -1; @@ -871,96 +761,95 @@ void GuiGameGrid::Reload( int Rows, int ListOffset ) pagesize = ROWS2PAGESIZE( rows ); // Page-Stuff - gameIndex = new int[pagesize]; - titleTT = new GuiTooltip *[pagesize]; -// cover = new GuiImageData *[pagesize]; - coverImg = new GuiImageAsync *[pagesize]; - game = new GuiButton *[pagesize]; - + gameIndex = new int[pagesize]; + titleTT = new GuiTooltip *[pagesize]; + // cover = new GuiImageData *[pagesize]; + coverImg = new GuiImageAsync *[pagesize]; + game = new GuiButton *[pagesize]; int wsi = Settings.widescreen ? 0 : 1; - int ( *Pos )[2][2] = VALUE4ROWS( rows, Pos1, Pos2, Pos3 ); - int ( *Skew )[8] = VALUE4ROWS( rows, Skew1, Skew2, Skew3 ); + int (*Pos)[2][2] = VALUE4ROWS( rows, Pos1, Pos2, Pos3 ); + int (*Skew)[8] = VALUE4ROWS( rows, Skew1, Skew2, Skew3 ); int ttoffset_x = Settings.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++ ) + for (int i = 0; i < pagesize; i++) { //------------------------ // Index //------------------------ - gameIndex[i] = GetGameIndex( i, rows, listOffset, gameList.size() ); + gameIndex[i] = GetGameIndex(i, rows, listOffset, gameList.size()); //------------------------ // Tooltip //------------------------ - if ( gameIndex[i] != -1 ) - titleTT[i] = new GuiTooltip( get_title( gameList[gameIndex[i]] ), THEME.tooltipAlpha ); - else - titleTT[i] = new GuiTooltip( NULL, THEME.tooltipAlpha ); + 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 ) -// cover[i] = LoadCoverImage(&gameList[gameIndex[i]], false /*bool Prefere3D*/); -// else -// cover[i] = new GuiImageData(NULL); + // 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 ) + if (gameIndex[i] != -1) { - coverImg[i] = new GuiImageAsync( GameGridLoadCoverImage, gameList[gameIndex[i]], sizeof( struct discHdr ), &noCover ); - if ( coverImg[i] ) + coverImg[i] = new GuiImageAsync(GameGridLoadCoverImage, gameList[gameIndex[i]], sizeof(struct discHdr), + &noCover); + if (coverImg[i]) { - coverImg[i]->SetWidescreen( Settings.widescreen ); + coverImg[i]->SetWidescreen(Settings.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 ) ); + 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 ) + 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 ); + 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 ); + 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 ); + game[i]->SetToolTip(titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE); break; default: break; } - if ( gameIndex[i] >= 0 ) + if (gameIndex[i] >= 0) { - game[i]->SetClickable( true ); - game[i]->SetVisible( true ); + game[i]->SetClickable(true); + game[i]->SetVisible(true); } else { - game[i]->SetVisible( false ); - game[i]->SetClickable( false ); + game[i]->SetVisible(false); + game[i]->SetClickable(false); // game[i]->RemoveSoundOver(); } } diff --git a/source/libwiigui/gui_gamegrid.h b/source/libwiigui/gui_gamegrid.h index 761a6305..0dd739df 100644 --- a/source/libwiigui/gui_gamegrid.h +++ b/source/libwiigui/gui_gamegrid.h @@ -4,23 +4,23 @@ #include "gui.h" #include "../usbloader/disc.h" class GuiImageAsync; -class GuiGameGrid : public GuiElement +class GuiGameGrid: public GuiElement { public: - GuiGameGrid( int w, int h, const char *themePath, const u8 *imagebg, int selected = 0, int offset = 0 ); + GuiGameGrid(int w, int h, const char *themePath, const u8 *imagebg, int selected = 0, int offset = 0); ~GuiGameGrid(); - int FindMenuItem( int c, int d ); + int FindMenuItem(int c, int d); int GetClickedOption(); int GetSelectedOption(); void ResetState(); - void SetFocus( int f ); + void SetFocus(int f); void Draw(); - void Update( GuiTrigger * t ); + void Update(GuiTrigger * t); int GetOffset(); - void Reload( int Rows, int ListOffset ); - void ChangeRows( int n ); + void Reload(int Rows, int ListOffset); + void ChangeRows(int n); protected: - GuiImageData noCover; + GuiImageData noCover; int selectedItem; int listOffset; int pagesize; @@ -34,7 +34,6 @@ class GuiGameGrid : public GuiElement GuiTooltip ** titleTT; GuiImageAsync ** coverImg; - GuiButton * btnRight; GuiButton * btnLeft; GuiButton * btnRowUp; diff --git a/source/libwiigui/gui_image.cpp b/source/libwiigui/gui_image.cpp index 4719a173..e2af5545 100644 --- a/source/libwiigui/gui_image.cpp +++ b/source/libwiigui/gui_image.cpp @@ -32,9 +32,9 @@ GuiImage::GuiImage() imgType = IMAGE_DATA; } -GuiImage::GuiImage( GuiImageData * img ) +GuiImage::GuiImage(GuiImageData * img) { - if ( img ) + if (img) { image = img->GetImage(); width = img->GetWidth(); @@ -62,12 +62,12 @@ GuiImage::GuiImage( GuiImageData * img ) 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; + imageangle = 0; tile = -1; stripe = 0; widescreen = 0; @@ -83,9 +83,9 @@ GuiImage::GuiImage( u8 * img, int w, int h ) imgType = IMAGE_TEXTURE; } -GuiImage::GuiImage( int w, int h, GXColor c ) +GuiImage::GuiImage(int w, int h, GXColor c) { - image = ( u8 * )memalign ( 32, w * h * 4 ); + image = (u8 *) memalign(32, w * h * 4); width = w; height = h; imageangle = 0; @@ -103,33 +103,33 @@ GuiImage::GuiImage( int w, int h, GXColor c ) yy4 = 0; imgType = IMAGE_COLOR; - if ( !image ) - return; + if (!image) return; int x, y; - for ( y = 0; y < h; y++ ) + for (y = 0; y < h; y++) { - for ( x = 0; x < w; x++ ) + for (x = 0; x < w; x++) { - this->SetPixel( x, y, c ); + this->SetPixel(x, y, c); } } int len = w * h * 4; - if ( len % 32 ) len += ( 32 - len % 32 ); - DCFlushRange( image, len ); + if (len % 32) len += (32 - len % 32); + DCFlushRange(image, len); } -GuiImage::GuiImage( GuiImage &srcimage ) : GuiElement() +GuiImage::GuiImage(GuiImage &srcimage) : + GuiElement() { width = srcimage.GetWidth(); height = srcimage.GetHeight(); int len = width * height * 4; - if ( len % 32 ) len += ( 32 - len % 32 ); - image = ( u8 * )memalign ( 32, len ); - memcpy( image, srcimage.GetImage(), len ); - DCFlushRange( image, len ); - imageangle = srcimage.GetAngle(); + 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; @@ -145,16 +145,17 @@ GuiImage::GuiImage( GuiImage &srcimage ) : GuiElement() imgType = IMAGE_COPY; } -GuiImage::GuiImage( GuiImage *srcimage ) : GuiElement() +GuiImage::GuiImage(GuiImage *srcimage) : + GuiElement() { width = srcimage->GetWidth(); height = srcimage->GetHeight(); int len = width * height * 4; - if ( len % 32 ) len += ( 32 - len % 32 ); - image = ( u8 * )memalign ( 32, len ); - memcpy( image, srcimage->GetImage(), len ); - DCFlushRange( image, len ); - imageangle = srcimage->GetAngle(); + 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; @@ -170,21 +171,21 @@ GuiImage::GuiImage( GuiImage *srcimage ) : GuiElement() imgType = IMAGE_COPY; } -GuiImage &GuiImage::operator=( GuiImage & srcimage ) +GuiImage &GuiImage::operator=(GuiImage & srcimage) { - if ( ( imgType == IMAGE_COLOR || imgType == IMAGE_COPY ) && image ) + if ((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { - free( image ); + free(image); image = NULL; } width = srcimage.GetWidth(); height = srcimage.GetHeight(); int len = width * height * 4; - if ( len % 32 ) len += ( 32 - len % 32 ); - image = ( u8 * )memalign ( 32, len ); - memcpy( image, srcimage.GetImage(), len ); - DCFlushRange( image, len ); + 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; @@ -207,9 +208,9 @@ GuiImage &GuiImage::operator=( GuiImage & srcimage ) */ GuiImage::~GuiImage() { - if ( ( imgType == IMAGE_COLOR || imgType == IMAGE_COPY ) && image ) + if ((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { - free( image ); + free(image); image = NULL; } } @@ -219,12 +220,12 @@ u8 * GuiImage::GetImage() return image; } -void GuiImage::SetImage( GuiImageData * img ) +void GuiImage::SetImage(GuiImageData * img) { LOCK( this ); - if ( ( imgType == IMAGE_COLOR || imgType == IMAGE_COPY ) && image ) + if ((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { - free( image ); + free(image); image = NULL; } @@ -234,12 +235,12 @@ void GuiImage::SetImage( GuiImageData * img ) imgType = IMAGE_DATA; } -void GuiImage::SetImage( u8 * img, int w, int h ) +void GuiImage::SetImage(u8 * img, int w, int h) { LOCK( this ); - if ( ( imgType == IMAGE_COLOR || imgType == IMAGE_COPY ) && image ) + if ((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { - free( image ); + free(image); image = NULL; } image = img; @@ -248,7 +249,7 @@ void GuiImage::SetImage( u8 * img, int w, int h ) imgType = IMAGE_TEXTURE; } -void GuiImage::SetAngle( float a ) +void GuiImage::SetAngle(float a) { LOCK( this ); imageangle = a; @@ -258,86 +259,84 @@ float GuiImage::GetAngle() return imageangle; } -void GuiImage::SetTile( int t ) +void GuiImage::SetTile(int t) { LOCK( this ); tile = t; } -void GuiImage::SetWidescreen( bool w ) +void GuiImage::SetWidescreen(bool w) { LOCK( this ); widescreen = w; } -void GuiImage::SetParentAngle( bool a ) +void GuiImage::SetParentAngle(bool a) { LOCK( this ); parentangle = a; } -GXColor GuiImage::GetPixel( int x, int y ) +GXColor GuiImage::GetPixel(int x, int y) { - if ( !image || this->GetWidth() <= 0 || x < 0 || y < 0 ) - return ( GXColor ) {0, 0, 0, 0}; + 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 ); + 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 ); + 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 ) +void GuiImage::SetPixel(int x, int y, GXColor color) { LOCK( this ); - if ( !image || this->GetWidth() <= 0 || x < 0 || y < 0 ) - return; + 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 x = 0; x < width; x++) { - for ( int y = 0; y < height; y++ ) + 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 ); - color.b = *( image + offset + 33 ); + offset = (((y >> 2) << 4) * width) + ((x >> 2) << 6) + (((y % 4 << 2) + x % 4) << 1); + color.r = *(image + offset + 1); + color.g = *(image + offset + 32); + color.b = *(image + offset + 33); - gray = ( 77 * color.r + 150 * color.g + 28 * color.b ) / 255; + gray = (77 * color.r + 150 * color.g + 28 * color.b) / 255; - *( image + offset + 1 ) = gray; - *( image + offset + 32 ) = gray; - *( image + offset + 33 ) = gray; + *(image + offset + 1) = gray; + *(image + offset + 32) = gray; + *(image + offset + 33) = gray; } } 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 ) +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; @@ -349,7 +348,7 @@ void GuiImage::SetSkew( int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, in xx4 = XX4; yy4 = YY4; } -void GuiImage::SetSkew( int *skew ) +void GuiImage::SetSkew(int *skew) { xx1 = *skew++; @@ -362,65 +361,56 @@ void GuiImage::SetSkew( int *skew ) yy4 = *skew; } - - -void GuiImage::ColorStripe( int shift ) +void GuiImage::ColorStripe(int shift) { LOCK( this ); int x, y; GXColor color; int alt = 0; - for ( y = 0; y < this->GetHeight(); y++ ) + for (y = 0; y < this->GetHeight(); y++) { - if ( y % 3 == 0 ) - alt ^= 1; + if (y % 3 == 0) alt ^= 1; - for ( x = 0; x < this->GetWidth(); x++ ) + for (x = 0; x < this->GetWidth(); x++) { - color = GetPixel( x, y ); + color = GetPixel(x, y); - if ( alt ) + if (alt) { - if ( color.r < 255 - shift ) + if (color.r < 255 - shift) color.r += shift; - else - color.r = 255; - if ( color.g < 255 - shift ) + else color.r = 255; + if (color.g < 255 - shift) color.g += shift; - else - color.g = 255; - if ( color.b < 255 - shift ) + else color.g = 255; + if (color.b < 255 - shift) color.b += shift; - else - color.b = 255; + else color.b = 255; color.a = 255; } else { - if ( color.r > shift ) + if (color.r > shift) color.r -= shift; - else - color.r = 0; - if ( color.g > shift ) + else color.r = 0; + if (color.g > shift) color.g -= shift; - else - color.g = 0; - if ( color.b > shift ) + else color.g = 0; + if (color.b > shift) color.b -= shift; - else - color.b = 0; + else color.b = 0; color.a = 255; } - SetPixel( x, y, color ); + 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); } /** @@ -430,39 +420,34 @@ void GuiImage::ColorStripe( int shift ) void GuiImage::Draw() { LOCK( this ); - if ( !image || !this->IsVisible() || tile == 0 ) - return; + if (!image || !this->IsVisible() || tile == 0) return; float currScale = this->GetScale(); int currLeft = this->GetLeft(); float currAngleDyn = this->GetAngleDyn(); - if ( currAngleDyn && parentangle ) - imageangle = currAngleDyn; + if (currAngleDyn && parentangle) imageangle = currAngleDyn; - - - if ( tile > 0 ) + if (tile > 0) { - for ( int i = 0; i < tile; i++ ) - Menu_DrawImg( currLeft + width*i, this->GetTop(), zoffset, width, height, image, imageangle, widescreen ? currScale*0.80 : currScale, currScale, this->GetAlpha(), xx1, yy1, xx2, yy2, xx3, yy3, xx4, yy4 ); + for (int i = 0; i < tile; i++) + Menu_DrawImg(currLeft + width * i, this->GetTop(), 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 (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(); } diff --git a/source/libwiigui/gui_image_async.cpp b/source/libwiigui/gui_image_async.cpp index d84e4eaf..a2fed80c 100644 --- a/source/libwiigui/gui_image_async.cpp +++ b/source/libwiigui/gui_image_async.cpp @@ -14,36 +14,36 @@ #include "gui_image_async.h" static mutex_t debugLock = LWP_MUTEX_NULL; -void debug( int Line, const char* Format, ... ) +void debug(int Line, const char* Format, ...) { - if ( debugLock == 0 ) LWP_MutexInit( &debugLock, false ); + if (debugLock == 0) LWP_MutexInit(&debugLock, false); - LWP_MutexLock( debugLock ); + LWP_MutexLock(debugLock); - FILE *fp = fopen( "SD:/debug.txt", "a" ); - if ( fp ) + 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 ); + 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 ); + vfprintf(fp, format, va); va_end( va ); - fclose( fp ); + fclose(fp); } - LWP_MutexUnlock( debugLock ); + LWP_MutexUnlock(debugLock); } //#define DEBUG(format, ...) debug(__LINE__, format, ##__VA_ARGS__) #define DEBUG(format, ...) -static void *memdup( const void* src, size_t len ) +static void *memdup(const void* src, size_t len) { - void *dst = malloc( len ); - if ( dst ) memcpy( dst, src, len ); + void *dst = malloc(len); + if (dst) memcpy(dst, src, len); return dst; } static std::vector List; @@ -54,25 +54,25 @@ static mutex_t InUseLock = LWP_MUTEX_NULL; static GuiImageAsync *InUse = NULL; static bool Quit = false; static bool CanSleep = true; -void *GuiImageAsyncThread( void *arg ) +void *GuiImageAsyncThread(void *arg) { - while ( !Quit ) + while (!Quit) { - LWP_MutexLock( ListLock ); - if ( List.size() ) + LWP_MutexLock(ListLock); + if (List.size()) { - LWP_MutexLock( InUseLock ); + LWP_MutexLock(InUseLock); InUse = List.front(); - List.erase( List.begin() ); + List.erase(List.begin()); - LWP_MutexUnlock( ListLock ); + LWP_MutexUnlock(ListLock); - if ( InUse ) + if (InUse) { - GuiImageData *data = InUse->callback( InUse->arg ); + GuiImageData *data = InUse->callback(InUse->arg); InUse->loadet_imgdata = data; - if ( InUse->loadet_imgdata && InUse->loadet_imgdata->GetImage() ) + 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 @@ -82,13 +82,12 @@ void *GuiImageAsyncThread( void *arg ) } } InUse = NULL; - LWP_MutexUnlock( InUseLock ); + LWP_MutexUnlock(InUseLock); } else { - LWP_MutexUnlock( ListLock ); - if ( !Quit && CanSleep ) - LWP_SuspendThread( Thread ); + LWP_MutexUnlock(ListLock); + if (!Quit && CanSleep) LWP_SuspendThread(Thread); } CanSleep = true; } @@ -98,28 +97,28 @@ void *GuiImageAsyncThread( void *arg ) static u32 GuiImageAsyncThreadInit() { - if ( 0 == ThreadCount++ ) + if (0 == ThreadCount++) { CanSleep = false; - LWP_MutexInit( &ListLock, false ); - LWP_MutexInit( &InUseLock, false ); - LWP_CreateThread( &Thread, GuiImageAsyncThread, NULL, NULL, 16384, 75 ); -// while(!CanSleep) -// usleep(20); + LWP_MutexInit(&ListLock, false); + LWP_MutexInit(&InUseLock, false); + LWP_CreateThread(&Thread, GuiImageAsyncThread, NULL, NULL, 16384, 75); + // while(!CanSleep) + // usleep(20); } return ThreadCount; } static u32 GuiImageAsyncThreadExit() { - if ( --ThreadCount == 0 ) + if (--ThreadCount == 0) { Quit = true; - LWP_ResumeThread( Thread ); -// while(Quit) -// usleep(20); - LWP_JoinThread( Thread, NULL ); - LWP_MutexDestroy( ListLock ); - LWP_MutexDestroy( InUseLock ); + 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; @@ -127,70 +126,62 @@ static u32 GuiImageAsyncThreadExit() return ThreadCount; } - -static void GuiImageAsyncThread_AddImage( GuiImageAsync* Image ) +static void GuiImageAsyncThread_AddImage(GuiImageAsync* Image) { - LWP_MutexLock( ListLock ); - List.push_back( Image ); - LWP_MutexUnlock( ListLock ); + LWP_MutexLock(ListLock); + List.push_back(Image); + LWP_MutexUnlock(ListLock); CanSleep = false; -// if(LWP_ThreadIsSuspended(Thread)) - LWP_ResumeThread( Thread ); + // if(LWP_ThreadIsSuspended(Thread)) + LWP_ResumeThread(Thread); } -static void GuiImageAsyncThread_RemoveImage( GuiImageAsync* Image ) +static void GuiImageAsyncThread_RemoveImage(GuiImageAsync* Image) { - LWP_MutexLock( ListLock ); - for ( std::vector::iterator iter = List.begin(); iter != List.end(); iter++ ) + LWP_MutexLock(ListLock); + for (std::vector::iterator iter = List.begin(); iter != List.end(); iter++) { - if ( *iter == Image ) + if (*iter == Image) { - List.erase( iter ); - LWP_MutexUnlock( ListLock ); + List.erase(iter); + LWP_MutexUnlock(ListLock); return; } } - if ( InUse == Image ) + if (InUse == Image) { - LWP_MutexLock( InUseLock ); - LWP_MutexUnlock( InUseLock ); + LWP_MutexLock(InUseLock); + LWP_MutexUnlock(InUseLock); } - LWP_MutexUnlock( ListLock ); + LWP_MutexUnlock(ListLock); } - /** * Constructor for the GuiImageAsync class. */ -GuiImageData *StdImageLoaderCallback( void *arg ) +GuiImageData *StdImageLoaderCallback(void *arg) { - return new GuiImageData( ( char* )arg, NULL ); + return new GuiImageData((char*) arg, NULL); } -GuiImageAsync::GuiImageAsync( const char *Filename, GuiImageData * PreloadImg ) : - GuiImage( PreloadImg ), - loadet_imgdata( NULL ), - callback( StdImageLoaderCallback ), - arg( strdup( Filename ) ) +GuiImageAsync::GuiImageAsync(const char *Filename, GuiImageData * PreloadImg) : + GuiImage(PreloadImg), loadet_imgdata(NULL), callback(StdImageLoaderCallback), arg(strdup(Filename)) { GuiImageAsyncThreadInit(); - GuiImageAsyncThread_AddImage( this ); + GuiImageAsyncThread_AddImage(this); } -GuiImageAsync::GuiImageAsync( ImageLoaderCallback Callback, void *Arg, int ArgLen, GuiImageData * PreloadImg ) : - GuiImage( PreloadImg ), - loadet_imgdata( NULL ), - callback( Callback ), - arg( memdup( Arg, ArgLen ) ) +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 ); + GuiImageAsyncThread_AddImage(this); } GuiImageAsync::~GuiImageAsync() { - GuiImageAsyncThread_RemoveImage( this ); + GuiImageAsyncThread_RemoveImage(this); GuiImageAsyncThreadExit(); DEBUG( "Deconstructor %p (loadet_imgdata=%p)", this, loadet_imgdata ); - if ( loadet_imgdata ) delete loadet_imgdata; - if ( arg ) free( arg ); + 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 a951eb93..b003d5d9 100644 --- a/source/libwiigui/gui_image_async.h +++ b/source/libwiigui/gui_image_async.h @@ -3,25 +3,23 @@ #// arg is a pointer created with malloc() // when the image is destroied then will also the arg deleted with free() -typedef GuiImageData * ( *ImageLoaderCallback )( void *arg ); +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(const char *Filename, GuiImageData * PreloadImg); + GuiImageAsync(ImageLoaderCallback Callback, void *arg, int arglen, GuiImageData * PreloadImg); ~GuiImageAsync(); private: GuiImageData *loadet_imgdata; - friend void loader( GuiImageAsync *InUse ); + friend void loader(GuiImageAsync *InUse); - friend void Setter( GuiImageAsync *InUse ); - friend void *GuiImageAsyncThread( void *arg ); + friend void Setter(GuiImageAsync *InUse); + friend void *GuiImageAsyncThread(void *arg); ImageLoaderCallback callback; void *arg; }; - - #endif /*_GUIIMAGEASYNC_H_*/ diff --git a/source/libwiigui/gui_imagedata.cpp b/source/libwiigui/gui_imagedata.cpp index 64df95e3..c3875ba4 100644 --- a/source/libwiigui/gui_imagedata.cpp +++ b/source/libwiigui/gui_imagedata.cpp @@ -33,153 +33,151 @@ extern "C" extern int idiotFlag; extern char idiotChar[50]; -GuiImageData::GuiImageData( const u8 * img ) +GuiImageData::GuiImageData(const u8 * img) { data = NULL; width = 0; height = 0; - if ( img ) + if (img) { PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromBuffer( img ); + IMGCTX ctx = PNGU_SelectImageFromBuffer(img); - if ( !ctx ) - return; + if (!ctx) return; - int res = PNGU_GetImageProperties( ctx, &imgProp ); + int res = PNGU_GetImageProperties(ctx, &imgProp); //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; - if ( res == PNGU_OK ) + if (res == PNGU_OK) { int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if ( len % 32 ) len += ( 32 - len % 32 ); - data = ( u8 * )memalign ( 32, len ); + if (len % 32) len += (32 - len % 32); + data = (u8 *) memalign(32, len); - if ( data ) + if (data) { - res = PNGU_DecodeTo4x4RGBA8 ( ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255 ); + res = PNGU_DecodeTo4x4RGBA8(ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); - if ( res == PNGU_OK ) + if (res == PNGU_OK) { width = imgProp.imgWidth; height = imgProp.imgHeight; - DCFlushRange( data, len ); + DCFlushRange(data, len); } else { - free( data ); + free(data); data = NULL; idiotFlag = 1; - snprintf( idiotChar, sizeof( idiotChar ), "%s", img ); + snprintf(idiotChar, sizeof(idiotChar), "%s", img); } } } - PNGU_ReleaseImageContext ( ctx ); + PNGU_ReleaseImageContext(ctx); } } -GuiImageData::GuiImageData( const u8 * img, int imgSize ) +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 + if (img[0] == 0xFF && img[1] == 0xD8) // IMAGE_JPEG { - LoadJpeg( img, imgSize ); + LoadJpeg(img, imgSize); } } } /** * Constructor for the GuiImageData class. */ -GuiImageData::GuiImageData( const char * imgPath, const u8 * buffer ) +GuiImageData::GuiImageData(const char * imgPath, const u8 * buffer) { data = NULL; width = 0; height = 0; - if ( imgPath ) + if (imgPath) { PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromDevice( imgPath ); + IMGCTX ctx = PNGU_SelectImageFromDevice(imgPath); //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; - if ( ctx ) + if (ctx) { - int res = PNGU_GetImageProperties( ctx, &imgProp ); + int res = PNGU_GetImageProperties(ctx, &imgProp); - if ( res == PNGU_OK ) + if (res == PNGU_OK) { int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if ( len % 32 ) len += ( 32 - len % 32 ); - data = ( u8 * )memalign ( 32, len ); + if (len % 32) len += (32 - len % 32); + data = (u8 *) memalign(32, len); - if ( data ) + if (data) { - res = PNGU_DecodeTo4x4RGBA8 ( ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255 ); + res = PNGU_DecodeTo4x4RGBA8(ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); - if ( res == PNGU_OK ) + if (res == PNGU_OK) { width = imgProp.imgWidth; height = imgProp.imgHeight; - DCFlushRange( data, len ); + DCFlushRange(data, len); } else { - free( data ); + free(data); data = NULL; idiotFlag = 1; - snprintf( idiotChar, sizeof( idiotChar ), "%s", imgPath ); + snprintf(idiotChar, sizeof(idiotChar), "%s", imgPath); } } } - PNGU_ReleaseImageContext ( ctx ); + PNGU_ReleaseImageContext(ctx); } } - if ( !data ) //use buffer data instead + if (!data) //use buffer data instead { width = 0; height = 0; - if ( buffer ) + if (buffer) { PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromBuffer( buffer ); + 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 ) + if (res == PNGU_OK) { int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if ( len % 32 ) len += ( 32 - len % 32 ); - data = ( u8 * )memalign ( 32, len ); + if (len % 32) len += (32 - len % 32); + data = (u8 *) memalign(32, len); - if ( data ) + if (data) { - res = PNGU_DecodeTo4x4RGBA8 ( ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255 ); + res = PNGU_DecodeTo4x4RGBA8(ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); - if ( res == PNGU_OK ) + if (res == PNGU_OK) { width = imgProp.imgWidth; height = imgProp.imgHeight; - DCFlushRange( data, len ); + DCFlushRange(data, len); } else { - free( data ); + free(data); data = NULL; } } } - PNGU_ReleaseImageContext ( ctx ); + PNGU_ReleaseImageContext(ctx); } } } @@ -187,7 +185,8 @@ GuiImageData::GuiImageData( const char * imgPath, const u8 * buffer ) /** * Constructor for the GuiImageData class. */ -GuiImageData::GuiImageData( const char *path, const char *file, const u8 *buffer, bool force_widescreen/*=false*/, const u8 *wbuffer/*=NULL*/ ) +GuiImageData::GuiImageData(const char *path, const char *file, const u8 *buffer, bool force_widescreen/*=false*/, + const u8 *wbuffer/*=NULL*/) { data = NULL; width = 0; @@ -196,100 +195,96 @@ GuiImageData::GuiImageData( const char *path, const char *file, const u8 *buffer char path_16_9[100]; char *imgPath; - snprintf( path_4_3, sizeof( path_4_3 ), "%s%s", path, file ); - if ( force_widescreen ) + 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 ); + snprintf(path_16_9, sizeof(path_16_9), "%sw%s", path, file); imgPath = path_16_9; - if ( wbuffer ) - buffer = wbuffer; + if (wbuffer) buffer = wbuffer; } - else - imgPath = path_4_3; + else imgPath = path_4_3; - for ( ;; ) + for (;;) { - if ( imgPath ) + if (imgPath) { PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromDevice( imgPath ); + IMGCTX ctx = PNGU_SelectImageFromDevice(imgPath); //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; - if ( ctx ) + if (ctx) { - int res = PNGU_GetImageProperties( ctx, &imgProp ); + int res = PNGU_GetImageProperties(ctx, &imgProp); - if ( res == PNGU_OK ) + if (res == PNGU_OK) { int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if ( len % 32 ) len += ( 32 - len % 32 ); - data = ( u8 * )memalign ( 32, len ); + if (len % 32) len += (32 - len % 32); + data = (u8 *) memalign(32, len); - if ( data ) + if (data) { - res = PNGU_DecodeTo4x4RGBA8 ( ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255 ); + res = PNGU_DecodeTo4x4RGBA8(ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); - if ( res == PNGU_OK ) + if (res == PNGU_OK) { width = imgProp.imgWidth; height = imgProp.imgHeight; - DCFlushRange( data, len ); + DCFlushRange(data, len); } else { - free( data ); + free(data); data = NULL; idiotFlag = 1; - snprintf( idiotChar, sizeof( idiotChar ), "%s", imgPath ); + snprintf(idiotChar, sizeof(idiotChar), "%s", imgPath); } } } - PNGU_ReleaseImageContext ( ctx ); + PNGU_ReleaseImageContext(ctx); } } - if ( data || imgPath == path_4_3 ) - break; + if (data || imgPath == path_4_3) break; imgPath = path_4_3; } - if ( !data ) //use buffer data instead + if (!data) //use buffer data instead { width = 0; height = 0; - if ( buffer ) + if (buffer) { PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromBuffer( buffer ); + 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 ) + if (res == PNGU_OK) { int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if ( len % 32 ) len += ( 32 - len % 32 ); - data = ( u8 * )memalign ( 32, len ); + if (len % 32) len += (32 - len % 32); + data = (u8 *) memalign(32, len); - if ( data ) + if (data) { - res = PNGU_DecodeTo4x4RGBA8 ( ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255 ); + res = PNGU_DecodeTo4x4RGBA8(ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); - if ( res == PNGU_OK ) + if (res == PNGU_OK) { width = imgProp.imgWidth; height = imgProp.imgHeight; - DCFlushRange( data, len ); + DCFlushRange(data, len); } else { - free( data ); + free(data); data = NULL; } } } - PNGU_ReleaseImageContext ( ctx ); + PNGU_ReleaseImageContext(ctx); } } } @@ -299,9 +294,9 @@ GuiImageData::GuiImageData( const char *path, const char *file, const u8 *buffer */ GuiImageData::~GuiImageData() { - if ( data ) + if (data) { - free( data ); + free(data); data = NULL; } } @@ -320,40 +315,40 @@ 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 x = 0; x < width; x++) { - for ( int y = 0; y < height; y++ ) + 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 ); - color.b = *( data + offset + 33 ); + offset = (((y >> 2) << 4) * width) + ((x >> 2) << 6) + (((y % 4 << 2) + x % 4) << 1); + color.r = *(data + offset + 1); + color.g = *(data + offset + 32); + color.b = *(data + offset + 33); - gray = ( 77 * color.r + 150 * color.g + 28 * color.b ) / 255; + gray = (77 * color.r + 150 * color.g + 28 * color.b) / 255; - *( data + offset + 1 ) = gray; - *( data + offset + 32 ) = gray; - *( data + offset + 33 ) = gray; + *(data + offset + 1) = gray; + *(data + offset + 32) = gray; + *(data + offset + 33) = gray; } } } // 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 ) +void GuiImageData::LoadJpeg(const u8 *img, int imgSize) { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; int n = imgSize; - while ( n > 1 ) + while (n > 1) { - if ( img[n - 1] == 0xff && img[n] == 0xd9 ) + if (img[n - 1] == 0xff && img[n] == 0xd9) { break; } @@ -361,15 +356,16 @@ void GuiImageData::LoadJpeg( const u8 *img, int imgSize ) } jpeg_create_decompress( &cinfo ); - cinfo.err = jpeg_std_error( &jerr ); + cinfo.err = jpeg_std_error(&jerr); cinfo.progress = NULL; - jpeg_mem_src( &cinfo, ( u8 * ) img, n ); - jpeg_read_header( &cinfo, TRUE ); - jpeg_calc_output_dimensions( &cinfo ); + jpeg_mem_src(&cinfo, (u8 *) img, n); + jpeg_read_header(&cinfo, TRUE); + jpeg_calc_output_dimensions(&cinfo); - if ( cinfo.output_width > new_width || cinfo.output_height > new_height ) + 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; + 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; @@ -377,36 +373,36 @@ void GuiImageData::LoadJpeg( const u8 *img, int imgSize ) cinfo.dct_method = JDCT_IFAST; } - jpeg_start_decompress( &cinfo ); + jpeg_start_decompress(&cinfo); int rowsize = cinfo.output_width * cinfo.num_components; - unsigned char *tempBuffer = ( unsigned char * ) malloc( rowsize * cinfo.output_height ); + 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 ) + while (cinfo.output_scanline < cinfo.output_height) { - jpeg_read_scanlines( &cinfo, row_pointer, 1 ); - memcpy( tempBuffer + location, row_pointer[0], rowsize ); + jpeg_read_scanlines(&cinfo, row_pointer, 1); + 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 ); + 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; - jpeg_finish_decompress( &cinfo ); - jpeg_destroy_decompress( &cinfo ); - free( row_pointer[0] ); - free( tempBuffer ); + jpeg_finish_decompress(&cinfo); + jpeg_destroy_decompress(&cinfo); + free(row_pointer[0]); + free(tempBuffer); } /** @@ -416,41 +412,42 @@ void GuiImageData::LoadJpeg( const u8 *img, int imgSize ) * @param dst * @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; unsigned int ar; unsigned int gb; - unsigned char *p = ( unsigned char* )dst; + unsigned char *p = (unsigned char*) dst; - for ( block = 0; block < height; block += 4 ) + for (block = 0; block < height; block += 4) { - for ( i = 0; i < width; i += 4 ) + for (i = 0; i < width; i += 4) { /* Alpha and Red */ - for ( c = 0; c < 4; ++c ) + for (c = 0; c < 4; ++c) { - for ( ar = 0; ar < 4; ++ar ) + for (ar = 0; ar < 4; ++ar) { /* Alpha pixels */ *p++ = 255; /* Red pixels */ - *p++ = src[( ( i + ar ) + ( ( block + c ) * width ) ) * 3]; + *p++ = src[((i + ar) + ((block + c) * width)) * 3]; } } /* Green and Blue */ - for ( c = 0; c < 4; ++c ) + for (c = 0; c < 4; ++c) { - for ( gb = 0; gb < 4; ++gb ) + for (gb = 0; gb < 4; ++gb) { /* Green pixels */ - *p++ = src[( ( ( i + gb ) + ( ( block + c ) * width ) ) * 3 ) + 1]; + *p++ = src[(((i + gb) + ((block + c) * width)) * 3) + 1]; /* Blue pixels */ - *p++ = src[( ( ( i + gb ) + ( ( block + c ) * width ) ) * 3 ) + 2]; + *p++ = src[(((i + gb) + ((block + c) * width)) * 3) + 2]; } } } /* i */ diff --git a/source/libwiigui/gui_keyboard.cpp b/source/libwiigui/gui_keyboard.cpp index 14aea3ff..376f13ff 100644 --- a/source/libwiigui/gui_keyboard.cpp +++ b/source/libwiigui/gui_keyboard.cpp @@ -18,7 +18,7 @@ */ unsigned int m; //const Key thekeys; -GuiKeyboard::GuiKeyboard( char * t, u32 max, int min, int lang ) +GuiKeyboard::GuiKeyboard(char * t, u32 max, int min, int lang) { width = 540; height = 400; @@ -32,462 +32,261 @@ GuiKeyboard::GuiKeyboard( char * t, u32 max, int min, int lang ) 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 + 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 ) + 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'}, - {':', ';'}, - {'\'', '"'} - }, + 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 ) ); + memcpy(keys, thekeys, sizeof(thekeys)); } //DVORAK// - if ( mode == 1 ) + 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'} - }, + 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 ) ); + { { ';', ':', '\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 ) + 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 ) ); + 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 ) + 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 ) ); + 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 ) + 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 ) ); + 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 ); + 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 ); + 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 ); + trigB->SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); int eurocheck = 0; - if ( mode > 1 ) + if (mode > 1) { eurocheck = -20; } - keyBackImg = new GuiImage( keyMedium ); - keyBackOverImg = new GuiImage( keyMediumOver ); - if ( mode == 3 ) + keyBackImg = new GuiImage(keyMedium); + keyBackOverImg = new GuiImage(keyMediumOver); + if (mode == 3) { - keyBackText = new GuiText( "Retour", 20, ( GXColor ) {0, 0, 0, 0xff} ); + keyBackText = new GuiText("Retour", 20, ( GXColor ) + { 0, 0, 0, 0xff}); } else { - keyBackText = new GuiText( "Back", 20, ( GXColor ) {0, 0, 0, 0xff} ); + 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 = 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->SetLabel(keyBackText); //keyBack->SetSoundOver(keySoundOver); //keyBack->SetSoundClick(keySoundClick); //keyBack->SetTrigger(trigA); - keyBack->SetTrigger( trigB ); - if ( mode > 1 ) + keyBack->SetTrigger(trigB); + if (mode > 1) { - keyBack->SetPosition( 11*42 + 40 + eurocheck, 0*42 + 120 ); + keyBack->SetPosition(11 * 42 + 40 + eurocheck, 0 * 42 + 120); } else { - keyBack->SetPosition( 10*42 + 40 + eurocheck, 0*42 + 120 ); + keyBack->SetPosition(10 * 42 + 40 + eurocheck, 0 * 42 + 120); }//(10*42+40, 0*42+80); //keyBack->SetEffectGrow(); - this->Append( keyBack ); + this->Append(keyBack); - keyClearImg = new GuiImage( keyMedium ); - keyClearOverImg = new GuiImage( keyMediumOver ); - if ( mode == 3 ) + keyClearImg = new GuiImage(keyMedium); + keyClearOverImg = new GuiImage(keyMediumOver); + if (mode == 3) { - keyClearText = new GuiText( "Effacer", 20, ( GXColor ) {0, 0, 0, 0xff} ); + keyClearText = new GuiText("Effacer", 20, ( GXColor ) + { 0, 0, 0, 0xff}); } else { - keyClearText = new GuiText( "Clear", 20, ( GXColor ) {0, 0, 0, 0xff} ); + 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(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->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 ); + 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 ); + 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->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 );} + 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 ); + 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->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 );} + 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 ); + 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->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 ); + 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 ); + 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->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 ); + 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 ); + 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); @@ -497,32 +296,34 @@ GuiKeyboard::GuiKeyboard( char * t, u32 max, int min, int lang ) //keySpace->SetPosition(0+eurocheck, 4*42+120);//(0, 4*42+80); //keySpace->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); //keySpace->SetEffectGrow(); - this->Append( keySpace ); + this->Append(keySpace); char txt[2] = { 0, 0 }; - for ( int i = 0; i < 4; i++ ) + for (int i = 0; i < 4; i++) { - for ( int j = 0; j < 11; j++ ) + for (int j = 0; j < 11; j++) { - if ( keys[i][j].ch != '\0' ) + if (keys[i][j].ch != '\0') { - keyImg[i][j] = new GuiImage( key ); - keyImgOver[i][j] = new GuiImage( keyOver ); + 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 ); + 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]->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] ); + this->Append(keyBtn[i][j]); } } } @@ -544,10 +345,14 @@ GuiKeyboard::~GuiKeyboard() delete keyShiftImg; delete keyShiftOverImg; delete keyShift; - if ( keyAlt ) - {delete keyAlt;} - if ( keyAlt2 ) - {delete keyAlt2;} + if (keyAlt) + { + delete keyAlt; + } + if (keyAlt2) + { + delete keyAlt2; + } delete keyBackText; delete keyBackImg; delete keyBackOverImg; @@ -566,11 +371,11 @@ GuiKeyboard::~GuiKeyboard() delete trigA; delete trigB; - for ( int i = 0; i < 4; i++ ) + for (int i = 0; i < 4; i++) { - for ( int j = 0; j < 11; j++ ) + for (int j = 0; j < 11; j++) { - if ( keys[i][j].ch != '\0' ) + if (keys[i][j].ch != '\0') { delete keyImg[i][j]; delete keyImgOver[i][j]; @@ -581,79 +386,82 @@ GuiKeyboard::~GuiKeyboard() } } -void GuiKeyboard::Update( GuiTrigger * t ) +void GuiKeyboard::Update(GuiTrigger * t) { LOCK( this ); - if ( _elements.size() == 0 || ( state == STATE_DISABLED && parentElement ) ) - return; + if (_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) return; - for ( u8 i = 0; i < _elements.size(); i++ ) + for (u8 i = 0; i < _elements.size(); i++) { - try { _elements.at( i )->Update( t ); } - catch ( const std::exception& e ) { } + try + { + _elements.at(i)->Update(t); + } + catch (const std::exception& e) + { + } } bool changedShiftKey = false; - if ( keySpace->GetState() == STATE_CLICKED ) + if (keySpace->GetState() == STATE_CLICKED) { - if ( strlen( kbtextstr ) < kbtextmaxlen - 1 ) // -1 --> kbtextmaxlen means with terminating '\0' + if (strlen(kbtextstr) < kbtextmaxlen - 1) // -1 --> kbtextmaxlen means with terminating '\0' { - kbtextstr[strlen( kbtextstr )] = ' '; - kbText->SetText( kbtextstr ); + kbtextstr[strlen(kbtextstr)] = ' '; + kbText->SetText(kbtextstr); } - keySpace->SetState( STATE_SELECTED, t->chan ); + keySpace->SetState(STATE_SELECTED, t->chan); } - else if ( keyBack->GetState() == STATE_CLICKED ) + else if (keyBack->GetState() == STATE_CLICKED) { - if ( strlen( kbtextstr ) > ( m ) ) + if (strlen(kbtextstr) > (m)) { - kbtextstr[strlen( kbtextstr )-1] = 0; - kbText->SetText( kbtextstr ); + kbtextstr[strlen(kbtextstr) - 1] = 0; + kbText->SetText(kbtextstr); } - keyBack->SetState( STATE_SELECTED, t->chan ); + keyBack->SetState(STATE_SELECTED, t->chan); } - else if ( keyClear->GetState() == STATE_CLICKED ) + else if (keyClear->GetState() == STATE_CLICKED) { - while ( strlen( kbtextstr ) > ( m ) ) + while (strlen(kbtextstr) > (m)) { - kbtextstr[strlen( kbtextstr )-1] = 0; - kbText->SetText( kbtextstr ); + kbtextstr[strlen(kbtextstr) - 1] = 0; + kbText->SetText(kbtextstr); } - keyClear->SetState( STATE_SELECTED, t->chan ); + keyClear->SetState(STATE_SELECTED, t->chan); } - else if ( keyShift->GetState() == STATE_CLICKED ) + else if (keyShift->GetState() == STATE_CLICKED) { changedShiftKey = true; shift ^= 1; - if ( alt ) alt ^= 1; - if ( alt2 ) alt2 ^= 1; - keyShift->SetState( STATE_SELECTED, t->chan ); + if (alt) alt ^= 1; + if (alt2) alt2 ^= 1; + keyShift->SetState(STATE_SELECTED, t->chan); } - else if ( keyAlt->GetState() == STATE_CLICKED ) + else if (keyAlt->GetState() == STATE_CLICKED) { changedShiftKey = true; alt ^= 1; - if ( shift ) shift ^= 1; - if ( alt2 ) alt2 ^= 1; - keyAlt->SetState( STATE_SELECTED, t->chan ); + if (shift) shift ^= 1; + if (alt2) alt2 ^= 1; + keyAlt->SetState(STATE_SELECTED, t->chan); } - else if ( keyAlt2->GetState() == STATE_CLICKED ) + else if (keyAlt2->GetState() == STATE_CLICKED) { changedShiftKey = true; alt2 ^= 1; - if ( shift ) shift ^= 1; - if ( alt ) alt ^= 1; - keyAlt2->SetState( STATE_SELECTED, t->chan ); + if (shift) shift ^= 1; + if (alt) alt ^= 1; + keyAlt2->SetState(STATE_SELECTED, t->chan); } - else if ( keyCaps->GetState() == STATE_CLICKED ) + else if (keyCaps->GetState() == STATE_CLICKED) { changedShiftKey = true; caps ^= 1; - keyCaps->SetState( STATE_SELECTED, t->chan ); + keyCaps->SetState(STATE_SELECTED, t->chan); } - bool update = false; char txt[2] = { 0, 0 }; @@ -661,38 +469,37 @@ void GuiKeyboard::Update( GuiTrigger * t ) do { update = false; - for ( int i = 0; i < 4; i++ ) + for (int i = 0; i < 4; i++) { - for ( int j = 0; j < 11; j++ ) + for (int j = 0; j < 11; j++) { - if ( keys[i][j].ch != '\0' ) + if (keys[i][j].ch != '\0') { - if ( shift || caps ) + if (shift || caps) txt[0] = keys[i][j].chShift; - else if ( alt ) + else if (alt) txt[0] = keys[i][j].chalt; - else if ( alt2 ) + else if (alt2) txt[0] = keys[i][j].chalt2; - else - txt[0] = keys[i][j].ch; + 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 (keyBtn[i][j]->GetState() == STATE_CLICKED) { - if ( strlen( kbtextstr ) < kbtextmaxlen - 1 ) // -1 --> kbtextmaxlen means with term. '\0' + if (strlen(kbtextstr) < kbtextmaxlen - 1) // -1 --> kbtextmaxlen means with term. '\0' { - kbtextstr[strlen( kbtextstr )] = txt[0]; - kbText->SetText( kbtextstr ); + kbtextstr[strlen(kbtextstr)] = txt[0]; + kbText->SetText(kbtextstr); } - keyBtn[i][j]->SetState( STATE_SELECTED, t->chan ); + keyBtn[i][j]->SetState(STATE_SELECTED, t->chan); - if ( shift || alt || alt2 ) + if (shift || alt || alt2) { - if ( shift ) shift ^= 1; - if ( alt ) alt ^= 1; - if ( alt2 ) alt2 ^= 1; + if (shift) shift ^= 1; + if (alt) alt ^= 1; + if (alt2) alt2 ^= 1; update = true; changedShiftKey = true; } @@ -700,23 +507,21 @@ void GuiKeyboard::Update( GuiTrigger * t ) } } } - } - while ( update ); + } while (update); - 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 + 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 (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 1e8543fc..9021f724 100644 --- a/source/libwiigui/gui_numpad.cpp +++ b/source/libwiigui/gui_numpad.cpp @@ -19,7 +19,7 @@ #define SAFEFREE(p) if(p){free(p);p=NULL;} -GuiNumpad::GuiNumpad( char * t, u32 max ) +GuiNumpad::GuiNumpad(char * t, u32 max) { width = 400; height = 370; @@ -27,70 +27,77 @@ GuiNumpad::GuiNumpad( char * t, u32 max ) 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 + 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 char thekeys[11] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '\0', '0' }; - memcpy( keys, thekeys, sizeof( thekeys ) ); + 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 ); + 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 ); + 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 ); + 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++ ) + for (int i = 0; i < 11; i++) { - if ( keys[i] != '\0' ) + if (keys[i] != '\0') { int col = i % 3; int row = i / 3; - keyImg[i] = new GuiImage( keyMedium ); - keyImgOver[i] = new GuiImage( keyMediumOver ); + 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] ); + 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]); } } } @@ -118,9 +125,9 @@ GuiNumpad::~GuiNumpad() SAFEFREE( trigA ) SAFEFREE( trigB ) - for ( int i = 0; i < 11; i++ ) + for (int i = 0; i < 11; i++) { - if ( keys[i] != '\0' ) + if (keys[i] != '\0') { SAFEFREE( keyImg[i] ) SAFEFREE( keyImgOver[i] ) @@ -130,66 +137,69 @@ GuiNumpad::~GuiNumpad() } } -void GuiNumpad::Update( GuiTrigger * t ) +void GuiNumpad::Update(GuiTrigger * t) { LOCK( this ); - if ( _elements.size() == 0 || ( state == STATE_DISABLED && parentElement ) ) - return; + if (_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) return; - for ( u8 i = 0; i < _elements.size(); i++ ) + 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 ) + try + { + _elements.at(i)->Update(t); + } + catch (const std::exception& e) { - kbtextstr[strlen( kbtextstr )-1] = 0; - kbText->SetText( kbtextstr ); } - keyBack->SetState( STATE_SELECTED, t->chan ); } - else if ( keyClear->GetState() == STATE_CLICKED ) + + if (keyBack->GetState() == STATE_CLICKED) { - memset( kbtextstr, 0, sizeof( kbtextstr ) ); - kbText->SetText( kbtextstr ); - keyClear->SetState( STATE_SELECTED, t->chan ); + 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++ ) + for (int i = 0; i < 11; i++) { - if ( keys[i] != '\0' ) + if (keys[i] != '\0') { - if ( keyBtn[i]->GetState() == STATE_CLICKED ) + if (keyBtn[i]->GetState() == STATE_CLICKED) { txt[0] = keys[i]; - if ( strlen( kbtextstr ) < kbtextmaxlen - 1 ) // -1 --> kbtextmaxlen means with term. '\0' + if (strlen(kbtextstr) < kbtextmaxlen - 1) // -1 --> kbtextmaxlen means with term. '\0' { - kbtextstr[strlen( kbtextstr )] = txt[0]; - kbText->SetText( kbtextstr ); + kbtextstr[strlen(kbtextstr)] = txt[0]; + kbText->SetText(kbtextstr); } - keyBtn[i]->SetState( STATE_SELECTED, t->chan ); + 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 + 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 (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 71428ebb..3ff0df1c 100644 --- a/source/libwiigui/gui_optionbrowser.cpp +++ b/source/libwiigui/gui_optionbrowser.cpp @@ -14,238 +14,242 @@ #include - #define GAMESELECTSIZE 30 static int scrollbaron, startat, loaded = 0; /** * Constructor for the GuiOptionBrowser class. */ -GuiOptionBrowser::GuiOptionBrowser( int w, int h, OptionList * l, const u8 *imagebg, int scrollon ) +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 ); + 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->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 ); - if ( scrollbaron == 1 ) + 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; i < PAGESIZE; i++ ) + // optionBg = new GuiImage(bgOptionsEntry); + for (int i = 0; i < PAGESIZE; i++) { - optionTxt[i] = new GuiText( ( char * ) NULL, 20, ( GXColor ) {0, 0, 0, 0xff} ); - optionTxt[i]->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - optionTxt[i]->SetPosition( 24, 0 ); + optionTxt[i] = new GuiText((char *) NULL, 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( ( char * ) NULL, 20, ( GXColor ) {0, 0, 0, 0xff} ); - optionVal[i]->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - optionVal[i]->SetPosition( 250, 0 ); + optionVal[i] = new GuiText((char *) 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 ) +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; + startat = start; loaded = 0; scrollbaron = scrollon; selectable = true; - listOffset = this->FindMenuItem( -1, 1 ); + 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->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 ); - if ( scrollbaron == 1 ) + 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; i < PAGESIZE; i++ ) + // optionBg = new GuiImage(bgOptionsEntry); + for (int i = 0; i < PAGESIZE; i++) { - optionTxt[i] = new GuiText( options->name[i], 20, ( GXColor ) {0, 0, 0, 0xff} ); - optionTxt[i]->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - optionTxt[i]->SetPosition( 24, 0 ); + optionTxt[i] = new GuiText(options->name[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( ( char * ) NULL, 20, ( GXColor ) {0, 0, 0, 0xff} ); - optionVal[i]->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - optionVal[i]->SetPosition( 250, 0 ); + optionVal[i] = new GuiText((char *) 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); } } @@ -254,7 +258,7 @@ GuiOptionBrowser::GuiOptionBrowser( int w, int h, OptionList * l, const char *th */ GuiOptionBrowser::~GuiOptionBrowser() { - if ( scrollbaron == 1 ) + if (scrollbaron == 1) { delete arrowUpBtn; delete arrowDownBtn; @@ -282,8 +286,8 @@ GuiOptionBrowser::~GuiOptionBrowser() delete trigA; delete btnSoundClick; -// delete optionBg; - for ( int i = 0; i < PAGESIZE; i++ ) + // delete optionBg; + for (int i = 0; i < PAGESIZE; i++) { delete optionTxt[i]; delete optionVal[i]; @@ -292,35 +296,34 @@ GuiOptionBrowser::~GuiOptionBrowser() } } -void GuiOptionBrowser::SetCol2Position( int x ) +void GuiOptionBrowser::SetCol2Position(int x) { LOCK( this ); - for ( int i = 0; i < PAGESIZE; i++ ) - optionVal[i]->SetPosition( x, 0 ); + for (int i = 0; i < PAGESIZE; i++) + optionVal[i]->SetPosition(x, 0); } -void GuiOptionBrowser::SetFocus( int f ) +void GuiOptionBrowser::SetFocus(int f) { LOCK( this ); focus = f; - for ( int i = 0; i < PAGESIZE; i++ ) + for (int i = 0; i < PAGESIZE; i++) optionBtn[i]->ResetState(); - 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 ) + if (state != STATE_DISABLED) { state = STATE_DEFAULT; stateChan = -1; } - for ( int i = 0; i < PAGESIZE; i++ ) + for (int i = 0; i < PAGESIZE; i++) { optionBtn[i]->ResetState(); } @@ -329,11 +332,11 @@ void GuiOptionBrowser::ResetState() int GuiOptionBrowser::GetClickedOption() { int found = -1; - for ( int i = 0; i < PAGESIZE; i++ ) + for (int i = 0; i < PAGESIZE; i++) { - if ( optionBtn[i]->GetState() == STATE_CLICKED ) + if (optionBtn[i]->GetState() == STATE_CLICKED) { - optionBtn[i]->SetState( STATE_SELECTED ); + optionBtn[i]->SetState(STATE_SELECTED); found = optionIndex[i]; break; } @@ -344,11 +347,11 @@ int GuiOptionBrowser::GetClickedOption() int GuiOptionBrowser::GetSelectedOption() { int found = -1; - for ( int i = 0; i < PAGESIZE; i++ ) + for (int i = 0; i < PAGESIZE; i++) { - if ( optionBtn[i]->GetState() == STATE_SELECTED ) + if (optionBtn[i]->GetState() == STATE_SELECTED) { - optionBtn[i]->SetState( STATE_SELECTED ); + optionBtn[i]->SetState(STATE_SELECTED); found = optionIndex[i]; break; } @@ -362,17 +365,15 @@ int GuiOptionBrowser::GetSelectedOption() * Help function to find the next visible menu item on the list ***************************************************************************/ -int GuiOptionBrowser::FindMenuItem( int currentItem, int 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 ) + if (strlen(options->name[nextItem]) > 0) return nextItem; - else - return FindMenuItem( nextItem, direction ); + else return FindMenuItem(nextItem, direction); } /** @@ -381,25 +382,23 @@ int GuiOptionBrowser::FindMenuItem( int currentItem, int direction ) void GuiOptionBrowser::Draw() { LOCK( this ); - if ( !this->IsVisible() ) - return; + if (!this->IsVisible()) return; bgOptionsImg->Draw(); int next = listOffset; - for ( int i = 0; i < PAGESIZE; i++ ) + for (int i = 0; i < PAGESIZE; i++) { - if ( next >= 0 ) + if (next >= 0) { optionBtn[i]->Draw(); - next = this->FindMenuItem( next, 1 ); + next = this->FindMenuItem(next, 1); } - else - break; + else break; } - if ( scrollbaron == 1 ) + if (scrollbaron == 1) { scrollbarImg->Draw(); arrowUpBtn->Draw(); @@ -409,141 +408,135 @@ void GuiOptionBrowser::Draw() this->UpdateEffects(); } - void GuiOptionBrowser::TriggerUpdate() { listChanged = true; } -void GuiOptionBrowser::Update( GuiTrigger * t ) +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 ((loaded == 0) && (startat > 0)) { - if ( startat > ( lang - 9 ) ) + if (startat > (lang - 9)) { - listOffset = ( lang - 9 ); + listOffset = (lang - 9); selectedItem = startat; - optionBtn[selectedItem]->SetState( STATE_SELECTED, t->chan ); + optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan); } - else if ( startat < 9 ) + else if (startat < 9) { selectedItem = startat; - optionBtn[selectedItem]->SetState( STATE_SELECTED, t->chan ); + optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan); } else { - listOffset = ( startat - 4 ); + listOffset = (startat - 4); selectedItem = startat; - optionBtn[selectedItem]->SetState( STATE_SELECTED, t->chan ); + optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan); } - this->SetFocus( 1 ); + this->SetFocus(1); loaded = 1; } - if ( state == STATE_DISABLED || !t ) - return; - + 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 ) + 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 ); + arrowUpBtn->Update(t); + arrowDownBtn->Update(t); + scrollbarBoxBtn->Update(t); } next = listOffset; - if ( listChanged ) + if (listChanged) { - for ( int i = 0; i < PAGESIZE; i++ ) + for (int i = 0; i < PAGESIZE; i++) { - if ( next >= 0 ) + if (next >= 0) { - if ( optionBtn[i]->GetState() == STATE_DISABLED ) + if (optionBtn[i]->GetState() == STATE_DISABLED) { - optionBtn[i]->SetVisible( true ); - optionBtn[i]->SetState( STATE_DEFAULT ); + optionBtn[i]->SetVisible(true); + optionBtn[i]->SetState(STATE_DEFAULT); } - optionTxt[i]->SetText( options->name[next] ); - optionVal[i]->SetText( options->value[next] ); + optionTxt[i]->SetText(options->name[next]); + optionVal[i]->SetText(options->value[next]); optionIndex[i] = next; - next = this->FindMenuItem( next, 1 ); + next = this->FindMenuItem(next, 1); } else { - optionBtn[i]->SetVisible( false ); - optionBtn[i]->SetState( STATE_DISABLED ); + optionBtn[i]->SetVisible(false); + optionBtn[i]->SetState(STATE_DISABLED); } } } - for ( int i = 0; i < PAGESIZE; i++ ) + for (int i = 0; i < PAGESIZE; i++) { - if ( focus ) + if (focus) { - if ( i != selectedItem && optionBtn[i]->GetState() == STATE_SELECTED ) + 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, t->chan ); + else if (i == selectedItem && optionBtn[i]->GetState() == STATE_DEFAULT) optionBtn[selectedItem]->SetState( + STATE_SELECTED, t->chan); } - optionBtn[i]->Update( t ); + optionBtn[i]->Update(t); - if ( optionBtn[i]->GetState() == STATE_SELECTED ) + if (optionBtn[i]->GetState() == STATE_SELECTED) { selectedItem = i; } } // pad/joystick navigation - if ( !focus ) - return; // skip navigation + if (!focus) return; // skip navigation - if ( scrollbaron == 1 ) + if (scrollbaron == 1) { - if ( t->Down() || - arrowDownBtn->GetState() == STATE_CLICKED || ////////////////////////////////////////////down - arrowDownBtn->GetState() == STATE_HELD ) + if (t->Down() || arrowDownBtn->GetState() == STATE_CLICKED || ////////////////////////////////////////////down + arrowDownBtn->GetState() == STATE_HELD) { - next = this->FindMenuItem( optionIndex[selectedItem], 1 ); + next = this->FindMenuItem(optionIndex[selectedItem], 1); - if ( next >= 0 ) + if (next >= 0) { - if ( selectedItem == PAGESIZE - 1 ) + if (selectedItem == PAGESIZE - 1) { // move list down by 1 - listOffset = this->FindMenuItem( listOffset, 1 ); + listOffset = this->FindMenuItem(listOffset, 1); } - else if ( optionBtn[selectedItem+1]->IsVisible() ) + else if (optionBtn[selectedItem + 1]->IsVisible()) { optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + optionBtn[selectedItem + 1]->SetState(STATE_SELECTED, t->chan); selectedItem++; } scrollbarBoxBtn->Draw(); - usleep( 10000 * scrolldelay ); + usleep(10000 * scrolldelay); - - } WPAD_ScanPads(); + } + WPAD_ScanPads(); u8 cnt, buttons = NULL; /* Get pressed buttons */ - for ( cnt = 0; cnt < 4; cnt++ ) - buttons |= WPAD_ButtonsHeld( cnt ); - if ( buttons == WPAD_BUTTON_A ) + for (cnt = 0; cnt < 4; cnt++) + buttons |= WPAD_ButtonsHeld(cnt); + if (buttons == WPAD_BUTTON_A) { } @@ -554,15 +547,14 @@ void GuiOptionBrowser::Update( GuiTrigger * t ) } } - else if ( t->Up() || - arrowUpBtn->GetState() == STATE_CLICKED || ////////////////////////////////////////////up - arrowUpBtn->GetState() == STATE_HELD ) + else if (t->Up() || arrowUpBtn->GetState() == STATE_CLICKED || ////////////////////////////////////////////up + arrowUpBtn->GetState() == STATE_HELD) { - prev = this->FindMenuItem( optionIndex[selectedItem], -1 ); + prev = this->FindMenuItem(optionIndex[selectedItem], -1); - if ( prev >= 0 ) + if (prev >= 0) { - if ( selectedItem == 0 ) + if (selectedItem == 0) { // move list up by 1 listOffset = prev; @@ -570,19 +562,19 @@ void GuiOptionBrowser::Update( GuiTrigger * t ) else { optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + optionBtn[selectedItem - 1]->SetState(STATE_SELECTED, t->chan); selectedItem--; } scrollbarBoxBtn->Draw(); - usleep( 10000 * scrolldelay ); + usleep(10000 * scrolldelay); - - } WPAD_ScanPads(); + } + WPAD_ScanPads(); u8 cnt, buttons = NULL; /* Get pressed buttons */ - for ( cnt = 0; cnt < 4; cnt++ ) - buttons |= WPAD_ButtonsHeld( cnt ); - if ( buttons == WPAD_BUTTON_A ) + for (cnt = 0; cnt < 4; cnt++) + buttons |= WPAD_ButtonsHeld(cnt); + if (buttons == WPAD_BUTTON_A) { } @@ -593,50 +585,45 @@ void GuiOptionBrowser::Update( GuiTrigger * t ) } } - if ( scrollbarBoxBtn->GetState() == STATE_HELD && - scrollbarBoxBtn->GetStateChan() == t->chan && - t->wpad.ir.valid && options->length > PAGESIZE ) + if (scrollbarBoxBtn->GetState() == STATE_HELD && scrollbarBoxBtn->GetStateChan() == t->chan && t->wpad.ir.valid + && options->length > PAGESIZE) { - scrollbarBoxBtn->SetPosition( width / 2 - 18 + 7, 0 ); + scrollbarBoxBtn->SetPosition(width / 2 - 18 + 7, 0); int position = t->wpad.ir.y - 50 - scrollbarBoxBtn->GetTop(); - listOffset = ( position * lang ) / 180 - selectedItem; + listOffset = (position * lang) / 180 - selectedItem; - if ( listOffset <= 0 ) + if (listOffset <= 0) { listOffset = 0; selectedItem = 0; } - else if ( listOffset + PAGESIZE >= lang ) + else if (listOffset + PAGESIZE >= lang) { listOffset = lang - PAGESIZE; selectedItem = PAGESIZE - 1; } } - int positionbar = 237 * ( listOffset + selectedItem ) / lang; + 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 (t->Right()) { - if ( listOffset < lang && lang > PAGESIZE ) + if (listOffset < lang && lang > PAGESIZE) { listOffset = listOffset + PAGESIZE; - if ( listOffset + PAGESIZE >= lang ) - listOffset = lang - PAGESIZE; + if (listOffset + PAGESIZE >= lang) listOffset = lang - PAGESIZE; } } - else if ( t->Left() ) + else if (t->Left()) { - if ( listOffset > 0 ) + if (listOffset > 0) { listOffset = listOffset - PAGESIZE; - if ( listOffset < 0 ) - listOffset = 0; + if (listOffset < 0) listOffset = 0; } } @@ -644,34 +631,33 @@ void GuiOptionBrowser::Update( GuiTrigger * t ) else { - - if ( t->Down() ) + if (t->Down()) { - next = this->FindMenuItem( optionIndex[selectedItem], 1 ); + next = this->FindMenuItem(optionIndex[selectedItem], 1); - if ( next >= 0 ) + if (next >= 0) { - if ( selectedItem == PAGESIZE - 1 ) + if (selectedItem == PAGESIZE - 1) { // move list down by 1 - listOffset = this->FindMenuItem( listOffset, 1 ); + listOffset = this->FindMenuItem(listOffset, 1); listChanged = true; } - else if ( optionBtn[selectedItem+1]->IsVisible() ) + else if (optionBtn[selectedItem + 1]->IsVisible()) { optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + optionBtn[selectedItem + 1]->SetState(STATE_SELECTED, t->chan); selectedItem++; } } } - else if ( t->Up() ) + else if (t->Up()) { - prev = this->FindMenuItem( optionIndex[selectedItem], -1 ); + prev = this->FindMenuItem(optionIndex[selectedItem], -1); - if ( prev >= 0 ) + if (prev >= 0) { - if ( selectedItem == 0 ) + if (selectedItem == 0) { // move list up by 1 listOffset = prev; @@ -680,13 +666,12 @@ void GuiOptionBrowser::Update( GuiTrigger * t ) else { optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + 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 a7d403be..c7d29207 100644 --- a/source/libwiigui/gui_searchbar.cpp +++ b/source/libwiigui/gui_searchbar.cpp @@ -11,93 +11,92 @@ extern GuiWindow * mainWindow; 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( ( char * ) NULL, 20, ( GXColor ) {0, 0, 0, 0xff} ), - button( &image, &imageOver, ALIGN_LEFT, ALIGN_TOP, x, y, trig, sndOver, sndClick, 1 ) + 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((char *) 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 ); + text.SetText(Char); + button.SetLabel(&text); } - wchar_t wchar; - GuiImage image; - GuiImage imageOver; - GuiText text; - GuiButton button; + wchar_t wchar; + GuiImage image; + GuiImage imageOver; + GuiText text; + GuiButton button; private: }; - -GuiSearchBar::GuiSearchBar( const wchar_t *SearchChars ) - : - inSide( 0 ), - text( ( char * ) 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 ) +GuiSearchBar::GuiSearchBar(const wchar_t *SearchChars) : + inSide(0), text((char *) 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 ); + trig.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - cnt = wcslen( SearchChars ); + cnt = wcslen(SearchChars); buttons = new cSearchButton*[cnt]; - wchar_t charstr[2] = {0, 0}; - int lines = ( cnt + 9 ) / 10; - int buttonsPerLine = ( cnt + lines - 1 ) / lines; + 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 < cnt; i++, x++ ) + if (width < 200) { - if ( x >= buttonsPerLine ) x = 0; - if ( x == 0 ) y++; + x_start += (200 - width) >> 1; + width = 200; + } + for (int i = 0; i < cnt; i++, x++) + { + if (x >= 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 ) ); + 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(gameList.GetCurrentFilter()); + text.SetPosition(10, 15); + text.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + text.SetWidescreen(Settings.widescreen); + text.SetMaxWidth(width - (10 + 2 * 42 + 10), SCROLL_HORIZONTAL); + this->Append(&text); - text.SetText( gameList.GetCurrentFilter() ); - text.SetPosition( 10, 15 ); - text.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - text.SetWidescreen( Settings.widescreen ); - text.SetMaxWidth( width - ( 10 + 2*42 + 10 ), SCROLL_HORIZONTAL ); - this->Append( &text ); + snprintf(imgPath, sizeof(imgPath), "%skeyboard_backspace_over.png", Settings.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); - snprintf( imgPath, sizeof( imgPath ), "%skeyboard_backspace_over.png", Settings.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 ); + snprintf(imgPath, sizeof(imgPath), "%skeyboard_clear_over.png", Settings.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); - snprintf( imgPath, sizeof( imgPath ), "%skeyboard_clear_over.png", Settings.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 ); - - -// SetPosition(100,100); + // SetPosition(100,100); } GuiSearchBar::~GuiSearchBar() { - if ( buttons ) + if (buttons) { - for ( int i = 0; i < cnt; i++ ) + for (int i = 0; i < cnt; i++) delete buttons[i]; - delete [] buttons; + delete[] buttons; } delete ClearBtn; delete ClearBtnImg; @@ -108,65 +107,61 @@ GuiSearchBar::~GuiSearchBar() delete BacspaceBtnImg; delete BacspaceBtnImg_Over; delete imgBacspaceBtn; - if ( inSide ) - mainWindow->SetState( STATE_DEFAULT ); + 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 ); + 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 ) +void GuiSearchBar::Update(GuiTrigger * t) { LOCK( this ); - if ( _elements.size() == 0 || ( state == STATE_DISABLED && parentElement ) ) - return; + if (_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) return; // cursor - if ( t->wpad.ir.valid && state != STATE_DISABLED ) + if (t->wpad.ir.valid && state != STATE_DISABLED) { - if ( this->IsInside( t->wpad.ir.x, t->wpad.ir.y ) ) + if (this->IsInside(t->wpad.ir.x, t->wpad.ir.y)) { - if ( inSide == 0 ) + if (inSide == 0) { - mainWindow->SetState( STATE_DISABLED ); - this->SetState( STATE_DEFAULT ); + mainWindow->SetState(STATE_DISABLED); + this->SetState(STATE_DEFAULT); } inSide |= 1 << t->chan; } - else if ( inSide ) + else if (inSide) { - inSide &= ~( 1 << t->chan ); - if ( inSide == 0 ) - mainWindow->SetState( STATE_DEFAULT ); + inSide &= ~(1 << t->chan); + if (inSide == 0) mainWindow->SetState(STATE_DEFAULT); } } - GuiWindow::Update( t ); + GuiWindow::Update(t); } wchar_t GuiSearchBar::GetClicked() { - if ( buttons ) + if (buttons) { - for ( int i = 0; i < cnt; i++ ) + for (int i = 0; i < cnt; i++) { - if ( buttons[i]->button.GetState() == STATE_CLICKED ) + if (buttons[i]->button.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; + if (BacspaceBtn->GetState() == STATE_CLICKED) return 8; + if (ClearBtn->GetState() == STATE_CLICKED) return 7; return 0; } /* -private: - SearchButtons *buttons; -}*/ - + private: + SearchButtons *buttons; + }*/ diff --git a/source/libwiigui/gui_searchbar.h b/source/libwiigui/gui_searchbar.h index 3665e3b5..f3cd7d01 100644 --- a/source/libwiigui/gui_searchbar.h +++ b/source/libwiigui/gui_searchbar.h @@ -1,38 +1,36 @@ #include "gui.h" - class cSearchButton; - -class GuiSearchBar : public GuiWindow +class GuiSearchBar: public GuiWindow { public: - GuiSearchBar( const wchar_t *SearchChars ); + GuiSearchBar(const wchar_t *SearchChars); ~GuiSearchBar(); void Draw(); - void Update( GuiTrigger * t ); + void Update(GuiTrigger * t); wchar_t GetClicked(); private: - u16 inSide; + u16 inSide; - GuiText text; + GuiText text; - GuiImageData* imgBacspaceBtn; - GuiImage* BacspaceBtnImg; - GuiImage* BacspaceBtnImg_Over; - GuiButton* BacspaceBtn; + GuiImageData* imgBacspaceBtn; + GuiImage* BacspaceBtnImg; + GuiImage* BacspaceBtnImg_Over; + GuiButton* BacspaceBtn; - GuiImageData* imgClearBtn; - GuiImage* ClearBtnImg; - GuiImage* ClearBtnImg_Over; - GuiButton* ClearBtn; + GuiImageData* imgClearBtn; + GuiImage* ClearBtnImg; + GuiImage* ClearBtnImg_Over; + GuiButton* ClearBtn; - cSearchButton **buttons; - int cnt; - GuiImageData keyImageData; - GuiImageData keyOverImageData; - GuiTrigger trig; - GuiSound sndOver; - GuiSound sndClick; + 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 90c408a3..2442fed2 100644 --- a/source/libwiigui/gui_sound.cpp +++ b/source/libwiigui/gui_sound.cpp @@ -16,10 +16,8 @@ #include "gui_sound_decoder.h" - #define BUFFER_SIZE 8192 - /*************************************************************** * * D E C O D E R – L I S T @@ -28,9 +26,10 @@ ***************************************************************/ GuiSoundDecoder::DecoderListEntry *GuiSoundDecoder::DecoderList = NULL; -GuiSoundDecoder::DecoderListEntry &GuiSoundDecoder::RegisterDecoder( DecoderListEntry &Decoder, GuiSoundDecoderCreate fnc ) +GuiSoundDecoder::DecoderListEntry &GuiSoundDecoder::RegisterDecoder(DecoderListEntry &Decoder, + GuiSoundDecoderCreate fnc) { - if ( Decoder.fnc != fnc ) + if (Decoder.fnc != fnc) { Decoder.fnc = fnc; Decoder.next = DecoderList; @@ -38,23 +37,27 @@ GuiSoundDecoder::DecoderListEntry &GuiSoundDecoder::RegisterDecoder( DecoderList } return Decoder; } -GuiSoundDecoder *GuiSoundDecoder::GetDecoder( const u8 * snd, u32 len, bool snd_is_allocated ) +GuiSoundDecoder *GuiSoundDecoder::GetDecoder(const u8 * snd, u32 len, bool snd_is_allocated) { - for ( DecoderListEntry *de = DecoderList; de; de = de->next ) + for (DecoderListEntry *de = DecoderList; de; de = de->next) { GuiSoundDecoder *d = NULL; - try { d = de->fnc( snd, len, snd_is_allocated ); } - catch ( const char *error ) + try { - gprintf( "%s", error ); + d = de->fnc(snd, len, snd_is_allocated); } - catch ( ... ) {} - if ( d ) return d; + 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 @@ -62,32 +65,30 @@ GuiSoundDecoder *GuiSoundDecoder::GetDecoder( const u8 * snd, u32 len, bool snd_ * ***************************************************************/ -static GuiSound *GuiSoundPlayer[16] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; +static GuiSound *GuiSoundPlayer[16] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, NULL, NULL }; -static lwp_t GuiSoundDecoderThreadHandle = LWP_THREAD_NULL; -static bool GuiSoundDecoderThreadRunning = false; +static lwp_t GuiSoundDecoderThreadHandle = LWP_THREAD_NULL; +static bool GuiSoundDecoderThreadRunning = false; static bool GuiSoundDecoderDataRquested = false; -void *GuiSoundDecoderThread( void *args ) +void *GuiSoundDecoderThread(void *args) { GuiSoundDecoderThreadRunning = true; do { - if ( GuiSoundDecoderDataRquested ) + if (GuiSoundDecoderDataRquested) { GuiSoundDecoderDataRquested = false; GuiSound **players = GuiSoundPlayer; - for ( int i = 0; i < 16; ++i , ++players ) + for (int i = 0; i < 16; ++i, ++players) { GuiSound *player = *players; - if ( player ) - player->DecoderCallback(); + if (player) player->DecoderCallback(); } } - if ( !GuiSoundDecoderDataRquested ) - usleep( 50 ); - } - while ( GuiSoundDecoderThreadRunning ); + if (!GuiSoundDecoderDataRquested) usleep(50); + } while (GuiSoundDecoderThreadRunning); return 0; } @@ -98,9 +99,9 @@ void *GuiSoundDecoderThread( void *args ) * ***************************************************************/ -void GuiSoundPlayerCallback( s32 Voice ) +void GuiSoundPlayerCallback(s32 Voice) { - if ( Voice >= 0 && Voice < 16 && GuiSoundPlayer[Voice] ) + if (Voice >= 0 && Voice < 16 && GuiSoundPlayer[Voice]) { GuiSoundPlayer[Voice]->PlayerCallback(); GuiSoundDecoderDataRquested = true; @@ -113,28 +114,34 @@ 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 ) + 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; + 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; + while (is_running) + usleep(50); + if (is_allocated) delete[] pcm_start; } - static GuiSoundDecoder *Create( const u8 * snd, u32 len, bool snd_is_allocated ) + static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) { - try { return new GuiSoundDecoderRAW( snd, len, snd_is_allocated ); } - catch ( ... ) {} + try + { + return new GuiSoundDecoderRAW(snd, len, snd_is_allocated); + } + catch (...) + { + } return NULL; } s32 GetFormat() @@ -146,19 +153,17 @@ class GuiSoundDecoderRAW : public GuiSoundDecoder return 48000; } /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read( u8 * buffer, int buffer_size ) + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read(u8 * buffer, int buffer_size) { - if ( pos >= pcm_end ) - return 0; // EOF + 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 ); + 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; @@ -169,11 +174,11 @@ class GuiSoundDecoderRAW : public GuiSoundDecoder 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; }; @@ -190,93 +195,91 @@ 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*/ ) +GuiSound::GuiSound(const u8 *s, int l, int v/*=100*/, bool r/*=true*/, bool a/*=false*/) { - if ( GuiSoundCount++ == 0 || GuiSoundDecoderThreadHandle == LWP_THREAD_NULL ) + if (GuiSoundCount++ == 0 || GuiSoundDecoderThreadHandle == LWP_THREAD_NULL) { - LWP_CreateThread( &GuiSoundDecoderThreadHandle, GuiSoundDecoderThread, NULL, NULL, 32768, 80 ); + LWP_CreateThread(&GuiSoundDecoderThreadHandle, GuiSoundDecoderThread, NULL, NULL, 32768, 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 ); + 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*/ ) +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 ) + 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; + else if (a) delete[] s; return false; } -GuiSound::GuiSound( const char *p, int v/*=100*/ ) +GuiSound::GuiSound(const char *p, int v/*=100*/) { - if ( GuiSoundCount++ == 0 || GuiSoundDecoderThreadHandle == LWP_THREAD_NULL ) + if (GuiSoundCount++ == 0 || GuiSoundDecoderThreadHandle == LWP_THREAD_NULL) { - LWP_CreateThread( &GuiSoundDecoderThreadHandle, GuiSoundDecoderThread, NULL, NULL, 32*1024, 80 ); + 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 ); + 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 ) +bool GuiSound::Load(const char *p) { - Stop(); // stop playing - if ( !play_buffer[0] ) return false; + Stop(); // stop playing + if (!play_buffer[0]) return false; bool ret = false; - voice = -2; // -2 marks loading from file + voice = -2; // -2 marks loading from file u32 filesize = 0; u8 *buffer = NULL; size_t result; - FILE * pFile = fopen ( p, "rb" ); - if ( pFile ) + FILE * pFile = fopen(p, "rb"); + if (pFile) { // get file size: - fseek ( pFile , 0 , SEEK_END ); - filesize = ftell ( pFile ); - fseek ( pFile , 0 , SEEK_SET ); + 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 ) + 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; + result = fread(buffer, 1, filesize, pFile); + if (result == filesize) + ret = Load(buffer, filesize, false, true); + else delete[] buffer; } - fclose ( pFile ); + fclose(pFile); } return ret; } @@ -286,76 +289,77 @@ bool GuiSound::Load( const char *p ) */ GuiSound::~GuiSound() { - if ( !loop ) while ( voice >= 0 ) usleep( 50 ); + if (!loop) while (voice >= 0) + usleep(50); Stop(); - if ( --GuiSoundCount == 0 && GuiSoundDecoderThreadHandle != LWP_THREAD_NULL ) + if (--GuiSoundCount == 0 && GuiSoundDecoderThreadHandle != LWP_THREAD_NULL) { GuiSoundDecoderThreadRunning = false; - LWP_JoinThread( GuiSoundDecoderThreadHandle, NULL ); + LWP_JoinThread(GuiSoundDecoderThreadHandle, NULL); GuiSoundDecoderThreadHandle = LWP_THREAD_NULL; } delete decoder; - free( play_buffer[0] ); + 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 + 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; + 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 ) + if (voice >= 0) { - s32 vol = ( 255 * volume ) / 100; - s32 format = decoder->GetFormat(); - s32 samplerate = decoder->GetSampleRate(); - s32 first_pos = buffer_pos; + 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 + 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 ); + ASND_SetVoice(voice, format, samplerate, 0, play_buffer[0], first_pos, vol, vol, GuiSoundPlayerCallback); } } /* -int GuiSound::PlayOggFile(char * path) -{ - if(Load(path)) - Play(); - return 1; -} -*/ + int GuiSound::PlayOggFile(char * path) + { + if(Load(path)) + Play(); + return 1; + } + */ void GuiSound::Stop() { - if ( voice < 0 ) return ; + if (voice < 0) return; GuiSoundPlayer[voice] = NULL; // disable Callbacks - SND_StopVoice( voice ); + SND_StopVoice(voice); voice = -1; } void GuiSound::Pause() { - if ( voice < 0 ) return ; - ASND_PauseVoice( voice, 1 ); + if (voice < 0) return; + ASND_PauseVoice(voice, 1); } void GuiSound::Resume() { - if ( voice < 0 ) return ; - ASND_PauseVoice( voice, 0 ); + if (voice < 0) return; + ASND_PauseVoice(voice, 0); } bool GuiSound::IsPlaying() @@ -363,80 +367,79 @@ bool GuiSound::IsPlaying() return voice >= 0; } -void GuiSound::SetVolume( int vol ) +void GuiSound::SetVolume(int vol) { volume = vol; - if ( voice < 0 ) return ; - int newvol = 255 * ( volume / 100.0 ); - ASND_ChangeVolumeVoice( voice, newvol, newvol ); + if (voice < 0) return; + int newvol = 255 * (volume / 100.0); + ASND_ChangeVolumeVoice(voice, newvol, newvol); } -void GuiSound::SetLoop( bool l ) +void GuiSound::SetLoop(bool l) { loop = l; } void GuiSound::DecoderCallback() { - if ( buffer_ready || buffer_eof ) // if buffer ready or EOF -> nothing - return; + if (buffer_ready || buffer_eof) // if buffer ready or EOF -> nothing + return; bool error = false; - while ( buffer_pos < BUFFER_SIZE ) + 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 + 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 + 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 + else if (ret < 0) // an ERROR { - if ( buffer_pos ) - break; // has data in buffer -> play the buffer - else if ( loop ) + if (buffer_pos) + break; // has data in buffer -> play the buffer + else if (loop) { - if ( !error ) // if no prev error + if (!error) // if no prev error { - decoder->Rewind(); // if loop -> rewind - error = true; // set error-state - continue; // and fill the buffer more + 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 + buffer_eof = true; // has prev error -> error in first block -> return EOF return; } else { - buffer_eof = true; // no loop -> return EOF + buffer_eof = true; // no loop -> return EOF return; } } - error = false; // clear error-state + error = false; // clear error-state } buffer_ready = true; } void GuiSound::PlayerCallback() { - if ( buffer_eof ) // if EOF + if (buffer_eof) // if EOF { - if ( ASND_TestPointer( voice, play_buffer[( buffer_nr+2 )%3] ) == 0 ) // test prev. Buffer - Stop(); + if (ASND_TestPointer(voice, play_buffer[(buffer_nr + 2) % 3]) == 0) // test prev. Buffer + Stop(); } - else if ( buffer_ready ) // if buffer ready + else if (buffer_ready) // if buffer ready { - if ( ASND_AddVoice( voice, play_buffer[buffer_nr], buffer_pos ) == SND_OK ) // add buffer + 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_nr = (buffer_nr + 1) % 3; + buffer_pos = 0; buffer_ready = false; - buffer_eof = false; + buffer_eof = false; } } } diff --git a/source/libwiigui/gui_sound_decoder.h b/source/libwiigui/gui_sound_decoder.h index f520894e..fd81babd 100644 --- a/source/libwiigui/gui_sound_decoder.h +++ b/source/libwiigui/gui_sound_decoder.h @@ -17,14 +17,20 @@ #define REGISTER_GUI_SOUND_DECODER(decoder) GuiSoundDecoder::DecoderListEntry decoder##_l = GuiSoundDecoder::RegisterDecoder(decoder##_l, decoder::Create) class GuiSoundDecoder; -typedef GuiSoundDecoder *( *GuiSoundDecoderCreate )( const u8 * snd, u32 len, bool snd_is_allocated ); +typedef GuiSoundDecoder *(*GuiSoundDecoderCreate)(const u8 * snd, u32 len, bool snd_is_allocated); 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() {}; + virtual ~GuiSoundDecoder() + { + } + ; // begin API // --------- // each Decoder must have an own static Create(...) fnc @@ -32,11 +38,11 @@ class GuiSoundDecoder 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; + 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; // ------- @@ -45,34 +51,33 @@ class GuiSoundDecoder struct DecoderListEntry { - GuiSoundDecoderCreate fnc; - DecoderListEntry *next; + GuiSoundDecoderCreate fnc; + DecoderListEntry *next; }; - static DecoderListEntry &RegisterDecoder( DecoderListEntry &Decoder, GuiSoundDecoderCreate fnc ); - static GuiSoundDecoder *GetDecoder( const u8 * snd, u32 len, bool snd_is_allocated ); + 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 + 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 ) +inline uint16_t be16(const uint8_t *p8) { - return *( ( uint16_t* )p8 ); + return *((uint16_t*) p8); } -inline uint32_t be32( const uint8_t *p8 ) +inline uint32_t be32(const uint8_t *p8) { - return *( ( uint32_t* )p8 ); + return *((uint32_t*) p8); } -inline uint16_t le16( const uint8_t *p8 ) +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 ) +inline uint32_t le32(const uint8_t *p8) { uint32_t ret = p8[3] << 24 | p8[2] << 16 | p8[1] << 8 | p8[0]; return ret; @@ -106,6 +111,4 @@ inline uint32_t le32( const uint8_t *p8 ) #define be32inc(p8) (p8+=4, be32(p8-4)) #define le32inc(p8) (p8+=4, le32(p8-4)) - - #endif /* GUI_SOUND_DECODER_H */ diff --git a/source/libwiigui/gui_sound_decoder_aiff.cpp b/source/libwiigui/gui_sound_decoder_aiff.cpp index c2f85e09..1811f7c8 100644 --- a/source/libwiigui/gui_sound_decoder_aiff.cpp +++ b/source/libwiigui/gui_sound_decoder_aiff.cpp @@ -24,76 +24,71 @@ # define UnsignedToFloat(u) (((double)((long)(u - 2147483647L - 1))) + 2147483648.0) -static double ConvertFromIeeeExtended( const u8* bytes ) +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 ) + if (expon == 0 && hiMant == 0 && loMant == 0) f = 0; else { - if ( expon == 0x7FFF ) + if (expon == 0x7FFF) f = HUGE_VAL; else { expon -= 16383; - f = ldexp( UnsignedToFloat( hiMant ), expon -= 31 ); - f += ldexp( UnsignedToFloat( loMant ), expon -= 32 ); + f = ldexp(UnsignedToFloat( hiMant ), expon -= 31); + f += ldexp(UnsignedToFloat( loMant ), expon -= 32); } } - if ( bytes[0] & 0x80 ) + if (bytes[0] & 0x80) return -f; - else - return f; + else return f; } // ------ -class GuiSoundDecoderAIFF : public GuiSoundDecoder +class GuiSoundDecoderAIFF: public GuiSoundDecoder { protected: - GuiSoundDecoderAIFF( const u8 * snd, u32 len, bool snd_is_allocated ) + GuiSoundDecoderAIFF(const u8 * snd, u32 len, bool snd_is_allocated) { - sound = snd; - length = len; - is_allocated = snd_is_allocated; + sound = snd; + length = len; + is_allocated = snd_is_allocated; is_running = false; 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 ) + 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 ) + 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 ); + 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; + pcm_start = in_ptr + 8; + pcm_end = chunk_start + chunk_size; break; } in_ptr = chunk_start + chunk_size; @@ -103,63 +98,61 @@ class GuiSoundDecoderAIFF : public GuiSoundDecoder public: ~GuiSoundDecoderAIFF() { - while ( is_running ) usleep( 50 ); - if ( is_allocated ) delete [] sound; + while (is_running) + usleep(50); + if (is_allocated) delete[] sound; } - static GuiSoundDecoder *Create( const u8 * snd, u32 len, bool snd_is_allocated ) + 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 ); + 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 ) + if (bytePerSample == 2) return channelCount == 2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; - else - return channelCount == 2 ? VOICE_STEREO_8BIT : VOICE_MONO_8BIT; + 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 ) + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read(u8 * buffer, int buffer_size) { - if ( currentPos >= pcm_end ) - return 0; // EOF + 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 ); + 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 ); + 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 0a4b43e7..ac7f872d 100644 --- a/source/libwiigui/gui_sound_decoder_bns.cpp +++ b/source/libwiigui/gui_sound_decoder_bns.cpp @@ -18,9 +18,6 @@ #include "gui_sound_decoder.h" #define BIG_ENDIAN_HOST 1 - - - class chanel_t { public: @@ -32,40 +29,39 @@ class chanel_t int DecodeNextBlock() { int Offset = 0; - if ( currentPos == loopStart ) + if (currentPos == loopStart) { loop_hist1 = hist1; loop_hist2 = hist2; } - if ( loop && currentPos >= endPos ) + if (loop && currentPos >= endPos) { currentPos = loopStart; - hist1 = loop_hist1; - hist2 = loop_hist2; - Offset = loopOffset; + hist1 = loop_hist1; + hist2 = loop_hist2; + Offset = loopOffset; } - if ( currentPos + 8 <= endPos ) + if (currentPos + 8 <= endPos) { - u16 index = ( *currentPos >> 4 ) & 0x07; - s32 scale = 1 << ( *currentPos++ & 0x0F ); - for ( int i = 0; i < 14; i += 2 ) + 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; + nibbles[i] = ((s8) *currentPos) >> 4; + nibbles[i + 1] = ((s8) ((*currentPos++) << 4)) >> 4; } - for ( int i = 0; i < 14; ++i ) + for (int i = 0; i < 14; ++i) { - s32 sample = ( scale * nibbles[i] ) << 11; + 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 ) + if (sample > 32767) sample = 32767; - else if ( sample < -32768 ) - sample = -32768; + else if (sample < -32768) sample = -32768; pcm[i] = sample; hist2 = hist1; @@ -76,98 +72,98 @@ class chanel_t 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; + 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 ) + GuiSoundDecoderBNS(const u8 * snd, u32 len, bool snd_is_allocated) { - sound = snd; - is_running = false; - is_allocated = snd_is_allocated; + sound = snd; + is_running = false; + is_allocated = snd_is_allocated; const u8 *in_ptr = sound; ///////////////// // READ HEADER // ///////////////// - if ( be32inc( in_ptr ) != 0x424E5320 /*'BNS '*/ ) throw( "Not a BNS" ); + 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" ); + 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); + 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].endPos = channel[0].startPos + be32inc( in_ptr ) - 8; /////////////// // READ INFO // /////////////// - in_ptr = infoStart + 8; // skip 'INFO' and Infosize + in_ptr = infoStart + 8; // skip 'INFO' and Infosize - in_ptr++; // skip u8 codeType = *in_ptr++; + in_ptr++; // skip u8 codeType = *in_ptr++; channel[0].loop = channel[1].loop = *in_ptr++; // u8 loopFlag; - channelCount = *in_ptr++; + channelCount = *in_ptr++; - in_ptr++; // skip unknown byte + in_ptr++; // skip unknown byte sampleRate = be16inc( in_ptr ); - in_ptr += 2; // skip unknown word + 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; + 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 += 4; // skip u32 SampleCount = be32inc(in_ptr); + in_ptr += 4; // skip u32 SampleCount = be32inc(in_ptr); - in_ptr += 24; // skip unknown Bytes + in_ptr += 24; // skip unknown Bytes - if ( channelCount == 2 ) + if (channelCount == 2) { - in_ptr += 4; // skip unknown long + in_ptr += 4; // skip unknown long u32 ChannelSplit = be32inc( in_ptr ); - in_ptr += 8; // skip 2x unknown long + 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].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 ); + channel[1].loopStart = channel[1].startPos + (channel[0].loopStart - channel[0].startPos); } - for ( int a = 0; a < 16; a++ ) + for (int a = 0; a < 16; a++) { - channel[0].coEfficients[a] = ( s16 )be16inc( in_ptr ); + channel[0].coEfficients[a] = (s16) be16inc( in_ptr ); } - if ( channelCount == 2 ) + if (channelCount == 2) { - in_ptr += 16; // skip 16 byte - for ( int a = 0; a < 16; a++ ) + in_ptr += 16; // skip 16 byte + for (int a = 0; a < 16; a++) { - channel[1].coEfficients[a] = ( s16 )be16inc( in_ptr ); + channel[1].coEfficients[a] = (s16) be16inc( in_ptr ); } } channel[0].Reset(); @@ -177,13 +173,14 @@ class GuiSoundDecoderBNS : public GuiSoundDecoder public: ~GuiSoundDecoderBNS() { - while ( is_running ) usleep( 50 ); - if ( is_allocated ) delete [] sound; + while (is_running) + usleep(50); + if (is_allocated) delete[] sound; } - static GuiSoundDecoder *Create( const u8 * snd, u32 len, bool snd_is_allocated ) + 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 ); + 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() @@ -195,40 +192,40 @@ class GuiSoundDecoderBNS : public GuiSoundDecoder return sampleRate; } /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read( u8 * buffer, int buffer_size ) + 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 ( ;; ) + for (;;) { - if ( currentBlockPos >= 14 ) + if (currentBlockPos >= 14) { int Offset = channel[0].DecodeNextBlock(); - if ( Offset < 0 || ( channelCount == 2 && channel[1].DecodeNextBlock() < 0 ) ) + if (Offset < 0 || (channelCount == 2 && channel[1].DecodeNextBlock() < 0)) { is_running = false; return write_pos - buffer; } currentBlockPos = Offset; } - for ( ; currentBlockPos < 14; ++currentBlockPos ) + for (; currentBlockPos < 14; ++currentBlockPos) { - if ( write_pos >= write_end ) + if (write_pos >= write_end) { is_running = false; return write_pos - buffer; } - *( ( s16* )write_pos ) = channel[0].pcm[currentBlockPos]; + *((s16*) write_pos) = channel[0].pcm[currentBlockPos]; write_pos += 2; - if ( channelCount == 2 ) // stereo + if (channelCount == 2) // stereo { - *( ( s16* )write_pos ) = channel[1].pcm[currentBlockPos]; + *((s16*) write_pos) = channel[1].pcm[currentBlockPos]; write_pos += 2; } } @@ -244,17 +241,17 @@ class GuiSoundDecoderBNS : public GuiSoundDecoder return 0; } private: - 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; -// const u8 *soundDataEnd; -// u32 soundDataLen; + 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; + // const u8 *soundDataEnd; + // u32 soundDataLen; }; REGISTER_GUI_SOUND_DECODER( GuiSoundDecoderBNS ); diff --git a/source/libwiigui/gui_sound_decoder_mpg.cpp b/source/libwiigui/gui_sound_decoder_mpg.cpp index ad08032e..40cb7512 100644 --- a/source/libwiigui/gui_sound_decoder_mpg.cpp +++ b/source/libwiigui/gui_sound_decoder_mpg.cpp @@ -19,19 +19,16 @@ #include #include - #include "gui_sound_decoder.h" -static inline s16 FixedToShort( mad_fixed_t Fixed ) +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 ); + 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) @@ -39,64 +36,65 @@ 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 ) + GuiSoundDecoderMPG(const u8 * snd, u32 len, bool snd_is_allocated) { - sound = snd; - length = len; - is_allocated = 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 ); + 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() ) + if (DecodeFirstFrame()) { mad_synth_finish( &madSynth ); - mad_frame_finish( &madFrame ); - mad_stream_finish( &madStream ); - throw( "Stream Error" ); + mad_frame_finish(&madFrame); + mad_stream_finish(&madStream); + throw("Stream Error"); } } public: ~GuiSoundDecoderMPG() { - while ( is_running ) usleep( 50 ); + while (is_running) + usleep(50); mad_synth_finish( &madSynth ); - mad_frame_finish( &madFrame ); - mad_stream_finish( &madStream ); - delete [] guardBuffer; - if ( is_allocated ) delete [] sound; + 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 ) + static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) { - struct mad_stream madStream; + 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 + 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 ) + 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_stream_finish(&madStream); + return new GuiSoundDecoderMPG(snd, len, snd_is_allocated); } - } - mad_header_finish( &madHeader ); - mad_stream_finish( &madStream ); + } mad_header_finish( &madHeader ); + mad_stream_finish(&madStream); return NULL; } s32 GetFormat() @@ -108,63 +106,63 @@ class GuiSoundDecoderMPG : public GuiSoundDecoder 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 ) + 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 + 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 + else buffer_size &= ~0x0001; // make size to a kind of 2 u8 *write_pos = buffer; u8 *write_end = buffer + buffer_size; - for ( ;; ) + for (;;) { - for ( ; madSynthPcmPos < madSynth.pcm.length; ++madSynthPcmPos ) + for (; madSynthPcmPos < madSynth.pcm.length; ++madSynthPcmPos) { - if ( write_pos >= write_end ) + 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[0][madSynthPcmPos]); + write_pos += 2; + if (MAD_NCHANNELS( &madFrame.header ) == 2) // stereo { - *( ( s16* )write_pos ) = FixedToShort( madSynth.pcm.samples[1][madSynthPcmPos] ); write_pos += 2; + *((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_frame_decode(&madFrame, &madStream)) { - if ( MAD_RECOVERABLE( madStream.error ) ) + if (MAD_RECOVERABLE( madStream.error )) { - if ( madStream.error != MAD_ERROR_LOSTSYNC || !guardBuffer ) - continue; + if (madStream.error != MAD_ERROR_LOSTSYNC || !guardBuffer) continue; } - else if ( madStream.error == MAD_ERROR_BUFLEN ) + else if (madStream.error == MAD_ERROR_BUFLEN) { - if ( !guardBuffer ) + if (!guardBuffer) { - u32 guardLen = ( madStream.bufend - madStream.next_frame ); - guardBuffer = new( std::nothrow ) u8[guardLen + MAD_BUFFER_GUARD]; - 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 ); + 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 ); + mad_timer_add(&madTimer, madFrame.header.duration); + mad_synth_frame(&madSynth, &madFrame); madSynthPcmPos = 0; } is_running = false; @@ -172,11 +170,13 @@ class GuiSoundDecoderMPG : public GuiSoundDecoder } int Rewind() { - while ( is_running ) usleep( 50 ); - delete [] guardBuffer; guardBuffer = NULL; - mad_stream_buffer( &madStream, sound, length ); + while (is_running) + usleep(50); + delete[] guardBuffer; + guardBuffer = NULL; + mad_stream_buffer(&madStream, sound, length); mad_synth_finish( &madSynth ); - mad_synth_init( &madSynth ); + mad_synth_init(&madSynth); madSynthPcmPos = 0; mad_timer_reset( &madTimer ); // decode first Frame @@ -185,30 +185,29 @@ class GuiSoundDecoderMPG : public GuiSoundDecoder private: int DecodeFirstFrame() { - for ( ;; ) + for (;;) { madStream.error = MAD_ERROR_NONE; - if ( mad_frame_decode( &madFrame, &madStream ) ) + if (mad_frame_decode(&madFrame, &madStream)) { - if ( MAD_RECOVERABLE( madStream.error ) ) + if (MAD_RECOVERABLE( madStream.error )) continue; - else - return -1; + else return -1; } - mad_timer_add( &madTimer, madFrame.header.duration ); - mad_synth_frame( &madSynth, &madFrame ); + 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; + 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 0e91cfa1..5cf4c76b 100644 --- a/source/libwiigui/gui_sound_decoder_ogg.cpp +++ b/source/libwiigui/gui_sound_decoder_ogg.cpp @@ -24,45 +24,40 @@ static struct { - char *mem; - int size; - int pos; + char *mem; + int size; + int pos; } file[4]; -static int f_read( void * punt, int bytes, int blocks, int *f ) +static int f_read(void * punt, int bytes, int blocks, int *f) { int b; int c = 0; int d; - if ( bytes * blocks <= 0 ) - return 0; + if (bytes * blocks <= 0) return 0; blocks *= bytes; - while ( blocks > 0 ) + while (blocks > 0) { b = blocks; - if ( b > 4096 ) - b = 4096; + if (b > 4096) b = 4096; - d = ( *f ) - 0x666; - if ( ( unsigned )( d ) <= ( 0x669 - 0x666 ) ) + d = (*f) - 0x666; + if ((unsigned) (d) <= (0x669 - 0x666)) { - if ( file[d].size == 0 ) - return -1; - if ( ( file[d].pos + b ) > file[d].size ) - b = file[d].size - file[d].pos; - if ( b > 0 ) + if (file[d].size == 0) return -1; + if ((file[d].pos + b) > file[d].size) b = file[d].size - file[d].pos; + if (b > 0) { - memcpy( punt, file[d].mem + file[d].pos, b ); + memcpy(punt, file[d].mem + file[d].pos, b); file[d].pos += b; } } - else - b = read( *f, ( ( char * ) punt ) + c, b ); + else b = read(*f, ((char *) punt) + c, b); - if ( b <= 0 ) + if (b <= 0) { return c / bytes; } @@ -72,117 +67,109 @@ static int f_read( void * punt, int bytes, int blocks, int *f ) return c / bytes; } -static int f_seek( int *f, ogg_int64_t offset, int mode ) +static int f_seek(int *f, ogg_int64_t offset, int mode) { - if ( f == NULL ) return( -1 ); + if (f == NULL) return (-1); int k; mode &= 3; - int d = ( *f ) - 0x666; - if ( ( unsigned )( d ) <= ( 0x669 - 0x666 ) ) + int d = (*f) - 0x666; + if ((unsigned) (d) <= (0x669 - 0x666)) { k = 0; - if ( file[d].size == 0 ) - return -1; + if (file[d].size == 0) return -1; - if ( mode == 0 ) + if (mode == 0) { - if ( ( offset ) >= file[d].size ) + if ((offset) >= file[d].size) { file[d].pos = file[d].size; k = -1; } - else if ( ( offset ) < 0 ) + else if ((offset) < 0) { file[d].pos = 0; k = -1; } - else - file[d].pos = offset; + else file[d].pos = offset; } - else if ( mode == 1 ) + else if (mode == 1) { - if ( ( file[d].pos + offset ) >= file[d].size ) + if ((file[d].pos + offset) >= file[d].size) { file[d].pos = file[d].size; k = -1; } - else if ( ( file[d].pos + offset ) < 0 ) + else if ((file[d].pos + offset) < 0) { file[d].pos = 0; k = -1; } - else - file[d].pos += offset; + else file[d].pos += offset; } - else if ( mode == 2 ) + else if (mode == 2) { - if ( ( file[d].size + offset ) >= file[d].size ) + if ((file[d].size + offset) >= file[d].size) { file[d].pos = file[d].size; k = -1; } - else if ( ( file[d].size + offset ) < 0 ) + else if ((file[d].size + offset) < 0) { file[d].pos = 0; k = -1; } - else - file[d].pos = file[d].size + offset; + else file[d].pos = file[d].size + offset; } } - else - k = lseek( *f, ( int ) offset, mode ); + else k = lseek(*f, (int) offset, mode); - if ( k < 0 ) + if (k < 0) k = -1; - else - k = 0; + else k = 0; return k; } -static int f_close( int *f ) +static int f_close(int *f) { - int d = ( *f ) - 0x666; - if ( ( unsigned )( d ) <= ( 0x669 - 0x666 ) ) + int d = (*f) - 0x666; + if ((unsigned) (d) <= (0x669 - 0x666)) { file[d].size = 0; file[d].pos = 0; - if ( file[d].mem ) + if (file[d].mem) { - file[d].mem = ( char * ) 0; + file[d].mem = (char *) 0; } return 0; } - else - return close( *f ); + else return close(*f); return 0; } -static long f_tell( int *f ) +static long f_tell(int *f) { int k; - int d = ( *f ) - 0x666; - if ( ( unsigned )( d ) <= ( 0x669 - 0x666 ) ) + int d = (*f) - 0x666; + if ((unsigned) (d) <= (0x669 - 0x666)) { k = file[d].pos; } - else - k = lseek( *f, 0, 1 ); + else k = lseek(*f, 0, 1); - return ( long ) k; + return (long) k; } -static int mem_open( char * ogg, int size ) +static int mem_open(char * ogg, int size) { static int one = 1; int n; - if ( one ) + if (one) { one = 0; @@ -193,72 +180,67 @@ static int mem_open( char * ogg, int size ) file[0].mem = ogg; file[0].size = size; file[0].pos = 0; - return ( 0x666 ); + return (0x666); } - for ( n = 0; n < 4; n++ ) + for (n = 0; n < 4; n++) { - if ( file[n].size == 0 ) + if (file[n].size == 0) { file[n].mem = ogg; file[n].size = size; file[n].pos = 0; - return ( 0x666 + n ); + return (0x666 + n); } } return -1; } -static int mem_close( int fd ) +static int mem_close(int fd) { - if ( ( unsigned )( ( fd ) - 0x666 ) <= ( 0x669 - 0x666 ) ) // it is a memory file descriptor? + if ((unsigned) ((fd) - 0x666) <= (0x669 - 0x666)) // it is a memory file descriptor? { fd -= 0x666; file[fd].size = 0; return 0; } - else - return f_close( &fd ); + else return f_close(&fd); } -static ov_callbacks callbacks = -{ - ( size_t ( * )( void *, size_t, size_t, void * ) ) f_read, - ( int ( * )( void *, ogg_int64_t, int ) ) f_seek, - ( int ( * )( void * ) ) f_close, - ( long ( * )( void * ) ) f_tell -}; +static ov_callbacks callbacks = { (size_t(*)(void *, size_t, size_t, void *)) f_read, + (int(*)(void *, ogg_int64_t, int)) f_seek, (int(*)(void *)) f_close, (long(*)(void *)) f_tell }; -class GuiSoundDecoderOGG : public GuiSoundDecoder +class GuiSoundDecoderOGG: public GuiSoundDecoder { protected: - GuiSoundDecoderOGG( const u8 * snd, u32 len, bool snd_is_allocated ) + 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" ); + 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_callbacks( ( void* )&ogg_fd, &ogg_file, NULL, 0, callbacks ) < 0 ) + if (ov_open_callbacks((void*) &ogg_fd, &ogg_file, NULL, 0, callbacks) < 0) { - mem_close( ogg_fd ); - throw( "ogg open failed" ); + mem_close(ogg_fd); + throw("ogg open failed"); } - ogg_info = ov_info( &ogg_file, -1 ); - bitstream = 0; - is_running = false; + 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; + 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 ) + 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 ); + 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() @@ -270,35 +252,34 @@ class GuiSoundDecoderOGG : public GuiSoundDecoder 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 ) + 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 ) + 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 + if (ret != OV_HOLE) ret = 0; // we says EOF } is_running = false; return ret; } int Rewind() { - return ov_time_seek( &ogg_file, 0 ); + 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 89d25f91..30f4d462 100644 --- a/source/libwiigui/gui_sound_decoder_wav.cpp +++ b/source/libwiigui/gui_sound_decoder_wav.cpp @@ -21,182 +21,182 @@ typedef struct { - u32 cueID; - u32 len; - u32 loops; + u32 cueID; + u32 len; + u32 loops; } plst_t; typedef struct { - const u8 *start; - const u8 *end; - u32 loops; + 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 ) + GuiSoundDecoderWAV(const u8 * snd, u32 len, bool snd_is_allocated) { - sound = snd; - is_running = false; - is_allocated = snd_is_allocated; + sound = snd; + is_running = false; + is_allocated = snd_is_allocated; 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" ); + 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 ); - 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" ); + channelCount = le16inc( in_ptr ); + if (channelCount < 1 || channelCount > 2) throw("only mono or stereo"); - sampleRate = le32inc( in_ptr ); + sampleRate = le32inc( in_ptr ); - in_ptr += 6; // skip and + in_ptr += 6; // skip and - bytePerSample = ( le16inc( in_ptr ) + 7 ) / 8; - if ( bytePerSample < 1 || bytePerSample > 2 ) throw( "only 1-16 bit/Sample" ); + bytePerSample = (le16inc( in_ptr ) + 7) / 8; + if (bytePerSample < 1 || bytePerSample > 2) throw("only 1-16 bit/Sample"); in_ptr += fmtLen - 16; - if ( be32inc( in_ptr ) != 0x64617461 /*'data'*/ ) throw( "No data-Tag" ); - + if (be32inc( in_ptr ) != 0x64617461 /*'data'*/) throw("No data-Tag"); soundDataStart = in_ptr + 4; - soundDataEnd = soundDataStart + le32( in_ptr ); + soundDataEnd = soundDataStart + le32(in_ptr); in_ptr = soundDataEnd; std::map cue; - std::vectorplst; + std::vector plst; - if ( ( ( u32 )in_ptr ) & 0x0001UL ) in_ptr++; - while ( ( in_ptr + 4 ) < ( sound + riffsize ) ) + if (((u32) in_ptr) & 0x0001UL) in_ptr++; + while ((in_ptr + 4) < (sound + riffsize)) { u32 tag = be32inc( in_ptr ); - switch ( tag ) + switch (tag) { case 0x63756520 /*'cue '*/: - in_ptr += 4; // skip size - for ( u32 count = le32inc( in_ptr ); count > 0; count-- ) + 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 += 4; // skip dwPosition + if (be32inc( in_ptr ) == 0x64617461 /*'data'*/) { - in_ptr += 8; // skip chunkStart - dwBlockStart + in_ptr += 8; // skip chunkStart - dwBlockStart cue[ID] = le32inc( in_ptr ); } - else - in_ptr += 12; // skip chunkStart - SammpleOffset + 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 )} ); + 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 ) + 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} ); + const u8 *end = soundDataStart + (i->len * bytePerSample * channelCount); + u32 loops = i->loops; + playlist.push_back(( playlist_t ) + { start, end, loops}); } - if ( playlist.size() == 0 ) + if (playlist.size() == 0) { - playlist.push_back( ( playlist_t ) {soundDataStart, soundDataEnd, 1} ); + playlist.push_back(( playlist_t ) + { soundDataStart, soundDataEnd, 1}); } Rewind(); } public: ~GuiSoundDecoderWAV() { - while ( is_running ) usleep( 50 ); - if ( is_allocated ) delete [] sound; + while (is_running) + usleep(50); + if (is_allocated) delete[] sound; } - static GuiSoundDecoder *Create( const u8 * snd, u32 len, bool snd_is_allocated ) + 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 ); + 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 ) + if (bytePerSample == 2) return channelCount == 2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; - else - return channelCount == 2 ? VOICE_STEREO_8BIT : VOICE_MONO_8BIT; + 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 ) + 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 ( ;; ) + for (;;) { - while ( currentPos < currentEnd ) + while (currentPos < currentEnd) { - if ( write_pos >= write_end ) + if (write_pos >= write_end) { is_running = false; return write_pos - buffer; } - if ( bytePerSample == 2 ) + if (bytePerSample == 2) { - *( ( s16* )write_pos ) = le16inc( currentPos ); + *((s16*) write_pos) = le16inc( currentPos ); write_pos += 2; - if ( channelCount == 2 ) // stereo + if (channelCount == 2) // stereo { - *( ( s16* )write_pos ) = le16inc( currentPos ); + *((s16*) write_pos) = le16inc( currentPos ); write_pos += 2; } } else { *write_pos++ = *currentPos++; - if ( channelCount == 2 ) // stereo - *write_pos++ = *currentPos++; + if (channelCount == 2) // stereo + *write_pos++ = *currentPos++; } } - if ( currentLoops > 1 ) + if (currentLoops > 1) { currentLoops--; currentPos = currentStart; continue; } - if ( currentPlaylist != playlist.end() ) - currentPlaylist++; - if ( currentPlaylist != playlist.end() ) + if (currentPlaylist != playlist.end()) currentPlaylist++; + if (currentPlaylist != playlist.end()) { - currentStart = currentPos = currentPlaylist->start; - currentEnd = currentPlaylist->end; - currentLoops = currentPlaylist->loops; + currentStart = currentPos = currentPlaylist->start; + currentEnd = currentPlaylist->end; + currentLoops = currentPlaylist->loops; continue; } else @@ -211,27 +211,27 @@ class GuiSoundDecoderWAV : public GuiSoundDecoder int Rewind() { currentPlaylist = playlist.begin(); - currentStart = currentPos = currentPlaylist->start; - currentEnd = currentPlaylist->end; - currentLoops = currentPlaylist->loops; + currentStart = currentPos = currentPlaylist->start; + currentEnd = currentPlaylist->end; + currentLoops = currentPlaylist->loops; return 0; } private: - const u8 *sound; - bool is_allocated; - bool is_running; + const u8 *sound; + bool is_allocated; + bool is_running; - u16 channelCount; - u32 sampleRate; - u16 bytePerSample; - const u8 *soundDataStart; - const u8 *soundDataEnd; + 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 *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 f8b1be0a..dde6518a 100644 --- a/source/libwiigui/gui_text.cpp +++ b/source/libwiigui/gui_text.cpp @@ -18,7 +18,8 @@ static int presetMaxWidth = 0; static int presetAlignmentHor = 0; static int presetAlignmentVert = 0; static u16 presetStyle = 0; -static GXColor presetColor = ( GXColor ) {255, 255, 255, 255}; +static GXColor presetColor = ( GXColor ) +{ 255, 255, 255, 255}; #define TEXT_SCROLL_DELAY 5 #define TEXT_SCROLL_INITIAL_DELAY 8 @@ -27,7 +28,7 @@ static GXColor presetColor = ( GXColor ) {255, 255, 255, 255}; * Constructor for the GuiText class. */ -GuiText::GuiText( const char * t, int s, GXColor c ) +GuiText::GuiText(const char * t, int s, GXColor c) { text = NULL; size = s; @@ -47,17 +48,16 @@ GuiText::GuiText( const char * t, int s, GXColor c ) alignmentHor = ALIGN_CENTRE; alignmentVert = ALIGN_MIDDLE; - if ( t ) + if (t) { - text = charToWideChar( t ); - if ( !text ) - return; + text = charToWideChar(t); + if (!text) return; - textWidth = fontSystem->getWidth( text, currentSize ); + textWidth = fontSystem->getWidth(text, currentSize); } } -GuiText::GuiText( const wchar_t * t, int s, GXColor c ) +GuiText::GuiText(const wchar_t * t, int s, GXColor c) { text = NULL; size = s; @@ -77,22 +77,21 @@ GuiText::GuiText( const wchar_t * t, int s, GXColor c ) alignmentHor = ALIGN_CENTRE; alignmentVert = ALIGN_MIDDLE; - if ( t ) + if (t) { - text = new ( std::nothrow ) wchar_t[wcslen( t )+1]; - if ( !text ) - return; + text = new (std::nothrow) wchar_t[wcslen(t) + 1]; + if (!text) return; - wcscpy( text, t ); + wcscpy(text, t); - textWidth = fontSystem->getWidth( text, currentSize ); + textWidth = fontSystem->getWidth(text, currentSize); } } /** * Constructor for the GuiText class, uses presets */ -GuiText::GuiText( const char * t ) +GuiText::GuiText(const char * t) { text = NULL; size = presetSize; @@ -112,27 +111,24 @@ GuiText::GuiText( const char * t ) alignmentHor = presetAlignmentHor; alignmentVert = presetAlignmentVert; - if ( t ) + if (t) { - text = charToWideChar( t ); - if ( !text ) - return; + text = charToWideChar(t); + if (!text) return; - textWidth = fontSystem->getWidth( text, currentSize ); + textWidth = fontSystem->getWidth(text, currentSize); } } - /** * Destructor for the GuiText class. */ GuiText::~GuiText() { - if ( text ) - delete [] text; + if (text) delete[] text; text = NULL; - if ( font ) + if (font) { delete font; font = NULL; @@ -141,12 +137,11 @@ GuiText::~GuiText() ClearDynamicText(); } -void GuiText::SetText( const char * t ) +void GuiText::SetText(const char * t) { LOCK( this ); - if ( text ) - delete [] text; + if (text) delete[] text; text = NULL; ClearDynamicText(); @@ -154,47 +149,42 @@ void GuiText::SetText( const char * t ) textScrollPos = 0; textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - if ( t ) + if (t) { - text = charToWideChar( t ); - if ( !text ) - return; + text = charToWideChar(t); + if (!text) return; - if ( passChar != 0 ) + if (passChar != 0) { - for ( u8 i = 0; i < wcslen( text ); i++ ) + for (u8 i = 0; i < wcslen(text); i++) text[i] = passChar; } - textWidth = fontSystem->getWidth( text, currentSize ); + textWidth = fontSystem->getWidth(text, currentSize); } } -void GuiText::SetTextf( const char *format, ... ) +void GuiText::SetTextf(const char *format, ...) { - if ( !format ) - SetText( ( char * ) NULL ); + if (!format) SetText((char *) NULL); char *tmp = 0; va_list va; va_start( va, format ); - if ( ( vasprintf( &tmp, format, va ) >= 0 ) && tmp ) + if ((vasprintf(&tmp, format, va) >= 0) && tmp) { - SetText( tmp ); + SetText(tmp); } va_end( va ); - if ( tmp ) - free( tmp ); + if (tmp) free(tmp); } - -void GuiText::SetText( const wchar_t * t ) +void GuiText::SetText(const wchar_t * t) { LOCK( this ); - if ( text ) - delete [] text; + if (text) delete[] text; text = NULL; ClearDynamicText(); @@ -202,35 +192,33 @@ void GuiText::SetText( const wchar_t * t ) textScrollPos = 0; textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - if ( t ) + if (t) { - text = new ( std::nothrow ) wchar_t[wcslen( t )+1]; - if ( !text ) - return; + text = new (std::nothrow) wchar_t[wcslen(t) + 1]; + if (!text) return; - wcscpy( text, t ); + wcscpy(text, t); - if ( passChar != 0 ) + if (passChar != 0) { - for ( u8 i = 0; i < wcslen( text ); i++ ) + for (u8 i = 0; i < wcslen(text); i++) text[i] = passChar; } - textWidth = fontSystem->getWidth( text, currentSize ); + textWidth = fontSystem->getWidth(text, currentSize); } } void GuiText::ClearDynamicText() { - for ( u32 i = 0; i < textDyn.size(); i++ ) + for (u32 i = 0; i < textDyn.size(); i++) { - if ( textDyn[i] ) - delete [] textDyn[i]; + if (textDyn[i]) delete[] textDyn[i]; } textDyn.clear(); } -void GuiText::SetPresets( int sz, GXColor c, int w, u16 s, int h, int v ) +void GuiText::SetPresets(int sz, GXColor c, int w, u16 s, int h, int v) { presetSize = sz; presetColor = c; @@ -240,21 +228,21 @@ void GuiText::SetPresets( int sz, GXColor c, int w, u16 s, int h, int v ) presetAlignmentVert = v; } -void GuiText::SetFontSize( int s ) +void GuiText::SetFontSize(int s) { LOCK( this ); size = s; } -void GuiText::SetMaxWidth( int width, int w ) +void GuiText::SetMaxWidth(int width, int w) { LOCK( this ); maxWidth = width; wrapMode = w; - if ( w == SCROLL_HORIZONTAL ) + if (w == SCROLL_HORIZONTAL) { textScrollPos = 0; textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; @@ -264,31 +252,31 @@ void GuiText::SetMaxWidth( int width, int w ) ClearDynamicText(); } -void GuiText::SetPassChar( wchar_t p ) +void GuiText::SetPassChar(wchar_t p) { LOCK( this ); passChar = p; } -void GuiText::SetColor( GXColor c ) +void GuiText::SetColor(GXColor c) { LOCK( this ); color = c; alpha = c.a; } -void GuiText::SetStyle( u16 s ) +void GuiText::SetStyle(u16 s) { LOCK( this ); style = s; } -void GuiText::SetAlignment( int hor, int vert ) +void GuiText::SetAlignment(int hor, int vert) { LOCK( this ); style = 0; - switch ( hor ) + switch (hor) { case ALIGN_LEFT: style |= FTGX_JUSTIFY_LEFT; @@ -300,7 +288,7 @@ void GuiText::SetAlignment( int hor, int vert ) style |= FTGX_JUSTIFY_CENTER; break; } - switch ( vert ) + switch (vert) { case ALIGN_TOP: style |= FTGX_ALIGN_TOP; @@ -317,25 +305,23 @@ void GuiText::SetAlignment( int hor, int vert ) alignmentVert = vert; } -void GuiText::SetLinesToDraw( int l ) +void GuiText::SetLinesToDraw(int l) { linestodraw = l; } int GuiText::GetTextWidth() { - if ( !text ) - return 0; + if (!text) return 0; - return fontSystem->getWidth( text, currentSize ); + return fontSystem->getWidth(text, currentSize); } -int GuiText::GetTextWidth( int ind ) +int GuiText::GetTextWidth(int ind) { - if ( ind < 0 || ind >= ( int ) textDyn.size() ) - return this->GetTextWidth(); + if (ind < 0 || ind >= (int) textDyn.size()) return this->GetTextWidth(); - return fontSystem->getWidth( textDyn[ind], currentSize ); + return fontSystem->getWidth(textDyn[ind], currentSize); } int GuiText::GetTextMaxWidth() @@ -343,10 +329,9 @@ int GuiText::GetTextMaxWidth() return maxWidth; } -const wchar_t * GuiText::GetDynText( int ind ) +const wchar_t * GuiText::GetDynText(int ind) { - if ( ind < 0 || ind >= ( int ) textDyn.size() ) - return text; + if (ind < 0 || ind >= (int) textDyn.size()) return text; return textDyn[ind]; } @@ -359,19 +344,17 @@ const wchar_t * GuiText::GetText() /** * Change font */ -bool GuiText::SetFont( const u8 *fontbuffer, const u32 filesize ) +bool GuiText::SetFont(const u8 *fontbuffer, const u32 filesize) { - if ( !fontbuffer || !filesize ) - return false; - + if (!fontbuffer || !filesize) return false; LOCK( this ); - if ( font ) + if (font) { delete font; font = NULL; } - font = new FreeTypeGX( fontbuffer, filesize ); - textWidth = font->getWidth( text, currentSize ); + font = new FreeTypeGX(fontbuffer, filesize); + textWidth = font->getWidth(text, currentSize); return true; } @@ -379,21 +362,21 @@ bool GuiText::SetFont( const u8 *fontbuffer, const u32 filesize ) void GuiText::MakeDottedText() { int pos = textDyn.size(); - textDyn.resize( pos + 1 ); + textDyn.resize(pos + 1); int i = 0, currentWidth = 0; textDyn[pos] = new wchar_t[maxWidth]; - while ( text[i] ) + while (text[i]) { - currentWidth += ( font ? font : fontSystem )->getCharWidth( text[i], currentSize, i > 0 ? text[i-1] : 0x0000 ); - if ( currentWidth >= maxWidth ) + currentWidth += (font ? font : fontSystem)->getCharWidth(text[i], currentSize, i > 0 ? text[i - 1] : 0x0000); + if (currentWidth >= maxWidth) { - if ( i > 3 ) + if (i > 3) { - textDyn[pos][i-3] = '.'; - textDyn[pos][i-2] = '.'; - textDyn[pos][i-1] = '.'; + textDyn[pos][i - 3] = '.'; + textDyn[pos][i - 2] = '.'; + textDyn[pos][i - 1] = '.'; } break; } @@ -407,19 +390,20 @@ void GuiText::MakeDottedText() void GuiText::ScrollText() { - if ( textDyn.size() == 0 ) + if (textDyn.size() == 0) { int pos = textDyn.size(); int i = 0, currentWidth = 0; - textDyn.resize( pos + 1 ); + textDyn.resize(pos + 1); textDyn[pos] = new wchar_t[maxWidth]; - while ( text[i] && currentWidth < maxWidth ) + while (text[i] && currentWidth < maxWidth) { textDyn[pos][i] = text[i]; - currentWidth += ( font ? font : fontSystem )->getCharWidth( text[i], currentSize, i > 0 ? text[i-1] : 0x0000 ); + currentWidth + += (font ? font : fontSystem)->getCharWidth(text[i], currentSize, i > 0 ? text[i - 1] : 0x0000); ++i; } @@ -428,21 +412,21 @@ void GuiText::ScrollText() return; } - if ( frameCount % textScrollDelay != 0 ) + if (frameCount % textScrollDelay != 0) { return; } - if ( textScrollInitialDelay ) + if (textScrollInitialDelay) { --textScrollInitialDelay; return; } - int strlen = wcslen( text ); + int strlen = wcslen(text); ++textScrollPos; - if ( textScrollPos > strlen ) + if (textScrollPos > strlen) { textScrollPos = 0; textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; @@ -451,16 +435,15 @@ void GuiText::ScrollText() int ch = textScrollPos; int pos = textDyn.size() - 1; - if ( textDyn[pos] ) - delete [] textDyn[pos]; + if (textDyn[pos]) delete[] textDyn[pos]; textDyn[pos] = new wchar_t[maxWidth]; int i = 0, currentWidth = 0; - while ( currentWidth < maxWidth ) + while (currentWidth < maxWidth) { - if ( ch > strlen - 1 ) + if (ch > strlen - 1) { textDyn[pos][i++] = ' '; textDyn[pos][i++] = ' '; @@ -472,15 +455,14 @@ void GuiText::ScrollText() ++ch; ++i; - currentWidth += ( font ? font : fontSystem )->getCharWidth( text[ch], currentSize, ch > 0 ? text[ch-1] : 0x0000 ); + currentWidth += (font ? font : fontSystem)->getCharWidth(text[ch], currentSize, ch > 0 ? text[ch - 1] : 0x0000); } textDyn[pos][i] = 0; } void GuiText::WrapText() { - if ( textDyn.size() > 0 ) - return; + if (textDyn.size() > 0) return; int i = 0; int ch = 0; @@ -489,22 +471,22 @@ void GuiText::WrapText() int lastSpaceIndex = -1; int currentWidth = 0; - while ( text[ch] && linenum < linestodraw ) + while (text[ch] && linenum < linestodraw) { - if ( linenum >= ( int ) textDyn.size() ) + if (linenum >= (int) textDyn.size()) { - textDyn.resize( linenum + 1 ); + textDyn.resize(linenum + 1); textDyn[linenum] = new wchar_t[maxWidth]; } textDyn[linenum][i] = text[ch]; - textDyn[linenum][i+1] = 0; + textDyn[linenum][i + 1] = 0; - currentWidth += ( font ? font : fontSystem )->getCharWidth( text[ch], currentSize, ch > 0 ? text[ch-1] : 0x0000 ); + currentWidth += (font ? font : fontSystem)->getCharWidth(text[ch], currentSize, ch > 0 ? text[ch - 1] : 0x0000); - if ( currentWidth >= maxWidth ) + if (currentWidth >= maxWidth) { - if ( lastSpace >= 0 ) + if (lastSpace >= 0) { textDyn[linenum][lastSpaceIndex] = 0; // discard space, and everything after ch = lastSpace; // go backwards to the last space @@ -512,19 +494,19 @@ void GuiText::WrapText() lastSpaceIndex = -1; } - if ( linenum + 1 == linestodraw && text[ch+1] != 0x0000 ) + if (linenum + 1 == linestodraw && text[ch + 1] != 0x0000) { - textDyn[linenum][i-2] = '.'; - textDyn[linenum][i-1] = '.'; + textDyn[linenum][i - 2] = '.'; + textDyn[linenum][i - 1] = '.'; textDyn[linenum][i] = '.'; - textDyn[linenum][i+1] = 0; + textDyn[linenum][i + 1] = 0; } currentWidth = 0; ++linenum; i = -1; } - if ( text[ch] == ' ' && i >= 0 ) + if (text[ch] == ' ' && i >= 0) { lastSpace = ch; lastSpaceIndex = i; @@ -539,62 +521,57 @@ void GuiText::WrapText() */ void GuiText::Draw() { - if ( !text ) - return; + if (!text) return; - if ( !IsVisible() ) - return; + if (!IsVisible()) return; GXColor c = color; c.a = GetAlpha(); int newSize = size * GetScale(); - if ( newSize != currentSize ) + if (newSize != currentSize) { currentSize = newSize; - if ( text ) - textWidth = ( font ? font : fontSystem )->getWidth( text, currentSize ); + if (text) textWidth = (font ? font : fontSystem)->getWidth(text, currentSize); } - if ( maxWidth > 0 && maxWidth <= textWidth ) + if (maxWidth > 0 && maxWidth <= textWidth) { - if ( wrapMode == DOTTED ) // text dotted + if (wrapMode == DOTTED) // text dotted { - if ( textDyn.size() == 0 ) - MakeDottedText(); + if (textDyn.size() == 0) MakeDottedText(); - if ( textDyn.size() > 0 ) - ( font ? font : fontSystem )->drawText( this->GetLeft(), this->GetTop(), 0, textDyn[textDyn.size()-1], currentSize, c, style ); + if (textDyn.size() > 0) (font ? font : fontSystem)->drawText(this->GetLeft(), this->GetTop(), 0, + textDyn[textDyn.size() - 1], currentSize, c, style); } - else if ( wrapMode == SCROLL_HORIZONTAL ) + else if (wrapMode == SCROLL_HORIZONTAL) { ScrollText(); - if ( textDyn.size() > 0 ) - ( font ? font : fontSystem )->drawText( this->GetLeft(), this->GetTop(), 0, textDyn[textDyn.size()-1], currentSize, c, style ); + if (textDyn.size() > 0) (font ? font : fontSystem)->drawText(this->GetLeft(), this->GetTop(), 0, + textDyn[textDyn.size() - 1], currentSize, c, style); } - else if ( wrapMode == WRAP ) + else if (wrapMode == WRAP) { int lineheight = currentSize + 6; int voffset = 0; - if ( alignmentVert == ALIGN_MIDDLE ) - voffset = -( lineheight * textDyn.size() ) / 2 + lineheight / 2; + if (alignmentVert == ALIGN_MIDDLE) voffset = -(lineheight * textDyn.size()) / 2 + lineheight / 2; - if ( textDyn.size() == 0 ) - WrapText(); + if (textDyn.size() == 0) WrapText(); - for ( u32 i = 0; i < textDyn.size(); i++ ) + for (u32 i = 0; i < textDyn.size(); i++) { - ( font ? font : fontSystem )->drawText( this->GetLeft(), this->GetTop() + voffset + i*lineheight, 0, textDyn[i], currentSize, c, style ); + (font ? font : fontSystem)->drawText(this->GetLeft(), this->GetTop() + voffset + i * lineheight, 0, + textDyn[i], currentSize, c, style); } } } else { - ( font ? font : fontSystem )->drawText( this->GetLeft(), this->GetTop(), 0, text, currentSize, c, style, textWidth ); + (font ? font : fontSystem)->drawText(this->GetLeft(), this->GetTop(), 0, text, currentSize, c, style, textWidth); } this->UpdateEffects(); } diff --git a/source/libwiigui/gui_tooltip.cpp b/source/libwiigui/gui_tooltip.cpp index 1972894e..ab94fd0d 100644 --- a/source/libwiigui/gui_tooltip.cpp +++ b/source/libwiigui/gui_tooltip.cpp @@ -10,28 +10,26 @@ #include "gui.h" -static GuiImageData tooltipLeft( tooltip_left_png ); -static GuiImageData tooltipTile( tooltip_tile_png ); -static GuiImageData tooltipRight( tooltip_right_png ); - +static GuiImageData tooltipLeft(tooltip_left_png); +static GuiImageData tooltipTile(tooltip_tile_png); +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 ) +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.SetParent(this); + tileImage.SetParent(this); + rightImage.SetParent(this); + leftImage.SetParentAngle(false); + tileImage.SetParentAngle(false); + rightImage.SetParentAngle(false); + SetText(t); + SetAlpha(Alpha); } /* @@ -39,7 +37,7 @@ GuiTooltip::GuiTooltip( const char *t, int Alpha/*=255*/ ) */ GuiTooltip::~GuiTooltip() { - if ( text ) delete text; + if (text) delete text; } float GuiTooltip::GetScale() @@ -52,40 +50,43 @@ float GuiTooltip::GetScale() /* !Sets the text of the GuiTooltip element * !\param t Text */ -void GuiTooltip::SetText( const char * t ) +void GuiTooltip::SetText(const char * t) { LOCK( this ); - if ( text ) + if (text) { delete text; text = NULL; } int tile_cnt = 0; - if ( t && ( text = new GuiText( t, 22, ( GXColor ) {0, 0, 0, 255} ) ) ) + 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; + 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 ); + 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; + if (!this->IsVisible()) return; leftImage.Draw(); tileImage.Draw(); rightImage.Draw(); - if ( text ) text->Draw(); + if (text) text->Draw(); this->UpdateEffects(); } diff --git a/source/libwiigui/gui_trigger.cpp b/source/libwiigui/gui_trigger.cpp index 94e443be..58e15598 100644 --- a/source/libwiigui/gui_trigger.cpp +++ b/source/libwiigui/gui_trigger.cpp @@ -18,8 +18,8 @@ static int scrollDelay = 0; GuiTrigger::GuiTrigger() { chan = -1; - memset( &wpad, 0, sizeof( WPADData ) ); - memset( &pad, 0, sizeof( PADData ) ); + memset(&wpad, 0, sizeof(WPADData)); + memset(&pad, 0, sizeof(PADData)); } /** @@ -34,7 +34,7 @@ GuiTrigger::~GuiTrigger() * - Element is selected * - Trigger button is pressed */ -void GuiTrigger::SetSimpleTrigger( s32 ch, u32 wiibtns, u16 gcbtns ) +void GuiTrigger::SetSimpleTrigger(s32 ch, u32 wiibtns, u16 gcbtns) { type = TRIGGER_SIMPLE; chan = ch; @@ -47,7 +47,7 @@ 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 ) +void GuiTrigger::SetHeldTrigger(s32 ch, u32 wiibtns, u16 gcbtns) { type = TRIGGER_HELD; chan = ch; @@ -59,7 +59,7 @@ void GuiTrigger::SetHeldTrigger( s32 ch, u32 wiibtns, u16 gcbtns ) * Sets a button trigger. Requires: * - Trigger button is pressed */ -void GuiTrigger::SetButtonOnlyTrigger( s32 ch, u32 wiibtns, u16 gcbtns ) +void GuiTrigger::SetButtonOnlyTrigger(s32 ch, u32 wiibtns, u16 gcbtns) { type = TRIGGER_BUTTON_ONLY; chan = ch; @@ -72,7 +72,7 @@ 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 ) +void GuiTrigger::SetButtonOnlyInFocusTrigger(s32 ch, u32 wiibtns, u16 gcbtns) { type = TRIGGER_BUTTON_ONLY_IN_FOCUS; chan = ch; @@ -86,7 +86,7 @@ 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 ) +s8 GuiTrigger::WPAD_Stick(u8 right, int axis) { #ifdef HW_RVL @@ -97,28 +97,28 @@ s8 GuiTrigger::WPAD_Stick( u8 right, int axis ) { case WPAD_EXP_NUNCHUK: case WPAD_EXP_GUITARHERO3: - if ( right == 0 ) - { - mag = wpad.exp.nunchuk.js.mag; - ang = wpad.exp.nunchuk.js.ang; - } - break; + 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; + 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; + break; } /* calculate x/y value (angle need to be converted into radian) */ @@ -127,9 +127,9 @@ s8 GuiTrigger::WPAD_Stick( u8 right, int axis ) double val; if ( axis == 0 ) // x-axis - val = mag * sin( ( PI * ang ) / 180.0f ); + val = mag * sin( ( PI * ang ) / 180.0f ); else // y-axis - val = mag * cos( ( PI * ang ) / 180.0f ); + val = mag * cos( ( PI * ang ) / 180.0f ); return ( s8 )( val * 128.0f ); @@ -142,26 +142,22 @@ 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 | 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 ) + 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 ) + else if (scrollDelay == 0) { scrollDelay = SCROLL_LOOP_DELAY; return true; } else { - if ( scrollDelay > 0 ) - scrollDelay--; + if (scrollDelay > 0) scrollDelay--; } } return false; @@ -171,26 +167,22 @@ 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 | 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 ) + 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 ) + else if (scrollDelay == 0) { scrollDelay = SCROLL_LOOP_DELAY; return true; } else { - if ( scrollDelay > 0 ) - scrollDelay--; + if (scrollDelay > 0) scrollDelay--; } } return false; @@ -200,26 +192,22 @@ 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 | 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 ) + 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 ) + else if (scrollDelay == 0) { scrollDelay = SCROLL_LOOP_DELAY; return true; } else { - if ( scrollDelay > 0 ) - scrollDelay--; + if (scrollDelay > 0) scrollDelay--; } } return false; @@ -229,26 +217,22 @@ 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 | 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 ) + 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 ) + else if (scrollDelay == 0) { scrollDelay = SCROLL_LOOP_DELAY; return true; } else { - if ( scrollDelay > 0 ) - scrollDelay--; + if (scrollDelay > 0) scrollDelay--; } } return false; diff --git a/source/libwiigui/gui_window.cpp b/source/libwiigui/gui_window.cpp index 0552b444..d536386b 100644 --- a/source/libwiigui/gui_window.cpp +++ b/source/libwiigui/gui_window.cpp @@ -17,7 +17,7 @@ GuiWindow::GuiWindow() focus = 0; // allow focus } -GuiWindow::GuiWindow( int w, int h ) +GuiWindow::GuiWindow(int w, int h) { width = w; height = h; @@ -28,39 +28,36 @@ GuiWindow::~GuiWindow() { } -void GuiWindow::Append( GuiElement* e ) +void GuiWindow::Append(GuiElement* e) { LOCK( this ); - if ( e == NULL ) - return; + 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 ) +void GuiWindow::Insert(GuiElement* e, u32 index) { LOCK( this ); - if ( e == NULL || index > ( _elements.size() - 1 ) ) - return; + 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 ) +void GuiWindow::Remove(GuiElement* e) { LOCK( this ); - if ( e == NULL ) - return; + if (e == NULL) return; - for ( u8 i = 0; i < _elements.size(); i++ ) + for (u8 i = 0; i < _elements.size(); i++) { - if ( e == _elements.at( i ) ) + if (e == _elements.at(i)) { - _elements.erase( _elements.begin() + i ); + _elements.erase(_elements.begin() + i); break; } } @@ -72,11 +69,10 @@ void GuiWindow::RemoveAll() _elements.clear(); } -GuiElement* GuiWindow::GetGuiElementAt( u32 index ) const +GuiElement* GuiWindow::GetGuiElementAt(u32 index) const { - if ( index >= _elements.size() ) - return NULL; - return _elements.at( index ); + if (index >= _elements.size()) return NULL; + return _elements.at(index); } u32 GuiWindow::GetSize() @@ -87,169 +83,196 @@ u32 GuiWindow::GetSize() void GuiWindow::Draw() { LOCK( this ); - if ( _elements.size() == 0 || !this->IsVisible() ) - return; + if (_elements.size() == 0 || !this->IsVisible()) return; - for ( u8 i = 0; i < _elements.size(); i++ ) + for (u8 i = 0; i < _elements.size(); i++) { - try { _elements.at( i )->Draw(); } - catch ( const std::exception& e ) { } + try + { + _elements.at(i)->Draw(); + } + catch (const std::exception& e) + { + } } 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; + if (_elements.size() == 0 || !this->IsVisible()) return; - for ( u8 i = 0; i < _elements.size(); i++ ) + for (u8 i = 0; i < _elements.size(); i++) { - try { _elements.at( i )->DrawTooltip(); } - catch ( const std::exception& e ) { } + try + { + _elements.at(i)->DrawTooltip(); + } + catch (const std::exception& e) + { + } } } void GuiWindow::ResetState() { LOCK( this ); - if ( state != STATE_DISABLED ) - state = STATE_DEFAULT; + if (state != STATE_DISABLED) state = STATE_DEFAULT; - for ( u8 i = 0; i < _elements.size(); i++ ) + for (u8 i = 0; i < _elements.size(); i++) { - try { _elements.at( i )->ResetState(); } - catch ( const std::exception& e ) { } + try + { + _elements.at(i)->ResetState(); + } + catch (const std::exception& e) + { + } } } -void GuiWindow::SetState( int s ) +void GuiWindow::SetState(int s) { LOCK( this ); state = s; - for ( u8 i = 0; i < _elements.size(); i++ ) + for (u8 i = 0; i < _elements.size(); i++) { - try { _elements.at( i )->SetState( s ); } - catch ( const std::exception& e ) { } + try + { + _elements.at(i)->SetState(s); + } + catch (const std::exception& e) + { + } } } -void GuiWindow::SetVisible( bool v ) +void GuiWindow::SetVisible(bool v) { LOCK( this ); visible = v; - for ( u8 i = 0; i < _elements.size(); i++ ) + for (u8 i = 0; i < _elements.size(); i++) { - try { _elements.at( i )->SetVisible( v ); } - catch ( const std::exception& e ) { } + try + { + _elements.at(i)->SetVisible(v); + } + catch (const std::exception& e) + { + } } } -void GuiWindow::SetFocus( int 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 ) +void GuiWindow::ChangeFocus(GuiElement* e) { LOCK( this ); - if ( parentElement ) - return; // this is only intended for the main window + if (parentElement) return; // this is only intended for the main window - for ( u8 i = 0; i < _elements.size(); i++ ) + 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 ); + 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 ) +void GuiWindow::ToggleFocus(GuiTrigger * t) { LOCK( this ); - if ( parentElement ) - return; // this is only intended for the main window + if (parentElement) return; // this is only intended for the main window int found = -1; int newfocus = -1; u8 i; // look for currently in focus element - for ( i = 0; i < _elements.size(); i++ ) + for (i = 0; i < _elements.size(); i++) { try { - if ( _elements.at( i )->IsFocused() == 1 ) + if (_elements.at(i)->IsFocused() == 1) { found = i; break; } } - catch ( const std::exception& e ) { } + catch (const std::exception& e) + { + } } // element with focus not found, try to give focus - if ( found == -1 ) + if (found == -1) { - for ( i = 0; i < _elements.size(); i++ ) + 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) + 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(i)->SetFocus(1); // give this element focus break; } } - catch ( const std::exception& e ) { } + 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 ) + 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++ ) + 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) + 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 + _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 ) { } + catch (const std::exception& e) + { + } } - if ( newfocus == -1 ) + if (newfocus == -1) { - for ( i = 0; i < found; i++ ) + 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) + 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 + _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 ) { } + catch (const std::exception& e) + { + } } } } @@ -259,24 +282,26 @@ int GuiWindow::GetSelected() { // find selected element int found = -1; - for ( u8 i = 0; i < _elements.size(); i++ ) + for (u8 i = 0; i < _elements.size(); i++) { try { - if ( _elements.at( i )->GetState() == STATE_SELECTED ) + if (_elements.at(i)->GetState() == STATE_SELECTED) { found = i; break; } } - catch ( const std::exception& e ) { } + 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 ) +void GuiWindow::MoveSelectionHor(int dir) { LOCK( this ); int found = -1; @@ -286,67 +311,65 @@ void GuiWindow::MoveSelectionHor( int dir ) int selected = this->GetSelected(); - if ( selected >= 0 ) + if (selected >= 0) { - left = _elements.at( selected )->GetLeft(); - top = _elements.at( selected )->GetTop(); + 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++ ) + for (i = 0; i < _elements.size(); i++) { try { - if ( _elements.at( i )->IsSelectable() ) + if (_elements.at(i)->IsSelectable()) { - if ( _elements.at( i )->GetLeft()*dir > left*dir && _elements.at( i )->GetTop() == top ) + if (_elements.at(i)->GetLeft() * dir > left * dir && _elements.at(i)->GetTop() == top) { - if ( found == -1 ) + if (found == -1) found = i; - else if ( _elements.at( i )->GetLeft()*dir < _elements.at( found )->GetLeft()*dir ) - found = i; // this is a better match + else if (_elements.at(i)->GetLeft() * dir < _elements.at(found)->GetLeft() * dir) found = i; // this is a better match } } } - catch ( const std::exception& e ) { } + catch (const std::exception& e) + { + } } - if ( found >= 0 ) - goto matchfound; + 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++ ) + for (i = 0; i < _elements.size(); i++) { try { - if ( _elements.at( i )->IsSelectable() ) + if (_elements.at(i)->IsSelectable()) { - if ( _elements.at( i )->GetTop()*dir > top*dir ) + if (_elements.at(i)->GetTop() * dir > top * dir) { - if ( found == -1 ) + 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 ) + 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 ) { } + catch (const std::exception& e) + { + } } // match found -matchfound: - if ( found >= 0 ) + matchfound: if (found >= 0) { - _elements.at( found )->SetState( STATE_SELECTED ); - if ( selected >= 0 ) - _elements.at( selected )->ResetState(); + _elements.at(found)->SetState(STATE_SELECTED); + if (selected >= 0) _elements.at(selected)->ResetState(); } } -void GuiWindow::MoveSelectionVert( int dir ) +void GuiWindow::MoveSelectionVert(int dir) { LOCK( this ); int found = -1; @@ -356,75 +379,73 @@ void GuiWindow::MoveSelectionVert( int dir ) int selected = this->GetSelected(); - if ( selected >= 0 ) + if (selected >= 0) { - left = _elements.at( selected )->GetLeft(); - top = _elements.at( selected )->GetTop(); + 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++ ) + for (i = 0; i < _elements.size(); i++) { try { - if ( _elements.at( i )->IsSelectable() ) + if (_elements.at(i)->IsSelectable()) { - if ( _elements.at( i )->GetTop()*dir > top*dir ) + if (_elements.at(i)->GetTop() * dir > top * dir) { - if ( found == -1 ) + if (found == -1) found = i; - else if ( _elements.at( i )->GetTop()*dir < _elements.at( found )->GetTop()*dir ) + 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; + 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 ) { } + catch (const std::exception& e) + { + } } - if ( found >= 0 ) - goto matchfound; + if (found >= 0) goto matchfound; // match found -matchfound: - if ( found >= 0 ) + matchfound: if (found >= 0) { - _elements.at( found )->SetState( STATE_SELECTED ); - if ( selected >= 0 ) - _elements.at( selected )->ResetState(); + _elements.at(found)->SetState(STATE_SELECTED); + if (selected >= 0) _elements.at(selected)->ResetState(); } } -void GuiWindow::Update( GuiTrigger * t ) +void GuiWindow::Update(GuiTrigger * t) { LOCK( this ); - if ( _elements.size() == 0 || ( state == STATE_DISABLED && parentElement ) ) - return; + if (_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) return; - for ( u8 i = 0; i < _elements.size(); i++ ) + for (u8 i = 0; i < _elements.size(); i++) { - try { _elements.at( i )->Update( t ); } - catch ( const std::exception& e ) { } + 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 + 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 (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 7c6f2e28..99e26656 100644 --- a/source/listfiles.c +++ b/source/listfiles.c @@ -9,32 +9,31 @@ #include "listfiles.h" #include "libfat/fat.h" - static char alldirfiles[300][70]; char filenames[80]; -bool findfile( const char * filename, const char * path ) +bool findfile(const char * filename, const char * path) { DIR *dir; struct dirent *file; - dir = opendir( path ); + dir = opendir(path); char temp[11]; - while ( ( file = readdir( dir ) ) ) + while ((file = readdir(dir))) { - snprintf( temp, sizeof( temp ), "%s", file->d_name ); - if ( !strncmpi( temp, filename, 11 ) ) + snprintf(temp, sizeof(temp), "%s", file->d_name); + if (!strncmpi(temp, filename, 11)) { - closedir( dir ); + closedir(dir); return true; } } - closedir( dir ); + closedir(dir); return false; } -bool subfoldercreate( const char * fullpath ) +bool subfoldercreate(const char * fullpath) { //check forsubfolders char dir[300]; @@ -42,155 +41,151 @@ bool subfoldercreate( const char * fullpath ) u32 len; struct stat st; - strlcpy( dir, fullpath, sizeof( dir ) ); - len = strlen( dir ); - if ( len && len < sizeof( dir ) - 2 && dir[len-1] != '/' ) + 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? + 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; + while (len && dir[len - 1] == '/') + dir[--len] = '\0'; // remove all trailing / + pch = strrchr(dir, '/'); + if (pch == NULL) return false; *pch = '\0'; - if ( subfoldercreate( dir ) ) + if (subfoldercreate(dir)) { *pch = '/'; - if ( mkdir( dir, 0777 ) == -1 ) - return false; + if (mkdir(dir, 0777) == -1) return false; } - else - return false; + else return false; } return true; } -bool subfolderremove( const char * fullpath, const char*fp ) +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 ) ) + 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 ) + while (cont) { cont = false; - dir = diropen( fullpath ); - if ( dir ) + dir = diropen(fullpath); + if (dir) { - char* bind = fullpath[strlen( fullpath )-1] == '/' ? "" : "/"; - while ( dirnext( dir, filename, &st ) == 0 ) + char* bind = fullpath[strlen(fullpath) - 1] == '/' ? "" : "/"; + while (dirnext(dir, filename, &st) == 0) { - if ( strcmp( filename, "." ) != 0 && strcmp( filename, ".." ) != 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 ); + 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 ); + dirclose(dir); } } } - return unlink( fullpath ) == 0; + return unlink(fullpath) == 0; } -char * GetFileName( int i ) +char * GetFileName(int i) { return alldirfiles[i]; } -s32 filenamescmp( const void *a, const void *b ) +s32 filenamescmp(const void *a, const void *b) { /* Compare strings */ - return stricmp( ( char * )a, ( char * )b ); + return stricmp((char *) a, (char *) b); } -int GetAllDirFiles( char * filespath ) +int GetAllDirFiles(char * filespath) { int countfiles = 0; struct stat st; DIR_ITER* dir; - dir = diropen ( filespath ); + dir = diropen(filespath); - if ( dir == NULL ) //If empty - return 0; - while ( dirnext( dir, filenames, &st ) == 0 ) + if (dir == NULL) //If empty + return 0; + while (dirnext(dir, filenames, &st) == 0) { - if ( ( st.st_mode & S_IFDIR ) == 0 ) + if ((st.st_mode & S_IFDIR) == 0) { // st.st_mode & S_IFDIR indicates a directory - snprintf( alldirfiles[countfiles], 70, "%s", filenames ); + snprintf(alldirfiles[countfiles], 70, "%s", filenames); countfiles++; } } - dirclose( dir ); - qsort( alldirfiles, countfiles, sizeof( char[70] ), filenamescmp ); + dirclose(dir); + qsort(alldirfiles, countfiles, sizeof(char[70]), filenamescmp); return countfiles; } -bool checkfile( char * path ) +bool checkfile(char * path) { FILE * f; - f = fopen( path, "r" ); - if ( f ) + f = fopen(path, "r"); + if (f) { - fclose( f ); + fclose(f); return true; } 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; char filename[1024]; - char pathptr[strlen( searchpath )+1]; - snprintf( pathptr, sizeof( pathptr ), "%s", searchpath ); + 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'; + pathptr[strlen(pathptr) - 1] = '\0'; } - dir = diropen( pathptr ); - if ( !dir ) - return false; + dir = diropen(pathptr); + if (!dir) return false; - while ( dirnext( dir, filename, &st ) == 0 && result == false ) + while (dirnext(dir, filename, &st) == 0 && result == false) { - if ( strcasecmp( filename, searched_filename ) == 0 ) + if (strcasecmp(filename, searched_filename) == 0) { - if ( outfilepath ) + if (outfilepath) { - sprintf( outfilepath, "%s/%s", pathptr, filename ); + sprintf(outfilepath, "%s/%s", pathptr, filename); } result = true; } - else if ( ( st.st_mode & S_IFDIR ) != 0 ) + else if ((st.st_mode & S_IFDIR) != 0) { - if ( strcmp( filename, "." ) != 0 && strcmp( filename, ".." ) != 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 ); + snprintf(newpath, sizeof(newpath), "%s/%s", pathptr, filename); + result = SearchFile(newpath, searched_filename, outfilepath); } } } - dirclose( dir ); + dirclose(dir); return result; } diff --git a/source/listfiles.h b/source/listfiles.h index bed90a7d..932cd467 100644 --- a/source/listfiles.h +++ b/source/listfiles.h @@ -6,12 +6,12 @@ extern "C" { #endif - bool findfile( const char * filename, const char * path ); - char * GetFileName( int i ); - int GetAllDirFiles( char * filespath ); - bool subfoldercreate( const char * fullpath ); - bool checkfile( char * path ); - bool SearchFile( const char * searchpath, const char * searched_filename, char * outfilepath ); + bool findfile(const char * filename, const char * path); + char * GetFileName(int i); + int GetAllDirFiles(char * filespath); + bool subfoldercreate(const char * fullpath); + bool checkfile(char * path); + bool SearchFile(const char * searchpath, const char * searched_filename, char * outfilepath); #ifdef __cplusplus } diff --git a/source/lstub.cpp b/source/lstub.cpp index 37fa3d78..fc78b35e 100644 --- a/source/lstub.cpp +++ b/source/lstub.cpp @@ -5,7 +5,6 @@ #include #include - #include "lstub.h" #include "filelist.h" #include "gecko.h" @@ -14,29 +13,26 @@ static char* determineStubTIDLocation() { - u32 *stubID = ( u32* )0x80001818; + u32 *stubID = (u32*) 0x80001818; //HBC stub 1.0.6 and lower, and stub.bin - if ( stubID[ 0 ] == 0x480004c1 && stubID[ 1 ] == 0x480004f5 ) - return ( char * )0x800024C6; + if (stubID[0] == 0x480004c1 && stubID[1] == 0x480004f5) + return (char *) 0x800024C6; //HBC stub changed @ version 1.0.7. this file was last updated for HBC 1.0.8 - else if ( stubID[ 0 ] == 0x48000859 && stubID[ 1 ] == 0x4800088d ) - return ( char * )0x8000286A; + else if (stubID[0] == 0x48000859 && stubID[1] == 0x4800088d) return (char *) 0x8000286A; //hexdump( stubID, 0x20 ); return NULL; } -s32 Set_Stub( u64 reqID ) +s32 Set_Stub(u64 reqID) { - if ( titles.IndexOf( reqID ) < 0 ) - return WII_EINSTALL; + if (titles.IndexOf(reqID) < 0) return WII_EINSTALL; char *stub = determineStubTIDLocation(); - if ( !stub ) - return -68; + if (!stub) return -68; stub[0] = TITLE_7( reqID ); stub[1] = TITLE_6( reqID ); @@ -45,44 +41,41 @@ s32 Set_Stub( u64 reqID ) stub[4] = TITLE_3( reqID ); stub[5] = TITLE_2( reqID ); stub[12] = TITLE_1( reqID ); - stub[13] = ( ( u8 )( reqID ) ); + stub[13] = ((u8) (reqID)); - DCFlushRange( stub, 0x10 ); + DCFlushRange(stub, 0x10); return 1; } -s32 Set_Stub_Split( u32 type, const char* reqID ) +s32 Set_Stub_Split(u32 type, const char* reqID) { char tmp[4]; u32 lower; - sprintf( tmp, "%c%c%c%c", reqID[0], reqID[1], reqID[2], reqID[3] ); - memcpy( &lower, tmp, 4 ); + sprintf(tmp, "%c%c%c%c", reqID[0], reqID[1], reqID[2], reqID[3]); + memcpy(&lower, tmp, 4); u64 reqID64 = TITLE_ID( type, lower ); - return Set_Stub( reqID64 ); + return Set_Stub(reqID64); } void loadStub() { - char *stubLoc = ( char * )0x80001800; - memcpy( stubLoc, stub_bin, stub_bin_size ); - DCFlushRange( stubLoc, stub_bin_size ); + char *stubLoc = (char *) 0x80001800; + memcpy(stubLoc, stub_bin, stub_bin_size); + DCFlushRange(stubLoc, stub_bin_size); } u64 getStubDest() { - if ( !hbcStubAvailable() ) - return 0; + if (!hbcStubAvailable()) return 0; - char ret[ 8 ]; + char ret[8]; u64 retu = 0; char *stub = determineStubTIDLocation(); - if ( !stub ) - return 0; - + if (!stub) return 0; ret[0] = stub[0]; ret[1] = stub[1]; @@ -93,22 +86,15 @@ u64 getStubDest() ret[6] = stub[12]; ret[7] = stub[13]; - memcpy( &retu, ret, 8 ); + memcpy(&retu, ret, 8); return retu; } u8 hbcStubAvailable() { - char * sig = ( char * )0x80001804; - return ( - sig[0] == 'S' && - sig[1] == 'T' && - sig[2] == 'U' && - sig[3] == 'B' && - sig[4] == 'H' && - sig[5] == 'A' && - sig[6] == 'X' && - sig[7] == 'X' ) ? 1 : 0; + char * sig = (char *) 0x80001804; + return (sig[0] == 'S' && sig[1] == 'T' && sig[2] == 'U' && sig[3] == 'B' && sig[4] == 'H' && sig[5] == 'A' + && sig[6] == 'X' && sig[7] == 'X') ? 1 : 0; } diff --git a/source/lstub.h b/source/lstub.h index b1937250..978d563f 100644 --- a/source/lstub.h +++ b/source/lstub.h @@ -9,10 +9,10 @@ //!returns WII_EINTERNAL if it cant get the list of installed titles with ES functions //!retuns -69 if the ID is not installed //!1 if successful -s32 Set_Stub( u64 reqID ); +s32 Set_Stub(u64 reqID); //!same as the above function, but expects a type and 4 char channel ID -s32 Set_Stub_Split( u32 type, const char* reqID ); +s32 Set_Stub_Split(u32 type, const char* reqID); //load the default HBC stub into memory. as long as nothing writes to the 0x80001800 // +0xDC7 memory block it will stay there. by default it has 0x00010001/JODI. @@ -26,5 +26,4 @@ u64 getStubDest(); //returns 0 or 1 depending on wether the stub is available u8 hbcStubAvailable(); - #endif diff --git a/source/main.cpp b/source/main.cpp index 625e765b..793f95b9 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -153,6 +153,6 @@ int main(int argc, char *argv[]) gprintf("\n\tEnd of Main()"); InitGUIThreads(); - MainMenu(MENU_CHECK); + MainMenu( MENU_CHECK); return 0; } diff --git a/source/main.h b/source/main.h index fb320832..f545ca60 100644 --- a/source/main.h +++ b/source/main.h @@ -10,7 +10,6 @@ #include "FreeTypeGX.h" - void DefaultSettings(); extern FreeTypeGX *fontSystem; diff --git a/source/memory.h b/source/memory.h index 9e6f9a1f..84250b91 100644 --- a/source/memory.h +++ b/source/memory.h @@ -27,10 +27,8 @@ extern "C" #define Online_Check ((u32*) 0x80003180) #define GameID_Address ((u32*) 0x80003184) - #define allocate_memory(size) memalign(32, (size+31)&(~31)) - #ifdef __cplusplus } #endif diff --git a/source/memory/mem2.cpp b/source/memory/mem2.cpp index a30a0877..3226e19b 100644 --- a/source/memory/mem2.cpp +++ b/source/memory/mem2.cpp @@ -1,4 +1,3 @@ - #include "mem2.h" #include "mem2alloc.hpp" @@ -6,7 +5,6 @@ #include #define MEM2_PRIORITY_SIZE 2097152 //2MB - // Forbid the use of MEM2 through malloc u32 MALLOC_MEM2 = 0; @@ -17,39 +15,39 @@ static bool g_bigGoesToMem2 = false; extern "C" { - void MEM2_takeBigOnes( bool b ) + void MEM2_takeBigOnes(bool b) { g_bigGoesToMem2 = b; } - void MEM2_init( unsigned int mem2Size ) + void MEM2_init(unsigned int mem2Size) { - g_mem2gp.init( mem2Size ); + g_mem2gp.init(mem2Size); } - void MEM2_cleanup( void ) + void MEM2_cleanup(void) { g_mem2gp.cleanup(); } - void *MEM2_alloc( unsigned int s ) + void *MEM2_alloc(unsigned int s) { - return g_mem2gp.allocate( s ); + return g_mem2gp.allocate(s); } - void MEM2_free( void *p ) + void MEM2_free(void *p) { - g_mem2gp.release( p ); + g_mem2gp.release(p); } - void *MEM2_realloc( void *p, unsigned int s ) + void *MEM2_realloc(void *p, unsigned int s) { - return g_mem2gp.reallocate( p, s ); + return g_mem2gp.reallocate(p, s); } - unsigned int MEM2_usableSize( void *p ) + unsigned int MEM2_usableSize(void *p) { - return CMEM2Alloc::usableSize( p ); + return CMEM2Alloc::usableSize(p); } unsigned int MEM2_freesize() @@ -64,138 +62,136 @@ extern "C" extern __typeof( free ) __real_free; extern __typeof( malloc_usable_size ) __real_malloc_usable_size; - void *__wrap_malloc( size_t size ) + void *__wrap_malloc(size_t size) { void *p; - if ( g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE ) + if (g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE) { - p = MEM2_alloc( size ); - if ( p != 0 ) + p = MEM2_alloc(size); + if (p != 0) { return p; } - return __real_malloc( size ); + return __real_malloc(size); } - p = __real_malloc( size ); - if ( p != 0 ) + p = __real_malloc(size); + if (p != 0) { return p; } - return MEM2_alloc( size ); + return MEM2_alloc(size); } - void *__wrap_calloc( size_t n, size_t size ) + void *__wrap_calloc(size_t n, size_t size) { void *p; - if ( g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE ) + if (g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE) { - p = MEM2_alloc( n * size ); - if ( p != 0 ) + p = MEM2_alloc(n * size); + if (p != 0) { - memset( p, 0, n * size ); + memset(p, 0, n * size); return p; } - return __real_calloc( n, size ); + return __real_calloc(n, size); } - p = __real_calloc( n, size ); - if ( p != 0 ) + p = __real_calloc(n, size); + if (p != 0) { return p; } - p = MEM2_alloc( n * size ); - if ( p != 0 ) + p = MEM2_alloc(n * size); + if (p != 0) { - memset( p, 0, n * size ); + memset(p, 0, n * size); } return p; } - void *__wrap_memalign( size_t a, size_t size ) + void *__wrap_memalign(size_t a, size_t size) { void *p; - if ( g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE ) + if (g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE) { - if ( a <= 32 && 32 % a == 0 ) + if (a <= 32 && 32 % a == 0) { - p = MEM2_alloc( size ); - if ( p != 0 ) + p = MEM2_alloc(size); + if (p != 0) { return p; } } - return __real_memalign( a, size ); + return __real_memalign(a, size); } - p = __real_memalign( a, size ); - if ( p != 0 || a > 32 || 32 % a != 0 ) + 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 ) + void __wrap_free(void *p) { - if ( !p ) - return; + if (!p) return; - if ( ( ( u32 )p & 0x10000000 ) != 0 ) + if (((u32) p & 0x10000000) != 0) { - MEM2_free( p ); + MEM2_free(p); } else { - __real_free( p ); + __real_free(p); } } - void *__wrap_realloc( void *p, size_t size ) + 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 ) ) + if (((u32) p & 0x10000000) != 0 || (p == 0 && g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE)) { - n = MEM2_realloc( p, size ); - if ( n != 0 ) + n = MEM2_realloc(p, size); + if (n != 0) { return n; } - n = __real_malloc( size ); - if ( n == 0 ) + n = __real_malloc(size); + if (n == 0) { return 0; } - if ( p != 0 ) + if (p != 0) { - memcpy( n, p, MEM2_usableSize( p ) < size ? MEM2_usableSize( p ) : size ); - MEM2_free( p ); + 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 ) + n = __real_realloc(p, size); + if (n != 0) { return n; } - n = MEM2_alloc( size ); - if ( n == 0 ) + n = MEM2_alloc(size); + if (n == 0) { return 0; } - if ( p != 0 ) + if (p != 0) { - memcpy( n, p, __real_malloc_usable_size( p ) < size ? __real_malloc_usable_size( p ) : size ); - __real_free( p ); + 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 ) + size_t __wrap_malloc_usable_size(void *p) { - if ( ( ( u32 )p & 0x10000000 ) != 0 ) - return MEM2_usableSize( p ); - return __real_malloc_usable_size( p ); + if (((u32) p & 0x10000000) != 0) return MEM2_usableSize(p); + return __real_malloc_usable_size(p); } } ///extern "C" diff --git a/source/memory/mem2.h b/source/memory/mem2.h index f71a013e..ceb1bab0 100644 --- a/source/memory/mem2.h +++ b/source/memory/mem2.h @@ -9,13 +9,13 @@ extern "C" { #endif - void MEM2_init( unsigned int mem2Size ); - void MEM2_cleanup( void ); - void MEM2_takeBigOnes( bool b ); - 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_init(unsigned int mem2Size); + void MEM2_cleanup(void); + void MEM2_takeBigOnes(bool b); + 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); unsigned int MEM2_freesize(); #ifdef __cplusplus diff --git a/source/memory/mem2alloc.cpp b/source/memory/mem2alloc.cpp index c8cde9f1..73b43f9d 100644 --- a/source/memory/mem2alloc.cpp +++ b/source/memory/mem2alloc.cpp @@ -1,105 +1,105 @@ - #include "mem2alloc.hpp" #include #include #include - 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 ) +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 * ) 0x93300000 ) //rest is reserved for usb/usb2/network and other stuff... (0xE0000 bytes) - m_endAddress = ( SBlock * ) 0x93300000; - SYS_SetArena2Lo( m_endAddress ); - LWP_MutexInit( &m_mutex, 0 ); + 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 *) 0x93300000) //rest is reserved for usb/usb2/network and other stuff... (0xE0000 bytes) + m_endAddress = (SBlock *) 0x93300000; + SYS_SetArena2Lo(m_endAddress); + LWP_MutexInit(&m_mutex, 0); } -void CMEM2Alloc::init( void *addr, void *end ) +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 ); + m_baseAddress = (SBlock *) (((u32) addr + 31) & ~31); + m_endAddress = (SBlock *) ((u32) end & ~31); + LWP_MutexInit(&m_mutex, 0); } -void CMEM2Alloc::cleanup( void ) +void CMEM2Alloc::cleanup(void) { - LWP_MutexDestroy( m_mutex ); + LWP_MutexDestroy(m_mutex); m_mutex = 0; m_first = 0; // Try to release the range we took through SYS functions - if ( SYS_GetArena2Lo() == m_endAddress ) - SYS_SetArena2Lo( m_baseAddress ); + if (SYS_GetArena2Lo() == m_endAddress) SYS_SetArena2Lo(m_baseAddress); m_baseAddress = 0; m_endAddress = 0; } -void CMEM2Alloc::clear( void ) +void CMEM2Alloc::clear(void) { m_first = 0; - memset( m_baseAddress, 0, ( u8 * )m_endAddress - ( u8 * )m_endAddress ); + memset(m_baseAddress, 0, (u8 *) m_endAddress - (u8 *) m_endAddress); } -unsigned int CMEM2Alloc::usableSize( void *p ) +unsigned int CMEM2Alloc::usableSize(void *p) { - return p == 0 ? 0 : ( ( SBlock * )p - 1 )->s * sizeof ( SBlock ); + return p == 0 ? 0 : ((SBlock *) p - 1)->s * sizeof(SBlock); } -void *CMEM2Alloc::allocate( unsigned int s ) +void *CMEM2Alloc::allocate(unsigned int s) { - if ( s == 0 ) - s = 1; + if (s == 0) s = 1; // - LockMutex lock( m_mutex ); + LockMutex lock(m_mutex); // - s = ( s - 1 ) / sizeof ( SBlock ) + 1; + s = (s - 1) / sizeof(SBlock) + 1; // First block - if ( m_first == 0 ) + if (m_first == 0) { - if ( m_baseAddress + s + 1 >= m_endAddress ) - return 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 ); + return (void *) (m_first + 1); } // Search for a free block SBlock *i; SBlock *j; - for ( i = m_first; i != 0; i = i->next ) + for (i = m_first; i != 0; i = i->next) { - if ( i->f && i->s >= s ) - break; + if (i->f && i->s >= s) break; j = i; } // Create a new block - if ( i == 0 ) + if (i == 0) { i = j + j->s + 1; - if ( i + s + 1 >= m_endAddress ) - return 0; + 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 ); + return (void *) (i + 1); } // Reuse a free block i->f = false; // Split it - if ( i->s > s + 1 ) + if (i->s > s + 1) { j = i + s + 1; j->f = true; @@ -108,87 +108,79 @@ void *CMEM2Alloc::allocate( unsigned int s ) j->next = i->next; j->prev = i; i->next = j; - if ( j->next != 0 ) - j->next->prev = j; + if (j->next != 0) j->next->prev = j; } - return ( void * )( i + 1 ); + return (void *) (i + 1); } -void CMEM2Alloc::release( void *p ) +void CMEM2Alloc::release(void *p) { - if ( p == 0 ) - return; + if (p == 0) return; - LockMutex lock( m_mutex ); - SBlock *i = ( SBlock * )p - 1; + LockMutex lock(m_mutex); + SBlock *i = (SBlock *) p - 1; i->f = true; // If there are no other blocks following yet, // set the remaining size to free size. - Dimok - if ( i->next == 0 ) - i->s = m_endAddress - i - 1; + if (i->next == 0) i->s = m_endAddress - i - 1; // Merge with previous block - if ( i->prev != 0 && i->prev->f ) + 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; + if (i->next != 0) i->next->prev = i; } // Merge with next block - if ( i->next != 0 && i->next->f ) + 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; + if (i->next != 0) i->next->prev = i; } } -void *CMEM2Alloc::reallocate( void *p, unsigned int s ) +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 ); + if (s == 0) s = 1; + if (p == 0) return allocate(s); - i = ( SBlock * )p - 1; - s = ( s - 1 ) / sizeof ( SBlock ) + 1; + i = (SBlock *) p - 1; + s = (s - 1) / sizeof(SBlock) + 1; { - LockMutex lock( m_mutex ); + LockMutex lock(m_mutex); //out of memory /* Dimok */ - if ( i + s + 1 >= m_endAddress ) + if (i + s + 1 >= m_endAddress) { return 0; } // Last block - if ( i->next == 0 && i + s + 1 < m_endAddress ) + if (i->next == 0 && i + s + 1 < m_endAddress) { i->s = s; return p; } // Size <= current size + next block - if ( i->next != 0 && i->s < s && i->next->f && i->s + i->next->s + 1 >= s ) + if (i->next != 0 && 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; + if (i->next != 0) i->next->prev = i; } // Size <= current size - if ( i->s >= s ) + if (i->s >= s) { // Split - if ( i->s > s + 1 ) + if (i->s > s + 1) { j = i + s + 1; j->f = true; @@ -197,42 +189,38 @@ void *CMEM2Alloc::reallocate( void *p, unsigned int s ) j->next = i->next; j->prev = i; i->next = j; - if ( j->next != 0 ) - j->next->prev = 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 ); + n = allocate(s * sizeof(SBlock)); + if (n == 0) return 0; + memcpy(n, p, i->s * sizeof(SBlock)); + release(p); return n; } unsigned int CMEM2Alloc::FreeSize() { - LockMutex lock( m_mutex ); + LockMutex lock(m_mutex); - if ( m_first == 0 ) - return ( const char * ) m_endAddress - ( const char * ) m_baseAddress; + if (m_first == 0) return (const char *) m_endAddress - (const char *) m_baseAddress; SBlock *i; unsigned int size = 0; - for ( i = m_first; i != 0; i = i->next ) + for (i = m_first; i != 0; i = i->next) { - if ( i->f && i->next != 0 ) + if (i->f && i->next != 0) size += i->s; - else if ( i->f && i->next == 0 ) + else if (i->f && i->next == 0) size += m_endAddress - i - 1; - else if ( !i->f && i->next == 0 ) - size += m_endAddress - i - i->s - 1; + else if (!i->f && i->next == 0) size += m_endAddress - i - i->s - 1; } - return size*sizeof( SBlock ); + return size * sizeof(SBlock); } diff --git a/source/memory/mem2alloc.hpp b/source/memory/mem2alloc.hpp index e66f524a..7ee71fae 100644 --- a/source/memory/mem2alloc.hpp +++ b/source/memory/mem2alloc.hpp @@ -8,35 +8,48 @@ 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; } - unsigned int FreeSize(); - // - 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; -private: - CMEM2Alloc(const 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; + } + unsigned int FreeSize(); + // + 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; + private: + CMEM2Alloc(const CMEM2Alloc &); }; #endif // !defined(__MEM2ALLOC_HPP) diff --git a/source/menu.cpp b/source/menu.cpp index f49897f3..8d89358d 100644 --- a/source/menu.cpp +++ b/source/menu.cpp @@ -56,20 +56,18 @@ GuiText * GameRegionTxt = NULL; GuiImage * coverImg = NULL; GuiImageData * cover = NULL; bool altdoldefault = true; -char headlessID[8] = {0}; +char headlessID[8] = { 0 }; static lwp_t guithread = LWP_THREAD_NULL; static bool guiHalt = true; static int ExitRequested = 0; - /*** Extern variables ***/ extern u8 shutdown; extern u8 reset; extern s32 gameSelected, gameStart; extern u8 boothomebrew; - /**************************************************************************** * ResumeGui * @@ -80,7 +78,7 @@ extern u8 boothomebrew; void ResumeGui() { guiHalt = false; - LWP_ResumeThread ( guithread ); + LWP_ResumeThread(guithread); } /**************************************************************************** @@ -93,12 +91,12 @@ void ResumeGui() ***************************************************************************/ void HaltGui() { - if ( guiHalt )return; + if (guiHalt) return; guiHalt = true; // wait for thread to finish - while ( !LWP_ThreadIsSuspended( guithread ) ) - usleep( 50 ); + while (!LWP_ThreadIsSuspended(guithread)) + usleep(50); } /**************************************************************************** @@ -106,28 +104,28 @@ void HaltGui() * * Primary thread to allow GUI to respond to state changes, and draws GUI ***************************************************************************/ -static void * UpdateGUI ( void *arg ) +static void * UpdateGUI(void *arg) { int i; - while ( !ExitRequested ) + while (!ExitRequested) { - if ( guiHalt ) + if (guiHalt) { - LWP_SuspendThread( guithread ); + LWP_SuspendThread(guithread); continue; } mainWindow->Draw(); - if ( Settings.tooltips == TooltipsOn && THEME.show_tooltip != 0 && mainWindow->GetState() != STATE_DISABLED ) - mainWindow->DrawTooltip(); + if (Settings.tooltips == TooltipsOn && THEME.show_tooltip != 0 && mainWindow->GetState() != STATE_DISABLED) mainWindow->DrawTooltip(); - for ( i = 3; i >= 0; i-- ) + for (i = 3; i >= 0; i--) { - if ( userInput[i].wpad.ir.valid ) + if (userInput[i].wpad.ir.valid) { - Menu_DrawImg( userInput[i].wpad.ir.x - 48, userInput[i].wpad.ir.y - 48, 200.0, - 96, 96, pointer[i]->GetImage(), userInput[i].wpad.ir.angle, Settings.widescreen ? 0.8 : 1, 1, 255, 0, 0, 0, 0, 0, 0, 0, 0 ); + Menu_DrawImg(userInput[i].wpad.ir.x - 48, userInput[i].wpad.ir.y - 48, 200.0, 96, 96, + pointer[i]->GetImage(), userInput[i].wpad.ir.angle, Settings.widescreen ? 0.8 : 1, 1, 255, 0, + 0, 0, 0, 0, 0, 0, 0); } } @@ -135,40 +133,39 @@ static void * UpdateGUI ( void *arg ) UpdatePads(); - for ( i = 0; i < 4; i++ ) - mainWindow->Update( &userInput[i] ); + for (i = 0; i < 4; i++) + mainWindow->Update(&userInput[i]); - if ( bgMusic ) - bgMusic->UpdateState(); + if (bgMusic) bgMusic->UpdateState(); - switch ( Settings.screensaver ) + switch (Settings.screensaver) { case 1: - WPad_SetIdleTime( 180 ); + WPad_SetIdleTime(180); break; case 2: - WPad_SetIdleTime( 300 ); + WPad_SetIdleTime(300); break; case 3: - WPad_SetIdleTime( 600 ); + WPad_SetIdleTime(600); break; case 4: - WPad_SetIdleTime( 1200 ); + WPad_SetIdleTime(1200); break; case 5: - WPad_SetIdleTime( 1800 ); + WPad_SetIdleTime(1800); break; case 6: - WPad_SetIdleTime( 3600 ); + WPad_SetIdleTime(3600); break; } } - for ( i = 5; i < 255; i += 10 ) + for (i = 5; i < 255; i += 10) { - if ( strcmp( headlessID, "" ) == 0 ) - mainWindow->Draw(); - Menu_DrawRectangle( 0, 0, screenwidth, screenheight, ( GXColor ) {0, 0, 0, i}, 1 ); + if (strcmp(headlessID, "") == 0) mainWindow->Draw(); + Menu_DrawRectangle(0, 0, screenwidth, screenheight, ( GXColor ) + { 0, 0, 0, i}, 1); Menu_Render(); } mainWindow->RemoveAll(); @@ -184,66 +181,67 @@ static void * UpdateGUI ( void *arg ) ***************************************************************************/ void InitGUIThreads() { - LWP_CreateThread( &guithread, UpdateGUI, NULL, NULL, 65536, LWP_PRIO_HIGHEST ); + LWP_CreateThread(&guithread, UpdateGUI, NULL, NULL, 65536, LWP_PRIO_HIGHEST); InitProgressThread(); InitNetworkThread(); - if ( Settings.autonetwork ) - ResumeNetworkThread(); + if (Settings.autonetwork) ResumeNetworkThread(); } void ExitGUIThreads() { ExitRequested = 1; - LWP_JoinThread( guithread, NULL ); + LWP_JoinThread(guithread, NULL); guithread = LWP_THREAD_NULL; } /**************************************************************************** * LoadCoverImage ***************************************************************************/ -GuiImageData *LoadCoverImage( struct discHdr *header, bool Prefere3D, bool noCover ) +GuiImageData *LoadCoverImage(struct discHdr *header, bool Prefere3D, bool noCover) { - if ( !header ) return NULL; + 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 ) + for (int i = 0; i < 2; ++i) { - char *coverPath = flag ? Settings.covers_path : Settings.covers2d_path; flag = !flag; + 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 ); + 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() ) + if (!Cover || !Cover->GetImage()) { - snprintf( Path, sizeof( Path ), "%s%s.png", coverPath, ID ); - delete Cover; Cover = new( std::nothrow ) GuiImageData( Path, NULL ); + snprintf(Path, sizeof(Path), "%s%s.png", coverPath, ID); + delete Cover; + Cover = new (std::nothrow) GuiImageData(Path, NULL); } - if ( Cover && Cover->GetImage() ) - break; + if (Cover && Cover->GetImage()) break; } //Load no image - if ( noCover && ( !Cover || !Cover->GetImage() ) ) + if (noCover && (!Cover || !Cover->GetImage())) { flag = Prefere3D; - for ( int i = 0; i < 2; ++i ) + for (int i = 0; i < 2; ++i) { - const char *nocoverPath = ( flag ? "%snoimage.png" : "%snoimage2d.png" ); flag = !flag; - snprintf( Path, sizeof( Path ), nocoverPath, Settings.theme_path ); - delete Cover; Cover = new( std::nothrow ) GuiImageData( Path, ( Prefere3D ? nocover_png : nocoverFlat_png ) ); - if ( Cover && Cover->GetImage() ) - break; + const char *nocoverPath = (flag ? "%snoimage.png" : "%snoimage2d.png"); + flag = !flag; + snprintf(Path, sizeof(Path), nocoverPath, Settings.theme_path); + delete Cover; + Cover = new (std::nothrow) GuiImageData(Path, (Prefere3D ? nocover_png : nocoverFlat_png)); + if (Cover && Cover->GetImage()) break; } } - if ( Cover && !Cover->GetImage() ) + if (Cover && !Cover->GetImage()) { delete Cover; Cover = NULL; @@ -254,7 +252,7 @@ GuiImageData *LoadCoverImage( struct discHdr *header, bool Prefere3D, bool noCov /**************************************************************************** * MainMenu ***************************************************************************/ -int MainMenu( int menu ) +int MainMenu(int menu) { currentMenu = menu; @@ -263,41 +261,39 @@ int MainMenu( int menu ) //if (strcmp(headlessID,"")!=0)HaltGui(); //WindowPrompt("Can you see me now",0,"ok"); - snprintf( imgPath, sizeof( imgPath ), "%splayer1_point.png", Settings.theme_path ); - pointer[0] = new GuiImageData( imgPath, player1_point_png ); - snprintf( imgPath, sizeof( imgPath ), "%splayer2_point.png", Settings.theme_path ); - pointer[1] = new GuiImageData( imgPath, player2_point_png ); - snprintf( imgPath, sizeof( imgPath ), "%splayer3_point.png", Settings.theme_path ); - pointer[2] = new GuiImageData( imgPath, player3_point_png ); - snprintf( imgPath, sizeof( imgPath ), "%splayer4_point.png", Settings.theme_path ); - pointer[3] = new GuiImageData( imgPath, player4_point_png ); + snprintf(imgPath, sizeof(imgPath), "%splayer1_point.png", Settings.theme_path); + pointer[0] = new GuiImageData(imgPath, player1_point_png); + snprintf(imgPath, sizeof(imgPath), "%splayer2_point.png", Settings.theme_path); + pointer[1] = new GuiImageData(imgPath, player2_point_png); + snprintf(imgPath, sizeof(imgPath), "%splayer3_point.png", Settings.theme_path); + pointer[2] = new GuiImageData(imgPath, player3_point_png); + snprintf(imgPath, sizeof(imgPath), "%splayer4_point.png", Settings.theme_path); + pointer[3] = new GuiImageData(imgPath, player4_point_png); - mainWindow = new GuiWindow( screenwidth, screenheight ); + mainWindow = new GuiWindow(screenwidth, screenheight); - if ( Settings.widescreen ) - snprintf( imgPath, sizeof( imgPath ), "%swbackground.png", Settings.theme_path ); - else - snprintf( imgPath, sizeof( imgPath ), "%sbackground.png", Settings.theme_path ); + if (Settings.widescreen) + snprintf(imgPath, sizeof(imgPath), "%swbackground.png", Settings.theme_path); + else snprintf(imgPath, sizeof(imgPath), "%sbackground.png", Settings.theme_path); - background = new GuiImageData( imgPath, Settings.widescreen ? wbackground_png : background_png ); + background = new GuiImageData(imgPath, Settings.widescreen ? wbackground_png : background_png); - bgImg = new GuiImage( background ); - mainWindow->Append( bgImg ); + bgImg = new GuiImage(background); + mainWindow->Append(bgImg); - if ( strcmp( headlessID, "" ) == 0 ) - ResumeGui(); + if (strcmp(headlessID, "") == 0) ResumeGui(); - bgMusic = new GuiBGM( bg_music_ogg, bg_music_ogg_size, Settings.volume ); - bgMusic->SetLoop( Settings.musicloopmode ); //loop music - bgMusic->Load( Settings.ogg_path ); + bgMusic = new GuiBGM(bg_music_ogg, bg_music_ogg_size, Settings.volume); + bgMusic->SetLoop(Settings.musicloopmode); //loop music + bgMusic->Load(Settings.ogg_path); bgMusic->Play(); - while ( currentMenu != MENU_EXIT ) + while (currentMenu != MENU_EXIT) { - bgMusic->SetVolume( Settings.volume ); -// gprintf("Current menu: %d\n", currentMenu); + bgMusic->SetVolume(Settings.volume); + // gprintf("Current menu: %d\n", currentMenu); - switch ( currentMenu ) + switch (currentMenu) { case MENU_CHECK: currentMenu = MenuCheck(); @@ -326,16 +322,15 @@ int MainMenu( int menu ) } } - // MemInfoPrompt(); - gprintf( "Exiting main GUI. mountMethod = %d\n", mountMethod ); + gprintf("Exiting main GUI. mountMethod = %d\n", mountMethod); CloseXMLDatabase(); NewTitles::DestroyInstance(); 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(); + 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(); bgMusic->Stop(); @@ -343,7 +338,7 @@ int MainMenu( int menu ) delete background; delete bgImg; delete mainWindow; - for ( int i = 0; i < 4; i++ ) + for (int i = 0; i < 4; i++) delete pointer[i]; delete GameRegionTxt; delete GameIDTxt; @@ -354,77 +349,77 @@ int MainMenu( int menu ) StopGX(); gettextCleanUp(); - if ( mountMethod == 3 ) + 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 ) ); + 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 ) ); + WII_LaunchTitle(TITLE_ID( ( header->id[5] == '1' ? 0x00010001 : 0x00010002 ), tid )); } - if ( mountMethod == 2 ) + if (mountMethod == 2) { - gprintf( "\nLoading BC for GameCube" ); + gprintf("\nLoading BC for GameCube"); WII_Initialize(); - WII_LaunchTitle( 0x0000000100000100ULL ); + WII_LaunchTitle(0x0000000100000100ULL); } - if ( boothomebrew == 1 ) + if (boothomebrew == 1) { - gprintf( "\nBootHomebrew" ); - BootHomebrew( Settings.selected_homebrew ); + gprintf("\nBootHomebrew"); + BootHomebrew(Settings.selected_homebrew); } - else if ( boothomebrew == 2 ) + else if (boothomebrew == 2) { - gprintf( "\nBootHomebrew from Menu" ); + gprintf("\nBootHomebrew from Menu"); //BootHomebrew(); BootHomebrewFromMem(); } else { - gprintf( "\tSettings.partition: %d\n", Settings.partition ); + gprintf("\tSettings.partition: %d\n", Settings.partition); struct discHdr *header = NULL; //if the GUI was "skipped" to boot a game from main(argv[1]) - if ( strcmp( headlessID, "" ) != 0 ) + if (strcmp(headlessID, "") != 0) { - gprintf( "\tHeadless mode (%s)\n", headlessID ); + gprintf("\tHeadless mode (%s)\n", headlessID); gameList.LoadUnfiltered(); - if ( !gameList.size() ) + if (!gameList.size()) { - gprintf( " ERROR : !gameCnt" ); - exit( 0 ); + gprintf(" ERROR : !gameCnt"); + exit(0); } //gprintf("\n\tgameCnt:%d",gameCnt); - for ( int i = 0; i < gameList.size(); i++ ) + for (int i = 0; i < gameList.size(); i++) { header = gameList[i]; char tmp[8]; - sprintf( tmp, "%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5] ); - if ( strcmp( tmp, headlessID ) == 0 ) + sprintf(tmp, "%c%c%c%c%c%c", header->id[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)\n", i ); + gprintf(" found (%d)\n", i); break; } //if the game was not found - if ( i == gameList.GameCount() - 1 ) + if (i == gameList.GameCount() - 1) { - gprintf( " not found (%d IDs checked)\n", i ); - exit( 0 ); + gprintf(" not found (%d IDs checked)\n", i); + exit(0); } } } - int ret = 0; - header = ( mountMethod ? dvdheader : gameList[gameSelected] ); + header = (mountMethod ? dvdheader : gameList[gameSelected]); - struct Game_CFG* game_cfg = CFG_get_game_opt( header->id ); + struct Game_CFG* game_cfg = CFG_get_game_opt(header->id); - if ( game_cfg ) + if (game_cfg) { videoChoice = game_cfg->video; languageChoice = game_cfg->language; @@ -433,13 +428,13 @@ int MainMenu( int menu ) fix002 = game_cfg->errorfix002; iosChoice = game_cfg->ios; countrystrings = game_cfg->patchcountrystrings; - if ( !altdoldefault ) + if (!altdoldefault) { alternatedol = game_cfg->loadalternatedol; alternatedoloffset = game_cfg->alternatedolstart; } reloadblock = game_cfg->iosreloadblock; - returnToLoaderGV = game_cfg->returnTo; + returnToLoaderGV = game_cfg->returnTo; } else { @@ -450,7 +445,7 @@ int MainMenu( int menu ) iosChoice = Settings.cios; fix002 = Settings.error002; countrystrings = Settings.patchcountrystrings; - if ( !altdoldefault ) + if (!altdoldefault) { alternatedol = off; alternatedoloffset = 0; @@ -459,39 +454,38 @@ int MainMenu( int menu ) returnToLoaderGV = 1; } - if ( !mountMethod ) + if (!mountMethod) { - gprintf( "Loading fragment list..." ); - ret = get_frag_list( header->id ); - gprintf( "%d\n", ret ); + gprintf("Loading fragment list..."); + ret = get_frag_list(header->id); + gprintf("%d\n", ret); - gprintf( "Setting fragment list..." ); - ret = set_frag_list( header->id ); - gprintf( "%d\n", ret ); + gprintf("Setting fragment list..."); + ret = set_frag_list(header->id); + gprintf("%d\n", ret); - ret = Disc_SetUSB( header->id ); - if ( ret < 0 ) Sys_BackToLoader(); - gprintf( "\tUSB set to game\n" ); + ret = Disc_SetUSB(header->id); + if (ret < 0) Sys_BackToLoader(); + gprintf("\tUSB set to game\n"); } else { - gprintf( "\tUSB not set, loading DVD\n" ); + gprintf("\tUSB not set, loading DVD\n"); } ret = Disc_Open(); - if ( ret < 0 ) Sys_BackToLoader(); + if (ret < 0) Sys_BackToLoader(); - if ( dvdheader ) - delete dvdheader; + if (dvdheader) delete dvdheader; - gprintf( "Loading BCA data..." ); - ret = do_bca_code( header->id ); - gprintf( "%d\n", ret ); + gprintf("Loading BCA data..."); + ret = do_bca_code(header->id); + gprintf("%d\n", ret); - if ( reloadblock == on && Sys_IsHermes() ) + if (reloadblock == on && Sys_IsHermes()) { enable_ES_ioctlv_vector(); - if ( load_from_fs == PART_FS_WBFS ) + if (load_from_fs == PART_FS_WBFS) { mload_close(); } @@ -499,7 +493,7 @@ int MainMenu( int menu ) u8 errorfixer002 = fix002; - switch ( languageChoice ) + switch (languageChoice) { case ConsoleLangDefault: configbytes[0] = 0xCD; @@ -552,7 +546,7 @@ int MainMenu( int menu ) u8 videoselected = 0; - switch ( videoChoice ) + switch (videoChoice) { case discdefault: videoselected = 0; @@ -584,7 +578,7 @@ int MainMenu( int menu ) } u32 cheat = 0; - switch ( ocarinaChoice ) + switch (ocarinaChoice) { case on: cheat = 1; @@ -600,7 +594,7 @@ int MainMenu( int menu ) } u8 vipatch = 0; - switch ( viChoice ) + switch (viChoice) { case on: vipatch = 1; @@ -615,28 +609,28 @@ int MainMenu( int menu ) break; } - u32 channel = 0; - if( returnToLoaderGV ) - { - int idx = titles.FindU32( Settings.returnTo ); - if( idx >= 0 ) - channel = TITLE_LOWER( titles.At( idx ) ); - } + u32 channel = 0; + if (returnToLoaderGV) + { + int idx = titles.FindU32(Settings.returnTo); + if (idx >= 0) channel = TITLE_LOWER( titles.At( idx ) ); + } - //This is temporary - SetCheatFilepath(Settings.Cheatcodespath); - SetBCAFilepath(Settings.BcaCodepath); + //This is temporary + SetCheatFilepath(Settings.Cheatcodespath); + SetBCAFilepath(Settings.BcaCodepath); - gprintf( "\tDisc_wiiBoot\n" ); + gprintf("\tDisc_wiiBoot\n"); - ret = Disc_WiiBoot( Settings.dolpath, videoselected, cheat, vipatch, countrystrings, errorfixer002, alternatedol, alternatedoloffset, channel ); - if ( ret < 0 ) + ret = Disc_WiiBoot(Settings.dolpath, videoselected, cheat, vipatch, countrystrings, errorfixer002, + alternatedol, alternatedoloffset, channel); + if (ret < 0) { Sys_LoadMenu(); } //should never get here - printf( "Returning entry point: 0x%0x\n", ret ); + printf("Returning entry point: 0x%0x\n", ret); } return 0; } diff --git a/source/menu.h b/source/menu.h index bd45a7ad..b15df932 100644 --- a/source/menu.h +++ b/source/menu.h @@ -13,10 +13,10 @@ #include "settings/CSettings.h" #include "main.h" -void InitGUIThreads( void ); -void ExitGUIThreads( void ); +void InitGUIThreads(void); +void ExitGUIThreads(void); -int MainMenu ( int menuitem ); +int MainMenu(int menuitem); enum { @@ -33,7 +33,7 @@ enum MENU_THEMEDOWNLOADER }; class GuiImageData; -GuiImageData *LoadCoverImage( struct discHdr *header, bool Prefere3D = true, bool noCover = true ); +GuiImageData *LoadCoverImage(struct discHdr *header, bool Prefere3D = true, bool noCover = true); class GuiSound; extern GuiSound *btnClick2; #endif diff --git a/source/menu/menu_check.cpp b/source/menu/menu_check.cpp index 8ddd659b..54b5c367 100644 --- a/source/menu/menu_check.cpp +++ b/source/menu/menu_check.cpp @@ -16,7 +16,7 @@ extern char headlessID[8]; ***************************************************************************/ int MenuCheck() { - gprintf( "\nMenuCheck()" ); + gprintf("\nMenuCheck()"); int menu = MENU_NONE; int i = 0; int choice; @@ -24,22 +24,23 @@ int MenuCheck() OptionList options; options.length = i; - VIDEO_WaitVSync (); + VIDEO_WaitVSync(); - wbfsinit = WBFS_Init( WBFS_DEVICE_USB ); - if ( wbfsinit < 0 ) + wbfsinit = WBFS_Init(WBFS_DEVICE_USB); + if (wbfsinit < 0) { - ret2 = WindowPrompt( tr( "No USB Device found." ), tr( "Do you want to retry for 30 secs?" ), "cIOS249", "cIOS222", tr( "Back to Wii Menu" ) ); + ret2 = WindowPrompt(tr( "No USB Device found." ), tr( "Do you want to retry for 30 secs?" ), "cIOS249", + "cIOS222", tr( "Back to Wii Menu" )); SDCard_deInit(); USBDevice_deInit(); - WPAD_Flush( 0 ); - WPAD_Disconnect( 0 ); + WPAD_Flush(0); + WPAD_Disconnect(0); WPAD_Shutdown(); - if ( ret2 == 1 ) + if (ret2 == 1) { Settings.cios = 249; } - else if ( ret2 == 2 ) + else if (ret2 == 2) { Settings.cios = 222; } @@ -47,36 +48,37 @@ int MenuCheck() { Sys_LoadMenu(); } - ret2 = DiscWait( tr( "No USB Device" ), tr( "Waiting for USB Device" ), 0, 0, 1 ); + ret2 = DiscWait(tr( "No USB Device" ), tr( "Waiting for USB Device" ), 0, 0, 1); //reinitialize SD and USB Wpad_Init(); - WPAD_SetDataFormat( WPAD_CHAN_ALL, WPAD_FMT_BTNS_ACC_IR ); - WPAD_SetVRes( WPAD_CHAN_ALL, screenwidth, screenheight ); - if ( ret2 < 0 ) + WPAD_SetDataFormat(WPAD_CHAN_ALL, WPAD_FMT_BTNS_ACC_IR); + WPAD_SetVRes(WPAD_CHAN_ALL, screenwidth, screenheight); + if (ret2 < 0) { - WindowPrompt ( tr( "Error !" ), tr( "USB Device not found" ), tr( "OK" ) ); + WindowPrompt(tr( "Error !" ), tr( "USB Device not found" ), tr( "OK" )); Sys_LoadMenu(); } } ret2 = -1; - memset( game_partition, 0, 6 ); + memset(game_partition, 0, 6); load_from_fs = -1; extern PartList partitions; // Added for slow HDD - for ( int runs = 0; runs < 10; runs++ ) + for (int runs = 0; runs < 10; runs++) { - if ( Partition_GetList( WBFS_DEVICE_USB, &partitions ) != 0 ) + if (Partition_GetList(WBFS_DEVICE_USB, &partitions) != 0) { - sleep( 1 ); + sleep(1); continue; } - if ( Settings.partition != -1 && partitions.num > Settings.partition ) + 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 ) ) + if (!WBFS_OpenPart(pinfo.part_fs, pinfo.index, partitions.pentry[Settings.partition].sector, + partitions.pentry[Settings.partition].size, (char *) &game_partition)) { ret2 = 0; load_from_fs = pinfo.part_fs; @@ -84,12 +86,12 @@ int MenuCheck() } } - if ( partitions.wbfs_n != 0 ) + if (partitions.wbfs_n != 0) { ret2 = WBFS_Open(); - for ( int p = 0; p < partitions.num; p++ ) + for (int p = 0; p < partitions.num; p++) { - if ( partitions.pinfo[p].fs_type == FS_TYPE_WBFS ) + if (partitions.pinfo[p].fs_type == FS_TYPE_WBFS) { Settings.partition = p; load_from_fs = PART_FS_WBFS; @@ -97,22 +99,23 @@ int MenuCheck() } } } - else if ( Sys_IsHermes() && ( partitions.fat_n != 0 || partitions.ntfs_n != 0 ) ) + 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++ ) + 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.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 ) ) + 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 ); + WBFS_GetCount(&count); - if ( count > 0 ) + if (count > 0) { load_from_fs = partitions.pinfo[i].part_fs; Settings.partition = i; @@ -127,18 +130,19 @@ int MenuCheck() } } - if ( ( ret2 >= 0 || load_from_fs != PART_FS_WBFS ) && isInserted( bootDevice ) ) + if ((ret2 >= 0 || load_from_fs != PART_FS_WBFS) && isInserted(bootDevice)) { Settings.Save(); break; } - sleep( 1 ); + sleep(1); } - if ( ret2 < 0 && load_from_fs != PART_FS_WBFS ) + 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 ) + 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(); } @@ -150,24 +154,23 @@ int MenuCheck() } ret2 = Disc_Init(); - if ( ret2 < 0 ) + if (ret2 < 0) { - WindowPrompt ( tr( "Error !" ), tr( "Could not initialize DIP module!" ), tr( "OK" ) ); + WindowPrompt(tr( "Error !" ), tr( "Could not initialize DIP module!" ), tr( "OK" )); Sys_LoadMenu(); } - if ( shutdown == 1 ) - Sys_Shutdown(); - if ( reset == 1 ) - Sys_Reboot(); + if (shutdown == 1) Sys_Shutdown(); + if (reset == 1) Sys_Reboot(); - if ( wbfsinit < 0 ) + if (wbfsinit < 0) { - sleep( 1 ); + 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 ); + 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); @@ -176,16 +179,14 @@ int MenuCheck() //Spieleliste laden //__Menu_GetEntries(0);//no point getting the gamelist here - if ( strcmp( headlessID, "" ) != 0 ) - menu = MENU_EXIT; + if (strcmp(headlessID, "") != 0) menu = MENU_EXIT; - if ( menu == MENU_NONE ) - menu = MENU_DISCLIST; + if (menu == MENU_NONE) menu = MENU_DISCLIST; //for HDDs with issues - if ( wbfsinit < 0 ) + if (wbfsinit < 0) { - sleep( 1 ); + sleep(1); USBDevice_Init(); SDCard_Init(); } diff --git a/source/menu/menu_disclist.cpp b/source/menu/menu_disclist.cpp index ee7c362a..f8adc607 100644 --- a/source/menu/menu_disclist.cpp +++ b/source/menu/menu_disclist.cpp @@ -39,8 +39,8 @@ GuiButton *Toolbar[9]; int idiotFlag = -1; char idiotChar[50]; -void DiscListWinUpdateCallback( void * e ); -void rockout( int f = 0 ); +void DiscListWinUpdateCallback(void * e); +void rockout(int f = 0); static u32 startat = 0; @@ -50,7 +50,7 @@ static u32 startat = 0; int MenuDiscList() { - gprintf( "MenuDiscList()\n" ); + gprintf("MenuDiscList()\n"); gameList.FilterList(); int offset = MIN( ( int )startat, gameList.size() - 1 ); startat = offset; @@ -63,11 +63,10 @@ int MenuDiscList() char IDfull[7]; u32 covert = 0; char imgPath[100]; - if ( !dvdheader ) - dvdheader = new struct discHdr; + if (!dvdheader) dvdheader = new struct discHdr; u8 mountMethodOLD = 0; - WDVD_GetCoverStatus( &covert ); + WDVD_GetCoverStatus(&covert); u32 covertOld = covert; f32 freespace, used, size = 0.0; @@ -78,7 +77,6 @@ int MenuDiscList() datagB = 0; int menu = MENU_NONE, dataef = 0; - u32 nolist; char text[MAX_CHARACTERS + 4]; int choice = 0, selectedold = 100; @@ -89,616 +87,642 @@ int MenuDiscList() char theTime[80] = ""; time_t lastrawtime = 0; - if ( mountMethod != 3 && WBFS_ShowFreeSpace() ) + if (mountMethod != 3 && WBFS_ShowFreeSpace()) { - WBFS_DiskSpace( &used, &freespace ); + WBFS_DiskSpace(&used, &freespace); } - if ( !gameList.size() ) //if there is no list of games to display + if (!gameList.size()) //if there is no list of games to display { nolist = 1; } - GuiSound btnSoundOver( button_over_pcm, button_over_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 ); + 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", Settings.theme_path ); - GuiImageData btnInstall( imgPath, button_install_png ); - snprintf( imgPath, sizeof( imgPath ), "%sbutton_install_over.png", Settings.theme_path ); - GuiImageData btnInstallOver( imgPath, button_install_over_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_install.png", Settings.theme_path); + GuiImageData btnInstall(imgPath, button_install_png); + snprintf(imgPath, sizeof(imgPath), "%sbutton_install_over.png", Settings.theme_path); + GuiImageData btnInstallOver(imgPath, button_install_over_png); - snprintf( imgPath, sizeof( imgPath ), "%ssettings_button.png", Settings.theme_path ); - GuiImageData btnSettings( imgPath, settings_button_png ); - snprintf( imgPath, sizeof( imgPath ), "%ssettings_button_over.png", Settings.theme_path ); - GuiImageData btnSettingsOver( imgPath, settings_button_over_png ); - GuiImageData dataID( &data1 ); + snprintf(imgPath, sizeof(imgPath), "%ssettings_button.png", Settings.theme_path); + GuiImageData btnSettings(imgPath, settings_button_png); + snprintf(imgPath, sizeof(imgPath), "%ssettings_button_over.png", Settings.theme_path); + GuiImageData btnSettingsOver(imgPath, settings_button_over_png); + GuiImageData dataID(&data1); - snprintf( imgPath, sizeof( imgPath ), "%swiimote_poweroff.png", Settings.theme_path ); - GuiImageData btnpwroff( imgPath, wiimote_poweroff_png ); - snprintf( imgPath, sizeof( imgPath ), "%swiimote_poweroff_over.png", Settings.theme_path ); - GuiImageData btnpwroffOver( imgPath, wiimote_poweroff_over_png ); - snprintf( imgPath, sizeof( imgPath ), "%smenu_button.png", Settings.theme_path ); - GuiImageData btnhome( imgPath, menu_button_png ); - snprintf( imgPath, sizeof( imgPath ), "%smenu_button_over.png", Settings.theme_path ); - GuiImageData btnhomeOver( imgPath, menu_button_over_png ); - snprintf( imgPath, sizeof( imgPath ), "%sSDcard_over.png", Settings.theme_path ); - GuiImageData btnsdcardOver( imgPath, sdcard_over_png ); - snprintf( imgPath, sizeof( imgPath ), "%sSDcard.png", Settings.theme_path ); - GuiImageData btnsdcard( imgPath, sdcard_png ); + snprintf(imgPath, sizeof(imgPath), "%swiimote_poweroff.png", Settings.theme_path); + GuiImageData btnpwroff(imgPath, wiimote_poweroff_png); + snprintf(imgPath, sizeof(imgPath), "%swiimote_poweroff_over.png", Settings.theme_path); + GuiImageData btnpwroffOver(imgPath, wiimote_poweroff_over_png); + snprintf(imgPath, sizeof(imgPath), "%smenu_button.png", Settings.theme_path); + GuiImageData btnhome(imgPath, menu_button_png); + snprintf(imgPath, sizeof(imgPath), "%smenu_button_over.png", Settings.theme_path); + GuiImageData btnhomeOver(imgPath, menu_button_over_png); + snprintf(imgPath, sizeof(imgPath), "%sSDcard_over.png", Settings.theme_path); + GuiImageData btnsdcardOver(imgPath, sdcard_over_png); + snprintf(imgPath, sizeof(imgPath), "%sSDcard.png", Settings.theme_path); + GuiImageData btnsdcard(imgPath, sdcard_png); + snprintf(imgPath, sizeof(imgPath), "%sfavIcon.png", Settings.theme_path); + GuiImageData imgfavIcon(imgPath, favIcon_png); + snprintf(imgPath, sizeof(imgPath), "%sfavIcon_gray.png", Settings.theme_path); + GuiImageData imgfavIcon_gray(imgPath, NULL); + snprintf(imgPath, sizeof(imgPath), "%ssearchIcon.png", Settings.theme_path); + GuiImageData imgsearchIcon(imgPath, searchIcon_png); + snprintf(imgPath, sizeof(imgPath), "%ssearchIcon_gray.png", Settings.theme_path); + GuiImageData imgsearchIcon_gray(imgPath, NULL); + snprintf(imgPath, sizeof(imgPath), "%sabcIcon.png", Settings.theme_path); + GuiImageData imgabcIcon(imgPath, abcIcon_png); + snprintf(imgPath, sizeof(imgPath), "%sabcIcon_gray.png", Settings.theme_path); + GuiImageData imgabcIcon_gray(imgPath, NULL); + snprintf(imgPath, sizeof(imgPath), "%srankIcon.png", Settings.theme_path); + GuiImageData imgrankIcon(imgPath, rankIcon_png); + snprintf(imgPath, sizeof(imgPath), "%srankIcon_gray.png", Settings.theme_path); + GuiImageData imgrankIcon_gray(imgPath, NULL); + snprintf(imgPath, sizeof(imgPath), "%splayCountIcon.png", Settings.theme_path); + GuiImageData imgplayCountIcon(imgPath, playCountIcon_png); + snprintf(imgPath, sizeof(imgPath), "%splayCountIcon_gray.png", Settings.theme_path); + GuiImageData imgplayCountIcon_gray(imgPath, NULL); + snprintf(imgPath, sizeof(imgPath), "%sarrangeGrid.png", Settings.theme_path); + GuiImageData imgarrangeGrid(imgPath, arrangeGrid_png); + snprintf(imgPath, sizeof(imgPath), "%sarrangeGrid_gray.png", Settings.theme_path); + GuiImageData imgarrangeGrid_gray(imgPath, NULL); + snprintf(imgPath, sizeof(imgPath), "%sarrangeList.png", Settings.theme_path); + GuiImageData imgarrangeList(imgPath, arrangeList_png); + snprintf(imgPath, sizeof(imgPath), "%sarrangeList_gray.png", Settings.theme_path); + GuiImageData imgarrangeList_gray(imgPath, NULL); + snprintf(imgPath, sizeof(imgPath), "%sarrangeCarousel.png", Settings.theme_path); + GuiImageData imgarrangeCarousel(imgPath, arrangeCarousel_png); + snprintf(imgPath, sizeof(imgPath), "%sarrangeCarousel_gray.png", Settings.theme_path); + GuiImageData imgarrangeCarousel_gray(imgPath, NULL); - snprintf( imgPath, sizeof( imgPath ), "%sfavIcon.png", Settings.theme_path ); - GuiImageData imgfavIcon( imgPath, favIcon_png ); - snprintf( imgPath, sizeof( imgPath ), "%sfavIcon_gray.png", Settings.theme_path ); - GuiImageData imgfavIcon_gray( imgPath, NULL ); - snprintf( imgPath, sizeof( imgPath ), "%ssearchIcon.png", Settings.theme_path ); - GuiImageData imgsearchIcon( imgPath, searchIcon_png ); - snprintf( imgPath, sizeof( imgPath ), "%ssearchIcon_gray.png", Settings.theme_path ); - GuiImageData imgsearchIcon_gray( imgPath, NULL ); - snprintf( imgPath, sizeof( imgPath ), "%sabcIcon.png", Settings.theme_path ); - GuiImageData imgabcIcon( imgPath, abcIcon_png ); - snprintf( imgPath, sizeof( imgPath ), "%sabcIcon_gray.png", Settings.theme_path ); - GuiImageData imgabcIcon_gray( imgPath, NULL ); - snprintf( imgPath, sizeof( imgPath ), "%srankIcon.png", Settings.theme_path ); - GuiImageData imgrankIcon( imgPath, rankIcon_png ); - snprintf( imgPath, sizeof( imgPath ), "%srankIcon_gray.png", Settings.theme_path ); - GuiImageData imgrankIcon_gray( imgPath, NULL ); - snprintf( imgPath, sizeof( imgPath ), "%splayCountIcon.png", Settings.theme_path ); - GuiImageData imgplayCountIcon( imgPath, playCountIcon_png ); - snprintf( imgPath, sizeof( imgPath ), "%splayCountIcon_gray.png", Settings.theme_path ); - GuiImageData imgplayCountIcon_gray( imgPath, NULL ); - snprintf( imgPath, sizeof( imgPath ), "%sarrangeGrid.png", Settings.theme_path ); - GuiImageData imgarrangeGrid( imgPath, arrangeGrid_png ); - snprintf( imgPath, sizeof( imgPath ), "%sarrangeGrid_gray.png", Settings.theme_path ); - GuiImageData imgarrangeGrid_gray( imgPath, NULL ); - snprintf( imgPath, sizeof( imgPath ), "%sarrangeList.png", Settings.theme_path ); - GuiImageData imgarrangeList( imgPath, arrangeList_png ); - snprintf( imgPath, sizeof( imgPath ), "%sarrangeList_gray.png", Settings.theme_path ); - GuiImageData imgarrangeList_gray( imgPath, NULL ); - snprintf( imgPath, sizeof( imgPath ), "%sarrangeCarousel.png", Settings.theme_path ); - GuiImageData imgarrangeCarousel( imgPath, arrangeCarousel_png ); - snprintf( imgPath, sizeof( imgPath ), "%sarrangeCarousel_gray.png", Settings.theme_path ); - GuiImageData imgarrangeCarousel_gray( imgPath, NULL ); + snprintf(imgPath, sizeof(imgPath), "%slock.png", Settings.theme_path); + GuiImageData imgLock(imgPath, lock_png); + snprintf(imgPath, sizeof(imgPath), "%slock_gray.png", Settings.theme_path); + GuiImageData imgLock_gray(imgPath, NULL); + snprintf(imgPath, sizeof(imgPath), "%sunlock.png", Settings.theme_path); + GuiImageData imgUnlock(imgPath, unlock_png); + snprintf(imgPath, sizeof(imgPath), "%sunlock_gray.png", Settings.theme_path); + GuiImageData imgUnlock_gray(imgPath, NULL); - snprintf( imgPath, sizeof( imgPath ), "%slock.png", Settings.theme_path ); - GuiImageData imgLock( imgPath, lock_png ); - snprintf( imgPath, sizeof( imgPath ), "%slock_gray.png", Settings.theme_path ); - GuiImageData imgLock_gray( imgPath, NULL ); - snprintf( imgPath, sizeof( imgPath ), "%sunlock.png", Settings.theme_path ); - GuiImageData imgUnlock( imgPath, unlock_png ); - snprintf( imgPath, sizeof( imgPath ), "%sunlock_gray.png", Settings.theme_path ); - GuiImageData imgUnlock_gray( imgPath, NULL ); - - snprintf( imgPath, sizeof( imgPath ), "%sdvd.png", Settings.theme_path ); - GuiImageData imgdvd( imgPath, dvd_png ); - snprintf( imgPath, sizeof( imgPath ), "%sdvd_gray.png", Settings.theme_path ); - GuiImageData imgdvd_gray( imgPath, NULL ); - - snprintf( imgPath, sizeof( imgPath ), "%sbrowser.png", Settings.theme_path ); - GuiImageData homebrewImgData( imgPath, browser_png ); - snprintf( imgPath, sizeof( imgPath ), "%sbrowser_over.png", Settings.theme_path ); - GuiImageData homebrewImgDataOver( imgPath, browser_over_png ); + snprintf(imgPath, sizeof(imgPath), "%sdvd.png", Settings.theme_path); + GuiImageData imgdvd(imgPath, dvd_png); + snprintf(imgPath, sizeof(imgPath), "%sdvd_gray.png", Settings.theme_path); + GuiImageData imgdvd_gray(imgPath, NULL); + snprintf(imgPath, sizeof(imgPath), "%sbrowser.png", Settings.theme_path); + GuiImageData homebrewImgData(imgPath, browser_png); + snprintf(imgPath, sizeof(imgPath), "%sbrowser_over.png", Settings.theme_path); + GuiImageData homebrewImgDataOver(imgPath, browser_over_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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, PAD_BUTTON_START ); + trigHome.SetButtonOnlyTrigger(-1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, PAD_BUTTON_START); GuiTrigger trig2; - trig2.SetButtonOnlyTrigger( -1, WPAD_BUTTON_2 | WPAD_CLASSIC_BUTTON_X, 0 ); + trig2.SetButtonOnlyTrigger(-1, WPAD_BUTTON_2 | WPAD_CLASSIC_BUTTON_X, 0); GuiTrigger trig1; - trig1.SetButtonOnlyTrigger( -1, WPAD_BUTTON_1 | WPAD_CLASSIC_BUTTON_Y, 0 ); + trig1.SetButtonOnlyTrigger(-1, WPAD_BUTTON_1 | WPAD_CLASSIC_BUTTON_Y, 0); GuiTrigger trigZ; - trigZ.SetButtonOnlyTrigger( -1, WPAD_NUNCHUK_BUTTON_Z | WPAD_CLASSIC_BUTTON_ZL, PAD_TRIGGER_Z ); + 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 ); + GuiButton screenShotBtn(0, 0); + screenShotBtn.SetPosition(0, 0); + screenShotBtn.SetTrigger(&trigZ); char spaceinfo[30]; - if ( load_from_fs == PART_FS_FAT ) + if (load_from_fs == PART_FS_FAT) { - memset( spaceinfo, 0, 30 ); + memset(spaceinfo, 0, 30); } else { - if ( !strcmp( Settings.db_language, "JA" ) ) + 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" ) ); + 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" ) ); + 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 ); + GuiText usedSpaceTxt(spaceinfo, 18, THEME.info); + usedSpaceTxt.SetAlignment(THEME.hddinfo_align, ALIGN_TOP); + usedSpaceTxt.SetPosition(THEME.hddinfo_x, THEME.hddinfo_y); char GamesCnt[15]; - sprintf( GamesCnt, "%s: %i", ( mountMethod != 3 ? tr( "Games" ) : tr( "Channels" ) ), gameList.size() ); - GuiText gamecntTxt( GamesCnt, 18, THEME.info ); + sprintf(GamesCnt, "%s: %i", (mountMethod != 3 ? tr( "Games" ) : tr( "Channels" )), gameList.size()); + GuiText gamecntTxt(GamesCnt, 18, THEME.info); - GuiButton gamecntBtn( 100, 18 ); - gamecntBtn.SetAlignment( THEME.gamecount_align, ALIGN_TOP ); - gamecntBtn.SetPosition( THEME.gamecount_x, THEME.gamecount_y ); - gamecntBtn.SetLabel( &gamecntTxt ); + 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.SetTrigger(&trigA); - GuiTooltip installBtnTT( tr( "Install a game" ) ); - if ( Settings.wsprompt == yes ) - installBtnTT.SetWidescreen( Settings.widescreen ); - installBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage installBtnImg( &btnInstall ); - GuiImage installBtnImgOver( &btnInstallOver ); - installBtnImg.SetWidescreen( Settings.widescreen ); - installBtnImgOver.SetWidescreen( Settings.widescreen ); + GuiTooltip installBtnTT(tr( "Install a game" )); + if (Settings.wsprompt == yes) installBtnTT.SetWidescreen(Settings.widescreen); + installBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage installBtnImg(&btnInstall); + GuiImage installBtnImgOver(&btnInstallOver); + installBtnImg.SetWidescreen(Settings.widescreen); + installBtnImgOver.SetWidescreen(Settings.widescreen); - GuiButton installBtn( &installBtnImg, &installBtnImgOver, ALIGN_LEFT, ALIGN_TOP, THEME.install_x, THEME.install_y, &trigA, &btnSoundOver, btnClick2, 1, &installBtnTT, 24, -30, 0, 5 ); + 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) settingsBtnTT.SetWidescreen(Settings.widescreen); + settingsBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage settingsBtnImg(&btnSettings); + settingsBtnImg.SetWidescreen(Settings.widescreen); + GuiImage settingsBtnImgOver(&btnSettingsOver); + settingsBtnImgOver.SetWidescreen(Settings.widescreen); + GuiButton settingsBtn(&settingsBtnImg, &settingsBtnImgOver, 0, 3, THEME.setting_x, THEME.setting_y, &trigA, + &btnSoundOver, btnClick2, 1, &settingsBtnTT, 65, -30, 0, 5); - GuiTooltip settingsBtnTT( tr( "Settings" ) ); - if ( Settings.wsprompt == yes ) - settingsBtnTT.SetWidescreen( Settings.widescreen ); - settingsBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage settingsBtnImg( &btnSettings ); - settingsBtnImg.SetWidescreen( Settings.widescreen ); - GuiImage settingsBtnImgOver( &btnSettingsOver ); - settingsBtnImgOver.SetWidescreen( Settings.widescreen ); - GuiButton settingsBtn( &settingsBtnImg, &settingsBtnImgOver, 0, 3, THEME.setting_x, THEME.setting_y, &trigA, &btnSoundOver, btnClick2, 1, &settingsBtnTT, 65, -30, 0, 5 ); - - GuiTooltip homeBtnTT( tr( "Back to HBC or Wii Menu" ) ); - if ( Settings.wsprompt == yes ) - homeBtnTT.SetWidescreen( Settings.widescreen ); - settingsBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage homeBtnImg( &btnhome ); - homeBtnImg.SetWidescreen( Settings.widescreen ); - GuiImage homeBtnImgOver( &btnhomeOver ); - homeBtnImgOver.SetWidescreen( Settings.widescreen ); - GuiButton homeBtn( &homeBtnImg, &homeBtnImgOver, 0, 3, THEME.home_x, THEME.home_y, &trigA, &btnSoundOver, btnClick2, 1, &homeBtnTT, 15, -30, 1, 5 ); + GuiTooltip homeBtnTT(tr( "Back to HBC or Wii Menu" )); + if (Settings.wsprompt == yes) homeBtnTT.SetWidescreen(Settings.widescreen); + settingsBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage homeBtnImg(&btnhome); + homeBtnImg.SetWidescreen(Settings.widescreen); + GuiImage homeBtnImgOver(&btnhomeOver); + homeBtnImgOver.SetWidescreen(Settings.widescreen); + GuiButton homeBtn(&homeBtnImg, &homeBtnImgOver, 0, 3, THEME.home_x, THEME.home_y, &trigA, &btnSoundOver, btnClick2, + 1, &homeBtnTT, 15, -30, 1, 5); homeBtn.RemoveSoundClick(); - homeBtn.SetTrigger( &trigHome ); + homeBtn.SetTrigger(&trigHome); - GuiTooltip poweroffBtnTT( tr( "Power off the Wii" ) ); - if ( Settings.wsprompt == yes ) - poweroffBtnTT.SetWidescreen( Settings.widescreen ); - poweroffBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage poweroffBtnImg( &btnpwroff ); - GuiImage poweroffBtnImgOver( &btnpwroffOver ); - poweroffBtnImg.SetWidescreen( Settings.widescreen ); - poweroffBtnImgOver.SetWidescreen( Settings.widescreen ); - GuiButton poweroffBtn( &poweroffBtnImg, &poweroffBtnImgOver, 0, 3, THEME.power_x, THEME.power_y, &trigA, &btnSoundOver, btnClick2, 1, &poweroffBtnTT, -10, -30, 1, 5 ); + GuiTooltip poweroffBtnTT(tr( "Power off the Wii" )); + if (Settings.wsprompt == yes) poweroffBtnTT.SetWidescreen(Settings.widescreen); + poweroffBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage poweroffBtnImg(&btnpwroff); + GuiImage poweroffBtnImgOver(&btnpwroffOver); + poweroffBtnImg.SetWidescreen(Settings.widescreen); + poweroffBtnImgOver.SetWidescreen(Settings.widescreen); + GuiButton poweroffBtn(&poweroffBtnImg, &poweroffBtnImgOver, 0, 3, THEME.power_x, THEME.power_y, &trigA, + &btnSoundOver, btnClick2, 1, &poweroffBtnTT, -10, -30, 1, 5); - GuiTooltip sdcardBtnTT( tr( "Reload SD" ) ); - if ( Settings.wsprompt == yes ) - sdcardBtnTT.SetWidescreen( Settings.widescreen ); - sdcardBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage sdcardImg( &btnsdcard ); - GuiImage sdcardImgOver( &btnsdcardOver ); - sdcardImg.SetWidescreen( Settings.widescreen ); - sdcardImgOver.SetWidescreen( Settings.widescreen ); - GuiButton sdcardBtn( &sdcardImg, &sdcardImgOver, 0, 3, THEME.sdcard_x, THEME.sdcard_y, &trigA, &btnSoundOver, btnClick2, 1, &sdcardBtnTT, 15, -30, 0, 5 ); + GuiTooltip sdcardBtnTT(tr( "Reload SD" )); + if (Settings.wsprompt == yes) sdcardBtnTT.SetWidescreen(Settings.widescreen); + sdcardBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage sdcardImg(&btnsdcard); + GuiImage sdcardImgOver(&btnsdcardOver); + sdcardImg.SetWidescreen(Settings.widescreen); + sdcardImgOver.SetWidescreen(Settings.widescreen); + GuiButton sdcardBtn(&sdcardImg, &sdcardImgOver, 0, 3, THEME.sdcard_x, THEME.sdcard_y, &trigA, &btnSoundOver, + btnClick2, 1, &sdcardBtnTT, 15, -30, 0, 5); - GuiButton gameInfo( 0, 0 ); - gameInfo.SetTrigger( &trig2 ); - gameInfo.SetSoundClick( btnClick2 ); + GuiButton gameInfo(0, 0); + gameInfo.SetTrigger(&trig2); + gameInfo.SetSoundClick(btnClick2); + GuiImage wiiBtnImg(&dataID); + wiiBtnImg.SetWidescreen(Settings.widescreen); + GuiButton wiiBtn(&wiiBtnImg, &wiiBtnImg, 0, 4, 0, -10, &trigA, &btnSoundOver, btnClick2, 0); - GuiImage wiiBtnImg( &dataID ); - wiiBtnImg.SetWidescreen( Settings.widescreen ); - GuiButton wiiBtn( &wiiBtnImg, &wiiBtnImg, 0, 4, 0, -10, &trigA, &btnSoundOver, btnClick2, 0 ); - - GuiTooltip favoriteBtnTT( tr( "Display favorites" ) ); - if ( Settings.wsprompt == yes ) - favoriteBtnTT.SetWidescreen( Settings.widescreen ); - favoriteBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage favoriteBtnImg( &imgfavIcon ); - favoriteBtnImg.SetWidescreen( Settings.widescreen ); - GuiImage favoriteBtnImg_g( &imgfavIcon_gray ); - if ( favoriteBtnImg_g.GetImage() == NULL ) { favoriteBtnImg_g = favoriteBtnImg; favoriteBtnImg_g.SetGrayscale();} - favoriteBtnImg_g.SetWidescreen( Settings.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 ); - - GuiTooltip searchBtnTT( tr( "Set Search-Filter" ) ); - if ( Settings.wsprompt == yes ) - searchBtnTT.SetWidescreen( Settings.widescreen ); - searchBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage searchBtnImg( &imgsearchIcon ); - searchBtnImg.SetWidescreen( Settings.widescreen ); - GuiImage searchBtnImg_g( &imgsearchIcon_gray ); - if ( searchBtnImg_g.GetImage() == NULL ) { searchBtnImg_g = searchBtnImg; searchBtnImg_g.SetGrayscale();} - searchBtnImg_g.SetWidescreen( Settings.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 ); - - GuiTooltip abcBtnTT( Settings.fave ? tr( "Sort by rank" ) : tr( "Sort alphabetically" ) ); - if ( Settings.wsprompt == yes ) - abcBtnTT.SetWidescreen( Settings.widescreen ); - abcBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage abcBtnImg( Settings.fave ? &imgrankIcon : &imgabcIcon ); - abcBtnImg.SetWidescreen( Settings.widescreen ); - GuiImage abcBtnImg_g( Settings.fave ? &imgrankIcon_gray : &imgabcIcon_gray ); - if ( abcBtnImg_g.GetImage() == NULL ) { abcBtnImg_g = abcBtnImg; abcBtnImg_g.SetGrayscale();} - abcBtnImg_g.SetWidescreen( Settings.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 ); - - GuiTooltip countBtnTT( tr( "Sort order by most played" ) ); - if ( Settings.wsprompt == yes ) - countBtnTT.SetWidescreen( Settings.widescreen ); - countBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage countBtnImg( &imgplayCountIcon ); - countBtnImg.SetWidescreen( Settings.widescreen ); - GuiImage countBtnImg_g( &imgplayCountIcon_gray ); - if ( countBtnImg_g.GetImage() == NULL ) { countBtnImg_g = countBtnImg; countBtnImg_g.SetGrayscale();} - countBtnImg_g.SetWidescreen( Settings.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 ); - - GuiTooltip listBtnTT( tr( "Display as a list" ) ); - if ( Settings.wsprompt == yes ) - listBtnTT.SetWidescreen( Settings.widescreen ); - listBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage listBtnImg( &imgarrangeList ); - listBtnImg.SetWidescreen( Settings.widescreen ); - GuiImage listBtnImg_g( &imgarrangeList_gray ); - if ( listBtnImg_g.GetImage() == NULL ) { listBtnImg_g = listBtnImg; listBtnImg_g.SetGrayscale();} - listBtnImg_g.SetWidescreen( Settings.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 ); - - GuiTooltip gridBtnTT( tr( "Display as a grid" ) ); - if ( Settings.wsprompt == yes ) - gridBtnTT.SetWidescreen( Settings.widescreen ); - gridBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage gridBtnImg( &imgarrangeGrid ); - gridBtnImg.SetWidescreen( Settings.widescreen ); - GuiImage gridBtnImg_g( &imgarrangeGrid_gray ); - if ( gridBtnImg_g.GetImage() == NULL ) { gridBtnImg_g = gridBtnImg; gridBtnImg_g.SetGrayscale();} - gridBtnImg_g.SetWidescreen( Settings.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( Settings.widescreen ); - carouselBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage carouselBtnImg( &imgarrangeCarousel ); - carouselBtnImg.SetWidescreen( Settings.widescreen ); - GuiImage carouselBtnImg_g( &imgarrangeCarousel_gray ); - if ( carouselBtnImg_g.GetImage() == NULL ) { carouselBtnImg_g = carouselBtnImg; carouselBtnImg_g.SetGrayscale();} - carouselBtnImg_g.SetWidescreen( Settings.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 ); - - GuiTooltip lockBtnTT( canUnlock ? tr( "Unlock Parental Control" ) : tr( "Parental Control disabled" ) ); - if ( Settings.wsprompt == yes ) - lockBtnTT.SetWidescreen( Settings.widescreen ); - lockBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage lockBtnImg( &imgLock ); - lockBtnImg.SetWidescreen( Settings.widescreen ); - GuiImage lockBtnImg_g( &imgLock_gray ); - if ( lockBtnImg_g.GetImage() == NULL ) { lockBtnImg_g = lockBtnImg; lockBtnImg_g.SetGrayscale(); } - lockBtnImg_g.SetWidescreen( Settings.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( Settings.widescreen ); - unlockBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage unlockBtnImg( &imgUnlock ); - unlockBtnImg.SetWidescreen( Settings.widescreen ); - GuiImage unlockBtnImg_g( &imgUnlock_gray ); - if ( unlockBtnImg_g.GetImage() == NULL ) { unlockBtnImg_g = unlockBtnImg; unlockBtnImg_g.SetGrayscale(); } - unlockBtnImg_g.SetWidescreen( Settings.widescreen ); - - if ( canUnlock && Settings.godmode ) + GuiTooltip favoriteBtnTT(tr( "Display favorites" )); + if (Settings.wsprompt == yes) favoriteBtnTT.SetWidescreen(Settings.widescreen); + favoriteBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage favoriteBtnImg(&imgfavIcon); + favoriteBtnImg.SetWidescreen(Settings.widescreen); + GuiImage favoriteBtnImg_g(&imgfavIcon_gray); + if (favoriteBtnImg_g.GetImage() == NULL) { - lockBtn.SetImage( &unlockBtnImg_g ); - lockBtn.SetImageOver( &unlockBtnImg_g ); - lockBtn.SetToolTip( &unlockBtnTT, 15, 52, 1, 3 ); + favoriteBtnImg_g = favoriteBtnImg; + favoriteBtnImg_g.SetGrayscale(); + } + favoriteBtnImg_g.SetWidescreen(Settings.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); + + GuiTooltip searchBtnTT(tr( "Set Search-Filter" )); + if (Settings.wsprompt == yes) searchBtnTT.SetWidescreen(Settings.widescreen); + searchBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage searchBtnImg(&imgsearchIcon); + searchBtnImg.SetWidescreen(Settings.widescreen); + GuiImage searchBtnImg_g(&imgsearchIcon_gray); + if (searchBtnImg_g.GetImage() == NULL) + { + searchBtnImg_g = searchBtnImg; + searchBtnImg_g.SetGrayscale(); + } + searchBtnImg_g.SetWidescreen(Settings.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); + + GuiTooltip abcBtnTT(Settings.fave ? tr( "Sort by rank" ) : tr( "Sort alphabetically" )); + if (Settings.wsprompt == yes) abcBtnTT.SetWidescreen(Settings.widescreen); + abcBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage abcBtnImg(Settings.fave ? &imgrankIcon : &imgabcIcon); + abcBtnImg.SetWidescreen(Settings.widescreen); + GuiImage abcBtnImg_g(Settings.fave ? &imgrankIcon_gray : &imgabcIcon_gray); + if (abcBtnImg_g.GetImage() == NULL) + { + abcBtnImg_g = abcBtnImg; + abcBtnImg_g.SetGrayscale(); + } + abcBtnImg_g.SetWidescreen(Settings.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); + + GuiTooltip countBtnTT(tr( "Sort order by most played" )); + if (Settings.wsprompt == yes) countBtnTT.SetWidescreen(Settings.widescreen); + countBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage countBtnImg(&imgplayCountIcon); + countBtnImg.SetWidescreen(Settings.widescreen); + GuiImage countBtnImg_g(&imgplayCountIcon_gray); + if (countBtnImg_g.GetImage() == NULL) + { + countBtnImg_g = countBtnImg; + countBtnImg_g.SetGrayscale(); + } + countBtnImg_g.SetWidescreen(Settings.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); + + GuiTooltip listBtnTT(tr( "Display as a list" )); + if (Settings.wsprompt == yes) listBtnTT.SetWidescreen(Settings.widescreen); + listBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage listBtnImg(&imgarrangeList); + listBtnImg.SetWidescreen(Settings.widescreen); + GuiImage listBtnImg_g(&imgarrangeList_gray); + if (listBtnImg_g.GetImage() == NULL) + { + listBtnImg_g = listBtnImg; + listBtnImg_g.SetGrayscale(); + } + listBtnImg_g.SetWidescreen(Settings.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); + + GuiTooltip gridBtnTT(tr( "Display as a grid" )); + if (Settings.wsprompt == yes) gridBtnTT.SetWidescreen(Settings.widescreen); + gridBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage gridBtnImg(&imgarrangeGrid); + gridBtnImg.SetWidescreen(Settings.widescreen); + GuiImage gridBtnImg_g(&imgarrangeGrid_gray); + if (gridBtnImg_g.GetImage() == NULL) + { + gridBtnImg_g = gridBtnImg; + gridBtnImg_g.SetGrayscale(); + } + gridBtnImg_g.SetWidescreen(Settings.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(Settings.widescreen); + carouselBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage carouselBtnImg(&imgarrangeCarousel); + carouselBtnImg.SetWidescreen(Settings.widescreen); + GuiImage carouselBtnImg_g(&imgarrangeCarousel_gray); + if (carouselBtnImg_g.GetImage() == NULL) + { + carouselBtnImg_g = carouselBtnImg; + carouselBtnImg_g.SetGrayscale(); + } + carouselBtnImg_g.SetWidescreen(Settings.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); + + GuiTooltip lockBtnTT(canUnlock ? tr( "Unlock Parental Control" ) : tr( "Parental Control disabled" )); + if (Settings.wsprompt == yes) lockBtnTT.SetWidescreen(Settings.widescreen); + lockBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage lockBtnImg(&imgLock); + lockBtnImg.SetWidescreen(Settings.widescreen); + GuiImage lockBtnImg_g(&imgLock_gray); + if (lockBtnImg_g.GetImage() == NULL) + { + lockBtnImg_g = lockBtnImg; + lockBtnImg_g.SetGrayscale(); + } + lockBtnImg_g.SetWidescreen(Settings.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(Settings.widescreen); + unlockBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage unlockBtnImg(&imgUnlock); + unlockBtnImg.SetWidescreen(Settings.widescreen); + GuiImage unlockBtnImg_g(&imgUnlock_gray); + if (unlockBtnImg_g.GetImage() == NULL) + { + unlockBtnImg_g = unlockBtnImg; + unlockBtnImg_g.SetGrayscale(); + } + unlockBtnImg_g.SetWidescreen(Settings.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); - */ + 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( Settings.widescreen ); - dvdBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage dvdBtnImg( &imgdvd ); - dvdBtnImg.SetWidescreen( Settings.widescreen ); - GuiImage dvdBtnImg_g( dvdBtnImg ); - dvdBtnImg_g.SetWidescreen( Settings.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 dvdBtnTT(tr( "Mount DVD drive" )); + if (Settings.wsprompt == yes) dvdBtnTT.SetWidescreen(Settings.widescreen); + dvdBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage dvdBtnImg(&imgdvd); + dvdBtnImg.SetWidescreen(Settings.widescreen); + GuiImage dvdBtnImg_g(dvdBtnImg); + dvdBtnImg_g.SetWidescreen(Settings.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 ) - homebrewBtnTT.SetWidescreen( Settings.widescreen ); - homebrewBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiImage homebrewImg( &homebrewImgData ); - GuiImage homebrewImgOver( &homebrewImgDataOver ); - homebrewImg.SetWidescreen( Settings.widescreen ); - homebrewImgOver.SetWidescreen( Settings.widescreen ); - GuiButton homebrewBtn( &homebrewImg, &homebrewImgOver, ALIGN_LEFT, ALIGN_TOP, THEME.homebrew_x, THEME.homebrew_y, &trigA, &btnSoundOver, btnClick2, 1, &homebrewBtnTT, 15, -30, 1, 5 ); + GuiTooltip homebrewBtnTT(tr( "Homebrew Launcher" )); + if (Settings.wsprompt == yes) homebrewBtnTT.SetWidescreen(Settings.widescreen); + homebrewBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiImage homebrewImg(&homebrewImgData); + GuiImage homebrewImgOver(&homebrewImgDataOver); + homebrewImg.SetWidescreen(Settings.widescreen); + homebrewImgOver.SetWidescreen(Settings.widescreen); + GuiButton homebrewBtn(&homebrewImg, &homebrewImgOver, ALIGN_LEFT, ALIGN_TOP, THEME.homebrew_x, THEME.homebrew_y, + &trigA, &btnSoundOver, btnClick2, 1, &homebrewBtnTT, 15, -30, 1, 5); - if ( Settings.fave ) + if (Settings.fave) { - favoriteBtn.SetImage( &favoriteBtnImg ); - favoriteBtn.SetImageOver( &favoriteBtnImg ); - favoriteBtn.SetAlpha( 255 ); + favoriteBtn.SetImage(&favoriteBtnImg); + favoriteBtn.SetImageOver(&favoriteBtnImg); + favoriteBtn.SetAlpha(255); } static bool show_searchwindow = false; - if ( *gameList.GetCurrentFilter() ) + if (*gameList.GetCurrentFilter()) { - if ( show_searchwindow && gameList.size() == 1 ) - show_searchwindow = false; - if ( !show_searchwindow ) - searchBtn.SetEffect( EFFECT_PULSE, 10, 105 ); - searchBtn.SetImage( &searchBtnImg ); - searchBtn.SetImageOver( &searchBtnImg ); - searchBtn.SetAlpha( 255 ); + if (show_searchwindow && gameList.size() == 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 ) + if (Settings.sort == ALL) { - abcBtn.SetImage( &abcBtnImg ); - abcBtn.SetImageOver( &abcBtnImg ); - abcBtn.SetAlpha( 255 ); + abcBtn.SetImage(&abcBtnImg); + abcBtn.SetImageOver(&abcBtnImg); + abcBtn.SetAlpha(255); } - else if ( Settings.sort == PLAYCOUNT ) + else if (Settings.sort == PLAYCOUNT) { - countBtn.SetImage( &countBtnImg ); - countBtn.SetImageOver( &countBtnImg ); - countBtn.SetAlpha( 255 ); + countBtn.SetImage(&countBtnImg); + countBtn.SetImageOver(&countBtnImg); + countBtn.SetAlpha(255); } - if ( Settings.gameDisplay == list ) + if (Settings.gameDisplay == list) { - listBtn.SetImage( &listBtnImg ); - listBtn.SetImageOver( &listBtnImg ); - listBtn.SetAlpha( 255 ); + listBtn.SetImage(&listBtnImg); + listBtn.SetImageOver(&listBtnImg); + listBtn.SetAlpha(255); } - else if ( Settings.gameDisplay == grid ) + else if (Settings.gameDisplay == grid) { - gridBtn.SetImage( &gridBtnImg ); - gridBtn.SetImageOver( &gridBtnImg ); - gridBtn.SetAlpha( 255 ); + gridBtn.SetImage(&gridBtnImg); + gridBtn.SetImageOver(&gridBtnImg); + gridBtn.SetAlpha(255); } - else if ( Settings.gameDisplay == carousel ) + else if (Settings.gameDisplay == carousel) { - carouselBtn.SetImage( &carouselBtnImg ); - carouselBtn.SetImageOver( &carouselBtnImg ); - carouselBtn.SetAlpha( 255 ); + carouselBtn.SetImage(&carouselBtnImg); + carouselBtn.SetImageOver(&carouselBtnImg); + carouselBtn.SetAlpha(255); } - if ( Settings.gameDisplay == list ) + 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 ); + 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 ) + 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 ); + 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 ) + 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.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 - GuiTooltip DownloadBtnTT( tr( "Click to Download Covers" ) ); - if ( Settings.wsprompt == yes ) - DownloadBtnTT.SetWidescreen( Settings.widescreen ); - DownloadBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiButton DownloadBtn( 0, 0 ); - DownloadBtn.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - DownloadBtn.SetPosition( THEME.covers_x, THEME.covers_y ); + GuiTooltip DownloadBtnTT(tr( "Click to Download Covers" )); + if (Settings.wsprompt == yes) DownloadBtnTT.SetWidescreen(Settings.widescreen); + DownloadBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiButton DownloadBtn(0, 0); + DownloadBtn.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + DownloadBtn.SetPosition(THEME.covers_x, THEME.covers_y); - GuiTooltip IDBtnTT( tr( "Click to change game ID" ) ); - if ( Settings.wsprompt == yes ) - IDBtnTT.SetWidescreen( Settings.widescreen ); - IDBtnTT.SetAlpha( THEME.tooltipAlpha ); - GuiButton idBtn( 0, 0 ); - idBtn.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - idBtn.SetPosition( THEME.id_x, THEME.id_y ); + GuiTooltip IDBtnTT(tr( "Click to change game ID" )); + if (Settings.wsprompt == yes) IDBtnTT.SetWidescreen(Settings.widescreen); + IDBtnTT.SetAlpha(THEME.tooltipAlpha); + GuiButton idBtn(0, 0); + idBtn.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + idBtn.SetPosition(THEME.id_x, THEME.id_y); - if ( Settings.godmode == 1 && mountMethod != 3 ) //only make the button have trigger & tooltip if in godmode + if (Settings.godmode == 1 && mountMethod != 3) //only make the button have trigger & tooltip if in godmode { - DownloadBtn.SetSoundOver( &btnSoundOver ); - DownloadBtn.SetTrigger( &trigA ); - DownloadBtn.SetTrigger( &trig1 ); - DownloadBtn.SetToolTip( &DownloadBtnTT, 205, -30 ); + DownloadBtn.SetSoundOver(&btnSoundOver); + DownloadBtn.SetTrigger(&trigA); + 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 { - DownloadBtn.SetRumble( false ); - idBtn.SetRumble( false ); + DownloadBtn.SetRumble(false); + idBtn.SetRumble(false); } GuiGameBrowser * gameBrowser = NULL; GuiGameGrid * gameGrid = NULL; GuiGameCarousel * gameCarousel = NULL; - if ( Settings.gameDisplay == list ) + if (Settings.gameDisplay == list) { - gameBrowser = new GuiGameBrowser( THEME.gamelist_w, THEME.gamelist_h, Settings.theme_path, bg_options_png, startat, offset ); - gameBrowser->SetPosition( THEME.gamelist_x, THEME.gamelist_y ); - gameBrowser->SetAlignment( ALIGN_LEFT, ALIGN_CENTRE ); + gameBrowser = new GuiGameBrowser(THEME.gamelist_w, THEME.gamelist_h, Settings.theme_path, bg_options_png, + startat, offset); + gameBrowser->SetPosition(THEME.gamelist_x, THEME.gamelist_y); + gameBrowser->SetAlignment(ALIGN_LEFT, ALIGN_CENTRE); } - else if ( Settings.gameDisplay == grid ) + else if (Settings.gameDisplay == grid) { - gameGrid = new GuiGameGrid( THEME.gamegrid_w, THEME.gamegrid_h, Settings.theme_path, bg_options_png, 0, 0 ); - gameGrid->SetPosition( THEME.gamegrid_x, THEME.gamegrid_y ); - gameGrid->SetAlignment( ALIGN_LEFT, ALIGN_CENTRE ); + gameGrid = new GuiGameGrid(THEME.gamegrid_w, THEME.gamegrid_h, Settings.theme_path, bg_options_png, 0, 0); + gameGrid->SetPosition(THEME.gamegrid_x, THEME.gamegrid_y); + gameGrid->SetAlignment(ALIGN_LEFT, ALIGN_CENTRE); } - else if ( Settings.gameDisplay == carousel ) + else if (Settings.gameDisplay == carousel) { //GuiGameCarousel gameCarousel(THEME.gamecarousel_w, THEME.gamecarousel_h, gameList, gameList.size(), Settings.theme_path, bg_options_png, startat, offset); - gameCarousel = new GuiGameCarousel( 640, 400, Settings.theme_path, bg_options_png, startat, offset ); - gameCarousel->SetPosition( THEME.gamecarousel_x, THEME.gamecarousel_y ); - gameCarousel->SetAlignment( ALIGN_LEFT, ALIGN_CENTRE ); + gameCarousel = new GuiGameCarousel(640, 400, Settings.theme_path, bg_options_png, startat, offset); + gameCarousel->SetPosition(THEME.gamecarousel_x, THEME.gamecarousel_y); + gameCarousel->SetAlignment(ALIGN_LEFT, ALIGN_CENTRE); } - GuiText clockTimeBack( "88:88", 40, ( GXColor ) {THEME.clock.r, THEME.clock.g, THEME.clock.b, THEME.clock.a / 6} ); - clockTimeBack.SetAlignment( THEME.clock_align, ALIGN_TOP ); - clockTimeBack.SetPosition( THEME.clock_x, THEME.clock_y ); - clockTimeBack.SetFont( clock_ttf, clock_ttf_size ); - GuiText clockTime( theTime, 40, THEME.clock ); - clockTime.SetAlignment( THEME.clock_align, ALIGN_TOP ); - clockTime.SetPosition( THEME.clock_x, THEME.clock_y ); - clockTime.SetFont( clock_ttf, clock_ttf_size ); + GuiText clockTimeBack("88:88", 40, ( GXColor ) + { THEME.clock.r, THEME.clock.g, THEME.clock.b, THEME.clock.a / 6}); + clockTimeBack.SetAlignment(THEME.clock_align, ALIGN_TOP); + clockTimeBack.SetPosition(THEME.clock_x, THEME.clock_y); + clockTimeBack.SetFont(clock_ttf, clock_ttf_size); + GuiText clockTime(theTime, 40, THEME.clock); + clockTime.SetAlignment(THEME.clock_align, ALIGN_TOP); + clockTime.SetPosition(THEME.clock_x, THEME.clock_y); + clockTime.SetFont(clock_ttf, clock_ttf_size); HaltGui(); - GuiWindow w( screenwidth, screenheight ); + GuiWindow w(screenwidth, screenheight); - if ( THEME.show_hddinfo == -1 || THEME.show_hddinfo == 1 ) //force show hdd info + if (THEME.show_hddinfo == -1 || THEME.show_hddinfo == 1) //force show hdd info { - w.Append( &usedSpaceTxt ); + w.Append(&usedSpaceTxt); } - if ( THEME.show_gamecount == -1 || THEME.show_gamecount == 1 ) //force show game cnt info + if (THEME.show_gamecount == -1 || THEME.show_gamecount == 1) //force show game cnt info { - w.Append( &gamecntBtn ); + w.Append(&gamecntBtn); } - w.Append( &sdcardBtn ); - w.Append( &poweroffBtn ); - w.Append( &gameInfo ); - if ( Settings.godmode ) - w.Append( &installBtn ); - w.Append( &homeBtn ); - w.Append( &settingsBtn ); - w.Append( &DownloadBtn ); - w.Append( &idBtn ); - w.Append( &screenShotBtn ); - + w.Append(&sdcardBtn); + w.Append(&poweroffBtn); + w.Append(&gameInfo); + if (Settings.godmode) w.Append(&installBtn); + w.Append(&homeBtn); + w.Append(&settingsBtn); + w.Append(&DownloadBtn); + w.Append(&idBtn); + w.Append(&screenShotBtn); // Begin Toolbar - w.Append( &favoriteBtn ); + w.Append(&favoriteBtn); Toolbar[0] = &favoriteBtn; - w.Append( &searchBtn ); + w.Append(&searchBtn); Toolbar[1] = &searchBtn; - w.Append( &abcBtn ); + w.Append(&abcBtn); Toolbar[2] = &abcBtn; - w.Append( &countBtn ); + w.Append(&countBtn); Toolbar[3] = &countBtn; - w.Append( &listBtn ); + w.Append(&listBtn); Toolbar[4] = &listBtn; - w.Append( &gridBtn ); + w.Append(&gridBtn); Toolbar[5] = &gridBtn; - w.Append( &carouselBtn ); + w.Append(&carouselBtn); Toolbar[6] = &carouselBtn; - w.Append( &lockBtn ); + w.Append(&lockBtn); Toolbar[7] = &lockBtn; - w.Append( &dvdBtn ); + w.Append(&dvdBtn); Toolbar[8] = &dvdBtn; - w.SetUpdateCallback( DiscListWinUpdateCallback ); + w.SetUpdateCallback(DiscListWinUpdateCallback); // End Toolbar + if (Settings.godmode == 1) w.Append(&homebrewBtn); - if ( Settings.godmode == 1 ) - w.Append( &homebrewBtn ); - - if ( ( Settings.hddinfo == hr12 ) || ( Settings.hddinfo == hr24 ) ) + if ((Settings.hddinfo == hr12) || (Settings.hddinfo == hr24)) { - w.Append( &clockTimeBack ); - w.Append( &clockTime ); + w.Append(&clockTimeBack); + w.Append(&clockTime); } - if ( Settings.gameDisplay == list ) + if (Settings.gameDisplay == list) { - mainWindow->Append( gameBrowser ); + mainWindow->Append(gameBrowser); } - if ( Settings.gameDisplay == grid ) + if (Settings.gameDisplay == grid) { - mainWindow->Append( gameGrid ); + mainWindow->Append(gameGrid); } - if ( Settings.gameDisplay == carousel ) + if (Settings.gameDisplay == carousel) { - mainWindow->Append( gameCarousel ); + mainWindow->Append(gameCarousel); } - mainWindow->Append( &w ); + mainWindow->Append(&w); GuiSearchBar *searchBar = NULL; - if ( show_searchwindow ) + if (show_searchwindow) { - searchBar = new GuiSearchBar( gameList.GetAvailableSearchChars() ); - if ( searchBar ) - mainWindow->Append( searchBar ); + searchBar = new GuiSearchBar(gameList.GetAvailableSearchChars()); + if (searchBar) mainWindow->Append(searchBar); } ResumeGui(); -// ShowMemInfo(); + // ShowMemInfo(); - while ( menu == MENU_NONE ) + while (menu == MENU_NONE) { - if ( idiotFlag == 1 ) + if (idiotFlag == 1) { - gprintf( "\tIdiot flag\n" ); + gprintf("\tIdiot flag\n"); 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." ) ); + 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." )); - int deleteImg = WindowPrompt( 0, idiotBuffer, tr( "OK" ), tr( "Delete" ) ); - if ( deleteImg == 0 ) + int deleteImg = WindowPrompt(0, idiotBuffer, tr( "OK" ), tr( "Delete" )); + if (deleteImg == 0) { - snprintf( idiotBuffer, sizeof( idiotBuffer ), "%s %s.", tr( "You are about to delete " ), idiotChar ); - deleteImg = WindowPrompt( tr( "Confirm" ), idiotBuffer, tr( "Delete" ), tr( "Cancel" ) ); - if ( deleteImg == 1 ) + snprintf(idiotBuffer, sizeof(idiotBuffer), "%s %s.", tr( "You are about to delete " ), idiotChar); + deleteImg = WindowPrompt(tr( "Confirm" ), idiotBuffer, tr( "Delete" ), tr( "Cancel" )); + if (deleteImg == 1) { - remove( idiotChar ); + remove(idiotChar); } } idiotFlag = -1; } - WDVD_GetCoverStatus( &covert );//for detecting if i disc has been inserted + WDVD_GetCoverStatus(&covert);//for detecting if i disc has been inserted // if the idiot is showing favorites and don't have any - if ( Settings.fave && !gameList.size() ) + if (Settings.fave && !gameList.size()) { - WindowPrompt( tr( "No Favorites" ), tr( "You are choosing to display favorites and you do not have any selected." ), tr( "Back" ) ); + WindowPrompt(tr( "No Favorites" ), + tr( "You are choosing to display favorites and you do not have any selected." ), tr( "Back" )); Settings.fave = !Settings.fave; - if ( isInserted( bootDevice ) ) + if (isInserted(bootDevice)) { Settings.Save(); } @@ -708,175 +732,289 @@ int MenuDiscList() } //CLOCK - time_t rawtime = time( 0 ); - if ( ( ( Settings.hddinfo == hr12 ) || ( Settings.hddinfo == hr24 ) ) && rawtime != lastrawtime ) + time_t rawtime = time(0); + if (((Settings.hddinfo == hr12) || (Settings.hddinfo == hr24)) && rawtime != lastrawtime) { lastrawtime = rawtime; - timeinfo = localtime ( &rawtime ); - if ( dataed < 1 ) + timeinfo = localtime(&rawtime); + if (dataed < 1) { - if ( Settings.hddinfo == hr12 ) + if (Settings.hddinfo == hr12) { - if ( rawtime & 1 ) - strftime( theTime, sizeof( theTime ), "%I:%M", timeinfo ); - else - strftime( theTime, sizeof( theTime ), "%I %M", timeinfo ); + if (rawtime & 1) + strftime(theTime, sizeof(theTime), "%I:%M", timeinfo); + else strftime(theTime, sizeof(theTime), "%I %M", timeinfo); } - if ( Settings.hddinfo == hr24 ) + if (Settings.hddinfo == hr24) { - if ( rawtime & 1 ) - strftime( theTime, sizeof( theTime ), "%H:%M", timeinfo ); - else - strftime( theTime, sizeof( theTime ), "%H %M", timeinfo ); + if (rawtime & 1) + strftime(theTime, sizeof(theTime), "%H:%M", timeinfo); + else strftime(theTime, sizeof(theTime), "%H %M", timeinfo); } - clockTime.SetText( theTime ); + clockTime.SetText(theTime); } - else if ( dataed > 0 ) + else if (dataed > 0) { - clockTime.SetTextf( "%i", ( dataed - 1 ) ); + clockTime.SetTextf("%i", (dataed - 1)); } } - if ( ( datagB < 1 ) && ( Settings.cios == 1 ) && ( Settings.videomode == ntsc ) && ( Settings.hddinfo == hr12 ) && ( Settings.quickboot == 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 ) + if ((datagB < 1) && (Settings.cios == 1) && (Settings.videomode == ntsc) && (Settings.hddinfo == hr12) + && (Settings.quickboot == 1) && (Settings.wsprompt == 0) && (Settings.language == ger) + && (Settings.tooltips == 0)) { - gprintf( "\n\tshutdown" ); + 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"); Sys_Shutdown(); } - if ( reset == 1 ) - Sys_Reboot(); + if (reset == 1) Sys_Reboot(); - if ( updateavailable == true ) + if (updateavailable == true) { - gprintf( "\tUpdate Available\n" ); + gprintf("\tUpdate Available\n"); HaltGui(); - GuiWindow ww( 640, 480 ); - w.SetState( STATE_DISABLED ); - mainWindow->Append( &ww ); + GuiWindow ww(640, 480); + w.SetState(STATE_DISABLED); + mainWindow->Append(&ww); ResumeGui(); ProgressUpdateWindow(); updateavailable = false; - mainWindow->Remove( &ww ); - w.SetState( STATE_DEFAULT ); + mainWindow->Remove(&ww); + w.SetState(STATE_DEFAULT); menu = MENU_DISCLIST; } - if ( poweroffBtn.GetState() == STATE_CLICKED ) + if (poweroffBtn.GetState() == STATE_CLICKED) { - - gprintf( "\tpoweroffBtn clicked\n" ); - choice = WindowPrompt( tr( "How to Shutdown?" ), 0, tr( "Full Shutdown" ), tr( "Shutdown to Idle" ), tr( "Cancel" ) ); - if ( choice == 2 ) + gprintf("\tpoweroffBtn clicked\n"); + choice = WindowPrompt(tr( "How to Shutdown?" ), 0, tr( "Full Shutdown" ), tr( "Shutdown to Idle" ), + tr( "Cancel" )); + if (choice == 2) { Sys_ShutdownToIdel(); } - else if ( choice == 1 ) + else if (choice == 1) { Sys_ShutdownToStandby(); } else { poweroffBtn.ResetState(); - if ( Settings.gameDisplay == list ) + if (Settings.gameDisplay == list) { - gameBrowser->SetFocus( 1 ); + gameBrowser->SetFocus(1); } - else if ( Settings.gameDisplay == grid ) + else if (Settings.gameDisplay == grid) { - gameGrid->SetFocus( 1 ); + gameGrid->SetFocus(1); } - else if ( Settings.gameDisplay == carousel ) + else if (Settings.gameDisplay == carousel) { - gameCarousel->SetFocus( 1 ); + gameCarousel->SetFocus(1); } } } - else if ( gamecntBtn.GetState() == STATE_CLICKED && mountMethod != 3 ) + else if (gamecntBtn.GetState() == STATE_CLICKED && mountMethod != 3) { - gprintf( "\tgameCntBtn clicked\n" ); + gprintf("\tgameCntBtn clicked\n"); 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 ) + 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" ) ); + 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 ) + else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf( "\tscreenShotBtn clicked\n" ); + gprintf("\tscreenShotBtn clicked\n"); screenShotBtn.ResetState(); - ScreenShot(); + ScreenShot(); } - else if ( homeBtn.GetState() == STATE_CLICKED ) + else if (homeBtn.GetState() == STATE_CLICKED) { - gprintf( "\thomeBtn clicked\n" ); + gprintf("\thomeBtn clicked\n"); bgMusic->Pause(); choice = WindowExitPrompt(); bgMusic->Resume(); - if ( choice == 3 ) + if (choice == 3) { Sys_LoadMenu(); // Back to System Menu } - else if ( choice == 2 ) + else if (choice == 2) { Sys_BackToLoader(); } else { homeBtn.ResetState(); - if ( Settings.gameDisplay == list ) + if (Settings.gameDisplay == list) { - gameBrowser->SetFocus( 1 ); + gameBrowser->SetFocus(1); } - else if ( Settings.gameDisplay == grid ) + else if (Settings.gameDisplay == grid) { - gameGrid->SetFocus( 1 ); + gameGrid->SetFocus(1); } - else if ( Settings.gameDisplay == carousel ) + else if (Settings.gameDisplay == carousel) { - gameCarousel->SetFocus( 1 ); + gameCarousel->SetFocus(1); } } } - else if ( wiiBtn.GetState() == STATE_CLICKED ) + else if (wiiBtn.GetState() == STATE_CLICKED) { - gprintf( "\twiiBtn clicked\n" ); + gprintf("\twiiBtn clicked\n"); dataed++; wiiBtn.ResetState(); - if ( Settings.gameDisplay == list ) + if (Settings.gameDisplay == list) { - gameBrowser->SetFocus( 1 ); + gameBrowser->SetFocus(1); } - else if ( Settings.gameDisplay == grid ) + else if (Settings.gameDisplay == grid) { - gameGrid->SetFocus( 1 ); + gameGrid->SetFocus(1); } - else if ( Settings.gameDisplay == carousel ) + else if (Settings.gameDisplay == carousel) { - gameCarousel->SetFocus( 1 ); + gameCarousel->SetFocus(1); } } - else if ( installBtn.GetState() == STATE_CLICKED ) + else if (installBtn.GetState() == STATE_CLICKED) { - choice = WindowPrompt( tr( "Install a game" ), 0, tr( "Yes" ), tr( "No" ) ); - if ( choice == 1 ) + choice = WindowPrompt(tr( "Install a game" ), 0, tr( "Yes" ), tr( "No" )); + if (choice == 1) { menu = MENU_INSTALL; break; @@ -884,71 +1022,73 @@ int MenuDiscList() else { installBtn.ResetState(); - if ( Settings.gameDisplay == list ) + if (Settings.gameDisplay == list) { - gameBrowser->SetFocus( 1 ); + gameBrowser->SetFocus(1); } - else if ( Settings.gameDisplay == grid ) + else if (Settings.gameDisplay == grid) { - gameGrid->SetFocus( 1 ); + gameGrid->SetFocus(1); } - else if ( Settings.gameDisplay == carousel ) + else if (Settings.gameDisplay == carousel) { - gameCarousel->SetFocus( 1 ); + gameCarousel->SetFocus(1); } } } - else if ( ( covert & 0x2 ) && ( covert != covertOld ) ) + else if ((covert & 0x2) && (covert != covertOld)) { - gprintf( "\tNew Disc Detected\n" ); - choice = WindowPrompt( tr( "New Disc Detected" ), 0, tr( "Install" ), tr( "Mount DVD drive" ), tr( "Cancel" ) ); - if ( choice == 1 ) + gprintf("\tNew Disc Detected\n"); + 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 ) + else if (choice == 2) { - dvdBtn.SetState( STATE_CLICKED ); + dvdBtn.SetState(STATE_CLICKED); } else { - if ( Settings.gameDisplay == list ) + if (Settings.gameDisplay == list) { - gameBrowser->SetFocus( 1 ); + gameBrowser->SetFocus(1); } - else if ( Settings.gameDisplay == grid ) + else if (Settings.gameDisplay == grid) { - gameGrid->SetFocus( 1 ); + gameGrid->SetFocus(1); } - else if ( Settings.gameDisplay == carousel ) + else if (Settings.gameDisplay == carousel) { - gameCarousel->SetFocus( 1 ); + gameCarousel->SetFocus(1); } } } - else if ( sdcardBtn.GetState() == STATE_CLICKED ) + else if (sdcardBtn.GetState() == STATE_CLICKED) { - gprintf( "\tsdCardBtn Clicked\n" ); + gprintf("\tsdCardBtn Clicked\n"); SDCard_deInit(); SDCard_Init(); - if ( Settings.gameDisplay == list ) + if (Settings.gameDisplay == list) { startat = gameBrowser->GetSelectedOption(); offset = gameBrowser->GetOffset(); } - else if ( Settings.gameDisplay == grid ) + else if (Settings.gameDisplay == grid) { startat = gameGrid->GetSelectedOption(); offset = gameGrid->GetOffset(); } - else if ( Settings.gameDisplay == carousel ) + else if (Settings.gameDisplay == carousel) { startat = gameCarousel->GetSelectedOption(); offset = gameCarousel->GetOffset(); } - if ( isInserted( bootDevice ) ) + 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() Settings.Load(); @@ -959,40 +1099,43 @@ int MenuDiscList() break; } - else if ( DownloadBtn.GetState() == STATE_CLICKED ) + else if (DownloadBtn.GetState() == STATE_CLICKED) { - gprintf( "\tDownloadBtn Clicked\n" ); - if ( isInserted( bootDevice ) ) + gprintf("\tDownloadBtn Clicked\n"); + if (isInserted(bootDevice)) { - choice = WindowPrompt( tr( "Cover Download" ), 0, tr( "Normal Covers" ), tr( "3D Covers" ), tr( "Disc Images" ), tr( "Back" ) ); // ask for download choice - if ( choice != 0 ) + 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; - missing = SearchMissingImages( choice2 ); - if ( IsNetworkInit() == false && missing == true ) + missing = SearchMissingImages(choice2); + if (IsNetworkInit() == false && missing == true) { - WindowPrompt( tr( "Network init error" ), 0, tr( "OK" ) ); + WindowPrompt(tr( "Network init error" ), 0, tr( "OK" )); } else { - if ( GetMissingFiles() != NULL && cntMissFiles > 0 ) + if (GetMissingFiles() != NULL && cntMissFiles > 0) { char tempCnt[40]; - sprintf( tempCnt, "%i %s", cntMissFiles, tr( "Missing files" ) ); - if ( choice != 3 )choice = WindowPrompt( tr( "Download Boxart image?" ), tempCnt, tr( "Yes" ), tr( "No" ) ); - else if ( choice == 3 )choice = WindowPrompt( tr( "Download Discart image?" ), tempCnt, tr( "Yes" ), tr( "No" ) ); - if ( choice == 1 ) + sprintf(tempCnt, "%i %s", cntMissFiles, tr( "Missing files" )); + if (choice != 3) + choice = WindowPrompt(tr( "Download Boxart image?" ), tempCnt, tr( "Yes" ), tr( "No" )); + else if (choice == 3) choice = WindowPrompt(tr( "Download Discart image?" ), tempCnt, + tr( "Yes" ), tr( "No" )); + if (choice == 1) { - ret = ProgressDownloadWindow( choice2 ); - if ( ret == 0 ) + ret = ProgressDownloadWindow(choice2); + if (ret == 0) { - WindowPrompt( tr( "Download finished" ), 0, tr( "OK" ) ); + WindowPrompt(tr( "Download finished" ), 0, tr( "OK" )); } else { - sprintf( tempCnt, "%i %s", ret, tr( "files not found on the server!" ) ); - WindowPrompt( tr( "Download finished" ), tempCnt, tr( "OK" ) ); + sprintf(tempCnt, "%i %s", ret, tr( "files not found on the server!" )); + WindowPrompt(tr( "Download finished" ), tempCnt, tr( "OK" )); } } } @@ -1001,38 +1144,38 @@ int MenuDiscList() } else { - WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to download images." ), tr( "OK" ) ); + WindowPrompt(tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to download images." ), tr( "OK" )); } menu = MENU_DISCLIST; DownloadBtn.ResetState(); - if ( Settings.gameDisplay == list ) + if (Settings.gameDisplay == list) { - gameBrowser->SetFocus( 1 ); + gameBrowser->SetFocus(1); } - else if ( Settings.gameDisplay == grid ) + else if (Settings.gameDisplay == grid) { - gameGrid->SetFocus( 1 ); + gameGrid->SetFocus(1); } - else if ( Settings.gameDisplay == carousel ) + else if (Settings.gameDisplay == carousel) { - gameCarousel->SetFocus( 1 ); + gameCarousel->SetFocus(1); } }//end download - else if ( settingsBtn.GetState() == STATE_CLICKED ) + else if (settingsBtn.GetState() == STATE_CLICKED) { - gprintf( "\tsettingsBtn Clicked\n" ); - if ( Settings.gameDisplay == list ) + gprintf("\tsettingsBtn Clicked\n"); + if (Settings.gameDisplay == list) { startat = gameBrowser->GetSelectedOption(); offset = gameBrowser->GetOffset(); } - else if ( Settings.gameDisplay == grid ) + else if (Settings.gameDisplay == grid) { startat = gameGrid->GetSelectedOption(); offset = gameGrid->GetOffset(); } - else if ( Settings.gameDisplay == carousel ) + else if (Settings.gameDisplay == carousel) { startat = gameCarousel->GetSelectedOption(); offset = gameCarousel->GetOffset(); @@ -1042,11 +1185,11 @@ int MenuDiscList() } - else if ( favoriteBtn.GetState() == STATE_CLICKED ) + else if (favoriteBtn.GetState() == STATE_CLICKED) { - gprintf( "\tfavoriteBtn Clicked\n" ); + gprintf("\tfavoriteBtn Clicked\n"); Settings.fave = !Settings.fave; - if ( isInserted( bootDevice ) ) + if (isInserted(bootDevice)) { Settings.Save(); } @@ -1056,103 +1199,98 @@ int MenuDiscList() } - else if ( searchBtn.GetState() == STATE_CLICKED && mountMethod != 3 ) + else if (searchBtn.GetState() == STATE_CLICKED && mountMethod != 3) { - gprintf( "\tsearchBtn Clicked\n" ); + gprintf("\tsearchBtn Clicked\n"); show_searchwindow = !show_searchwindow; HaltGui(); - if ( searchBar ) + if (searchBar) { - mainWindow->Remove( searchBar ); + mainWindow->Remove(searchBar); delete searchBar; searchBar = NULL; } - if ( show_searchwindow ) + if (show_searchwindow) { - if ( *gameList.GetCurrentFilter() ) + if (*gameList.GetCurrentFilter()) { searchBtn.StopEffect(); searchBtn.SetEffectGrow(); } - searchBar = new GuiSearchBar( gameList.GetAvailableSearchChars() ); - if ( searchBar ) - mainWindow->Append( searchBar ); + searchBar = new GuiSearchBar(gameList.GetAvailableSearchChars()); + if (searchBar) mainWindow->Append(searchBar); } else { - if ( *gameList.GetCurrentFilter() ) - searchBtn.SetEffect( EFFECT_PULSE, 10, 105 ); + if (*gameList.GetCurrentFilter()) searchBtn.SetEffect(EFFECT_PULSE, 10, 105); } searchBtn.ResetState(); ResumeGui(); } - else if ( searchBar && ( searchChar = searchBar->GetClicked() ) ) + else if (searchBar && (searchChar = searchBar->GetClicked())) { - if ( searchChar > 27 ) + if (searchChar > 27) { - int len = gameList.GetCurrentFilter() ? wcslen( gameList.GetCurrentFilter() ) : 0; - wchar_t newFilter[len+2]; - if ( gameList.GetCurrentFilter() ) - wcscpy( newFilter, gameList.GetCurrentFilter() ); + int len = gameList.GetCurrentFilter() ? wcslen(gameList.GetCurrentFilter()) : 0; + wchar_t newFilter[len + 2]; + if (gameList.GetCurrentFilter()) wcscpy(newFilter, gameList.GetCurrentFilter()); newFilter[len] = searchChar; - newFilter[len+1] = 0; + newFilter[len + 1] = 0; - - gameList.FilterList( newFilter ); + gameList.FilterList(newFilter); menu = MENU_DISCLIST; break; } - else if ( searchChar == 7 ) // Close + else if (searchChar == 7) // Close { show_searchwindow = false; HaltGui(); - if ( searchBar ) + if (searchBar) { - mainWindow->Remove( searchBar ); + mainWindow->Remove(searchBar); delete searchBar; searchBar = NULL; } - if ( *gameList.GetCurrentFilter() ) + if (*gameList.GetCurrentFilter()) { - searchBtn.SetEffect( EFFECT_PULSE, 10, 105 ); - searchBtn.SetImage( &searchBtnImg ); - searchBtn.SetImageOver( &searchBtnImg ); - searchBtn.SetAlpha( 255 ); + 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 ); + searchBtn.SetImage(&searchBtnImg_g); + searchBtn.SetImageOver(&searchBtnImg_g); + searchBtn.SetAlpha(180); } ResumeGui(); } - else if ( searchChar == 8 ) // Backspace + else if (searchChar == 8) // Backspace { - int len = wcslen( gameList.GetCurrentFilter() ); - wchar_t newFilter[len+1]; - if ( gameList.GetCurrentFilter() ) - wcscpy( newFilter, gameList.GetCurrentFilter() ); - newFilter[len > 0 ? len-1 : 0] = 0; - gameList.FilterList( newFilter ); + int len = wcslen(gameList.GetCurrentFilter()); + wchar_t newFilter[len + 1]; + if (gameList.GetCurrentFilter()) wcscpy(newFilter, gameList.GetCurrentFilter()); + newFilter[len > 0 ? len - 1 : 0] = 0; + gameList.FilterList(newFilter); menu = MENU_DISCLIST; break; } } - else if ( abcBtn.GetState() == STATE_CLICKED ) + else if (abcBtn.GetState() == STATE_CLICKED) { - gprintf( "\tabcBtn clicked\n" ); - if ( Settings.sort != ALL ) + gprintf("\tabcBtn clicked\n"); + if (Settings.sort != ALL) { Settings.sort = ALL; - if ( isInserted( bootDevice ) ) + if (isInserted(bootDevice)) { Settings.Save(); } @@ -1164,13 +1302,13 @@ int MenuDiscList() abcBtn.ResetState(); } - else if ( countBtn.GetState() == STATE_CLICKED ) + else if (countBtn.GetState() == STATE_CLICKED) { - gprintf( "\tcountBtn Clicked\n" ); - if ( Settings.sort != PLAYCOUNT ) + gprintf("\tcountBtn Clicked\n"); + if (Settings.sort != PLAYCOUNT) { - Settings.sort = PLAYCOUNT; - if ( isInserted( bootDevice ) ) + Settings.sort = PLAYCOUNT; + if (isInserted(bootDevice)) { Settings.Save(); } @@ -1183,14 +1321,14 @@ int MenuDiscList() } - else if ( listBtn.GetState() == STATE_CLICKED ) + else if (listBtn.GetState() == STATE_CLICKED) { - gprintf( "\tlistBtn Clicked\n" ); - if ( Settings.gameDisplay != list ) + gprintf("\tlistBtn Clicked\n"); + if (Settings.gameDisplay != list) { Settings.gameDisplay = list; menu = MENU_DISCLIST; - if ( isInserted( bootDevice ) ) + if (isInserted(bootDevice)) { Settings.Save(); } @@ -1203,15 +1341,15 @@ int MenuDiscList() } } - else if ( gridBtn.GetState() == STATE_CLICKED ) + else if (gridBtn.GetState() == STATE_CLICKED) { - gprintf( "\tgridBtn Clicked\n" ); - if ( Settings.gameDisplay != grid ) + gprintf("\tgridBtn Clicked\n"); + if (Settings.gameDisplay != grid) { Settings.gameDisplay = grid; menu = MENU_DISCLIST; - if ( isInserted( bootDevice ) ) + if (isInserted(bootDevice)) { Settings.Save(); } @@ -1224,14 +1362,14 @@ int MenuDiscList() } } - else if ( carouselBtn.GetState() == STATE_CLICKED ) + else if (carouselBtn.GetState() == STATE_CLICKED) { - gprintf( "\tcarouselBtn Clicked\n" ); - if ( Settings.gameDisplay != carousel ) + gprintf("\tcarouselBtn Clicked\n"); + if (Settings.gameDisplay != carousel) { Settings.gameDisplay = carousel; menu = MENU_DISCLIST; - if ( isInserted( bootDevice ) ) + if (isInserted(bootDevice)) { Settings.Save(); } @@ -1244,52 +1382,56 @@ int MenuDiscList() } } - else if ( homebrewBtn.GetState() == STATE_CLICKED ) + else if (homebrewBtn.GetState() == STATE_CLICKED) { - gprintf( "\thomebrewBtn Clicked\n" ); + gprintf("\thomebrewBtn Clicked\n"); menu = MENU_HOMEBREWBROWSE; break; } - else if ( gameInfo.GetState() == STATE_CLICKED && mountMethod != 3 ) + else if (gameInfo.GetState() == STATE_CLICKED && mountMethod != 3) { - gprintf( "\tgameinfo Clicked\n" ); + gprintf("\tgameinfo Clicked\n"); gameInfo.ResetState(); - if ( selectImg1 >= 0 && selectImg1 < ( s32 )gameList.size() ) + if (selectImg1 >= 0 && selectImg1 < (s32) gameList.size()) { gameSelected = selectImg1; rockout(); struct discHdr *header = gameList[selectImg1]; - 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] ); - choice = showGameInfo( IDfull ); - rockout( 2 ); - if ( choice == 2 ) - homeBtn.SetState( STATE_CLICKED ); - if ( choice == 3 ) + 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]); + choice = showGameInfo(IDfull); + rockout(2); + if (choice == 2) homeBtn.SetState(STATE_CLICKED); + if (choice == 3) { menu = MENU_DISCLIST; break; } } } - else if ( lockBtn.GetState() == STATE_CLICKED ) + else if (lockBtn.GetState() == STATE_CLICKED) { - gprintf( "\tlockBtn clicked\n" ); + gprintf("\tlockBtn clicked\n"); lockBtn.ResetState(); - if ( !canUnlock ) + 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" ) ); + 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 (Settings.godmode) { - if ( WindowPrompt( tr( "Parental Control" ), tr( "Are you sure you want to enable Parent Control?" ), tr( "Yes" ), tr( "No" ) ) == 1 ) + 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 ); + lockBtn.SetImage(&lockBtnImg_g); + lockBtn.SetImageOver(&lockBtnImg_g); + lockBtn.SetToolTip(&lockBtnTT, 15, 52, 1, 3); // Retrieve the gamelist again menu = MENU_DISCLIST; @@ -1300,17 +1442,17 @@ int MenuDiscList() { // Require the user to enter the PIN code char pin[5]; - memset( &pin, 0, 5 ); - int ret = OnScreenNumpad( ( char * ) & pin, 5 ); + memset(&pin, 0, 5); + int ret = OnScreenNumpad((char *) &pin, 5); - if ( ret == 1 ) + if (ret == 1) { - if ( memcmp( pin, Settings.Parental.pin, 4 ) == 0 ) + 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 ); + lockBtn.SetImage(&unlockBtnImg_g); + lockBtn.SetImageOver(&unlockBtnImg_g); + lockBtn.SetToolTip(&unlockBtnTT, 15, 52, 1, 3); // Retrieve the gamelist again menu = MENU_DISCLIST; @@ -1318,92 +1460,92 @@ int MenuDiscList() } else { - WindowPrompt( tr( "Parental Control" ), tr( "Invalid PIN code" ), tr( "OK" ) ); + WindowPrompt(tr( "Parental Control" ), tr( "Invalid PIN code" ), tr( "OK" )); } } } } } - else if ( dvdBtn.GetState() == STATE_CLICKED ) + else if (dvdBtn.GetState() == STATE_CLICKED) { - gprintf( "\tdvdBtn Clicked\n" ); - mountMethodOLD = ( mountMethod == 3 ? mountMethod : 0 ); + gprintf("\tdvdBtn Clicked\n"); + mountMethodOLD = (mountMethod == 3 ? mountMethod : 0); - mountMethod = DiscMount( dvdheader ); + mountMethod = DiscMount(dvdheader); dvdBtn.ResetState(); rockout(); //break; } - if ( Settings.gameDisplay == grid ) + if (Settings.gameDisplay == grid) { int selectimg; - DownloadBtn.SetSize( 0, 0 ); + DownloadBtn.SetSize(0, 0); selectimg = gameGrid->GetSelectedOption(); gameSelected = gameGrid->GetClickedOption(); selectImg1 = selectimg; } - if ( Settings.gameDisplay == carousel ) + if (Settings.gameDisplay == carousel) { int selectimg; - DownloadBtn.SetSize( 0, 0 ); + DownloadBtn.SetSize(0, 0); selectimg = gameCarousel->GetSelectedOption(); gameSelected = gameCarousel->GetClickedOption(); selectImg1 = selectimg; } - if ( Settings.gameDisplay == list ) + if (Settings.gameDisplay == list) { //Get selected game under cursor int selectimg; - DownloadBtn.SetSize( 160, 224 ); - idBtn.SetSize( 100, 40 ); + DownloadBtn.SetSize(160, 224); + idBtn.SetSize(100, 40); selectimg = gameBrowser->GetSelectedOption(); gameSelected = gameBrowser->GetClickedOption(); selectImg1 = selectimg; - if ( gameSelected > 0 ) //if click occured - selectimg = gameSelected; + if (gameSelected > 0) //if click occured + selectimg = gameSelected; char gameregion[7]; - if ( ( selectimg >= 0 ) && ( selectimg < ( s32 ) gameList.size() ) ) + if ((selectimg >= 0) && (selectimg < (s32) gameList.size())) { - if ( selectimg != selectedold ) + if (selectimg != selectedold) { selectedold = selectimg;//update displayed cover, game ID, and region if the selected game changes struct discHdr *header = gameList[selectimg]; - 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] ); - w.Remove( &DownloadBtn ); + 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]); + w.Remove(&DownloadBtn); - if ( GameIDTxt ) + if (GameIDTxt) { - w.Remove( &idBtn ); + w.Remove(&idBtn); delete GameIDTxt; GameIDTxt = NULL; } - if ( GameRegionTxt ) + if (GameRegionTxt) { - w.Remove( GameRegionTxt ); + w.Remove(GameRegionTxt); delete GameRegionTxt; GameRegionTxt = NULL; } - switch ( header->id[3] ) + switch (header->id[3]) { case 'E': - sprintf( gameregion, "NTSC U" ); + sprintf(gameregion, "NTSC U"); break; case 'J': - sprintf( gameregion, "NTSC J" ); + sprintf(gameregion, "NTSC J"); break; case 'W': - sprintf( gameregion, "NTSC T" ); + sprintf(gameregion, "NTSC T"); break; default: case 'K': - sprintf( gameregion, "NTSC K" ); + sprintf(gameregion, "NTSC K"); break; case 'P': case 'D': @@ -1415,63 +1557,63 @@ int MenuDiscList() case 'X': case 'Y': case 'Z': - sprintf( gameregion, " PAL " ); + sprintf(gameregion, " PAL "); break; } //load game cover - if ( cover ) + if (cover) { delete cover; cover = NULL; } - cover = LoadCoverImage( header ); + cover = LoadCoverImage(header); - if ( coverImg ) + if (coverImg) { delete coverImg; coverImg = NULL; } - coverImg = new GuiImage( cover ); - coverImg->SetWidescreen( Settings.widescreen ); + coverImg = new GuiImage(cover); + coverImg->SetWidescreen(Settings.widescreen); - DownloadBtn.SetImage( coverImg );// put the new image on the download button - w.Append( &DownloadBtn ); + DownloadBtn.SetImage(coverImg);// put the new image on the download button + w.Append(&DownloadBtn); - if ( ( Settings.sinfo == GameID ) || ( Settings.sinfo == Both ) ) + if ((Settings.sinfo == GameID) || (Settings.sinfo == Both)) { - GameIDTxt = new GuiText( IDfull, 22, THEME.info ); - GameIDTxt->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); + GameIDTxt = new GuiText(IDfull, 22, THEME.info); + GameIDTxt->SetAlignment(ALIGN_LEFT, ALIGN_TOP); //GameIDTxt->SetPosition(THEME.id_x,THEME.id_y); - idBtn.SetEffect( EFFECT_FADE, 20 ); - idBtn.SetLabel( GameIDTxt ); - w.Append( &idBtn ); + idBtn.SetEffect(EFFECT_FADE, 20); + idBtn.SetLabel(GameIDTxt); + w.Append(&idBtn); } //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 ) + if (((Settings.sinfo == GameRegion) || (Settings.sinfo == Both)) && mountMethod != 3) { - GameRegionTxt = new GuiText( gameregion, 22, THEME.info ); - GameRegionTxt->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - GameRegionTxt->SetPosition( THEME.region_x, THEME.region_y ); - GameRegionTxt->SetEffect( EFFECT_FADE, 20 ); - w.Append( GameRegionTxt ); + GameRegionTxt = new GuiText(gameregion, 22, THEME.info); + GameRegionTxt->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + GameRegionTxt->SetPosition(THEME.region_x, THEME.region_y); + GameRegionTxt->SetEffect(EFFECT_FADE, 20); + w.Append(GameRegionTxt); } } } - if ( idBtn.GetState() == STATE_CLICKED && mountMethod != 3 ) + if (idBtn.GetState() == STATE_CLICKED && mountMethod != 3) { - gprintf( "\n\tidBtn Clicked" ); + gprintf("\n\tidBtn Clicked"); struct discHdr * header = gameList[gameBrowser->GetSelectedOption()]; //enter new game ID char entered[10]; - snprintf( entered, sizeof( entered ), "%s", IDfull ); + snprintf(entered, sizeof(entered), "%s", IDfull); //entered[9] = '\0'; - int result = OnScreenKeyboard( entered, 7, 0 ); - if ( result == 1 ) + int result = OnScreenKeyboard(entered, 7, 0); + if (result == 1) { - WBFS_ReIDGame( header->id, entered ); + WBFS_ReIDGame(header->id, entered); //__Menu_GetEntries(); menu = MENU_DISCLIST; } @@ -1481,42 +1623,41 @@ int MenuDiscList() startat = gameBrowser->GetOffset(), offset = startat; } - if ( ( ( gameSelected >= 0 ) && ( gameSelected < ( s32 )gameList.size() ) ) - || mountMethod == 1 - || mountMethod == 2 ) + if (((gameSelected >= 0) && (gameSelected < (s32) gameList.size())) || mountMethod == 1 || mountMethod == 2) { - if ( searchBar ) + if (searchBar) { HaltGui(); - mainWindow->Remove( searchBar ); + mainWindow->Remove(searchBar); ResumeGui(); } rockout(); - struct discHdr *header = ( mountMethod == 1 || mountMethod == 2 ? dvdheader : gameList[gameSelected] ); + 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 + 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 ) ) + WBFS_GameSize(header->id, &size); + if (strlen(get_title(header)) < (MAX_CHARACTERS + 3)) { - sprintf( text, "%s", get_title( header ) ); + sprintf(text, "%s", get_title(header)); } else { - strncpy( text, get_title( header ), MAX_CHARACTERS ); + strncpy(text, get_title(header), MAX_CHARACTERS); text[MAX_CHARACTERS] = '\0'; - strncat( text, "...", 3 ); + 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 - 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 ); + 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; @@ -1527,52 +1668,51 @@ int MenuDiscList() ocarinaChoice = Settings.ocarina; } - - if ( Settings.quickboot == yes ) //quickboot game + if (Settings.quickboot == yes) //quickboot game { - if ( alternatedol == on ) + if (alternatedol == on) { /* Open dol File and check exist */ - sprintf( nipple, "%s%s.dol", Settings.dolpath, IDfull ); - exeFile = fopen ( nipple , "rb" ); - if ( exeFile == NULL ) + sprintf(nipple, "%s%s.dol", Settings.dolpath, IDfull); + exeFile = fopen(nipple, "rb"); + if (exeFile == NULL) { - sprintf( nipple, "%s %s", nipple, tr( "does not exist!" ) ); - WindowPrompt( tr( "Error" ), nipple, tr( "OK" ) ); + sprintf(nipple, "%s %s", nipple, tr( "does not exist!" )); + WindowPrompt(tr( "Error" ), nipple, tr( "OK" )); menu = MENU_CHECK; - wiilight( 0 ); + wiilight(0); break; } else { - fclose( exeFile ); + fclose(exeFile); } } - if ( ocarinaChoice != off ) + if (ocarinaChoice != off) { /* Open gct File and check exist */ - sprintf( nipple, "%s%s.gct", Settings.Cheatcodespath, IDfull ); - exeFile = fopen ( nipple , "rb" ); - if ( exeFile == NULL ) + sprintf(nipple, "%s%s.gct", Settings.Cheatcodespath, IDfull); + exeFile = fopen(nipple, "rb"); + if (exeFile == NULL) { - gprintf( "\ttried to load missing gct.\n" ); - sprintf( nipple, "%s %s", nipple, tr( "does not exist! Loading game without cheats." ) ); - WindowPrompt( tr( "Error" ), nipple, NULL, NULL, NULL, NULL, 170 ); + gprintf("\ttried to load missing gct.\n"); + sprintf(nipple, "%s %s", nipple, tr( "does not exist! Loading game without cheats." )); + WindowPrompt(tr( "Error" ), nipple, NULL, NULL, NULL, NULL, 170); } else { - fclose( exeFile ); + fclose(exeFile); } } - wiilight( 0 ); - if ( isInserted( bootDevice ) ) + wiilight(0); + if (isInserted(bootDevice)) { //////////save game play count//////////////// - struct Game_NUM* game_num = CFG_get_game_num( header->id ); + struct Game_NUM* game_num = CFG_get_game_num(header->id); - if ( game_num ) + if (game_num) { favoritevar = game_num->favorite; playcount = game_num->count; @@ -1584,8 +1724,9 @@ 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 ); + 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); } menu = MENU_EXIT; @@ -1593,179 +1734,181 @@ int MenuDiscList() } bool returnHere = true;// prompt to start game - while ( returnHere ) + while (returnHere) { returnHere = false; - if ( Settings.wiilight != wiilight_forInstall ) wiilight( 1 ); + if (Settings.wiilight != wiilight_forInstall) wiilight(1); choice = GameWindowPrompt(); // header = gameList[gameSelected]; //reset header - if ( choice == 1 ) + if (choice == 1) { - if ( alternatedol == on ) + if (alternatedol == on) { /* Open dol File and check exist */ - sprintf( nipple, "%s%s.dol", Settings.dolpath, IDfull ); - exeFile = fopen ( nipple , "rb" ); - if ( exeFile == NULL ) + sprintf(nipple, "%s%s.dol", Settings.dolpath, IDfull); + 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." ) ); - WindowPrompt( tr( "Error" ), nipple, tr( "OK" ) ); + 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." )); + WindowPrompt(tr( "Error" ), nipple, tr( "OK" )); menu = MENU_CHECK; - wiilight( 0 ); + wiilight(0); break; } else { - fclose( exeFile ); + fclose(exeFile); } } - if ( ocarinaChoice != off ) + if (ocarinaChoice != off) { /* Open gct File and check exist */ - sprintf( nipple, "%s%s.gct", Settings.Cheatcodespath, IDfull ); - exeFile = fopen ( nipple , "rb" ); - if ( exeFile == NULL ) + sprintf(nipple, "%s%s.gct", Settings.Cheatcodespath, IDfull); + exeFile = fopen(nipple, "rb"); + if (exeFile == NULL) { - gprintf( "\ttried to load gct file that isn't there\n" ); - sprintf( nipple, "%s %s", nipple, tr( "does not exist! Loading game without cheats." ) ); - WindowPrompt( tr( "Error" ), nipple, NULL, NULL, NULL, NULL, 170 ); + gprintf("\ttried to load gct file that isn't there\n"); + sprintf(nipple, "%s %s", nipple, tr( "does not exist! Loading game without cheats." )); + WindowPrompt(tr( "Error" ), nipple, NULL, NULL, NULL, NULL, 170); } else { - fclose( exeFile ); + fclose(exeFile); } } - wiilight( 0 ); + wiilight(0); returnHere = false; menu = MENU_EXIT; } - else if ( choice == 2 ) + else if (choice == 2) { - wiilight( 0 ); + wiilight(0); HaltGui(); - if ( Settings.gameDisplay == list ) mainWindow->Remove( gameBrowser ); - else if ( Settings.gameDisplay == grid ) mainWindow->Remove( gameGrid ); - else if ( Settings.gameDisplay == carousel ) mainWindow->Remove( gameCarousel ); - mainWindow->Remove( &w ); + if (Settings.gameDisplay == list) + mainWindow->Remove(gameBrowser); + else if (Settings.gameDisplay == grid) + mainWindow->Remove(gameGrid); + else if (Settings.gameDisplay == carousel) mainWindow->Remove(gameCarousel); + mainWindow->Remove(&w); ResumeGui(); //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 ); + header = (mountMethod == 1 || mountMethod == 2 ? dvdheader : gameList[gameSelected]); + int settret = GameSettings(header); /* unneeded for now, kept in case database gets a separate language setting - //menu = MENU_DISCLIST; // refresh titles (needed if the language setting has changed) - */ + //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 ); - else if ( Settings.gameDisplay == carousel ) mainWindow->Append( gameCarousel ); - mainWindow->Append( &w ); + if (Settings.gameDisplay == list) + mainWindow->Append(gameBrowser); + else if (Settings.gameDisplay == grid) + mainWindow->Append(gameGrid); + else if (Settings.gameDisplay == carousel) mainWindow->Append(gameCarousel); + mainWindow->Append(&w); ResumeGui(); - if ( settret == 1 ) //if deleted + if (settret == 1) //if deleted { menu = MENU_DISCLIST; break; } returnHere = true; - rockout( 2 ); + rockout(2); } - else if ( choice == 3 && !mountMethod ) //WBFS renaming + else if (choice == 3 && !mountMethod) //WBFS renaming { - wiilight( 0 ); + wiilight(0); //re-evaluate header now in case they changed games while on the game prompt header = gameList[gameSelected]; //enter new game title char entered[60]; - snprintf( entered, sizeof( entered ), "%s", get_title( header ) ); + snprintf(entered, sizeof(entered), "%s", get_title(header)); entered[59] = '\0'; - int result = OnScreenKeyboard( entered, 60, 0 ); - if ( result == 1 ) + int result = OnScreenKeyboard(entered, 60, 0); + if (result == 1) { - WBFS_RenameGame( header->id, entered ); + WBFS_RenameGame(header->id, entered); gameList.ReadGameList(); gameList.FilterList(); menu = MENU_DISCLIST; } } - else if ( choice == 0 ) + else if (choice == 0) { - rockout( 2 ); - if ( mountMethod == 1 || mountMethod == 2 )mountMethod = mountMethodOLD; - if ( Settings.gameDisplay == list ) + rockout(2); + if (mountMethod == 1 || mountMethod == 2) mountMethod = mountMethodOLD; + if (Settings.gameDisplay == list) { - gameBrowser->SetFocus( 1 ); + gameBrowser->SetFocus(1); } - else if ( Settings.gameDisplay == grid ) + else if (Settings.gameDisplay == grid) { - gameGrid->SetFocus( 1 ); + gameGrid->SetFocus(1); } - else if ( Settings.gameDisplay == carousel ) + else if (Settings.gameDisplay == carousel) { - gameCarousel->SetFocus( 1 ); + gameCarousel->SetFocus(1); } } - } - if ( searchBar ) + if (searchBar) { HaltGui(); - mainWindow->Append( searchBar ); + mainWindow->Append(searchBar); ResumeGui(); } } // to skip the first call of windowScreensaver at startup when wiimote is not connected - if ( IsWpadConnected() ) + if (IsWpadConnected()) { check = 1; } // screensaver is called when wiimote shuts down, depending on the wiimotet idletime - if ( !IsWpadConnected() && check != 0 && Settings.screensaver != 0 ) + if (!IsWpadConnected() && check != 0 && Settings.screensaver != 0) { check++; int screensaverIsOn = 0; - if ( check == 11500 ) //to allow time for the wii to turn off and not show the screensaver + if (check == 11500) //to allow time for the wii to turn off and not show the screensaver { screensaverIsOn = WindowScreensaver(); } - if ( screensaverIsOn == 1 )check = 0; + if (screensaverIsOn == 1) check = 0; } covertOld = covert; } // set alt dol default - if ( menu == MENU_EXIT && altdoldefault ) + 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 ); + 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) { - if ( game_cfg->alternatedolstart != 0 ) - altdoldefault = false; + if (game_cfg->alternatedolstart != 0) altdoldefault = false; } - if ( altdoldefault ) + if (altdoldefault) { - int autodol = autoSelectDol( ( char* )header->id, true ); - if ( autodol > 0 ) + int autodol = autoSelectDol((char*) header->id, true); + if (autodol > 0) { alternatedol = 2; alternatedoloffset = autodol; char temp[20]; - sprintf( temp, "%d", autodol ); + 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 ) + int autodol = autoSelectDolMenu((char*) header->id, true); + if (autodol > 0) { alternatedol = 2; alternatedoloffset = autodol; @@ -1773,15 +1916,15 @@ int MenuDiscList() } } } -//no need to close sd here. we still need to get settings and codes and shit + //no need to close sd here. we still need to get settings and codes and shit /*if (menu == MENU_EXIT) { - SDCard_deInit(); - }*/ + 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 ); + mainWindow->Append(bgImg); delete searchBar; searchBar = NULL; delete gameBrowser; @@ -1794,54 +1937,53 @@ int MenuDiscList() return menu; } -void DiscListWinUpdateCallback( void * e ) +void DiscListWinUpdateCallback(void * e) { - GuiWindow *w = ( GuiWindow * )e; - for ( int i = 0; i < 8; ++i ) + GuiWindow *w = (GuiWindow *) e; + for (int i = 0; i < 8; ++i) { - if ( Toolbar[i]->GetState() == STATE_SELECTED ) + if (Toolbar[i]->GetState() == STATE_SELECTED) { - w->Remove( Toolbar[i] ); - w->Append( Toolbar[i] ); // draw the selected Icon allways on top + w->Remove(Toolbar[i]); + w->Append(Toolbar[i]); // draw the selected Icon allways on top break; } } } -void rockout( int f ) +void rockout(int f) { HaltGui(); char imgPath[100]; - if ( gameSelected >= 0 && gameSelected < gameList.size() && - ( strcasestr( get_title( gameList[gameSelected] ), "guitar" ) || - strcasestr( get_title( gameList[gameSelected] ), "band" ) || - strcasestr( get_title( gameList[gameSelected] ), "rock" ) ) ) + if (gameSelected >= 0 && gameSelected < gameList.size() && (strcasestr(get_title(gameList[gameSelected]), "guitar") + || strcasestr(get_title(gameList[gameSelected]), "band") || strcasestr(get_title(gameList[gameSelected]), + "rock"))) { - for ( int i = 0; i < 4; i++ ) + for (int i = 0; i < 4; i++) delete pointer[i]; - snprintf( imgPath, sizeof( imgPath ), "%srplayer1_point.png", Settings.theme_path ); - pointer[0] = new GuiImageData( imgPath, rplayer1_point_png ); - snprintf( imgPath, sizeof( imgPath ), "%srplayer2_point.png", Settings.theme_path ); - pointer[1] = new GuiImageData( imgPath, rplayer2_point_png ); - snprintf( imgPath, sizeof( imgPath ), "%srplayer3_point.png", Settings.theme_path ); - pointer[2] = new GuiImageData( imgPath, rplayer3_point_png ); - snprintf( imgPath, sizeof( imgPath ), "%srplayer4_point.png", Settings.theme_path ); - pointer[3] = new GuiImageData( imgPath, rplayer4_point_png ); + snprintf(imgPath, sizeof(imgPath), "%srplayer1_point.png", Settings.theme_path); + pointer[0] = new GuiImageData(imgPath, rplayer1_point_png); + snprintf(imgPath, sizeof(imgPath), "%srplayer2_point.png", Settings.theme_path); + pointer[1] = new GuiImageData(imgPath, rplayer2_point_png); + snprintf(imgPath, sizeof(imgPath), "%srplayer3_point.png", Settings.theme_path); + pointer[2] = new GuiImageData(imgPath, rplayer3_point_png); + snprintf(imgPath, sizeof(imgPath), "%srplayer4_point.png", Settings.theme_path); + pointer[3] = new GuiImageData(imgPath, rplayer4_point_png); } else { - for ( int i = 0; i < 4; i++ ) + for (int i = 0; i < 4; i++) delete pointer[i]; - snprintf( imgPath, sizeof( imgPath ), "%splayer1_point.png", Settings.theme_path ); - pointer[0] = new GuiImageData( imgPath, player1_point_png ); - snprintf( imgPath, sizeof( imgPath ), "%splayer2_point.png", Settings.theme_path ); - pointer[1] = new GuiImageData( imgPath, player2_point_png ); - snprintf( imgPath, sizeof( imgPath ), "%splayer3_point.png", Settings.theme_path ); - pointer[2] = new GuiImageData( imgPath, player3_point_png ); - snprintf( imgPath, sizeof( imgPath ), "%splayer4_point.png", Settings.theme_path ); - pointer[3] = new GuiImageData( imgPath, player4_point_png ); + snprintf(imgPath, sizeof(imgPath), "%splayer1_point.png", Settings.theme_path); + pointer[0] = new GuiImageData(imgPath, player1_point_png); + snprintf(imgPath, sizeof(imgPath), "%splayer2_point.png", Settings.theme_path); + pointer[1] = new GuiImageData(imgPath, player2_point_png); + snprintf(imgPath, sizeof(imgPath), "%splayer3_point.png", Settings.theme_path); + pointer[2] = new GuiImageData(imgPath, player3_point_png); + snprintf(imgPath, sizeof(imgPath), "%splayer4_point.png", Settings.theme_path); + pointer[3] = new GuiImageData(imgPath, player4_point_png); } ResumeGui(); } diff --git a/source/menu/menu_format.cpp b/source/menu/menu_format.cpp index face4873..ca452b96 100644 --- a/source/menu/menu_format.cpp +++ b/source/menu/menu_format.cpp @@ -17,14 +17,14 @@ int MenuFormat() { USBDevice_deInit(); - sleep( 1 ); + sleep(1); USBStorage2_Init(); int menu = MENU_NONE; char imgPath[100]; - customOptionList options( MAX_PARTITIONS_EX ); + customOptionList options(MAX_PARTITIONS_EX); extern PartList partitions; u32 cnt, counter = 0; @@ -32,93 +32,95 @@ int MenuFormat() char text[ISFS_MAXPATH]; //create the partitionlist - for ( cnt = 0; cnt < ( u32 ) partitions.num; cnt++ ) + for (cnt = 0; cnt < (u32) partitions.num; cnt++) { partitionEntry *entry = &partitions.pentry[cnt]; /* Calculate size in gigabytes */ - f32 size = entry->size * ( partitions.sector_size / GB_SIZE ); + f32 size = entry->size * (partitions.sector_size / GB_SIZE); - if ( size ) + if (size) { - options.SetName( counter, "%s %d:", tr( "Partition" ), cnt + 1 ); - options.SetValue( counter, "%.2fGB", size ); + options.SetName(counter, "%s %d:", tr( "Partition" ), cnt + 1); + options.SetValue(counter, "%.2fGB", size); } else { - options.SetName( counter, "%s %d:", tr( "Partition" ), cnt + 1 ); - options.SetValue( counter, tr( "Can't be formatted" ) ); + options.SetName(counter, "%s %d:", tr( "Partition" ), cnt + 1); + options.SetValue(counter, tr( "Can't be formatted" )); } counter++; } - GuiSound btnSoundOver( button_over_pcm, button_over_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 ); + 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", Settings.theme_path ); - GuiImageData btnpwroff( imgPath, wiimote_poweroff_png ); - snprintf( imgPath, sizeof( imgPath ), "%swiimote_poweroff_over.png", Settings.theme_path ); - GuiImageData btnpwroffOver( imgPath, wiimote_poweroff_over_png ); - snprintf( imgPath, sizeof( imgPath ), "%smenu_button.png", Settings.theme_path ); - GuiImageData btnhome( imgPath, menu_button_png ); - snprintf( imgPath, sizeof( imgPath ), "%smenu_button_over.png", Settings.theme_path ); - 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 ); - + snprintf(imgPath, sizeof(imgPath), "%swiimote_poweroff.png", Settings.theme_path); + GuiImageData btnpwroff(imgPath, wiimote_poweroff_png); + snprintf(imgPath, sizeof(imgPath), "%swiimote_poweroff_over.png", Settings.theme_path); + GuiImageData btnpwroffOver(imgPath, wiimote_poweroff_over_png); + snprintf(imgPath, sizeof(imgPath), "%smenu_button.png", Settings.theme_path); + GuiImageData btnhome(imgPath, menu_button_png); + snprintf(imgPath, sizeof(imgPath), "%smenu_button_over.png", Settings.theme_path); + 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); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + trigHome.SetButtonOnlyTrigger(-1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0); - GuiImage poweroffBtnImg( &btnpwroff ); - GuiImage poweroffBtnImgOver( &btnpwroffOver ); - poweroffBtnImg.SetWidescreen( Settings.widescreen ); - poweroffBtnImgOver.SetWidescreen( Settings.widescreen ); - GuiButton poweroffBtn( &poweroffBtnImg, &poweroffBtnImgOver, 0, 3, THEME.power_x, THEME.power_y, &trigA, &btnSoundOver, btnClick2, 1 ); - GuiImage exitBtnImg( &btnhome ); - GuiImage exitBtnImgOver( &btnhomeOver ); - exitBtnImg.SetWidescreen( Settings.widescreen ); - exitBtnImgOver.SetWidescreen( Settings.widescreen ); - GuiButton exitBtn( &exitBtnImg, &exitBtnImgOver, 0, 3, THEME.home_x, THEME.home_y, &trigA, &btnSoundOver, btnClick2, 1 ); - exitBtn.SetTrigger( &trigHome ); + GuiImage poweroffBtnImg(&btnpwroff); + GuiImage poweroffBtnImgOver(&btnpwroffOver); + poweroffBtnImg.SetWidescreen(Settings.widescreen); + poweroffBtnImgOver.SetWidescreen(Settings.widescreen); + GuiButton poweroffBtn(&poweroffBtnImg, &poweroffBtnImgOver, 0, 3, THEME.power_x, THEME.power_y, &trigA, + &btnSoundOver, btnClick2, 1); + GuiImage exitBtnImg(&btnhome); + GuiImage exitBtnImgOver(&btnhomeOver); + exitBtnImg.SetWidescreen(Settings.widescreen); + exitBtnImgOver.SetWidescreen(Settings.widescreen); + GuiButton exitBtn(&exitBtnImg, &exitBtnImgOver, 0, 3, THEME.home_x, THEME.home_y, &trigA, &btnSoundOver, btnClick2, + 1); + exitBtn.SetTrigger(&trigHome); - GuiCustomOptionBrowser optionBrowser( 396, 280, &options, Settings.theme_path, "bg_options_settings.png", bg_options_settings_png, 0, 10 ); - optionBrowser.SetPosition( 0, 40 ); - optionBrowser.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + GuiCustomOptionBrowser optionBrowser(396, 280, &options, Settings.theme_path, "bg_options_settings.png", + bg_options_settings_png, 0, 10); + optionBrowser.SetPosition(0, 40); + optionBrowser.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); HaltGui(); - GuiWindow w( screenwidth, screenheight ); - w.Append( &poweroffBtn ); - w.Append( &exitBtn ); + GuiWindow w(screenwidth, screenheight); + w.Append(&poweroffBtn); + w.Append(&exitBtn); - mainWindow->Append( &w ); - mainWindow->Append( &optionBrowser ); + mainWindow->Append(&w); + mainWindow->Append(&optionBrowser); ResumeGui(); - while ( menu == MENU_NONE ) + while (menu == MENU_NONE) { - VIDEO_WaitVSync (); + VIDEO_WaitVSync(); ret = optionBrowser.GetClickedOption(); - if ( ret >= 0 ) + if (ret >= 0) { - if ( Settings.godmode == 1 ) + if (Settings.godmode == 1) { partitionEntry *entry = &partitions.pentry[ret]; - if ( entry->size ) + if (entry->size) { - if ( load_from_fs == PART_FS_FAT ) + 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 ); + 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; @@ -127,25 +129,26 @@ snprintf( imgPath, sizeof( imgPath ), "%swiimote_poweroff.png", Settings.theme_p } 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 ) + 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 ) + ret = FormatingPartition(tr( "Formatting, please wait..." ), entry); + if (ret < 0) { - WindowPrompt( tr( "Error !" ), tr( "Failed formating" ), tr( "Return" ) ); + WindowPrompt(tr( "Error !" ), tr( "Failed formating" ), tr( "Return" )); menu = MENU_SETTINGS; } else { - sleep( 1 ); + sleep(1); ret = WBFS_Open(); - sprintf( text, "%s %s", text, tr( "formatted!" ) ); - WindowPrompt( tr( "Success:" ), text, tr( "OK" ) ); - if ( ret < 0 ) + 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" ) ); + WindowPrompt(tr( "ERROR" ), tr( "Failed to open partition" ), tr( "OK" )); Sys_LoadMenu(); } menu = MENU_DISCLIST; @@ -153,60 +156,58 @@ snprintf( imgPath, sizeof( imgPath ), "%swiimote_poweroff.png", Settings.theme_p } } } - else if ( Settings.godmode == 0 ) + else if (Settings.godmode == 0) { - mainWindow->Remove( &optionBrowser ); + mainWindow->Remove(&optionBrowser); char entered[20] = ""; - int result = OnScreenKeyboard( entered, 20, 0 ); - mainWindow->Append( &optionBrowser ); - if ( result == 1 ) + int result = OnScreenKeyboard(entered, 20, 0); + mainWindow->Append(&optionBrowser); + if (result == 1) { - if ( !strcmp( entered, Settings.unlockCode ) ) //if password correct + if (!strcmp(entered, Settings.unlockCode)) //if password correct { - if ( Settings.godmode == 0 ) + if (Settings.godmode == 0) { - WindowPrompt( tr( "Correct Password" ), tr( "All the features of USB Loader GX are unlocked." ), tr( "OK" ) ); + WindowPrompt(tr( "Correct Password" ), + tr( "All the features of USB Loader GX are unlocked." ), tr( "OK" )); Settings.godmode = 1; } } else { - WindowPrompt( tr( "Wrong Password" ), tr( "USB Loader GX is protected" ), tr( "OK" ) ); + WindowPrompt(tr( "Wrong Password" ), tr( "USB Loader GX is protected" ), tr( "OK" )); } } } } } - if ( shutdown == 1 ) - Sys_Shutdown(); - if ( reset == 1 ) - Sys_Reboot(); + if (shutdown == 1) Sys_Shutdown(); + if (reset == 1) Sys_Reboot(); - if ( poweroffBtn.GetState() == STATE_CLICKED ) + if (poweroffBtn.GetState() == STATE_CLICKED) { - choice = WindowPrompt ( tr( "Shutdown System" ), tr( "Are you sure?" ), tr( "Yes" ), tr( "No" ) ); - if ( choice == 1 ) + choice = WindowPrompt(tr( "Shutdown System" ), tr( "Are you sure?" ), tr( "Yes" ), tr( "No" )); + if (choice == 1) { Sys_Shutdown(); } } - else if ( exitBtn.GetState() == STATE_CLICKED ) + else if (exitBtn.GetState() == STATE_CLICKED) { - choice = WindowPrompt ( tr( "Return to Wii Menu" ), tr( "Are you sure?" ), tr( "Yes" ), tr( "No" ) ); - if ( choice == 1 ) + choice = WindowPrompt(tr( "Return to Wii Menu" ), tr( "Are you sure?" ), tr( "Yes" ), tr( "No" )); + if (choice == 1) { Sys_LoadMenu(); } } } - HaltGui(); - mainWindow->Remove( &optionBrowser ); - mainWindow->Remove( &w ); + mainWindow->Remove(&optionBrowser); + mainWindow->Remove(&w); ResumeGui(); return menu; diff --git a/source/menu/menu_install.cpp b/source/menu/menu_install.cpp index 08406d9a..6055d2f3 100644 --- a/source/menu/menu_install.cpp +++ b/source/menu/menu_install.cpp @@ -14,117 +14,116 @@ float gamesize; int MenuInstall() { - gprintf( "\nMenuInstall()" ); + gprintf("\nMenuInstall()"); int menu = MENU_NONE; static struct discHdr headerdisc ATTRIBUTE_ALIGN( 32 ); - Disc_SetUSB( NULL ); + Disc_SetUSB(NULL); int ret, choice = 0; char name[200]; - GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf( imgPath, sizeof( imgPath ), "%sbattery.png", Settings.theme_path ); - GuiImageData battery( imgPath, battery_png ); - snprintf( imgPath, sizeof( imgPath ), "%sbattery_bar.png", Settings.theme_path ); - GuiImageData batteryBar( imgPath, battery_bar_png ); - snprintf( imgPath, sizeof( imgPath ), "%sbattery_red.png", Settings.theme_path ); - GuiImageData batteryRed( imgPath, battery_red_png ); - snprintf( imgPath, sizeof( imgPath ), "%sbattery_bar_red.png", Settings.theme_path ); - GuiImageData batteryBarRed( imgPath, battery_bar_red_png ); + snprintf(imgPath, sizeof(imgPath), "%sbattery.png", Settings.theme_path); + GuiImageData battery(imgPath, battery_png); + snprintf(imgPath, sizeof(imgPath), "%sbattery_bar.png", Settings.theme_path); + GuiImageData batteryBar(imgPath, battery_bar_png); + snprintf(imgPath, sizeof(imgPath), "%sbattery_red.png", Settings.theme_path); + GuiImageData batteryRed(imgPath, battery_red_png); + snprintf(imgPath, sizeof(imgPath), "%sbattery_bar_red.png", Settings.theme_path); + GuiImageData batteryBarRed(imgPath, battery_bar_red_png); HaltGui(); - GuiWindow w( screenwidth, screenheight ); + GuiWindow w(screenwidth, screenheight); - mainWindow->Append( &w ); + mainWindow->Append(&w); ResumeGui(); - while ( menu == MENU_NONE ) + while (menu == MENU_NONE) { - VIDEO_WaitVSync (); + VIDEO_WaitVSync(); - ret = DiscWait( tr( "Insert Disk" ), tr( "Waiting..." ), tr( "Cancel" ), 0, 0 ); - if ( ret < 0 ) + ret = DiscWait(tr( "Insert Disk" ), tr( "Waiting..." ), tr( "Cancel" ), 0, 0); + if (ret < 0) { - WindowPrompt ( tr( "Error reading Disc" ), 0, tr( "Back" ) ); + WindowPrompt(tr( "Error reading Disc" ), 0, tr( "Back" )); menu = MENU_DISCLIST; break; } ret = Disc_Open(); - if ( ret < 0 ) + if (ret < 0) { - WindowPrompt ( tr( "Could not open Disc" ), 0, tr( "Back" ) ); + WindowPrompt(tr( "Could not open Disc" ), 0, tr( "Back" )); menu = MENU_DISCLIST; break; } ret = Disc_IsWii(); - if ( ret < 0 ) + if (ret < 0) { - choice = WindowPrompt ( tr( "Not a Wii Disc" ), tr( "Insert a Wii Disc!" ), tr( "OK" ), tr( "Back" ) ); + choice = WindowPrompt(tr( "Not a Wii Disc" ), tr( "Insert a Wii Disc!" ), tr( "OK" ), tr( "Back" )); - if ( choice == 1 ) + if (choice == 1) { menu = MENU_INSTALL; break; } - else - menu = MENU_DISCLIST; + else menu = MENU_DISCLIST; break; } - Disc_ReadHeader( &headerdisc ); - snprintf( name, sizeof( name ), "%s", headerdisc.title ); + Disc_ReadHeader(&headerdisc); + snprintf(name, sizeof(name), "%s", headerdisc.title); - ret = WBFS_CheckGame( headerdisc.id ); - if ( ret ) + ret = WBFS_CheckGame(headerdisc.id); + if (ret) { - WindowPrompt ( tr( "Game is already installed:" ), name, tr( "Back" ) ); + WindowPrompt(tr( "Game is already installed:" ), name, tr( "Back" )); menu = MENU_DISCLIST; break; } f32 freespace, used; - WBFS_DiskSpace( &used, &freespace ); + WBFS_DiskSpace(&used, &freespace); gamesize = WBFS_EstimeGameSize() / GB_SIZE; char gametxt[50]; - sprintf( gametxt, "%s : %.2fGB", name, gamesize ); + sprintf(gametxt, "%s : %.2fGB", name, gamesize); - wiilight( 1 ); - choice = WindowPrompt( tr( "Continue to install game?" ), gametxt, tr( "OK" ), tr( "Cancel" ) ); + wiilight(1); + choice = WindowPrompt(tr( "Continue to install game?" ), gametxt, tr( "OK" ), tr( "Cancel" )); - if ( choice == 1 ) + if (choice == 1) { - sprintf( gametxt, "%s", tr( "Installing game:" ) ); + sprintf(gametxt, "%s", tr( "Installing game:" )); - if ( gamesize > freespace ) + if (gamesize > freespace) { char errortxt[50]; - sprintf( errortxt, "%s: %.2fGB, %s: %.2fGB", tr( "Game Size" ), gamesize, tr( "Free Space" ), freespace ); - WindowPrompt( tr( "Not enough free space!" ), errortxt, tr( "OK" ) ); + sprintf(errortxt, "%s: %.2fGB, %s: %.2fGB", tr( "Game Size" ), gamesize, tr( "Free Space" ), freespace); + WindowPrompt(tr( "Not enough free space!" ), errortxt, tr( "OK" )); menu = MENU_DISCLIST; break; } else { - USBStorage2_Watchdog( 0 ); - SetupGameInstallProgress( gametxt, name ); + USBStorage2_Watchdog(0); + SetupGameInstallProgress(gametxt, name); ret = WBFS_AddGame(); ProgressStop(); - USBStorage2_Watchdog( 1 ); - wiilight( 0 ); - if ( ret != 0 ) + USBStorage2_Watchdog(1); + wiilight(0); + if (ret != 0) { - WindowPrompt( tr( "Install Error!" ), 0, tr( "Back" ) ); + WindowPrompt(tr( "Install Error!" ), 0, tr( "Back" )); menu = MENU_DISCLIST; break; } @@ -134,11 +133,11 @@ int MenuInstall() gameList.FilterList(); GuiSound * instsuccess = NULL; bgMusic->Pause(); - instsuccess = new GuiSound( success_ogg, success_ogg_size, Settings.sfxvolume ); - instsuccess->SetVolume( Settings.sfxvolume ); - instsuccess->SetLoop( 0 ); + 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" ) ); + WindowPrompt(tr( "Successfully installed:" ), name, tr( "OK" )); instsuccess->Stop(); delete instsuccess; bgMusic->Resume(); @@ -153,24 +152,24 @@ int MenuInstall() break; } - if ( shutdown == 1 ) + if (shutdown == 1) { - wiilight( 0 ); + wiilight(0); Sys_Shutdown(); } - if ( reset == 1 ) + if (reset == 1) { - wiilight( 0 ); + wiilight(0); Sys_Reboot(); } } //Turn off the WiiLight - wiilight( 0 ); + wiilight(0); HaltGui(); - mainWindow->Remove( &w ); + mainWindow->Remove(&w); ResumeGui(); return menu; } diff --git a/source/mload/dip_plugin.c b/source/mload/dip_plugin.c index 07529582..ec9fabfc 100644 --- a/source/mload/dip_plugin.c +++ b/source/mload/dip_plugin.c @@ -1,375 +1,332 @@ #define size_dip_plugin 5920 -unsigned char dip_plugin[5920] __attribute__( ( aligned ( 32 ) ) ) = -{ - 0x13, 0x77, 0xe6, 0x11, 0x12, 0x34, 0x00, 0x01, 0x20, 0x22, 0xdd, 0xac, 0x20, 0x20, 0x10, 0x11, - 0x20, 0x20, 0x0b, 0x9d, 0x20, 0x20, 0x0b, 0x71, 0x20, 0x20, 0x5d, 0xc1, 0x20, 0x20, 0x00, 0x49, - 0x20, 0x20, 0x2b, 0x4d, 0x20, 0x20, 0x39, 0x35, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x77, 0xf6, 0x20, 0x13, 0x77, 0xef, 0xe0, - 0x13, 0x77, 0xed, 0xd5, 0x13, 0x77, 0xf7, 0x20, 0x00, 0x00, 0x08, 0xa0, 0xe1, 0xa0, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x71, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x73, - 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x83, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x69, - 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x79, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x5b, - 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x6b, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x5b, - 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x89, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x5b, - 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x79, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x55, - 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x4f, 0xb5, 0x10, 0x1c, 0x03, 0x22, 0x20, 0x1c, 0x0c, - 0x48, 0x0d, 0x1c, 0x19, 0xf7, 0xff, 0xff, 0xec, 0x48, 0x0b, 0x21, 0x20, 0xf7, 0xff, 0xff, 0xd4, - 0x4a, 0x0a, 0x23, 0x01, 0x68, 0x11, 0x42, 0x19, 0xd1, 0xfc, 0x22, 0x20, 0x1c, 0x20, 0x49, 0x06, - 0xf7, 0xff, 0xff, 0xde, 0x1c, 0x20, 0x21, 0x20, 0xf7, 0xff, 0xff, 0xc6, 0x4b, 0x04, 0x68, 0x18, - 0xbc, 0x10, 0xbc, 0x02, 0x47, 0x08, 0x46, 0xc0, 0x0d, 0x00, 0x60, 0x00, 0x0d, 0x00, 0x60, 0x1c, - 0x0d, 0x00, 0x60, 0x20, 0xb5, 0x70, 0xb0, 0x88, 0x4b, 0x08, 0x1c, 0x06, 0x1c, 0x0d, 0x46, 0x6c, - 0x93, 0x00, 0x60, 0x61, 0x92, 0x02, 0xf7, 0xff, 0xff, 0xcb, 0x1c, 0x31, 0x1c, 0x2a, 0x46, 0x68, - 0xf0, 0x00, 0xfe, 0xe8, 0xb0, 0x08, 0xbc, 0x70, 0xbc, 0x02, 0x47, 0x08, 0xa8, 0x00, 0x00, 0x00, - 0xb5, 0xf0, 0xb0, 0x8b, 0x0a, 0xcb, 0x1c, 0x07, 0x1c, 0x0d, 0x92, 0x01, 0x93, 0x00, 0x26, 0x00, - 0xac, 0x02, 0x4b, 0x0d, 0x1c, 0x38, 0x60, 0x23, 0x23, 0x00, 0x60, 0x63, 0x60, 0xa3, 0x9b, 0x00, - 0x1c, 0x29, 0x60, 0xe3, 0x9b, 0x01, 0x36, 0x01, 0x61, 0x23, 0xf7, 0xff, 0xff, 0xa9, 0x1c, 0x20, - 0x1c, 0x39, 0x1c, 0x2a, 0xf0, 0x00, 0xfe, 0xc6, 0x2e, 0x1f, 0xdc, 0x01, 0x28, 0x00, 0xd1, 0xe8, - 0xb0, 0x0b, 0xbc, 0xf0, 0xbc, 0x02, 0x47, 0x08, 0xd0, 0x00, 0x00, 0x00, 0xb5, 0xf0, 0xb0, 0x89, - 0x90, 0x05, 0x91, 0x06, 0x92, 0x07, 0x29, 0x00, 0xd0, 0x79, 0x23, 0x80, 0x0a, 0x52, 0x01, 0x1b, - 0x92, 0x02, 0x26, 0x00, 0x93, 0x04, 0xe0, 0x6f, 0x9a, 0x06, 0x1b, 0x94, 0x9a, 0x02, 0x02, 0x53, - 0x9a, 0x07, 0x42, 0x9a, 0xd8, 0x01, 0x23, 0x00, 0xe0, 0x02, 0x9a, 0x07, 0x1a, 0xd3, 0x00, 0x9b, - 0x93, 0x01, 0x9b, 0x05, 0x22, 0x1f, 0x19, 0x9f, 0x42, 0x17, 0xd1, 0x1c, 0x4b, 0x33, 0x42, 0x9f, - 0xd9, 0x01, 0x23, 0x00, 0xe0, 0x02, 0x23, 0xc0, 0x04, 0x5b, 0x1b, 0xdb, 0x4a, 0x30, 0x18, 0xb9, - 0x4a, 0x30, 0x42, 0x91, 0xd8, 0x01, 0x4b, 0x30, 0x1b, 0xdb, 0x4a, 0x30, 0x42, 0x93, 0xd8, 0x01, - 0x23, 0x00, 0xe0, 0x02, 0x42, 0xa3, 0xd9, 0x00, 0x1c, 0x23, 0x4a, 0x2c, 0x43, 0x93, 0xd0, 0x02, - 0x9a, 0x01, 0x2a, 0x00, 0xd0, 0x2a, 0x9a, 0x01, 0x19, 0x13, 0x9a, 0x04, 0x42, 0x93, 0xd9, 0x01, - 0x9b, 0x01, 0x1a, 0xd4, 0x20, 0x80, 0x01, 0x00, 0x21, 0x20, 0xf7, 0xff, 0xff, 0x31, 0x90, 0x03, - 0x28, 0x00, 0xd1, 0x02, 0x25, 0x01, 0x42, 0x6d, 0xe0, 0x32, 0x21, 0x80, 0x98, 0x03, 0x01, 0x09, - 0x9a, 0x02, 0xf7, 0xff, 0xff, 0x85, 0x1c, 0x05, 0x28, 0x00, 0xd1, 0x0b, 0x9a, 0x03, 0x9b, 0x01, - 0x1c, 0x38, 0x18, 0xd1, 0x1c, 0x22, 0xf7, 0xff, 0xff, 0x33, 0x9a, 0x05, 0x1c, 0x21, 0x19, 0x90, - 0xf7, 0xff, 0xff, 0x1a, 0x98, 0x03, 0xf7, 0xff, 0xff, 0x0b, 0xe0, 0x0c, 0x1c, 0x1c, 0x4b, 0x14, - 0x42, 0x9c, 0xd9, 0x01, 0x24, 0xff, 0x03, 0xe4, 0x9b, 0x05, 0x1c, 0x21, 0x19, 0x98, 0x9a, 0x02, - 0xf7, 0xff, 0xff, 0x66, 0x1c, 0x05, 0x2d, 0x00, 0xd1, 0x0a, 0x9a, 0x01, 0x9b, 0x02, 0x19, 0x36, - 0x18, 0xa4, 0x0a, 0xe4, 0x19, 0x1b, 0x93, 0x02, 0x9a, 0x06, 0x42, 0x96, 0xd3, 0x8c, 0x25, 0x00, - 0xb0, 0x09, 0x1c, 0x28, 0xbc, 0xf0, 0xbc, 0x02, 0x47, 0x08, 0x46, 0xc0, 0x01, 0x7f, 0xff, 0xff, - 0xf0, 0x00, 0x00, 0x00, 0x03, 0x61, 0x7f, 0xff, 0x13, 0x61, 0x80, 0x00, 0x00, 0x00, 0x07, 0xff, - 0x00, 0x7f, 0x7f, 0xff, 0xb5, 0x00, 0x4b, 0x07, 0xb0, 0x89, 0x93, 0x00, 0x46, 0x68, 0x23, 0x00, - 0x21, 0x00, 0x22, 0x00, 0x93, 0x01, 0x93, 0x02, 0xf0, 0x00, 0xfe, 0x1c, 0xb0, 0x09, 0xbc, 0x02, - 0x47, 0x08, 0x46, 0xc0, 0xe3, 0x00, 0x00, 0x00, 0xb5, 0xf8, 0x4e, 0x26, 0x27, 0x01, 0x1c, 0x04, - 0x60, 0x37, 0x21, 0x20, 0xf7, 0xff, 0xfe, 0xec, 0x7b, 0x22, 0x7b, 0x63, 0x06, 0x12, 0x04, 0x1b, - 0x43, 0x13, 0x7b, 0xa2, 0x02, 0x12, 0x43, 0x13, 0x7b, 0xe2, 0x43, 0x13, 0x2b, 0x08, 0xd1, 0x30, - 0x7e, 0x22, 0x7e, 0x63, 0x06, 0x12, 0x04, 0x1b, 0x43, 0x13, 0x7e, 0xa2, 0x25, 0xc5, 0x02, 0x12, - 0x43, 0x13, 0x7e, 0xe2, 0x01, 0xad, 0x43, 0x13, 0x68, 0x18, 0x68, 0x59, 0xf7, 0xff, 0xfe, 0xd0, - 0x7e, 0x22, 0x7e, 0x63, 0x06, 0x12, 0x04, 0x1b, 0x43, 0x13, 0x7e, 0xa2, 0x1c, 0x28, 0x02, 0x12, - 0x43, 0x13, 0x7e, 0xe2, 0x21, 0x08, 0x43, 0x13, 0x68, 0x1b, 0x68, 0x5c, 0xf7, 0xff, 0xfe, 0xc0, - 0x04, 0x24, 0x43, 0x27, 0x4c, 0x0c, 0x60, 0x2f, 0x1c, 0x28, 0x21, 0x04, 0x60, 0x27, 0xf7, 0xff, - 0xfe, 0x9b, 0x1c, 0x20, 0x21, 0x04, 0xf7, 0xff, 0xfe, 0x97, 0x23, 0x00, 0x60, 0x33, 0x20, 0x00, - 0xe0, 0x04, 0x1c, 0x20, 0xf0, 0x00, 0xfd, 0x3d, 0x23, 0x00, 0x60, 0x33, 0xbc, 0xf8, 0xbc, 0x02, - 0x47, 0x08, 0x46, 0xc0, 0x13, 0x77, 0xf7, 0x20, 0x00, 0x00, 0x31, 0x88, 0xb5, 0x10, 0x4b, 0x09, - 0x69, 0x1c, 0x2c, 0x00, 0xd0, 0x02, 0xf0, 0x00, 0xfb, 0xe3, 0xe0, 0x07, 0x68, 0x5b, 0x2b, 0x00, - 0xd0, 0x02, 0xf7, 0xff, 0xfe, 0xfb, 0xe0, 0x01, 0xf7, 0xff, 0xfe, 0xbc, 0xbc, 0x10, 0xbc, 0x02, - 0x47, 0x08, 0x46, 0xc0, 0x13, 0x77, 0xf7, 0x28, 0xb5, 0xf0, 0xb0, 0x85, 0x4b, 0x80, 0x90, 0x02, - 0x91, 0x03, 0x68, 0xdd, 0x68, 0x99, 0x18, 0x6d, 0x18, 0xad, 0x95, 0x00, 0x69, 0x1b, 0x2b, 0x00, - 0xd0, 0x13, 0x4b, 0x7c, 0x68, 0x1b, 0x2b, 0x00, 0xdd, 0x00, 0xe0, 0xe8, 0x4b, 0x7a, 0x68, 0x19, - 0x29, 0x00, 0xd0, 0x02, 0x20, 0x00, 0xf7, 0xff, 0xfe, 0x6f, 0x4b, 0x77, 0x22, 0x00, 0x60, 0x1a, - 0x23, 0x01, 0x4a, 0x76, 0x42, 0x5b, 0x60, 0x13, 0xe0, 0xd9, 0x4b, 0x74, 0x4a, 0x74, 0x68, 0x1b, - 0x42, 0x93, 0xd1, 0x00, 0xe0, 0xa5, 0x2b, 0x00, 0xda, 0x00, 0xe0, 0xa2, 0x4c, 0x6e, 0x68, 0x23, - 0x2b, 0x00, 0xd1, 0x06, 0x21, 0x80, 0x20, 0x00, 0x01, 0x89, 0x22, 0x20, 0xf7, 0xff, 0xfe, 0x44, - 0x60, 0x20, 0x20, 0x80, 0x01, 0x00, 0x21, 0x20, 0xf7, 0xff, 0xfe, 0x32, 0x1c, 0x04, 0x28, 0x00, - 0xd1, 0x03, 0x23, 0x01, 0x4a, 0x65, 0x42, 0x5b, 0x60, 0x13, 0x4e, 0x64, 0x68, 0x33, 0x2b, 0x00, - 0xda, 0x02, 0x21, 0x00, 0x91, 0x01, 0xe0, 0x26, 0x1c, 0x35, 0x27, 0x00, 0x68, 0x32, 0x21, 0x80, - 0x1c, 0x13, 0x33, 0x10, 0x02, 0x5b, 0x02, 0x52, 0x1c, 0x20, 0x01, 0x09, 0x93, 0x01, 0xf7, 0xff, - 0xff, 0x95, 0x28, 0x00, 0xda, 0x03, 0x23, 0x01, 0x42, 0x5b, 0x60, 0x33, 0xe0, 0x13, 0x78, 0x23, - 0x2b, 0x43, 0xd1, 0x08, 0x78, 0x63, 0x2b, 0x49, 0xd1, 0x05, 0x78, 0xa3, 0x2b, 0x53, 0xd1, 0x02, - 0x78, 0xe3, 0x2b, 0x4f, 0xd0, 0x07, 0x68, 0x2b, 0x2b, 0x00, 0xd0, 0x01, 0x60, 0x2f, 0xe7, 0xdd, - 0x23, 0x01, 0x42, 0x5b, 0x60, 0x2b, 0x4e, 0x4d, 0x68, 0x33, 0x2b, 0x00, 0xdb, 0x54, 0x4b, 0x4a, - 0x68, 0x1b, 0x2b, 0x00, 0xd0, 0x50, 0x79, 0x62, 0x79, 0xa3, 0x02, 0x12, 0x04, 0x1b, 0x18, 0xd2, - 0x79, 0x23, 0x48, 0x48, 0x18, 0xd2, 0x79, 0xe3, 0x21, 0x00, 0x06, 0x1b, 0x18, 0xd2, 0x4b, 0x46, - 0x08, 0x92, 0x60, 0x1a, 0x22, 0x80, 0x01, 0x12, 0xf0, 0x00, 0xfa, 0x50, 0x27, 0x08, 0x25, 0x00, - 0x4a, 0x42, 0x42, 0x17, 0xd1, 0x11, 0x4b, 0x42, 0x42, 0x9d, 0xdd, 0x0e, 0x68, 0x33, 0x12, 0xfa, - 0x18, 0xd2, 0x21, 0x80, 0x02, 0x52, 0x1c, 0x20, 0x01, 0x09, 0xf7, 0xff, 0xff, 0x4f, 0x28, 0x00, - 0xda, 0x03, 0x23, 0x01, 0x42, 0x5b, 0x60, 0x33, 0xe0, 0x20, 0x20, 0x07, 0x40, 0x28, 0xd1, 0x05, - 0x4b, 0x31, 0x10, 0xea, 0x68, 0x1b, 0x99, 0x01, 0x00, 0x92, 0x50, 0xd1, 0x4b, 0x33, 0x40, 0x3b, - 0x5c, 0xe3, 0x2b, 0x00, 0xd0, 0x0c, 0x4a, 0x2f, 0x21, 0x01, 0x10, 0xeb, 0x40, 0x81, 0x1c, 0x08, - 0x5c, 0xd1, 0x43, 0x01, 0x54, 0xd1, 0x4b, 0x2c, 0x9a, 0x01, 0x68, 0x1b, 0x18, 0xd2, 0x92, 0x01, - 0x23, 0x80, 0x35, 0x01, 0x01, 0xdb, 0x37, 0x01, 0x42, 0x9d, 0xd1, 0xc9, 0x4b, 0x23, 0x68, 0x1a, - 0x2a, 0x00, 0xdb, 0x01, 0x4a, 0x22, 0x60, 0x1a, 0x2c, 0x00, 0xd0, 0x02, 0x1c, 0x20, 0xf7, 0xff, - 0xfd, 0x97, 0x4b, 0x1e, 0x4c, 0x1c, 0x68, 0x1a, 0x4b, 0x1d, 0x42, 0x9a, 0xd1, 0x1e, 0x4b, 0x1e, - 0x98, 0x00, 0x68, 0x1d, 0x1c, 0x29, 0xf0, 0x00, 0xfc, 0xf3, 0x68, 0x23, 0x08, 0xc1, 0x24, 0x07, - 0x00, 0x8a, 0x58, 0xd2, 0x40, 0x20, 0x23, 0x00, 0x4e, 0x16, 0x24, 0x01, 0xe0, 0x05, 0x5c, 0x77, - 0x41, 0x1f, 0x42, 0x27, 0xd0, 0x00, 0x19, 0x52, 0x33, 0x01, 0x42, 0x83, 0xd3, 0xf7, 0x9b, 0x00, - 0x3d, 0x01, 0x40, 0x1d, 0x19, 0x52, 0x98, 0x02, 0x99, 0x03, 0xe0, 0x0b, 0x68, 0x21, 0x29, 0x00, - 0xd0, 0x02, 0x20, 0x00, 0xf7, 0xff, 0xfd, 0x90, 0x4b, 0x07, 0x22, 0x00, 0x60, 0x1a, 0x98, 0x02, - 0x99, 0x03, 0x9a, 0x00, 0xf7, 0xff, 0xfe, 0xea, 0xb0, 0x05, 0xbc, 0xf0, 0xbc, 0x02, 0x47, 0x08, - 0x13, 0x77, 0xf7, 0x28, 0x13, 0x77, 0xf7, 0xa0, 0x13, 0x77, 0xf7, 0x24, 0x13, 0x77, 0xf6, 0x04, - 0x7f, 0xff, 0xff, 0xff, 0x13, 0x77, 0xf7, 0xc0, 0x13, 0x77, 0xf7, 0x50, 0x00, 0x00, 0x07, 0xff, - 0x00, 0x00, 0x07, 0xf7, 0xb5, 0x70, 0x22, 0x00, 0x21, 0x20, 0x1c, 0x04, 0xf7, 0xff, 0xfe, 0xe4, - 0x69, 0xa2, 0x4b, 0x09, 0x1c, 0x05, 0x42, 0x9a, 0xd1, 0x09, 0x4b, 0x08, 0x21, 0x01, 0x68, 0x1a, - 0x70, 0x11, 0x68, 0x1b, 0x78, 0x5b, 0x2b, 0x00, 0xd1, 0x01, 0xf7, 0xff, 0xfd, 0x51, 0x1c, 0x28, - 0xbc, 0x70, 0xbc, 0x02, 0x47, 0x08, 0x46, 0xc0, 0x5d, 0x1c, 0x9e, 0xa3, 0x13, 0x77, 0xe0, 0x08, - 0xb5, 0xf0, 0xb0, 0x83, 0x92, 0x01, 0x4a, 0xb9, 0x1c, 0x05, 0x68, 0x13, 0x1c, 0x0c, 0x78, 0x06, - 0x2b, 0x00, 0xd0, 0x0e, 0x4b, 0xb6, 0x4f, 0xb7, 0x68, 0x1a, 0x68, 0x38, 0x21, 0x00, 0xf0, 0x00, - 0xf9, 0x95, 0x4a, 0xb3, 0x68, 0x38, 0x68, 0x11, 0xf7, 0xff, 0xfd, 0x26, 0x4a, 0xaf, 0x23, 0x00, - 0x60, 0x13, 0x2e, 0xe0, 0xd0, 0x55, 0x4f, 0xb0, 0x23, 0x00, 0x62, 0x3b, 0x2e, 0xd0, 0xd1, 0x00, - 0xe1, 0x6e, 0x2e, 0xd0, 0xd8, 0x26, 0x2e, 0x79, 0xd0, 0x62, 0x2e, 0x79, 0xd8, 0x0f, 0x2e, 0x15, - 0xd1, 0x00, 0xe0, 0xb3, 0x2e, 0x15, 0xd8, 0x03, 0x2e, 0x13, 0xd2, 0x00, 0xe1, 0x6a, 0xe0, 0x8d, - 0x2e, 0x70, 0xd1, 0x00, 0xe1, 0x00, 0x2e, 0x71, 0xd0, 0x00, 0xe1, 0x63, 0xe0, 0xe6, 0x2e, 0xa4, - 0xd1, 0x00, 0xe0, 0xbf, 0x2e, 0xa4, 0xd8, 0x06, 0x2e, 0x8a, 0xd1, 0x00, 0xe1, 0x18, 0x2e, 0x8d, - 0xd0, 0x00, 0xe1, 0x57, 0xe1, 0x4c, 0x2e, 0xa8, 0xd1, 0x00, 0xe1, 0x49, 0x2e, 0xab, 0xd0, 0x00, - 0xe1, 0x50, 0xe0, 0x36, 0x2e, 0xf1, 0xd0, 0x50, 0x2e, 0xf1, 0xd8, 0x10, 0x2e, 0xe0, 0xd0, 0x20, - 0x2e, 0xe0, 0xd8, 0x06, 0x2e, 0xd9, 0xd1, 0x00, 0xe0, 0x94, 0x2e, 0xda, 0xd0, 0x00, 0xe1, 0x41, - 0xe0, 0xad, 0x2e, 0xe4, 0xd0, 0x31, 0x2e, 0xf0, 0xd0, 0x00, 0xe1, 0x3b, 0xe0, 0x3a, 0x2e, 0xf4, - 0xd0, 0x47, 0x2e, 0xf4, 0xd8, 0x05, 0x2e, 0xf2, 0xd0, 0x3e, 0x2e, 0xf3, 0xd0, 0x00, 0xe1, 0x31, - 0xe0, 0x3d, 0x2e, 0xf6, 0xd0, 0x4e, 0x2e, 0xf6, 0xd3, 0x4a, 0x2e, 0xff, 0xd0, 0x00, 0xe1, 0x29, - 0xe0, 0x71, 0x4b, 0x85, 0x6a, 0x1a, 0x2a, 0x00, 0xd1, 0x03, 0x69, 0x1b, 0x2b, 0x00, 0xd1, 0x00, - 0xe1, 0x20, 0x1c, 0x20, 0x21, 0x00, 0x9a, 0x01, 0xf0, 0x00, 0xf9, 0x28, 0x4b, 0x7e, 0x6a, 0x1b, - 0xe0, 0x1c, 0x68, 0x7b, 0x2b, 0x00, 0xd0, 0x00, 0xe1, 0x1a, 0x4b, 0x7b, 0x69, 0x1b, 0xe0, 0x00, - 0x69, 0x3b, 0x2b, 0x00, 0xd0, 0x00, 0xe1, 0x13, 0xe1, 0x0c, 0x68, 0x7b, 0x2b, 0x00, 0xd1, 0x03, - 0x69, 0x3b, 0x2b, 0x00, 0xd1, 0x00, 0xe1, 0x05, 0x1c, 0x20, 0x21, 0x00, 0x9a, 0x01, 0xf0, 0x00, - 0xf9, 0x0d, 0xe0, 0x04, 0x68, 0x6b, 0x60, 0xbb, 0xe1, 0x02, 0x68, 0xbb, 0x60, 0x23, 0x99, 0x01, - 0x1c, 0x20, 0xf7, 0xff, 0xfc, 0x99, 0xe0, 0xfb, 0x68, 0x6b, 0x60, 0x3b, 0xe0, 0xf8, 0x68, 0x3b, - 0xe7, 0xf4, 0x68, 0x6b, 0x61, 0x3b, 0x2b, 0x00, 0xd0, 0x06, 0x1c, 0x38, 0x1c, 0x29, 0x30, 0x18, - 0x31, 0x08, 0x22, 0x06, 0xf7, 0xff, 0xfc, 0x9c, 0x69, 0x6a, 0x4b, 0x63, 0x61, 0x5a, 0xe0, 0xe7, - 0x69, 0x3b, 0xe7, 0xe3, 0x79, 0x2b, 0x37, 0x05, 0x77, 0xfb, 0xe0, 0xe1, 0x2c, 0x00, 0xd1, 0x00, - 0xe0, 0xde, 0x2e, 0x13, 0xd1, 0x0b, 0x69, 0x3b, 0x2b, 0x00, 0xd0, 0x0f, 0x4b, 0x5b, 0x68, 0x1b, - 0x2b, 0x00, 0xd0, 0x07, 0xf0, 0x00, 0xf9, 0xb4, 0x28, 0x00, 0xd0, 0x0b, 0xe0, 0x0c, 0x69, 0x3b, - 0x2b, 0x00, 0xd0, 0x03, 0x4b, 0x56, 0x68, 0x1b, 0x2b, 0x00, 0xda, 0x05, 0x4b, 0x55, 0x68, 0x1b, - 0x07, 0xda, 0xd5, 0x01, 0x23, 0x00, 0xe7, 0xc1, 0x23, 0x02, 0xe7, 0xbf, 0x4b, 0x51, 0x22, 0x01, - 0x68, 0x1b, 0x43, 0x93, 0xe7, 0xba, 0x68, 0x6b, 0x48, 0x4f, 0x1c, 0x21, 0x40, 0x18, 0xf7, 0xff, - 0xfc, 0x73, 0xe0, 0xb6, 0x68, 0x7b, 0x2b, 0x00, 0xd1, 0x03, 0x69, 0x3b, 0x2b, 0x00, 0xd1, 0x00, - 0xe0, 0xa8, 0x68, 0x6a, 0x68, 0xab, 0x07, 0x92, 0x43, 0x1a, 0x4b, 0x48, 0x40, 0x1a, 0x4b, 0x42, - 0x60, 0xda, 0xe0, 0xa5, 0x68, 0x7b, 0x2b, 0x00, 0xd1, 0x03, 0x69, 0x3b, 0x2b, 0x00, 0xd1, 0x00, - 0xe0, 0x98, 0x4a, 0x43, 0x4b, 0x3c, 0x20, 0xa0, 0x62, 0x1a, 0x02, 0x00, 0xe0, 0x99, 0x4e, 0x41, - 0x21, 0x40, 0x1c, 0x30, 0xf7, 0xff, 0xfc, 0x4c, 0x1c, 0x33, 0x33, 0x40, 0xe0, 0x03, 0x36, 0x01, - 0x42, 0x9e, 0xd1, 0x00, 0xe0, 0x86, 0x78, 0x32, 0x2a, 0x00, 0xd0, 0xf8, 0x49, 0x39, 0x1c, 0x20, - 0x22, 0x40, 0xf7, 0xff, 0xfc, 0x35, 0x1c, 0x20, 0x21, 0x40, 0xe7, 0x82, 0x1d, 0xbb, 0x22, 0x01, - 0x77, 0xda, 0x68, 0x3b, 0x2b, 0x00, 0xd1, 0x05, 0x1c, 0x28, 0x1c, 0x21, 0x9a, 0x01, 0xf0, 0x00, - 0xfb, 0x51, 0xe0, 0x04, 0x68, 0x69, 0x68, 0xaa, 0x1c, 0x20, 0xf7, 0xff, 0xfd, 0x9d, 0x4b, 0x26, - 0x22, 0x00, 0x33, 0x06, 0x77, 0xda, 0xe0, 0x6c, 0x69, 0x3b, 0x2b, 0x00, 0xd1, 0x06, 0x1c, 0x28, - 0x1c, 0x21, 0x9a, 0x01, 0xf0, 0x00, 0xfb, 0x3e, 0x28, 0x00, 0xd1, 0x0e, 0x4b, 0x1e, 0x68, 0xda, - 0x2a, 0x00, 0xd1, 0x09, 0x68, 0x9a, 0x2a, 0x00, 0xd1, 0x06, 0x69, 0x1a, 0x2a, 0x00, 0xd1, 0x03, - 0x69, 0xa0, 0x49, 0x21, 0x42, 0x88, 0xd0, 0x09, 0x20, 0x00, 0x1e, 0x43, 0x41, 0x98, 0x4b, 0x16, - 0x99, 0x01, 0x60, 0x58, 0x1c, 0x20, 0xf7, 0xff, 0xfe, 0x8d, 0xe0, 0x4a, 0x60, 0x5a, 0xe0, 0x47, - 0x1d, 0x7b, 0x7f, 0xdb, 0x2b, 0x00, 0xd1, 0x43, 0x1d, 0xba, 0x77, 0xd3, 0x60, 0x3b, 0x60, 0x7b, - 0x60, 0xbb, 0x60, 0xfb, 0x62, 0x3b, 0x69, 0x3b, 0x2b, 0x00, 0xd1, 0x04, 0x69, 0x7a, 0x4b, 0x13, - 0x3a, 0x01, 0x60, 0x1a, 0xe0, 0x2e, 0xf7, 0xff, 0xfc, 0xe5, 0x69, 0x38, 0x1c, 0x39, 0x31, 0x18, - 0x69, 0x7a, 0x38, 0x01, 0xf0, 0x00, 0xf8, 0x62, 0xe0, 0x2b, 0x46, 0xc0, 0x13, 0x77, 0xf6, 0x00, - 0x13, 0x77, 0xe0, 0x48, 0x13, 0x77, 0xe0, 0x44, 0x13, 0x77, 0xf7, 0x28, 0x13, 0x77, 0xf7, 0xa4, - 0x13, 0x77, 0xf6, 0x08, 0x0d, 0x00, 0x60, 0x04, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, - 0x00, 0x05, 0x31, 0x00, 0x13, 0x77, 0xef, 0xe0, 0x5d, 0x1c, 0x9e, 0xa3, 0x13, 0x77, 0xf6, 0x04, - 0x68, 0xaa, 0x68, 0x69, 0x2e, 0xd0, 0xd1, 0x01, 0x02, 0x52, 0x02, 0xc9, 0x1c, 0x20, 0xf7, 0xff, - 0xfd, 0x33, 0xe0, 0x06, 0x1c, 0x28, 0x1c, 0x21, 0x9a, 0x01, 0xf0, 0x00, 0xfa, 0xdb, 0xe0, 0x00, - 0x20, 0x00, 0xb0, 0x03, 0xbc, 0xf0, 0xbc, 0x02, 0x47, 0x08, 0x46, 0xc0, 0xb5, 0xf0, 0x2a, 0x00, - 0xd0, 0x29, 0x24, 0x03, 0x1c, 0x03, 0x40, 0x23, 0x27, 0x04, 0x1a, 0xfb, 0x06, 0x0e, 0x40, 0x23, - 0x0e, 0x36, 0x1c, 0x05, 0x42, 0x93, 0xd9, 0x01, 0x1c, 0x13, 0xe0, 0x01, 0x2b, 0x00, 0xd0, 0x05, - 0x1c, 0x1c, 0xe0, 0x01, 0x70, 0x2e, 0x35, 0x01, 0x3c, 0x01, 0xd2, 0xfb, 0x04, 0x0c, 0x06, 0x0d, - 0x43, 0x25, 0x43, 0x0d, 0x02, 0x0c, 0x1c, 0x29, 0x43, 0x21, 0x18, 0xc4, 0xe0, 0x01, 0xc4, 0x02, - 0x1c, 0x2b, 0x1d, 0x1d, 0x42, 0x95, 0xd9, 0xfa, 0x18, 0xc0, 0xe0, 0x01, 0x33, 0x01, 0x70, 0x06, - 0x30, 0x01, 0x42, 0x93, 0xd3, 0xfa, 0xbc, 0xf0, 0xbc, 0x01, 0x47, 0x00, 0xb5, 0xf0, 0xb0, 0x85, - 0x1c, 0x05, 0x1c, 0x0e, 0x28, 0x01, 0xd9, 0x02, 0x25, 0x01, 0x42, 0x6d, 0xe0, 0x89, 0x4b, 0x47, - 0x92, 0x03, 0x68, 0x1a, 0x2a, 0x00, 0xd1, 0x02, 0x4a, 0x45, 0x60, 0x1a, 0xe0, 0x05, 0x4b, 0x45, - 0x68, 0x18, 0x28, 0x00, 0xdb, 0x01, 0xf7, 0xff, 0xfb, 0x47, 0x4a, 0x42, 0x23, 0x01, 0x42, 0x5b, - 0x60, 0x13, 0x4a, 0x41, 0x4b, 0x41, 0x21, 0x00, 0x60, 0x11, 0x60, 0x19, 0x78, 0x31, 0x29, 0x5f, - 0xd1, 0x2b, 0x78, 0x71, 0x29, 0x44, 0xd1, 0x28, 0x78, 0xb1, 0x29, 0x45, 0xd1, 0x1e, 0x78, 0xf2, - 0x2a, 0x56, 0xd1, 0x22, 0x22, 0x01, 0x60, 0x1a, 0x79, 0x32, 0x2a, 0x57, 0xd1, 0x01, 0x22, 0x02, - 0x60, 0x1a, 0x4c, 0x37, 0x21, 0x80, 0x1c, 0x20, 0x00, 0x49, 0xf7, 0xff, 0xfb, 0x49, 0x1c, 0x20, - 0x21, 0x00, 0xf7, 0xff, 0xfb, 0x39, 0x4b, 0x2f, 0x1c, 0x05, 0x60, 0x18, 0x28, 0x00, 0xdb, 0x01, - 0x25, 0x00, 0xe0, 0x4e, 0x4b, 0x2d, 0x22, 0x00, 0x60, 0x1a, 0xe0, 0x4a, 0x29, 0x56, 0xd1, 0x04, - 0x78, 0xf3, 0x2b, 0x44, 0xd1, 0x01, 0x23, 0x01, 0x60, 0x13, 0x4b, 0x2a, 0x00, 0xaa, 0x58, 0xd0, - 0x21, 0x01, 0xf7, 0xff, 0xfb, 0x21, 0x4c, 0x23, 0x60, 0x20, 0x28, 0x00, 0xda, 0x06, 0x2d, 0x00, - 0xd1, 0x04, 0x48, 0x25, 0x21, 0x01, 0xf7, 0xff, 0xfb, 0x17, 0x60, 0x20, 0x4f, 0x1d, 0x68, 0x3d, - 0x2d, 0x00, 0xdb, 0x2e, 0x4c, 0x19, 0x1c, 0x31, 0x68, 0x20, 0x22, 0x06, 0x30, 0x20, 0xf7, 0xff, - 0xfb, 0x0f, 0x68, 0x20, 0x22, 0x04, 0xa9, 0x03, 0x30, 0x3c, 0xf7, 0xff, 0xfb, 0x09, 0x68, 0x20, - 0x26, 0x04, 0x1c, 0x03, 0x33, 0x20, 0x60, 0x03, 0x23, 0x06, 0x60, 0x43, 0x1c, 0x03, 0x33, 0x3c, - 0x60, 0x83, 0x60, 0xc6, 0x21, 0x40, 0xf7, 0xff, 0xfa, 0xe7, 0x68, 0x23, 0x68, 0x38, 0x49, 0x13, - 0x93, 0x00, 0x22, 0x02, 0x23, 0x00, 0xf7, 0xff, 0xfa, 0xe3, 0x1c, 0x05, 0x68, 0x20, 0x21, 0x40, - 0x1c, 0x03, 0x33, 0x20, 0x60, 0x03, 0x33, 0x1c, 0x60, 0x46, 0x60, 0x83, 0x60, 0xc6, 0xf7, 0xff, - 0xfa, 0xd3, 0xb0, 0x05, 0x1c, 0x28, 0xbc, 0xf0, 0xbc, 0x02, 0x47, 0x08, 0x13, 0x77, 0xf7, 0x54, - 0x13, 0x77, 0xf7, 0x60, 0x13, 0x77, 0xf6, 0x08, 0x13, 0x77, 0xf7, 0xa4, 0x13, 0x77, 0xf7, 0xa0, - 0x13, 0x77, 0xf6, 0x20, 0x13, 0x77, 0xf0, 0x48, 0x13, 0x77, 0xf0, 0x20, 0x57, 0x46, 0x53, 0x01, - 0xb5, 0x00, 0x4b, 0x0b, 0xb0, 0x83, 0x68, 0x1b, 0x2b, 0x00, 0xd0, 0x0c, 0x4b, 0x09, 0x68, 0x18, - 0x28, 0x00, 0xdb, 0x08, 0x4b, 0x08, 0x49, 0x09, 0x68, 0x1b, 0x22, 0x00, 0x93, 0x00, 0x23, 0x00, - 0xf7, 0xff, 0xfa, 0xae, 0xe0, 0x00, 0x20, 0x01, 0xb0, 0x03, 0xbc, 0x02, 0x47, 0x08, 0x46, 0xc0, - 0x13, 0x77, 0xf7, 0xa4, 0x13, 0x77, 0xf6, 0x08, 0x13, 0x77, 0xf7, 0x54, 0x57, 0x46, 0x53, 0x04, - 0xb5, 0xf0, 0x4d, 0x94, 0xb0, 0x87, 0x68, 0x2b, 0x90, 0x03, 0x91, 0x02, 0x92, 0x04, 0x2b, 0x00, - 0xda, 0x00, 0xe0, 0xf1, 0x4b, 0x90, 0x68, 0x1b, 0x2b, 0x00, 0xd1, 0x00, 0xe0, 0xef, 0x3b, 0x01, - 0x2b, 0x01, 0xd9, 0x00, 0xe0, 0xaa, 0x4c, 0x8d, 0x68, 0x23, 0x2b, 0x00, 0xd1, 0x06, 0x21, 0x80, - 0x20, 0x00, 0x01, 0x89, 0x22, 0x20, 0xf7, 0xff, 0xfa, 0x87, 0x60, 0x20, 0x20, 0x80, 0x01, 0x00, - 0x21, 0x20, 0xf7, 0xff, 0xfa, 0x75, 0x1c, 0x04, 0x28, 0x00, 0xd1, 0x03, 0x23, 0x01, 0x4a, 0x82, - 0x42, 0x5b, 0x60, 0x13, 0x4b, 0x80, 0x68, 0x1b, 0x2b, 0x00, 0xda, 0x01, 0x25, 0x00, 0xe0, 0x21, - 0x4d, 0x7c, 0x21, 0x00, 0x68, 0x28, 0x22, 0x00, 0xf7, 0xff, 0xfa, 0x56, 0x28, 0x00, 0xdb, 0x13, - 0x22, 0x80, 0x68, 0x28, 0x1c, 0x21, 0x01, 0x12, 0xf7, 0xff, 0xfa, 0x4a, 0x28, 0x00, 0xdb, 0x0b, - 0x78, 0x23, 0x2b, 0x43, 0xd1, 0x08, 0x78, 0x63, 0x2b, 0x49, 0xd1, 0x05, 0x78, 0xa3, 0x2b, 0x53, - 0xd1, 0x02, 0x78, 0xe3, 0x2b, 0x4f, 0xd0, 0x03, 0x23, 0x01, 0x4a, 0x6f, 0x42, 0x5b, 0x60, 0x13, - 0x25, 0x80, 0x01, 0xad, 0x4a, 0x6c, 0x68, 0x13, 0x2b, 0x00, 0xdb, 0x62, 0x4b, 0x6b, 0x68, 0x1b, - 0x2b, 0x00, 0xd0, 0x5e, 0x79, 0x62, 0x79, 0xa3, 0x02, 0x12, 0x04, 0x1b, 0x18, 0xd2, 0x79, 0x23, - 0x48, 0x67, 0x18, 0xd2, 0x79, 0xe3, 0x21, 0x00, 0x06, 0x1b, 0x18, 0xd2, 0x4b, 0x65, 0x08, 0x92, - 0x60, 0x1a, 0x22, 0x80, 0x01, 0x12, 0xf7, 0xff, 0xfe, 0x99, 0x27, 0x08, 0x26, 0x00, 0x4b, 0x62, - 0x42, 0x1f, 0xd1, 0x21, 0x4a, 0x61, 0x42, 0x96, 0xdd, 0x1e, 0x4b, 0x5b, 0x68, 0x1a, 0x4b, 0x59, - 0x2a, 0x02, 0xd1, 0x03, 0x12, 0xf9, 0x68, 0x18, 0x02, 0x49, 0xe0, 0x02, 0x49, 0x5c, 0x68, 0x18, - 0x40, 0x39, 0x22, 0x00, 0xf7, 0xff, 0xfa, 0x08, 0x28, 0x00, 0xdb, 0x08, 0x4b, 0x51, 0x22, 0x80, - 0x68, 0x18, 0x1c, 0x21, 0x01, 0x12, 0xf7, 0xff, 0xf9, 0xfb, 0x28, 0x00, 0xda, 0x04, 0x23, 0x01, - 0x4a, 0x4d, 0x42, 0x5b, 0x60, 0x13, 0xe0, 0x1d, 0x20, 0x07, 0x40, 0x30, 0xd1, 0x04, 0x4b, 0x4b, - 0x10, 0xf2, 0x68, 0x1b, 0x00, 0x92, 0x50, 0xd5, 0x4b, 0x4b, 0x40, 0x3b, 0x5c, 0xe3, 0x2b, 0x00, - 0xd0, 0x0a, 0x4a, 0x47, 0x21, 0x01, 0x10, 0xf3, 0x40, 0x81, 0x1c, 0x08, 0x5c, 0xd1, 0x43, 0x01, - 0x54, 0xd1, 0x4b, 0x44, 0x68, 0x1b, 0x18, 0xed, 0x23, 0x80, 0x36, 0x01, 0x01, 0xdb, 0x37, 0x01, - 0x42, 0x9e, 0xd1, 0xbc, 0x4b, 0x3c, 0x68, 0x1a, 0x2a, 0x00, 0xdb, 0x02, 0x21, 0x04, 0x43, 0x0a, - 0x60, 0x1a, 0x2c, 0x00, 0xd0, 0x02, 0x1c, 0x20, 0xf7, 0xff, 0xf9, 0xd2, 0x4b, 0x36, 0x4c, 0x37, - 0x68, 0x1b, 0x93, 0x05, 0x2b, 0x03, 0xdd, 0x2e, 0x4b, 0x36, 0x98, 0x04, 0x68, 0x1d, 0x1c, 0x29, - 0xf0, 0x00, 0xf9, 0x2e, 0x68, 0x23, 0x08, 0xc2, 0x24, 0x07, 0x00, 0x91, 0x58, 0xc9, 0x40, 0x20, - 0x23, 0x00, 0x4e, 0x2f, 0x24, 0x01, 0xe0, 0x05, 0x5c, 0xb7, 0x41, 0x1f, 0x42, 0x27, 0xd0, 0x00, - 0x19, 0x49, 0x33, 0x01, 0x42, 0x83, 0xd3, 0xf7, 0x9a, 0x04, 0x3d, 0x01, 0x40, 0x15, 0x9a, 0x05, - 0x19, 0x49, 0x4b, 0x24, 0x07, 0x92, 0xd5, 0x01, 0x68, 0x18, 0xe0, 0x01, 0x68, 0x18, 0x00, 0x89, - 0x22, 0x00, 0xf7, 0xff, 0xf9, 0xa1, 0x4b, 0x1f, 0x99, 0x03, 0x68, 0x18, 0x9a, 0x02, 0xf7, 0xff, - 0xf9, 0x97, 0x24, 0x00, 0xe0, 0x31, 0x68, 0x21, 0x29, 0x00, 0xd0, 0x02, 0x20, 0x00, 0xf7, 0xff, - 0xf9, 0xbb, 0x4b, 0x1a, 0x22, 0x00, 0x60, 0x1a, 0x24, 0x01, 0x42, 0x64, 0xe0, 0x25, 0x4c, 0x1d, - 0x9b, 0x04, 0x68, 0x20, 0x21, 0x40, 0x62, 0x03, 0x9a, 0x02, 0x63, 0xc2, 0x9b, 0x03, 0x61, 0x82, - 0x61, 0x03, 0xf7, 0xff, 0xf9, 0x91, 0x98, 0x03, 0x99, 0x02, 0xf7, 0xff, 0xf9, 0x8d, 0x4b, 0x16, - 0x68, 0x1b, 0x2b, 0x00, 0xd0, 0x04, 0x68, 0x23, 0x68, 0x28, 0x49, 0x14, 0x93, 0x00, 0xe0, 0x03, - 0x68, 0x23, 0x49, 0x13, 0x68, 0x28, 0x93, 0x00, 0x22, 0x02, 0x23, 0x01, 0xf7, 0xff, 0xf9, 0x80, - 0x99, 0x02, 0x1c, 0x04, 0x98, 0x03, 0xf7, 0xff, 0xf9, 0x93, 0xb0, 0x07, 0x1c, 0x20, 0xbc, 0xf0, - 0xbc, 0x02, 0x47, 0x08, 0x13, 0x77, 0xf6, 0x08, 0x13, 0x77, 0xf7, 0xa0, 0x13, 0x77, 0xf7, 0x24, - 0x13, 0x77, 0xf7, 0xc0, 0x13, 0x77, 0xf7, 0x50, 0x00, 0x00, 0x07, 0xff, 0x00, 0x00, 0x07, 0xf7, - 0xff, 0xff, 0xf8, 0x00, 0x13, 0x77, 0xf7, 0x54, 0x13, 0x77, 0xf7, 0xa4, 0x57, 0x46, 0x53, 0x03, - 0x57, 0x46, 0x53, 0x02, 0xb4, 0x7c, 0xb5, 0x00, 0xf7, 0xff, 0xfa, 0x7e, 0xbc, 0x02, 0xbc, 0x7c, - 0x47, 0x08, 0xb5, 0x70, 0xb0, 0x88, 0x68, 0x85, 0x1c, 0x01, 0x4b, 0x01, 0x47, 0x18, 0x00, 0x00, - 0x20, 0x10, 0x00, 0xd5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xe6, 0x00, 0x08, 0x10, 0xe1, 0x2f, 0xff, 0x1e, 0xe6, 0x00, 0x07, 0xf0, 0xe1, 0x2f, 0xff, 0x1e, - 0xe6, 0x00, 0x03, 0x30, 0xe1, 0x2f, 0xff, 0x1e, 0xe6, 0x00, 0x03, 0x50, 0xe1, 0x2f, 0xff, 0x1e, - 0xe6, 0x00, 0x03, 0x90, 0xe1, 0x2f, 0xff, 0x1e, 0xe6, 0x00, 0x03, 0xb0, 0xe1, 0x2f, 0xff, 0x1e, - 0xe6, 0x00, 0x03, 0xd0, 0xe1, 0x2f, 0xff, 0x1e, 0xe6, 0x00, 0x03, 0xf0, 0xe1, 0x2f, 0xff, 0x1e, - 0xe6, 0x00, 0x04, 0x10, 0xe1, 0x2f, 0xff, 0x1e, 0xe6, 0x00, 0x04, 0x50, 0xe1, 0x2f, 0xff, 0x1e, - 0xef, 0x00, 0x00, 0xcc, 0xe1, 0x2f, 0xff, 0x1e, 0x46, 0x72, 0x1c, 0x01, 0x20, 0x04, 0xdf, 0xab, - 0x47, 0x10, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, - 0xe9, 0x2d, 0x40, 0x80, 0xe5, 0x9f, 0x70, 0x9c, 0xe5, 0x97, 0x70, 0x00, 0xeb, 0x00, 0x00, 0x1f, - 0xe8, 0xbd, 0x40, 0x80, 0xe1, 0x2f, 0xff, 0x1e, 0xe9, 0x2d, 0x40, 0x80, 0xe5, 0x9f, 0x70, 0x88, - 0xe5, 0x97, 0x70, 0x00, 0xeb, 0x00, 0x00, 0x19, 0xe8, 0xbd, 0x40, 0x80, 0xe1, 0x2f, 0xff, 0x1e, - 0xe9, 0x2d, 0x40, 0x80, 0xe5, 0x9f, 0x70, 0x74, 0xe5, 0x97, 0x70, 0x00, 0xeb, 0x00, 0x00, 0x13, - 0xe8, 0xbd, 0x40, 0x80, 0xe1, 0x2f, 0xff, 0x1e, 0xe9, 0x2d, 0x40, 0x80, 0xe5, 0x9f, 0x70, 0x60, - 0xe5, 0x97, 0x70, 0x00, 0xeb, 0x00, 0x00, 0x0d, 0xe8, 0xbd, 0x40, 0x80, 0xe1, 0x2f, 0xff, 0x1e, - 0xe9, 0x2d, 0x40, 0x80, 0xe5, 0x9f, 0x70, 0x4c, 0xe5, 0x97, 0x70, 0x00, 0xeb, 0x00, 0x00, 0x07, - 0xe8, 0xbd, 0x40, 0x80, 0xe1, 0x2f, 0xff, 0x1e, 0xe9, 0x2d, 0x40, 0x80, 0xe5, 0x9f, 0x70, 0x38, - 0xe5, 0x97, 0x70, 0x00, 0xeb, 0x00, 0x00, 0x01, 0xe8, 0xbd, 0x40, 0x80, 0xe1, 0x2f, 0xff, 0x1e, - 0xe1, 0x2f, 0xff, 0x17, 0xb5, 0xf0, 0x46, 0x5f, 0x46, 0x56, 0x46, 0x4d, 0x46, 0x44, 0xb4, 0xf0, - 0x4b, 0x07, 0x68, 0x1b, 0x47, 0x18, 0x00, 0x00, 0x13, 0x77, 0xe0, 0x10, 0x13, 0x77, 0xe0, 0x14, - 0x13, 0x77, 0xe0, 0x18, 0x13, 0x77, 0xe0, 0x1c, 0x13, 0x77, 0xe0, 0x20, 0x13, 0x77, 0xe0, 0x24, - 0x13, 0x77, 0xe0, 0x0c, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, - 0x29, 0x00, 0xd0, 0x34, 0x23, 0x01, 0x22, 0x00, 0xb4, 0x10, 0x42, 0x88, 0xd3, 0x2c, 0x24, 0x01, - 0x07, 0x24, 0x42, 0xa1, 0xd2, 0x04, 0x42, 0x81, 0xd2, 0x02, 0x01, 0x09, 0x01, 0x1b, 0xe7, 0xf8, - 0x00, 0xe4, 0x42, 0xa1, 0xd2, 0x04, 0x42, 0x81, 0xd2, 0x02, 0x00, 0x49, 0x00, 0x5b, 0xe7, 0xf8, - 0x42, 0x88, 0xd3, 0x01, 0x1a, 0x40, 0x43, 0x1a, 0x08, 0x4c, 0x42, 0xa0, 0xd3, 0x02, 0x1b, 0x00, - 0x08, 0x5c, 0x43, 0x22, 0x08, 0x8c, 0x42, 0xa0, 0xd3, 0x02, 0x1b, 0x00, 0x08, 0x9c, 0x43, 0x22, - 0x08, 0xcc, 0x42, 0xa0, 0xd3, 0x02, 0x1b, 0x00, 0x08, 0xdc, 0x43, 0x22, 0x28, 0x00, 0xd0, 0x03, - 0x09, 0x1b, 0xd0, 0x01, 0x09, 0x09, 0xe7, 0xe3, 0x1c, 0x10, 0xbc, 0x10, 0x47, 0x70, 0xb5, 0x02, - 0xf0, 0x00, 0xf8, 0x0c, 0x20, 0x00, 0xbc, 0x06, 0x47, 0x10, 0x46, 0xc0, 0xb5, 0x03, 0xf7, 0xff, - 0xff, 0xbf, 0xbc, 0x0e, 0x43, 0x42, 0x1a, 0x89, 0x47, 0x18, 0x46, 0xc0, 0x47, 0x70, 0x46, 0xc0, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x2f, 0x64, 0x65, 0x76, 0x2f, 0x75, 0x73, 0x62, 0x32, 0x00, 0x2f, 0x64, 0x65, 0x76, 0x2f, 0x73, - 0x64, 0x69, 0x6f, 0x2f, 0x73, 0x64, 0x68, 0x63, 0x00, 0x2f, 0x64, 0x65, 0x76, 0x2f, 0x75, 0x73, - 0x62, 0x2f, 0x65, 0x68, 0x63, 0x00, 0x00, 0x00, 0x13, 0x77, 0xf0, 0x20, 0x13, 0x77, 0xf0, 0x2a, - 0x13, 0x77, 0xf0, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x66, 0x69, 0x6c, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -}; +unsigned char dip_plugin[5920] __attribute__( ( aligned ( 32 ) ) ) = { 0x13, 0x77, 0xe6, 0x11, 0x12, 0x34, 0x00, 0x01, + 0x20, 0x22, 0xdd, 0xac, 0x20, 0x20, 0x10, 0x11, 0x20, 0x20, 0x0b, 0x9d, 0x20, 0x20, 0x0b, 0x71, 0x20, 0x20, + 0x5d, 0xc1, 0x20, 0x20, 0x00, 0x49, 0x20, 0x20, 0x2b, 0x4d, 0x20, 0x20, 0x39, 0x35, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x77, 0xf6, 0x20, 0x13, 0x77, + 0xef, 0xe0, 0x13, 0x77, 0xed, 0xd5, 0x13, 0x77, 0xf7, 0x20, 0x00, 0x00, 0x08, 0xa0, 0xe1, 0xa0, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0xc0, + 0x47, 0x78, 0xea, 0x00, 0x03, 0x71, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x73, 0x46, 0xc0, 0x47, 0x78, + 0xea, 0x00, 0x03, 0x83, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x69, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, + 0x03, 0x79, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x5b, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x6b, + 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x5b, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x89, 0x46, 0xc0, + 0x47, 0x78, 0xea, 0x00, 0x03, 0x5b, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x79, 0x46, 0xc0, 0x47, 0x78, + 0xea, 0x00, 0x03, 0x55, 0x46, 0xc0, 0x47, 0x78, 0xea, 0x00, 0x03, 0x4f, 0xb5, 0x10, 0x1c, 0x03, 0x22, 0x20, + 0x1c, 0x0c, 0x48, 0x0d, 0x1c, 0x19, 0xf7, 0xff, 0xff, 0xec, 0x48, 0x0b, 0x21, 0x20, 0xf7, 0xff, 0xff, 0xd4, + 0x4a, 0x0a, 0x23, 0x01, 0x68, 0x11, 0x42, 0x19, 0xd1, 0xfc, 0x22, 0x20, 0x1c, 0x20, 0x49, 0x06, 0xf7, 0xff, + 0xff, 0xde, 0x1c, 0x20, 0x21, 0x20, 0xf7, 0xff, 0xff, 0xc6, 0x4b, 0x04, 0x68, 0x18, 0xbc, 0x10, 0xbc, 0x02, + 0x47, 0x08, 0x46, 0xc0, 0x0d, 0x00, 0x60, 0x00, 0x0d, 0x00, 0x60, 0x1c, 0x0d, 0x00, 0x60, 0x20, 0xb5, 0x70, + 0xb0, 0x88, 0x4b, 0x08, 0x1c, 0x06, 0x1c, 0x0d, 0x46, 0x6c, 0x93, 0x00, 0x60, 0x61, 0x92, 0x02, 0xf7, 0xff, + 0xff, 0xcb, 0x1c, 0x31, 0x1c, 0x2a, 0x46, 0x68, 0xf0, 0x00, 0xfe, 0xe8, 0xb0, 0x08, 0xbc, 0x70, 0xbc, 0x02, + 0x47, 0x08, 0xa8, 0x00, 0x00, 0x00, 0xb5, 0xf0, 0xb0, 0x8b, 0x0a, 0xcb, 0x1c, 0x07, 0x1c, 0x0d, 0x92, 0x01, + 0x93, 0x00, 0x26, 0x00, 0xac, 0x02, 0x4b, 0x0d, 0x1c, 0x38, 0x60, 0x23, 0x23, 0x00, 0x60, 0x63, 0x60, 0xa3, + 0x9b, 0x00, 0x1c, 0x29, 0x60, 0xe3, 0x9b, 0x01, 0x36, 0x01, 0x61, 0x23, 0xf7, 0xff, 0xff, 0xa9, 0x1c, 0x20, + 0x1c, 0x39, 0x1c, 0x2a, 0xf0, 0x00, 0xfe, 0xc6, 0x2e, 0x1f, 0xdc, 0x01, 0x28, 0x00, 0xd1, 0xe8, 0xb0, 0x0b, + 0xbc, 0xf0, 0xbc, 0x02, 0x47, 0x08, 0xd0, 0x00, 0x00, 0x00, 0xb5, 0xf0, 0xb0, 0x89, 0x90, 0x05, 0x91, 0x06, + 0x92, 0x07, 0x29, 0x00, 0xd0, 0x79, 0x23, 0x80, 0x0a, 0x52, 0x01, 0x1b, 0x92, 0x02, 0x26, 0x00, 0x93, 0x04, + 0xe0, 0x6f, 0x9a, 0x06, 0x1b, 0x94, 0x9a, 0x02, 0x02, 0x53, 0x9a, 0x07, 0x42, 0x9a, 0xd8, 0x01, 0x23, 0x00, + 0xe0, 0x02, 0x9a, 0x07, 0x1a, 0xd3, 0x00, 0x9b, 0x93, 0x01, 0x9b, 0x05, 0x22, 0x1f, 0x19, 0x9f, 0x42, 0x17, + 0xd1, 0x1c, 0x4b, 0x33, 0x42, 0x9f, 0xd9, 0x01, 0x23, 0x00, 0xe0, 0x02, 0x23, 0xc0, 0x04, 0x5b, 0x1b, 0xdb, + 0x4a, 0x30, 0x18, 0xb9, 0x4a, 0x30, 0x42, 0x91, 0xd8, 0x01, 0x4b, 0x30, 0x1b, 0xdb, 0x4a, 0x30, 0x42, 0x93, + 0xd8, 0x01, 0x23, 0x00, 0xe0, 0x02, 0x42, 0xa3, 0xd9, 0x00, 0x1c, 0x23, 0x4a, 0x2c, 0x43, 0x93, 0xd0, 0x02, + 0x9a, 0x01, 0x2a, 0x00, 0xd0, 0x2a, 0x9a, 0x01, 0x19, 0x13, 0x9a, 0x04, 0x42, 0x93, 0xd9, 0x01, 0x9b, 0x01, + 0x1a, 0xd4, 0x20, 0x80, 0x01, 0x00, 0x21, 0x20, 0xf7, 0xff, 0xff, 0x31, 0x90, 0x03, 0x28, 0x00, 0xd1, 0x02, + 0x25, 0x01, 0x42, 0x6d, 0xe0, 0x32, 0x21, 0x80, 0x98, 0x03, 0x01, 0x09, 0x9a, 0x02, 0xf7, 0xff, 0xff, 0x85, + 0x1c, 0x05, 0x28, 0x00, 0xd1, 0x0b, 0x9a, 0x03, 0x9b, 0x01, 0x1c, 0x38, 0x18, 0xd1, 0x1c, 0x22, 0xf7, 0xff, + 0xff, 0x33, 0x9a, 0x05, 0x1c, 0x21, 0x19, 0x90, 0xf7, 0xff, 0xff, 0x1a, 0x98, 0x03, 0xf7, 0xff, 0xff, 0x0b, + 0xe0, 0x0c, 0x1c, 0x1c, 0x4b, 0x14, 0x42, 0x9c, 0xd9, 0x01, 0x24, 0xff, 0x03, 0xe4, 0x9b, 0x05, 0x1c, 0x21, + 0x19, 0x98, 0x9a, 0x02, 0xf7, 0xff, 0xff, 0x66, 0x1c, 0x05, 0x2d, 0x00, 0xd1, 0x0a, 0x9a, 0x01, 0x9b, 0x02, + 0x19, 0x36, 0x18, 0xa4, 0x0a, 0xe4, 0x19, 0x1b, 0x93, 0x02, 0x9a, 0x06, 0x42, 0x96, 0xd3, 0x8c, 0x25, 0x00, + 0xb0, 0x09, 0x1c, 0x28, 0xbc, 0xf0, 0xbc, 0x02, 0x47, 0x08, 0x46, 0xc0, 0x01, 0x7f, 0xff, 0xff, 0xf0, 0x00, + 0x00, 0x00, 0x03, 0x61, 0x7f, 0xff, 0x13, 0x61, 0x80, 0x00, 0x00, 0x00, 0x07, 0xff, 0x00, 0x7f, 0x7f, 0xff, + 0xb5, 0x00, 0x4b, 0x07, 0xb0, 0x89, 0x93, 0x00, 0x46, 0x68, 0x23, 0x00, 0x21, 0x00, 0x22, 0x00, 0x93, 0x01, + 0x93, 0x02, 0xf0, 0x00, 0xfe, 0x1c, 0xb0, 0x09, 0xbc, 0x02, 0x47, 0x08, 0x46, 0xc0, 0xe3, 0x00, 0x00, 0x00, + 0xb5, 0xf8, 0x4e, 0x26, 0x27, 0x01, 0x1c, 0x04, 0x60, 0x37, 0x21, 0x20, 0xf7, 0xff, 0xfe, 0xec, 0x7b, 0x22, + 0x7b, 0x63, 0x06, 0x12, 0x04, 0x1b, 0x43, 0x13, 0x7b, 0xa2, 0x02, 0x12, 0x43, 0x13, 0x7b, 0xe2, 0x43, 0x13, + 0x2b, 0x08, 0xd1, 0x30, 0x7e, 0x22, 0x7e, 0x63, 0x06, 0x12, 0x04, 0x1b, 0x43, 0x13, 0x7e, 0xa2, 0x25, 0xc5, + 0x02, 0x12, 0x43, 0x13, 0x7e, 0xe2, 0x01, 0xad, 0x43, 0x13, 0x68, 0x18, 0x68, 0x59, 0xf7, 0xff, 0xfe, 0xd0, + 0x7e, 0x22, 0x7e, 0x63, 0x06, 0x12, 0x04, 0x1b, 0x43, 0x13, 0x7e, 0xa2, 0x1c, 0x28, 0x02, 0x12, 0x43, 0x13, + 0x7e, 0xe2, 0x21, 0x08, 0x43, 0x13, 0x68, 0x1b, 0x68, 0x5c, 0xf7, 0xff, 0xfe, 0xc0, 0x04, 0x24, 0x43, 0x27, + 0x4c, 0x0c, 0x60, 0x2f, 0x1c, 0x28, 0x21, 0x04, 0x60, 0x27, 0xf7, 0xff, 0xfe, 0x9b, 0x1c, 0x20, 0x21, 0x04, + 0xf7, 0xff, 0xfe, 0x97, 0x23, 0x00, 0x60, 0x33, 0x20, 0x00, 0xe0, 0x04, 0x1c, 0x20, 0xf0, 0x00, 0xfd, 0x3d, + 0x23, 0x00, 0x60, 0x33, 0xbc, 0xf8, 0xbc, 0x02, 0x47, 0x08, 0x46, 0xc0, 0x13, 0x77, 0xf7, 0x20, 0x00, 0x00, + 0x31, 0x88, 0xb5, 0x10, 0x4b, 0x09, 0x69, 0x1c, 0x2c, 0x00, 0xd0, 0x02, 0xf0, 0x00, 0xfb, 0xe3, 0xe0, 0x07, + 0x68, 0x5b, 0x2b, 0x00, 0xd0, 0x02, 0xf7, 0xff, 0xfe, 0xfb, 0xe0, 0x01, 0xf7, 0xff, 0xfe, 0xbc, 0xbc, 0x10, + 0xbc, 0x02, 0x47, 0x08, 0x46, 0xc0, 0x13, 0x77, 0xf7, 0x28, 0xb5, 0xf0, 0xb0, 0x85, 0x4b, 0x80, 0x90, 0x02, + 0x91, 0x03, 0x68, 0xdd, 0x68, 0x99, 0x18, 0x6d, 0x18, 0xad, 0x95, 0x00, 0x69, 0x1b, 0x2b, 0x00, 0xd0, 0x13, + 0x4b, 0x7c, 0x68, 0x1b, 0x2b, 0x00, 0xdd, 0x00, 0xe0, 0xe8, 0x4b, 0x7a, 0x68, 0x19, 0x29, 0x00, 0xd0, 0x02, + 0x20, 0x00, 0xf7, 0xff, 0xfe, 0x6f, 0x4b, 0x77, 0x22, 0x00, 0x60, 0x1a, 0x23, 0x01, 0x4a, 0x76, 0x42, 0x5b, + 0x60, 0x13, 0xe0, 0xd9, 0x4b, 0x74, 0x4a, 0x74, 0x68, 0x1b, 0x42, 0x93, 0xd1, 0x00, 0xe0, 0xa5, 0x2b, 0x00, + 0xda, 0x00, 0xe0, 0xa2, 0x4c, 0x6e, 0x68, 0x23, 0x2b, 0x00, 0xd1, 0x06, 0x21, 0x80, 0x20, 0x00, 0x01, 0x89, + 0x22, 0x20, 0xf7, 0xff, 0xfe, 0x44, 0x60, 0x20, 0x20, 0x80, 0x01, 0x00, 0x21, 0x20, 0xf7, 0xff, 0xfe, 0x32, + 0x1c, 0x04, 0x28, 0x00, 0xd1, 0x03, 0x23, 0x01, 0x4a, 0x65, 0x42, 0x5b, 0x60, 0x13, 0x4e, 0x64, 0x68, 0x33, + 0x2b, 0x00, 0xda, 0x02, 0x21, 0x00, 0x91, 0x01, 0xe0, 0x26, 0x1c, 0x35, 0x27, 0x00, 0x68, 0x32, 0x21, 0x80, + 0x1c, 0x13, 0x33, 0x10, 0x02, 0x5b, 0x02, 0x52, 0x1c, 0x20, 0x01, 0x09, 0x93, 0x01, 0xf7, 0xff, 0xff, 0x95, + 0x28, 0x00, 0xda, 0x03, 0x23, 0x01, 0x42, 0x5b, 0x60, 0x33, 0xe0, 0x13, 0x78, 0x23, 0x2b, 0x43, 0xd1, 0x08, + 0x78, 0x63, 0x2b, 0x49, 0xd1, 0x05, 0x78, 0xa3, 0x2b, 0x53, 0xd1, 0x02, 0x78, 0xe3, 0x2b, 0x4f, 0xd0, 0x07, + 0x68, 0x2b, 0x2b, 0x00, 0xd0, 0x01, 0x60, 0x2f, 0xe7, 0xdd, 0x23, 0x01, 0x42, 0x5b, 0x60, 0x2b, 0x4e, 0x4d, + 0x68, 0x33, 0x2b, 0x00, 0xdb, 0x54, 0x4b, 0x4a, 0x68, 0x1b, 0x2b, 0x00, 0xd0, 0x50, 0x79, 0x62, 0x79, 0xa3, + 0x02, 0x12, 0x04, 0x1b, 0x18, 0xd2, 0x79, 0x23, 0x48, 0x48, 0x18, 0xd2, 0x79, 0xe3, 0x21, 0x00, 0x06, 0x1b, + 0x18, 0xd2, 0x4b, 0x46, 0x08, 0x92, 0x60, 0x1a, 0x22, 0x80, 0x01, 0x12, 0xf0, 0x00, 0xfa, 0x50, 0x27, 0x08, + 0x25, 0x00, 0x4a, 0x42, 0x42, 0x17, 0xd1, 0x11, 0x4b, 0x42, 0x42, 0x9d, 0xdd, 0x0e, 0x68, 0x33, 0x12, 0xfa, + 0x18, 0xd2, 0x21, 0x80, 0x02, 0x52, 0x1c, 0x20, 0x01, 0x09, 0xf7, 0xff, 0xff, 0x4f, 0x28, 0x00, 0xda, 0x03, + 0x23, 0x01, 0x42, 0x5b, 0x60, 0x33, 0xe0, 0x20, 0x20, 0x07, 0x40, 0x28, 0xd1, 0x05, 0x4b, 0x31, 0x10, 0xea, + 0x68, 0x1b, 0x99, 0x01, 0x00, 0x92, 0x50, 0xd1, 0x4b, 0x33, 0x40, 0x3b, 0x5c, 0xe3, 0x2b, 0x00, 0xd0, 0x0c, + 0x4a, 0x2f, 0x21, 0x01, 0x10, 0xeb, 0x40, 0x81, 0x1c, 0x08, 0x5c, 0xd1, 0x43, 0x01, 0x54, 0xd1, 0x4b, 0x2c, + 0x9a, 0x01, 0x68, 0x1b, 0x18, 0xd2, 0x92, 0x01, 0x23, 0x80, 0x35, 0x01, 0x01, 0xdb, 0x37, 0x01, 0x42, 0x9d, + 0xd1, 0xc9, 0x4b, 0x23, 0x68, 0x1a, 0x2a, 0x00, 0xdb, 0x01, 0x4a, 0x22, 0x60, 0x1a, 0x2c, 0x00, 0xd0, 0x02, + 0x1c, 0x20, 0xf7, 0xff, 0xfd, 0x97, 0x4b, 0x1e, 0x4c, 0x1c, 0x68, 0x1a, 0x4b, 0x1d, 0x42, 0x9a, 0xd1, 0x1e, + 0x4b, 0x1e, 0x98, 0x00, 0x68, 0x1d, 0x1c, 0x29, 0xf0, 0x00, 0xfc, 0xf3, 0x68, 0x23, 0x08, 0xc1, 0x24, 0x07, + 0x00, 0x8a, 0x58, 0xd2, 0x40, 0x20, 0x23, 0x00, 0x4e, 0x16, 0x24, 0x01, 0xe0, 0x05, 0x5c, 0x77, 0x41, 0x1f, + 0x42, 0x27, 0xd0, 0x00, 0x19, 0x52, 0x33, 0x01, 0x42, 0x83, 0xd3, 0xf7, 0x9b, 0x00, 0x3d, 0x01, 0x40, 0x1d, + 0x19, 0x52, 0x98, 0x02, 0x99, 0x03, 0xe0, 0x0b, 0x68, 0x21, 0x29, 0x00, 0xd0, 0x02, 0x20, 0x00, 0xf7, 0xff, + 0xfd, 0x90, 0x4b, 0x07, 0x22, 0x00, 0x60, 0x1a, 0x98, 0x02, 0x99, 0x03, 0x9a, 0x00, 0xf7, 0xff, 0xfe, 0xea, + 0xb0, 0x05, 0xbc, 0xf0, 0xbc, 0x02, 0x47, 0x08, 0x13, 0x77, 0xf7, 0x28, 0x13, 0x77, 0xf7, 0xa0, 0x13, 0x77, + 0xf7, 0x24, 0x13, 0x77, 0xf6, 0x04, 0x7f, 0xff, 0xff, 0xff, 0x13, 0x77, 0xf7, 0xc0, 0x13, 0x77, 0xf7, 0x50, + 0x00, 0x00, 0x07, 0xff, 0x00, 0x00, 0x07, 0xf7, 0xb5, 0x70, 0x22, 0x00, 0x21, 0x20, 0x1c, 0x04, 0xf7, 0xff, + 0xfe, 0xe4, 0x69, 0xa2, 0x4b, 0x09, 0x1c, 0x05, 0x42, 0x9a, 0xd1, 0x09, 0x4b, 0x08, 0x21, 0x01, 0x68, 0x1a, + 0x70, 0x11, 0x68, 0x1b, 0x78, 0x5b, 0x2b, 0x00, 0xd1, 0x01, 0xf7, 0xff, 0xfd, 0x51, 0x1c, 0x28, 0xbc, 0x70, + 0xbc, 0x02, 0x47, 0x08, 0x46, 0xc0, 0x5d, 0x1c, 0x9e, 0xa3, 0x13, 0x77, 0xe0, 0x08, 0xb5, 0xf0, 0xb0, 0x83, + 0x92, 0x01, 0x4a, 0xb9, 0x1c, 0x05, 0x68, 0x13, 0x1c, 0x0c, 0x78, 0x06, 0x2b, 0x00, 0xd0, 0x0e, 0x4b, 0xb6, + 0x4f, 0xb7, 0x68, 0x1a, 0x68, 0x38, 0x21, 0x00, 0xf0, 0x00, 0xf9, 0x95, 0x4a, 0xb3, 0x68, 0x38, 0x68, 0x11, + 0xf7, 0xff, 0xfd, 0x26, 0x4a, 0xaf, 0x23, 0x00, 0x60, 0x13, 0x2e, 0xe0, 0xd0, 0x55, 0x4f, 0xb0, 0x23, 0x00, + 0x62, 0x3b, 0x2e, 0xd0, 0xd1, 0x00, 0xe1, 0x6e, 0x2e, 0xd0, 0xd8, 0x26, 0x2e, 0x79, 0xd0, 0x62, 0x2e, 0x79, + 0xd8, 0x0f, 0x2e, 0x15, 0xd1, 0x00, 0xe0, 0xb3, 0x2e, 0x15, 0xd8, 0x03, 0x2e, 0x13, 0xd2, 0x00, 0xe1, 0x6a, + 0xe0, 0x8d, 0x2e, 0x70, 0xd1, 0x00, 0xe1, 0x00, 0x2e, 0x71, 0xd0, 0x00, 0xe1, 0x63, 0xe0, 0xe6, 0x2e, 0xa4, + 0xd1, 0x00, 0xe0, 0xbf, 0x2e, 0xa4, 0xd8, 0x06, 0x2e, 0x8a, 0xd1, 0x00, 0xe1, 0x18, 0x2e, 0x8d, 0xd0, 0x00, + 0xe1, 0x57, 0xe1, 0x4c, 0x2e, 0xa8, 0xd1, 0x00, 0xe1, 0x49, 0x2e, 0xab, 0xd0, 0x00, 0xe1, 0x50, 0xe0, 0x36, + 0x2e, 0xf1, 0xd0, 0x50, 0x2e, 0xf1, 0xd8, 0x10, 0x2e, 0xe0, 0xd0, 0x20, 0x2e, 0xe0, 0xd8, 0x06, 0x2e, 0xd9, + 0xd1, 0x00, 0xe0, 0x94, 0x2e, 0xda, 0xd0, 0x00, 0xe1, 0x41, 0xe0, 0xad, 0x2e, 0xe4, 0xd0, 0x31, 0x2e, 0xf0, + 0xd0, 0x00, 0xe1, 0x3b, 0xe0, 0x3a, 0x2e, 0xf4, 0xd0, 0x47, 0x2e, 0xf4, 0xd8, 0x05, 0x2e, 0xf2, 0xd0, 0x3e, + 0x2e, 0xf3, 0xd0, 0x00, 0xe1, 0x31, 0xe0, 0x3d, 0x2e, 0xf6, 0xd0, 0x4e, 0x2e, 0xf6, 0xd3, 0x4a, 0x2e, 0xff, + 0xd0, 0x00, 0xe1, 0x29, 0xe0, 0x71, 0x4b, 0x85, 0x6a, 0x1a, 0x2a, 0x00, 0xd1, 0x03, 0x69, 0x1b, 0x2b, 0x00, + 0xd1, 0x00, 0xe1, 0x20, 0x1c, 0x20, 0x21, 0x00, 0x9a, 0x01, 0xf0, 0x00, 0xf9, 0x28, 0x4b, 0x7e, 0x6a, 0x1b, + 0xe0, 0x1c, 0x68, 0x7b, 0x2b, 0x00, 0xd0, 0x00, 0xe1, 0x1a, 0x4b, 0x7b, 0x69, 0x1b, 0xe0, 0x00, 0x69, 0x3b, + 0x2b, 0x00, 0xd0, 0x00, 0xe1, 0x13, 0xe1, 0x0c, 0x68, 0x7b, 0x2b, 0x00, 0xd1, 0x03, 0x69, 0x3b, 0x2b, 0x00, + 0xd1, 0x00, 0xe1, 0x05, 0x1c, 0x20, 0x21, 0x00, 0x9a, 0x01, 0xf0, 0x00, 0xf9, 0x0d, 0xe0, 0x04, 0x68, 0x6b, + 0x60, 0xbb, 0xe1, 0x02, 0x68, 0xbb, 0x60, 0x23, 0x99, 0x01, 0x1c, 0x20, 0xf7, 0xff, 0xfc, 0x99, 0xe0, 0xfb, + 0x68, 0x6b, 0x60, 0x3b, 0xe0, 0xf8, 0x68, 0x3b, 0xe7, 0xf4, 0x68, 0x6b, 0x61, 0x3b, 0x2b, 0x00, 0xd0, 0x06, + 0x1c, 0x38, 0x1c, 0x29, 0x30, 0x18, 0x31, 0x08, 0x22, 0x06, 0xf7, 0xff, 0xfc, 0x9c, 0x69, 0x6a, 0x4b, 0x63, + 0x61, 0x5a, 0xe0, 0xe7, 0x69, 0x3b, 0xe7, 0xe3, 0x79, 0x2b, 0x37, 0x05, 0x77, 0xfb, 0xe0, 0xe1, 0x2c, 0x00, + 0xd1, 0x00, 0xe0, 0xde, 0x2e, 0x13, 0xd1, 0x0b, 0x69, 0x3b, 0x2b, 0x00, 0xd0, 0x0f, 0x4b, 0x5b, 0x68, 0x1b, + 0x2b, 0x00, 0xd0, 0x07, 0xf0, 0x00, 0xf9, 0xb4, 0x28, 0x00, 0xd0, 0x0b, 0xe0, 0x0c, 0x69, 0x3b, 0x2b, 0x00, + 0xd0, 0x03, 0x4b, 0x56, 0x68, 0x1b, 0x2b, 0x00, 0xda, 0x05, 0x4b, 0x55, 0x68, 0x1b, 0x07, 0xda, 0xd5, 0x01, + 0x23, 0x00, 0xe7, 0xc1, 0x23, 0x02, 0xe7, 0xbf, 0x4b, 0x51, 0x22, 0x01, 0x68, 0x1b, 0x43, 0x93, 0xe7, 0xba, + 0x68, 0x6b, 0x48, 0x4f, 0x1c, 0x21, 0x40, 0x18, 0xf7, 0xff, 0xfc, 0x73, 0xe0, 0xb6, 0x68, 0x7b, 0x2b, 0x00, + 0xd1, 0x03, 0x69, 0x3b, 0x2b, 0x00, 0xd1, 0x00, 0xe0, 0xa8, 0x68, 0x6a, 0x68, 0xab, 0x07, 0x92, 0x43, 0x1a, + 0x4b, 0x48, 0x40, 0x1a, 0x4b, 0x42, 0x60, 0xda, 0xe0, 0xa5, 0x68, 0x7b, 0x2b, 0x00, 0xd1, 0x03, 0x69, 0x3b, + 0x2b, 0x00, 0xd1, 0x00, 0xe0, 0x98, 0x4a, 0x43, 0x4b, 0x3c, 0x20, 0xa0, 0x62, 0x1a, 0x02, 0x00, 0xe0, 0x99, + 0x4e, 0x41, 0x21, 0x40, 0x1c, 0x30, 0xf7, 0xff, 0xfc, 0x4c, 0x1c, 0x33, 0x33, 0x40, 0xe0, 0x03, 0x36, 0x01, + 0x42, 0x9e, 0xd1, 0x00, 0xe0, 0x86, 0x78, 0x32, 0x2a, 0x00, 0xd0, 0xf8, 0x49, 0x39, 0x1c, 0x20, 0x22, 0x40, + 0xf7, 0xff, 0xfc, 0x35, 0x1c, 0x20, 0x21, 0x40, 0xe7, 0x82, 0x1d, 0xbb, 0x22, 0x01, 0x77, 0xda, 0x68, 0x3b, + 0x2b, 0x00, 0xd1, 0x05, 0x1c, 0x28, 0x1c, 0x21, 0x9a, 0x01, 0xf0, 0x00, 0xfb, 0x51, 0xe0, 0x04, 0x68, 0x69, + 0x68, 0xaa, 0x1c, 0x20, 0xf7, 0xff, 0xfd, 0x9d, 0x4b, 0x26, 0x22, 0x00, 0x33, 0x06, 0x77, 0xda, 0xe0, 0x6c, + 0x69, 0x3b, 0x2b, 0x00, 0xd1, 0x06, 0x1c, 0x28, 0x1c, 0x21, 0x9a, 0x01, 0xf0, 0x00, 0xfb, 0x3e, 0x28, 0x00, + 0xd1, 0x0e, 0x4b, 0x1e, 0x68, 0xda, 0x2a, 0x00, 0xd1, 0x09, 0x68, 0x9a, 0x2a, 0x00, 0xd1, 0x06, 0x69, 0x1a, + 0x2a, 0x00, 0xd1, 0x03, 0x69, 0xa0, 0x49, 0x21, 0x42, 0x88, 0xd0, 0x09, 0x20, 0x00, 0x1e, 0x43, 0x41, 0x98, + 0x4b, 0x16, 0x99, 0x01, 0x60, 0x58, 0x1c, 0x20, 0xf7, 0xff, 0xfe, 0x8d, 0xe0, 0x4a, 0x60, 0x5a, 0xe0, 0x47, + 0x1d, 0x7b, 0x7f, 0xdb, 0x2b, 0x00, 0xd1, 0x43, 0x1d, 0xba, 0x77, 0xd3, 0x60, 0x3b, 0x60, 0x7b, 0x60, 0xbb, + 0x60, 0xfb, 0x62, 0x3b, 0x69, 0x3b, 0x2b, 0x00, 0xd1, 0x04, 0x69, 0x7a, 0x4b, 0x13, 0x3a, 0x01, 0x60, 0x1a, + 0xe0, 0x2e, 0xf7, 0xff, 0xfc, 0xe5, 0x69, 0x38, 0x1c, 0x39, 0x31, 0x18, 0x69, 0x7a, 0x38, 0x01, 0xf0, 0x00, + 0xf8, 0x62, 0xe0, 0x2b, 0x46, 0xc0, 0x13, 0x77, 0xf6, 0x00, 0x13, 0x77, 0xe0, 0x48, 0x13, 0x77, 0xe0, 0x44, + 0x13, 0x77, 0xf7, 0x28, 0x13, 0x77, 0xf7, 0xa4, 0x13, 0x77, 0xf6, 0x08, 0x0d, 0x00, 0x60, 0x04, 0x7f, 0xff, + 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x05, 0x31, 0x00, 0x13, 0x77, 0xef, 0xe0, 0x5d, 0x1c, 0x9e, 0xa3, + 0x13, 0x77, 0xf6, 0x04, 0x68, 0xaa, 0x68, 0x69, 0x2e, 0xd0, 0xd1, 0x01, 0x02, 0x52, 0x02, 0xc9, 0x1c, 0x20, + 0xf7, 0xff, 0xfd, 0x33, 0xe0, 0x06, 0x1c, 0x28, 0x1c, 0x21, 0x9a, 0x01, 0xf0, 0x00, 0xfa, 0xdb, 0xe0, 0x00, + 0x20, 0x00, 0xb0, 0x03, 0xbc, 0xf0, 0xbc, 0x02, 0x47, 0x08, 0x46, 0xc0, 0xb5, 0xf0, 0x2a, 0x00, 0xd0, 0x29, + 0x24, 0x03, 0x1c, 0x03, 0x40, 0x23, 0x27, 0x04, 0x1a, 0xfb, 0x06, 0x0e, 0x40, 0x23, 0x0e, 0x36, 0x1c, 0x05, + 0x42, 0x93, 0xd9, 0x01, 0x1c, 0x13, 0xe0, 0x01, 0x2b, 0x00, 0xd0, 0x05, 0x1c, 0x1c, 0xe0, 0x01, 0x70, 0x2e, + 0x35, 0x01, 0x3c, 0x01, 0xd2, 0xfb, 0x04, 0x0c, 0x06, 0x0d, 0x43, 0x25, 0x43, 0x0d, 0x02, 0x0c, 0x1c, 0x29, + 0x43, 0x21, 0x18, 0xc4, 0xe0, 0x01, 0xc4, 0x02, 0x1c, 0x2b, 0x1d, 0x1d, 0x42, 0x95, 0xd9, 0xfa, 0x18, 0xc0, + 0xe0, 0x01, 0x33, 0x01, 0x70, 0x06, 0x30, 0x01, 0x42, 0x93, 0xd3, 0xfa, 0xbc, 0xf0, 0xbc, 0x01, 0x47, 0x00, + 0xb5, 0xf0, 0xb0, 0x85, 0x1c, 0x05, 0x1c, 0x0e, 0x28, 0x01, 0xd9, 0x02, 0x25, 0x01, 0x42, 0x6d, 0xe0, 0x89, + 0x4b, 0x47, 0x92, 0x03, 0x68, 0x1a, 0x2a, 0x00, 0xd1, 0x02, 0x4a, 0x45, 0x60, 0x1a, 0xe0, 0x05, 0x4b, 0x45, + 0x68, 0x18, 0x28, 0x00, 0xdb, 0x01, 0xf7, 0xff, 0xfb, 0x47, 0x4a, 0x42, 0x23, 0x01, 0x42, 0x5b, 0x60, 0x13, + 0x4a, 0x41, 0x4b, 0x41, 0x21, 0x00, 0x60, 0x11, 0x60, 0x19, 0x78, 0x31, 0x29, 0x5f, 0xd1, 0x2b, 0x78, 0x71, + 0x29, 0x44, 0xd1, 0x28, 0x78, 0xb1, 0x29, 0x45, 0xd1, 0x1e, 0x78, 0xf2, 0x2a, 0x56, 0xd1, 0x22, 0x22, 0x01, + 0x60, 0x1a, 0x79, 0x32, 0x2a, 0x57, 0xd1, 0x01, 0x22, 0x02, 0x60, 0x1a, 0x4c, 0x37, 0x21, 0x80, 0x1c, 0x20, + 0x00, 0x49, 0xf7, 0xff, 0xfb, 0x49, 0x1c, 0x20, 0x21, 0x00, 0xf7, 0xff, 0xfb, 0x39, 0x4b, 0x2f, 0x1c, 0x05, + 0x60, 0x18, 0x28, 0x00, 0xdb, 0x01, 0x25, 0x00, 0xe0, 0x4e, 0x4b, 0x2d, 0x22, 0x00, 0x60, 0x1a, 0xe0, 0x4a, + 0x29, 0x56, 0xd1, 0x04, 0x78, 0xf3, 0x2b, 0x44, 0xd1, 0x01, 0x23, 0x01, 0x60, 0x13, 0x4b, 0x2a, 0x00, 0xaa, + 0x58, 0xd0, 0x21, 0x01, 0xf7, 0xff, 0xfb, 0x21, 0x4c, 0x23, 0x60, 0x20, 0x28, 0x00, 0xda, 0x06, 0x2d, 0x00, + 0xd1, 0x04, 0x48, 0x25, 0x21, 0x01, 0xf7, 0xff, 0xfb, 0x17, 0x60, 0x20, 0x4f, 0x1d, 0x68, 0x3d, 0x2d, 0x00, + 0xdb, 0x2e, 0x4c, 0x19, 0x1c, 0x31, 0x68, 0x20, 0x22, 0x06, 0x30, 0x20, 0xf7, 0xff, 0xfb, 0x0f, 0x68, 0x20, + 0x22, 0x04, 0xa9, 0x03, 0x30, 0x3c, 0xf7, 0xff, 0xfb, 0x09, 0x68, 0x20, 0x26, 0x04, 0x1c, 0x03, 0x33, 0x20, + 0x60, 0x03, 0x23, 0x06, 0x60, 0x43, 0x1c, 0x03, 0x33, 0x3c, 0x60, 0x83, 0x60, 0xc6, 0x21, 0x40, 0xf7, 0xff, + 0xfa, 0xe7, 0x68, 0x23, 0x68, 0x38, 0x49, 0x13, 0x93, 0x00, 0x22, 0x02, 0x23, 0x00, 0xf7, 0xff, 0xfa, 0xe3, + 0x1c, 0x05, 0x68, 0x20, 0x21, 0x40, 0x1c, 0x03, 0x33, 0x20, 0x60, 0x03, 0x33, 0x1c, 0x60, 0x46, 0x60, 0x83, + 0x60, 0xc6, 0xf7, 0xff, 0xfa, 0xd3, 0xb0, 0x05, 0x1c, 0x28, 0xbc, 0xf0, 0xbc, 0x02, 0x47, 0x08, 0x13, 0x77, + 0xf7, 0x54, 0x13, 0x77, 0xf7, 0x60, 0x13, 0x77, 0xf6, 0x08, 0x13, 0x77, 0xf7, 0xa4, 0x13, 0x77, 0xf7, 0xa0, + 0x13, 0x77, 0xf6, 0x20, 0x13, 0x77, 0xf0, 0x48, 0x13, 0x77, 0xf0, 0x20, 0x57, 0x46, 0x53, 0x01, 0xb5, 0x00, + 0x4b, 0x0b, 0xb0, 0x83, 0x68, 0x1b, 0x2b, 0x00, 0xd0, 0x0c, 0x4b, 0x09, 0x68, 0x18, 0x28, 0x00, 0xdb, 0x08, + 0x4b, 0x08, 0x49, 0x09, 0x68, 0x1b, 0x22, 0x00, 0x93, 0x00, 0x23, 0x00, 0xf7, 0xff, 0xfa, 0xae, 0xe0, 0x00, + 0x20, 0x01, 0xb0, 0x03, 0xbc, 0x02, 0x47, 0x08, 0x46, 0xc0, 0x13, 0x77, 0xf7, 0xa4, 0x13, 0x77, 0xf6, 0x08, + 0x13, 0x77, 0xf7, 0x54, 0x57, 0x46, 0x53, 0x04, 0xb5, 0xf0, 0x4d, 0x94, 0xb0, 0x87, 0x68, 0x2b, 0x90, 0x03, + 0x91, 0x02, 0x92, 0x04, 0x2b, 0x00, 0xda, 0x00, 0xe0, 0xf1, 0x4b, 0x90, 0x68, 0x1b, 0x2b, 0x00, 0xd1, 0x00, + 0xe0, 0xef, 0x3b, 0x01, 0x2b, 0x01, 0xd9, 0x00, 0xe0, 0xaa, 0x4c, 0x8d, 0x68, 0x23, 0x2b, 0x00, 0xd1, 0x06, + 0x21, 0x80, 0x20, 0x00, 0x01, 0x89, 0x22, 0x20, 0xf7, 0xff, 0xfa, 0x87, 0x60, 0x20, 0x20, 0x80, 0x01, 0x00, + 0x21, 0x20, 0xf7, 0xff, 0xfa, 0x75, 0x1c, 0x04, 0x28, 0x00, 0xd1, 0x03, 0x23, 0x01, 0x4a, 0x82, 0x42, 0x5b, + 0x60, 0x13, 0x4b, 0x80, 0x68, 0x1b, 0x2b, 0x00, 0xda, 0x01, 0x25, 0x00, 0xe0, 0x21, 0x4d, 0x7c, 0x21, 0x00, + 0x68, 0x28, 0x22, 0x00, 0xf7, 0xff, 0xfa, 0x56, 0x28, 0x00, 0xdb, 0x13, 0x22, 0x80, 0x68, 0x28, 0x1c, 0x21, + 0x01, 0x12, 0xf7, 0xff, 0xfa, 0x4a, 0x28, 0x00, 0xdb, 0x0b, 0x78, 0x23, 0x2b, 0x43, 0xd1, 0x08, 0x78, 0x63, + 0x2b, 0x49, 0xd1, 0x05, 0x78, 0xa3, 0x2b, 0x53, 0xd1, 0x02, 0x78, 0xe3, 0x2b, 0x4f, 0xd0, 0x03, 0x23, 0x01, + 0x4a, 0x6f, 0x42, 0x5b, 0x60, 0x13, 0x25, 0x80, 0x01, 0xad, 0x4a, 0x6c, 0x68, 0x13, 0x2b, 0x00, 0xdb, 0x62, + 0x4b, 0x6b, 0x68, 0x1b, 0x2b, 0x00, 0xd0, 0x5e, 0x79, 0x62, 0x79, 0xa3, 0x02, 0x12, 0x04, 0x1b, 0x18, 0xd2, + 0x79, 0x23, 0x48, 0x67, 0x18, 0xd2, 0x79, 0xe3, 0x21, 0x00, 0x06, 0x1b, 0x18, 0xd2, 0x4b, 0x65, 0x08, 0x92, + 0x60, 0x1a, 0x22, 0x80, 0x01, 0x12, 0xf7, 0xff, 0xfe, 0x99, 0x27, 0x08, 0x26, 0x00, 0x4b, 0x62, 0x42, 0x1f, + 0xd1, 0x21, 0x4a, 0x61, 0x42, 0x96, 0xdd, 0x1e, 0x4b, 0x5b, 0x68, 0x1a, 0x4b, 0x59, 0x2a, 0x02, 0xd1, 0x03, + 0x12, 0xf9, 0x68, 0x18, 0x02, 0x49, 0xe0, 0x02, 0x49, 0x5c, 0x68, 0x18, 0x40, 0x39, 0x22, 0x00, 0xf7, 0xff, + 0xfa, 0x08, 0x28, 0x00, 0xdb, 0x08, 0x4b, 0x51, 0x22, 0x80, 0x68, 0x18, 0x1c, 0x21, 0x01, 0x12, 0xf7, 0xff, + 0xf9, 0xfb, 0x28, 0x00, 0xda, 0x04, 0x23, 0x01, 0x4a, 0x4d, 0x42, 0x5b, 0x60, 0x13, 0xe0, 0x1d, 0x20, 0x07, + 0x40, 0x30, 0xd1, 0x04, 0x4b, 0x4b, 0x10, 0xf2, 0x68, 0x1b, 0x00, 0x92, 0x50, 0xd5, 0x4b, 0x4b, 0x40, 0x3b, + 0x5c, 0xe3, 0x2b, 0x00, 0xd0, 0x0a, 0x4a, 0x47, 0x21, 0x01, 0x10, 0xf3, 0x40, 0x81, 0x1c, 0x08, 0x5c, 0xd1, + 0x43, 0x01, 0x54, 0xd1, 0x4b, 0x44, 0x68, 0x1b, 0x18, 0xed, 0x23, 0x80, 0x36, 0x01, 0x01, 0xdb, 0x37, 0x01, + 0x42, 0x9e, 0xd1, 0xbc, 0x4b, 0x3c, 0x68, 0x1a, 0x2a, 0x00, 0xdb, 0x02, 0x21, 0x04, 0x43, 0x0a, 0x60, 0x1a, + 0x2c, 0x00, 0xd0, 0x02, 0x1c, 0x20, 0xf7, 0xff, 0xf9, 0xd2, 0x4b, 0x36, 0x4c, 0x37, 0x68, 0x1b, 0x93, 0x05, + 0x2b, 0x03, 0xdd, 0x2e, 0x4b, 0x36, 0x98, 0x04, 0x68, 0x1d, 0x1c, 0x29, 0xf0, 0x00, 0xf9, 0x2e, 0x68, 0x23, + 0x08, 0xc2, 0x24, 0x07, 0x00, 0x91, 0x58, 0xc9, 0x40, 0x20, 0x23, 0x00, 0x4e, 0x2f, 0x24, 0x01, 0xe0, 0x05, + 0x5c, 0xb7, 0x41, 0x1f, 0x42, 0x27, 0xd0, 0x00, 0x19, 0x49, 0x33, 0x01, 0x42, 0x83, 0xd3, 0xf7, 0x9a, 0x04, + 0x3d, 0x01, 0x40, 0x15, 0x9a, 0x05, 0x19, 0x49, 0x4b, 0x24, 0x07, 0x92, 0xd5, 0x01, 0x68, 0x18, 0xe0, 0x01, + 0x68, 0x18, 0x00, 0x89, 0x22, 0x00, 0xf7, 0xff, 0xf9, 0xa1, 0x4b, 0x1f, 0x99, 0x03, 0x68, 0x18, 0x9a, 0x02, + 0xf7, 0xff, 0xf9, 0x97, 0x24, 0x00, 0xe0, 0x31, 0x68, 0x21, 0x29, 0x00, 0xd0, 0x02, 0x20, 0x00, 0xf7, 0xff, + 0xf9, 0xbb, 0x4b, 0x1a, 0x22, 0x00, 0x60, 0x1a, 0x24, 0x01, 0x42, 0x64, 0xe0, 0x25, 0x4c, 0x1d, 0x9b, 0x04, + 0x68, 0x20, 0x21, 0x40, 0x62, 0x03, 0x9a, 0x02, 0x63, 0xc2, 0x9b, 0x03, 0x61, 0x82, 0x61, 0x03, 0xf7, 0xff, + 0xf9, 0x91, 0x98, 0x03, 0x99, 0x02, 0xf7, 0xff, 0xf9, 0x8d, 0x4b, 0x16, 0x68, 0x1b, 0x2b, 0x00, 0xd0, 0x04, + 0x68, 0x23, 0x68, 0x28, 0x49, 0x14, 0x93, 0x00, 0xe0, 0x03, 0x68, 0x23, 0x49, 0x13, 0x68, 0x28, 0x93, 0x00, + 0x22, 0x02, 0x23, 0x01, 0xf7, 0xff, 0xf9, 0x80, 0x99, 0x02, 0x1c, 0x04, 0x98, 0x03, 0xf7, 0xff, 0xf9, 0x93, + 0xb0, 0x07, 0x1c, 0x20, 0xbc, 0xf0, 0xbc, 0x02, 0x47, 0x08, 0x13, 0x77, 0xf6, 0x08, 0x13, 0x77, 0xf7, 0xa0, + 0x13, 0x77, 0xf7, 0x24, 0x13, 0x77, 0xf7, 0xc0, 0x13, 0x77, 0xf7, 0x50, 0x00, 0x00, 0x07, 0xff, 0x00, 0x00, + 0x07, 0xf7, 0xff, 0xff, 0xf8, 0x00, 0x13, 0x77, 0xf7, 0x54, 0x13, 0x77, 0xf7, 0xa4, 0x57, 0x46, 0x53, 0x03, + 0x57, 0x46, 0x53, 0x02, 0xb4, 0x7c, 0xb5, 0x00, 0xf7, 0xff, 0xfa, 0x7e, 0xbc, 0x02, 0xbc, 0x7c, 0x47, 0x08, + 0xb5, 0x70, 0xb0, 0x88, 0x68, 0x85, 0x1c, 0x01, 0x4b, 0x01, 0x47, 0x18, 0x00, 0x00, 0x20, 0x10, 0x00, 0xd5, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe6, 0x00, 0x08, 0x10, 0xe1, 0x2f, + 0xff, 0x1e, 0xe6, 0x00, 0x07, 0xf0, 0xe1, 0x2f, 0xff, 0x1e, 0xe6, 0x00, 0x03, 0x30, 0xe1, 0x2f, 0xff, 0x1e, + 0xe6, 0x00, 0x03, 0x50, 0xe1, 0x2f, 0xff, 0x1e, 0xe6, 0x00, 0x03, 0x90, 0xe1, 0x2f, 0xff, 0x1e, 0xe6, 0x00, + 0x03, 0xb0, 0xe1, 0x2f, 0xff, 0x1e, 0xe6, 0x00, 0x03, 0xd0, 0xe1, 0x2f, 0xff, 0x1e, 0xe6, 0x00, 0x03, 0xf0, + 0xe1, 0x2f, 0xff, 0x1e, 0xe6, 0x00, 0x04, 0x10, 0xe1, 0x2f, 0xff, 0x1e, 0xe6, 0x00, 0x04, 0x50, 0xe1, 0x2f, + 0xff, 0x1e, 0xef, 0x00, 0x00, 0xcc, 0xe1, 0x2f, 0xff, 0x1e, 0x46, 0x72, 0x1c, 0x01, 0x20, 0x04, 0xdf, 0xab, + 0x47, 0x10, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0xe9, 0x2d, + 0x40, 0x80, 0xe5, 0x9f, 0x70, 0x9c, 0xe5, 0x97, 0x70, 0x00, 0xeb, 0x00, 0x00, 0x1f, 0xe8, 0xbd, 0x40, 0x80, + 0xe1, 0x2f, 0xff, 0x1e, 0xe9, 0x2d, 0x40, 0x80, 0xe5, 0x9f, 0x70, 0x88, 0xe5, 0x97, 0x70, 0x00, 0xeb, 0x00, + 0x00, 0x19, 0xe8, 0xbd, 0x40, 0x80, 0xe1, 0x2f, 0xff, 0x1e, 0xe9, 0x2d, 0x40, 0x80, 0xe5, 0x9f, 0x70, 0x74, + 0xe5, 0x97, 0x70, 0x00, 0xeb, 0x00, 0x00, 0x13, 0xe8, 0xbd, 0x40, 0x80, 0xe1, 0x2f, 0xff, 0x1e, 0xe9, 0x2d, + 0x40, 0x80, 0xe5, 0x9f, 0x70, 0x60, 0xe5, 0x97, 0x70, 0x00, 0xeb, 0x00, 0x00, 0x0d, 0xe8, 0xbd, 0x40, 0x80, + 0xe1, 0x2f, 0xff, 0x1e, 0xe9, 0x2d, 0x40, 0x80, 0xe5, 0x9f, 0x70, 0x4c, 0xe5, 0x97, 0x70, 0x00, 0xeb, 0x00, + 0x00, 0x07, 0xe8, 0xbd, 0x40, 0x80, 0xe1, 0x2f, 0xff, 0x1e, 0xe9, 0x2d, 0x40, 0x80, 0xe5, 0x9f, 0x70, 0x38, + 0xe5, 0x97, 0x70, 0x00, 0xeb, 0x00, 0x00, 0x01, 0xe8, 0xbd, 0x40, 0x80, 0xe1, 0x2f, 0xff, 0x1e, 0xe1, 0x2f, + 0xff, 0x17, 0xb5, 0xf0, 0x46, 0x5f, 0x46, 0x56, 0x46, 0x4d, 0x46, 0x44, 0xb4, 0xf0, 0x4b, 0x07, 0x68, 0x1b, + 0x47, 0x18, 0x00, 0x00, 0x13, 0x77, 0xe0, 0x10, 0x13, 0x77, 0xe0, 0x14, 0x13, 0x77, 0xe0, 0x18, 0x13, 0x77, + 0xe0, 0x1c, 0x13, 0x77, 0xe0, 0x20, 0x13, 0x77, 0xe0, 0x24, 0x13, 0x77, 0xe0, 0x0c, 0x46, 0xc0, 0x46, 0xc0, + 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x29, 0x00, 0xd0, 0x34, 0x23, 0x01, 0x22, 0x00, 0xb4, 0x10, + 0x42, 0x88, 0xd3, 0x2c, 0x24, 0x01, 0x07, 0x24, 0x42, 0xa1, 0xd2, 0x04, 0x42, 0x81, 0xd2, 0x02, 0x01, 0x09, + 0x01, 0x1b, 0xe7, 0xf8, 0x00, 0xe4, 0x42, 0xa1, 0xd2, 0x04, 0x42, 0x81, 0xd2, 0x02, 0x00, 0x49, 0x00, 0x5b, + 0xe7, 0xf8, 0x42, 0x88, 0xd3, 0x01, 0x1a, 0x40, 0x43, 0x1a, 0x08, 0x4c, 0x42, 0xa0, 0xd3, 0x02, 0x1b, 0x00, + 0x08, 0x5c, 0x43, 0x22, 0x08, 0x8c, 0x42, 0xa0, 0xd3, 0x02, 0x1b, 0x00, 0x08, 0x9c, 0x43, 0x22, 0x08, 0xcc, + 0x42, 0xa0, 0xd3, 0x02, 0x1b, 0x00, 0x08, 0xdc, 0x43, 0x22, 0x28, 0x00, 0xd0, 0x03, 0x09, 0x1b, 0xd0, 0x01, + 0x09, 0x09, 0xe7, 0xe3, 0x1c, 0x10, 0xbc, 0x10, 0x47, 0x70, 0xb5, 0x02, 0xf0, 0x00, 0xf8, 0x0c, 0x20, 0x00, + 0xbc, 0x06, 0x47, 0x10, 0x46, 0xc0, 0xb5, 0x03, 0xf7, 0xff, 0xff, 0xbf, 0xbc, 0x0e, 0x43, 0x42, 0x1a, 0x89, + 0x47, 0x18, 0x46, 0xc0, 0x47, 0x70, 0x46, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2f, 0x64, + 0x65, 0x76, 0x2f, 0x75, 0x73, 0x62, 0x32, 0x00, 0x2f, 0x64, 0x65, 0x76, 0x2f, 0x73, 0x64, 0x69, 0x6f, 0x2f, + 0x73, 0x64, 0x68, 0x63, 0x00, 0x2f, 0x64, 0x65, 0x76, 0x2f, 0x75, 0x73, 0x62, 0x2f, 0x65, 0x68, 0x63, 0x00, + 0x00, 0x00, 0x13, 0x77, 0xf0, 0x20, 0x13, 0x77, 0xf0, 0x2a, 0x13, 0x77, 0xf0, 0x39, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x66, 0x69, 0x6c, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; diff --git a/source/mload/fatffs_util.c b/source/mload/fatffs_util.c index 6ea44c64..001d1b73 100644 --- a/source/mload/fatffs_util.c +++ b/source/mload/fatffs_util.c @@ -1,24 +1,23 @@ /* - From Custom IOS Module (FAT) + From Custom IOS Module (FAT) - Copyright (C) 2009 Waninkoko. - Copyright (C) 2010 Hermes. + Copyright (C) 2009 Waninkoko. + Copyright (C) 2010 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 - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "fatffs_util.h" @@ -31,50 +30,45 @@ extern u32 nand_mode; -s32 FAT_DeleteDir( const char *dirpath ) +s32 FAT_DeleteDir(const char *dirpath) { DIR_ITER *dir; s32 ret; /* Open directory */ - dir = diropen( dirpath ); - if ( !dir ) - return -1; + dir = diropen(dirpath); + if (!dir) return -1; /* Read entries */ - for ( ;; ) + for (;;) { - char filename[256], newpath[256]; + char filename[256], newpath[256]; struct stat filestat; /* Read entry */ - if ( dirnext( dir, filename, &filestat ) ) - break; + if (dirnext(dir, filename, &filestat)) break; /* Non valid entry */ - if ( filename[0] == '.' ) - continue; + if (filename[0] == '.') continue; /* Generate entry path */ - strcpy( newpath, dirpath ); - strcat( newpath, "/" ); - strcat( newpath, filename ); + strcpy(newpath, dirpath); + strcat(newpath, "/"); + strcat(newpath, filename); /* Delete directory contents */ - if ( filestat.st_mode & S_IFDIR ) - FAT_DeleteDir( newpath ); + if (filestat.st_mode & S_IFDIR) FAT_DeleteDir(newpath); /* Delete object */ - ret = remove( newpath ); + ret = remove(newpath); /* Error */ - if ( ret != 0 ) - break; + if (ret != 0) break; } /* Close directory */ - dirclose( dir ); + dirclose(dir); return 0; } @@ -83,7 +77,7 @@ static int global_error = 0; static char temp_read_buffer[16384] ATTRIBUTE_ALIGN( 32 ); -s32 _FFS_to_FAT_Copy( const char *ffsdirpath, const char *fatdirpath ) +s32 _FFS_to_FAT_Copy(const char *ffsdirpath, const char *fatdirpath) { int n; u32 blocks, ionodes; @@ -93,79 +87,101 @@ s32 _FFS_to_FAT_Copy( const char *ffsdirpath, const char *fatdirpath ) u32 ionodes_temp; - if ( ISFS_GetUsage( ffsdirpath, &blocks, &ionodes ) ) {global_error = -1; return -1;} + if (ISFS_GetUsage(ffsdirpath, &blocks, &ionodes)) + { + global_error = -1; + return -1; + } + list = memalign(32, ionodes * 13); - list = memalign( 32, ionodes * 13 ); + if (!list) + { + global_error = -2; + return -2; + } - if ( !list ) {global_error = -2; return -2;} - - if ( ISFS_ReadDir( ffsdirpath, list , &ionodes ) ) {free( list ); global_error = -3; return -3;} - - if ( ionodes ) mkdir( fatdirpath, S_IRWXO | S_IRWXG | S_IRWXU ); + if (ISFS_ReadDir(ffsdirpath, list, &ionodes)) + { + free(list); + global_error = -3; + return -3; + } + if (ionodes) mkdir(fatdirpath, S_IRWXO | S_IRWXG | S_IRWXU); /* Read entries */ - for ( n = 0; n < ionodes; n++ ) + for (n = 0; n < ionodes; n++) { - char * filename; + char * filename; char newffspath[256], newfatpath[256]; /* Read entry */ filename = &list[pos]; - pos += strlen( &list[pos] ) + 1; + pos += strlen(&list[pos]) + 1; /* Non valid entry */ - if ( filename[0] == '.' ) - continue; + if (filename[0] == '.') continue; /* Generate entry path */ - strcpy( newffspath, ffsdirpath ); - strcat( newffspath, "/" ); - strcat( newffspath, filename ); + strcpy(newffspath, ffsdirpath); + strcat(newffspath, "/"); + strcat(newffspath, filename); - strcpy( newfatpath, fatdirpath ); - strcat( newfatpath, "/" ); - strcat( newfatpath, filename ); + strcpy(newfatpath, fatdirpath); + strcat(newfatpath, "/"); + strcat(newfatpath, filename); - ret = ISFS_ReadDir( newffspath, NULL, &ionodes_temp ); - if ( ret == 0 ) // it is a directory + ret = ISFS_ReadDir(newffspath, NULL, &ionodes_temp); + if (ret == 0) // it is a directory { - _FFS_to_FAT_Copy( newffspath, newfatpath ); + _FFS_to_FAT_Copy(newffspath, newfatpath); - if ( global_error ) {free( list ); return global_error;} + if (global_error) + { + free(list); + return global_error; + } } else // copy the file { int fd; FILE *fp; - fd = ISFS_Open( newffspath, ISFS_OPEN_READ ); - if ( fd < 0 ) + fd = ISFS_Open(newffspath, ISFS_OPEN_READ); + if (fd < 0) { global_error = -4; - free( list ); return global_error; + free(list); + return global_error; } else { int len; - fp = fopen( newfatpath, "w" ); - if ( !fd ) {ISFS_Close( fd ); global_error = -5; free( list ); return global_error;} - - len = ISFS_Seek( fd, 0, 2 ); - //if(len<0) {ISFS_Close(fd);global_error=-6;free(list);return global_error;} - ISFS_Seek( fd, 0, 0 ); - - while ( len > 0 ) + fp = fopen(newfatpath, "w"); + if (!fd) { - ret = len; if ( len > 16384 ) ret = 16384; - if ( ISFS_Read( fd, temp_read_buffer, ret ) != ret ) + ISFS_Close(fd); + global_error = -5; + free(list); + return global_error; + } + + len = ISFS_Seek(fd, 0, 2); + //if(len<0) {ISFS_Close(fd);global_error=-6;free(list);return global_error;} + ISFS_Seek(fd, 0, 0); + + while (len > 0) + { + ret = len; + if (len > 16384) ret = 16384; + if (ISFS_Read(fd, temp_read_buffer, ret) != ret) { global_error = -7; break; } - if ( fwrite( temp_read_buffer, 1, ret, fp ) != ret ) + if (fwrite(temp_read_buffer, 1, ret, fp) != ret) { global_error = -8; break; @@ -173,20 +189,24 @@ s32 _FFS_to_FAT_Copy( const char *ffsdirpath, const char *fatdirpath ) len -= ret; } - fclose( fp ); - ISFS_Close( fd ); + fclose(fp); + ISFS_Close(fd); - if ( global_error ) {free( list ); return global_error;} + if (global_error) + { + free(list); + return global_error; + } } } } - free( list ); + free(list); return 0; } -s32 FFS_to_FAT_Copy( const char *ffsdirpath, const char *fatdirpath ) +s32 FFS_to_FAT_Copy(const char *ffsdirpath, const char *fatdirpath) { u32 blocks, ionodes; int ret; @@ -195,33 +215,34 @@ s32 FFS_to_FAT_Copy( const char *ffsdirpath, const char *fatdirpath ) ISFS_Initialize(); - ret = ISFS_GetUsage( ffsdirpath, &blocks, &ionodes ); + ret = ISFS_GetUsage(ffsdirpath, &blocks, &ionodes); - if ( ret == 0 ) + if (ret == 0) { int n = 0; // creating the path directory - strcpy( create_dir, fatdirpath ); + strcpy(create_dir, fatdirpath); - while ( create_dir[n] != 0 && create_dir[n] != '/' ) n++; + while (create_dir[n] != 0 && create_dir[n] != '/') + n++; - if ( create_dir[n] == '/' ) n++; + if (create_dir[n] == '/') n++; - while ( create_dir[n] != 0 ) + while (create_dir[n] != 0) { - if ( create_dir[n] == '/' ) + if (create_dir[n] == '/') { create_dir[n] = 0; - mkdir( create_dir, S_IRWXO | S_IRWXG | S_IRWXU ); + mkdir(create_dir, S_IRWXO | S_IRWXG | S_IRWXU); create_dir[n] = '/'; } n++; } global_error = 0; // copy files - _FFS_to_FAT_Copy( ffsdirpath, fatdirpath ); + _FFS_to_FAT_Copy(ffsdirpath, fatdirpath); ret = global_error = 0; } @@ -229,66 +250,62 @@ s32 FFS_to_FAT_Copy( const char *ffsdirpath, const char *fatdirpath ) ISFS_Deinitialize(); - return ret; } static char temp_cad[512]; -void create_FAT_FFS_Directory( struct discHdr *header ) +void create_FAT_FFS_Directory(struct discHdr *header) { - char device[2][4] = - { - "sd:", - "ud:" - }; + char device[2][4] = { "sd:", "ud:" }; + if (!header) return; - if ( !header ) return; + sprintf((char *) temp_cad, "%s/nand%c", &device[(nand_mode & 2) != 0][0], (nand_mode & 0xc) ? 49 + + ((nand_mode >> 2) & 3) : '\0'); - sprintf( ( char * ) temp_cad, "%s/nand%c", &device[( nand_mode & 2 )!=0][0], ( nand_mode & 0xc ) ? 49 + ( ( nand_mode >> 2 ) & 3 ) : '\0' ); - - sprintf( ( char * ) temp_cad + 32, "%2.2x%2.2x%2.2x%2.2x", header->id[0], header->id[1], header->id[2], header->id[3] ); - - - sprintf( ( char * ) temp_cad + 64, "%s/title/00010000/%s", temp_cad, temp_cad + 32 ); - sprintf( ( char * ) temp_cad + 128, "%s/title/00010004/%s", temp_cad, temp_cad + 32 ); - sprintf( ( char * ) temp_cad + 256, "/title/00010000/%s", temp_cad + 32 ); - sprintf( ( char * ) temp_cad + 384, "/title/00010004/%s", temp_cad + 32 ); + sprintf((char *) temp_cad + 32, "%2.2x%2.2x%2.2x%2.2x", header->id[0], header->id[1], header->id[2], header->id[3]); + sprintf((char *) temp_cad + 64, "%s/title/00010000/%s", temp_cad, temp_cad + 32); + sprintf((char *) temp_cad + 128, "%s/title/00010004/%s", temp_cad, temp_cad + 32); + sprintf((char *) temp_cad + 256, "/title/00010000/%s", temp_cad + 32); + sprintf((char *) temp_cad + 384, "/title/00010004/%s", temp_cad + 32); } -int test_FAT_game( char * directory ) +int test_FAT_game(char * directory) { DIR_ITER * dir = NULL; - dir = diropen( directory ); + dir = diropen(directory); - if ( dir ) {dirclose( dir ); return 1;} + if (dir) + { + dirclose(dir); + return 1; + } return 0; } - -char *get_FAT_directory1( void ) +char *get_FAT_directory1(void) { return temp_cad + 64; } -char *get_FAT_directory2( void ) +char *get_FAT_directory2(void) { return temp_cad + 128; } -char *get_FFS_directory1( void ) +char *get_FFS_directory1(void) { return temp_cad + 256; } -char *get_FFS_directory2( void ) +char *get_FFS_directory2(void) { return temp_cad + 384; } diff --git a/source/mload/fatffs_util.h b/source/mload/fatffs_util.h index 92fd7995..c438776b 100644 --- a/source/mload/fatffs_util.h +++ b/source/mload/fatffs_util.h @@ -5,20 +5,20 @@ #include "usbloader/disc.h" -s32 FAT_DeleteDir( const char *dirpath ); +s32 FAT_DeleteDir(const char *dirpath); -s32 FFS_to_FAT_Copy( const char *ffsdirpath, const char *fatdirpath ); +s32 FFS_to_FAT_Copy(const char *ffsdirpath, const char *fatdirpath); -void create_FAT_FFS_Directory( struct discHdr *header ); +void create_FAT_FFS_Directory(struct discHdr *header); -int test_FAT_game( char * directory ); +int test_FAT_game(char * directory); -char *get_FAT_directory1( void ); +char *get_FAT_directory1(void); -char *get_FAT_directory2( void ); +char *get_FAT_directory2(void); -char *get_FFS_directory1( void ); +char *get_FFS_directory1(void); -char *get_FFS_directory2( void ); +char *get_FFS_directory2(void); #endif diff --git a/source/mload/mload.c b/source/mload/mload.c index 47c18b5b..4825cc7d 100644 --- a/source/mload/mload.c +++ b/source/mload/mload.c @@ -1,19 +1,19 @@ /* 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 - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "mload.h" #include "dip_plugin.h" @@ -39,38 +39,37 @@ int mload_init() { int n; - if ( hid < 0 ) hid = iosCreateHeap( 0x800 ); + if (hid < 0) hid = iosCreateHeap(0x800); - if ( hid < 0 ) + if (hid < 0) { - if ( mload_fd >= 0 ) - IOS_Close( mload_fd ); + if (mload_fd >= 0) IOS_Close(mload_fd); mload_fd = -1; return hid; } - if ( mload_fd >= 0 ) + if (mload_fd >= 0) { return 0; } - for ( n = 0; n < 20; n++ ) // try 5 seconds + for (n = 0; n < 20; n++) // try 5 seconds { - mload_fd = IOS_Open( mload_fs, 0 ); + 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 (mload_fd < 0) { - if ( hid >= 0 ) + if (hid >= 0) { - iosDestroyHeap( hid ); + iosDestroyHeap(hid); hid = -1; } } @@ -86,15 +85,15 @@ int mload_close() { int ret; - if ( hid >= 0 ) + if (hid >= 0) { - iosDestroyHeap( hid ); + iosDestroyHeap(hid); hid = -1; } - if ( mload_fd < 0 ) return -1; + if (mload_fd < 0) return -1; - ret = IOS_Close( mload_fd ); + ret = IOS_Close(mload_fd); mload_fd = -1; @@ -109,9 +108,9 @@ 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; @@ -121,13 +120,13 @@ 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) { 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; @@ -138,43 +137,48 @@ 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) { int ret; void *buf = NULL; + if (mload_init() < 0) return -1; - if ( mload_init() < 0 ) return -1; - - if ( hid >= 0 ) + if (hid >= 0) { - iosDestroyHeap( hid ); + 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;} - - - 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;} - -out: - if ( hid >= 0 ) + if (!buf) { - iosDestroyHeap( hid ); + ret = -1; + goto out; + } + + 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; + } + + out: if (hid >= 0) + { + iosDestroyHeap(hid); hid = -1; } @@ -187,43 +191,43 @@ 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 mload_elf(void *my_elf, data_elf *data_elf) { int n, m; int p; u8 *adr; - u32 elf = ( u32 ) my_elf; + 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; + 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; - data_elf->start = ( void * ) head->entry; + data_elf->start = (void *) head->entry; - for ( n = 0; n < head->phnum; n++ ) + for (n = 0; n < head->phnum; n++) { - entries = ( void * ) ( elf + p ); - p += sizeof( elfphentry ); + entries = (void *) (elf + p); + p += sizeof(elfphentry); - if ( entries->type == 4 ) + if (entries->type == 4) { - adr = ( void * ) ( elf + entries->offset ); + 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 ) + for (m = 4; m < entries->memsz; m += 8) { - switch ( getbe32( m ) ) + switch (getbe32( m )) { case 0x9: - data_elf->start = ( void * ) getbe32( m + 4 ); + data_elf->start = (void *) getbe32( m + 4 ); break; case 0x7D: data_elf->prio = getbe32( m + 4 ); @@ -232,7 +236,7 @@ int mload_elf( void *my_elf, data_elf *data_elf ) data_elf->size_stack = getbe32( m + 4 ); break; case 0x7F: - data_elf->stack = ( void * ) ( getbe32( m + 4 ) ); + data_elf->stack = (void *) (getbe32( m + 4 )); break; } @@ -240,12 +244,12 @@ int mload_elf( void *my_elf, data_elf *data_elf ) } } - 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; } } @@ -257,15 +261,14 @@ 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) { int ret; + if (mload_init() < 0) return -1; - if ( mload_init() < 0 ) return -1; - - ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_RUN_THREAD, "iiii:", starlet_addr, starlet_top_stack, stack_size, priority ); - + ret = IOS_IoctlvFormat(hid, mload_fd, MLOAD_RUN_THREAD, "iiii:", starlet_addr, starlet_top_stack, stack_size, + priority); return ret; } @@ -274,13 +277,13 @@ int mload_run_thread( void *starlet_addr, void *starlet_top_stack, int stack_siz // stops one starlet thread -int mload_stop_thread( int id ) +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; @@ -290,13 +293,13 @@ int mload_stop_thread( int id ) // continue one stopped starlet thread -int mload_continue_thread( int id ) +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 ); + ret = IOS_IoctlvFormat(hid, mload_fd, MLOAD_CONTINUE_THREAD, "i:", id); return ret; @@ -305,47 +308,46 @@ 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) { - if ( mload_init() < 0 ) return -1; + 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 ) +int mload_read(void* buf, u32 size) { - if ( mload_init() < 0 ) return -1; + 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 ) +int mload_write(const void * buf, u32 size) { - if ( mload_init() < 0 ) return -1; + 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 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; } @@ -358,93 +360,91 @@ 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 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 ); + ret = IOS_IoctlvFormat(hid, mload_fd, MLOAD_SET_ES_IOCTLV, "i:", starlet_addr); return ret; } - - -int mload_getw( const void * addr, u32 *dat ) +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; } -int mload_geth( const void * addr, u16 *dat ) +int mload_geth(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_GETH, "i:h", addr, dat ); + ret = IOS_IoctlvFormat(hid, mload_fd, MLOAD_GETH, "i:h", addr, dat); return ret; } -int mload_getb( const void * addr, u8 *dat ) +int mload_getb(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_GETB, "i:b", addr, dat ); + ret = IOS_IoctlvFormat(hid, mload_fd, MLOAD_GETB, "i:b", addr, dat); return ret; } -int mload_setw( const void * addr, u32 dat ) +int mload_setw(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_SETW, "ii:", addr, dat ); + ret = IOS_IoctlvFormat(hid, mload_fd, MLOAD_SETW, "ii:", addr, dat); return ret; } -int mload_seth( const void * addr, u16 dat ) +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; } -int mload_setb( const void * addr, u8 dat ) +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; } @@ -458,15 +458,14 @@ 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; } - /*--------------------------------------------------------------------------------------------------------------*/ // to get IOS base for dev/es to create the cIOS @@ -475,123 +474,122 @@ 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; } /* -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); - } - } - } + fclose(fp); + } + } + } - if(!external_ehcmodule) - { - if(mload_init()<0) return -1; + if(!external_ehcmodule) + { + if(mload_init()<0) return -1; - if (IOS_GetRevision() == 4) { - gprintf("Loading ehcmodule v4\n"); - mload_elf((void *) ehcmodule_frag_v4_bin, &my_data_elf); - } else if (IOS_GetRevision() == 0) { // 0? Strange value for v5 ehcmodule - gprintf("Loading ehcmodule v5\n"); - mload_elf((void *) ehcmodule_frag_v5_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 (IOS_GetRevision() == 4) { + gprintf("Loading ehcmodule v4\n"); + mload_elf((void *) ehcmodule_frag_v4_bin, &my_data_elf); + } else if (IOS_GetRevision() == 0) { // 0? Strange value for v5 ehcmodule + gprintf("Loading ehcmodule v5\n"); + mload_elf((void *) ehcmodule_frag_v5_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); - // 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; - } + // 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(is_ios==36) - { - // IOS 36 - memcpy(ios_36, dip_plugin, 4); // copy the entry_point - memcpy((void *) dip_plugin, ios_36, 4*10); // copy the adresses from the array + if(is_ios==36) + { + // IOS 36 + memcpy(ios_36, dip_plugin, 4); // copy the entry_point + memcpy((void *) 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); + 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); + // enables DIP plugin + mload_seek(0x20209040, SEEK_SET); + mload_write(ios_36, 4); - } - if(is_ios==38) - { - // IOS 38 + } + if(is_ios==38) + { + // IOS 38 - memcpy(ios_38, dip_plugin, 4); // copy the entry_point - memcpy((void *) dip_plugin, ios_38, 4*10); // copy the adresses from the array + memcpy(ios_38, dip_plugin, 4); // copy the entry_point + memcpy((void *) 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); + 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); + // enables DIP plugin + mload_seek(0x20208030, SEEK_SET); + mload_write(ios_38, 4); - } + } - mload_close(); + mload_close(); -return 0; -} - -int patch_cios_data() { - patch_datas[0]=*((u32 *) (dip_plugin+16*4)); - mload_set_ES_ioctlv_vector((void *) patch_datas[0]); - return 1; -} -*/ + return 0; + } + int patch_cios_data() { + patch_datas[0]=*((u32 *) (dip_plugin+16*4)); + mload_set_ES_ioctlv_vector((void *) patch_datas[0]); + return 1; + } + */ diff --git a/source/mload/mload.h b/source/mload/mload.h index faf5efa3..31eef26e 100644 --- a/source/mload/mload.h +++ b/source/mload/mload.h @@ -1,24 +1,23 @@ /* 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 - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #ifndef __MLOAD_H__ #define __MLOAD_H__ - #include #include #include @@ -55,175 +54,169 @@ extern "C" { #endif - -// from IOS ELF stripper of neimod + // from IOS ELF stripper of neimod #define getbe32(x) ((adr[x]<<24) | (adr[x+1]<<16) | (adr[x+2]<<8) | (adr[x+3])) typedef struct { - u32 ident0; - u32 ident1; - u32 ident2; - u32 ident3; - u32 machinetype; - u32 version; - u32 entry; - u32 phoff; - u32 shoff; - u32 flags; - u16 ehsize; - u16 phentsize; - u16 phnum; - u16 shentsize; - u16 shnum; - u16 shtrndx; + u32 ident0; + u32 ident1; + u32 ident2; + u32 ident3; + u32 machinetype; + u32 version; + u32 entry; + u32 phoff; + u32 shoff; + u32 flags; + u16 ehsize; + u16 phentsize; + u16 phnum; + u16 shentsize; + u16 shnum; + u16 shtrndx; } elfheader; typedef struct { - u32 type; - u32 offset; - u32 vaddr; - u32 paddr; - u32 filesz; - u32 memsz; - u32 flags; - u32 align; + 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; + void *start; + int prio; + void *stack; + int size_stack; } data_elf; /*--------------------------------------------------------------------------------------------------------------*/ -// to init/test if the device is running + // to init/test if the device is running int mload_init(); /*--------------------------------------------------------------------------------------------------------------*/ -// to close the device (remember call it when rebooting the IOS!) + // to close the device (remember call it when rebooting the IOS!) int mload_close(); /*--------------------------------------------------------------------------------------------------------------*/ -// to get the thread id of mload + // to get the thread id of mload int mload_get_thread_id(); /*--------------------------------------------------------------------------------------------------------------*/ -// get the base and the size of the memory readable/writable to load modules + // 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 + // 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 + // 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) + // 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 + // stops one starlet thread - int mload_stop_thread( int id ); + int mload_stop_thread(int id); /*--------------------------------------------------------------------------------------------------------------*/ -// continue one stopped starlet thread + // 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) + // 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) + // 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) + // 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) + // 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) + // get the ehci datas ( ehcmodule.elf uses this address) void * mload_get_ehci_data(); /*--------------------------------------------------------------------------------------------------------------*/ -// set the dev/es ioctlv in routine + // 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 + // 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(); /*--------------------------------------------------------------------------------------------------------------*/ - -// to get IOS base for dev/es to create the cIOS + // to get IOS base for dev/es to create the cIOS 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); +/*--------------------------------------------------------------------------------------------------------------*/ #ifdef __cplusplus } #endif - #endif diff --git a/source/mload/mload_modules.c b/source/mload/mload_modules.c index 69bfa677..39be7628 100644 --- a/source/mload/mload_modules.c +++ b/source/mload/mload_modules.c @@ -11,77 +11,60 @@ int global_mount; int sd_ok = 0; int ud_ok = 0; -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) + }; +static u32 ios_37[16] ATTRIBUTE_ALIGN( 32 ) = { 0, // DI_EmulateCmd + 0, 0x2022DD60, // dvd_read_controlling_data + 0x20200F04 + 1, // handle_di_cmd_reentry (thumb) + 0x2020096C + 1, // ios_shared_alloc_aligned (thumb) + 0x2020093C + 1, // ios_shared_free (thumb) + 0x20205E54 + 1, // ios_memcpy (thumb) + 0x20200048 + 1, // ios_fatal_di_error (thumb) + 0x20202A70 + 1, // ios_doReadHashEncryptedState (thumb) + 0x2020387C + 1, // ios_printf (thumb) + }; -static u32 ios_37[16] ATTRIBUTE_ALIGN( 32 ) = -{ - 0, // DI_EmulateCmd - 0, - 0x2022DD60, // dvd_read_controlling_data - 0x20200F04 + 1, // handle_di_cmd_reentry (thumb) - 0x2020096C + 1, // ios_shared_alloc_aligned (thumb) - 0x2020093C + 1, // ios_shared_free (thumb) - 0x20205E54 + 1, // ios_memcpy (thumb) - 0x20200048 + 1, // ios_fatal_di_error (thumb) - 0x20202A70 + 1, // ios_doReadHashEncryptedState (thumb) - 0x2020387C + 1, // ios_printf (thumb) -}; - -static u32 ios_57[16] ATTRIBUTE_ALIGN( 32 ) = -{ - 0, // DI_EmulateCmd - 0, - 0x2022cd60, // dvd_read_controlling_data - 0x20200f04 + 1, // handle_di_cmd_reentry (thumb) - 0x2020096c + 1, // ios_shared_alloc_aligned (thumb) // no usado - 0x2020093C + 1, // ios_shared_free (thumb) // no usado - 0x20205EF0 + 1, // ios_memcpy (thumb) - 0x20200048 + 1, // ios_fatal_di_error (thumb) - 0x20202944 + 1, // ios_doReadHashEncryptedState (thumb) - 0x20203750 + 1, // ios_printf (thumb) -}; - -static u32 ios_60[16] ATTRIBUTE_ALIGN( 32 ) = -{ - 0, // DI_EmulateCmd - 0, - 0x2022cd60, // dvd_read_controlling_data - 0x20200f04 + 1, // handle_di_cmd_reentry (thumb) - 0x2020096c + 1, // ios_shared_alloc_aligned (thumb) // no usado - 0x2020093C + 1, // ios_shared_free (thumb) // no usado - 0x20205e00 + 1, // ios_memcpy (thumb) - 0x20200048 + 1, // ios_fatal_di_error (thumb) - 0x20202944 + 1, // ios_doReadHashEncryptedState (thumb) - 0x20203750 + 1, // ios_printf (thumb) -}; +static u32 ios_57[16] ATTRIBUTE_ALIGN( 32 ) = { 0, // DI_EmulateCmd + 0, 0x2022cd60, // dvd_read_controlling_data + 0x20200f04 + 1, // handle_di_cmd_reentry (thumb) + 0x2020096c + 1, // ios_shared_alloc_aligned (thumb) // no usado + 0x2020093C + 1, // ios_shared_free (thumb) // no usado + 0x20205EF0 + 1, // ios_memcpy (thumb) + 0x20200048 + 1, // ios_fatal_di_error (thumb) + 0x20202944 + 1, // ios_doReadHashEncryptedState (thumb) + 0x20203750 + 1, // ios_printf (thumb) + }; +static u32 ios_60[16] ATTRIBUTE_ALIGN( 32 ) = { 0, // DI_EmulateCmd + 0, 0x2022cd60, // dvd_read_controlling_data + 0x20200f04 + 1, // handle_di_cmd_reentry (thumb) + 0x2020096c + 1, // ios_shared_alloc_aligned (thumb) // no usado + 0x2020093C + 1, // ios_shared_free (thumb) // no usado + 0x20205e00 + 1, // ios_memcpy (thumb) + 0x20200048 + 1, // ios_fatal_di_error (thumb) + 0x20202944 + 1, // ios_doReadHashEncryptedState (thumb) + 0x20203750 + 1, // ios_printf (thumb) + }; u32 patch_datas[8] ATTRIBUTE_ALIGN( 32 ); @@ -100,13 +83,13 @@ int load_ehc_module() FILE *fp; -// WARNING!!!: load external module suspended + // WARNING!!!: load external module suspended if ( sd_ok && !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/usbloadergx/ehcmodule.elf", "rb" ); if ( fp != 0 ) { @@ -114,13 +97,13 @@ int load_ehc_module() size_external_ehcmodule = ftell( fp ); external_ehcmodule = memalign( 32, size_external_ehcmodule ); if ( !external_ehcmodule ) - {fclose( fp );} + { 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;} + { free( external_ehcmodule ); external_ehcmodule = NULL;} fclose( fp ); } @@ -129,57 +112,56 @@ int load_ehc_module() #endif /* - if(mload_init()<0) return -1; - mload_elf((void *) logmodule, &my_data_elf); - my_thread_id= mload_run_thread(my_data_elf.start, my_data_elf.stack, my_data_elf.size_stack, my_data_elf.prio); - if(my_thread_id<0) return -1; - */ + if(mload_init()<0) return -1; + mload_elf((void *) logmodule, &my_data_elf); + my_thread_id= mload_run_thread(my_data_elf.start, my_data_elf.stack, my_data_elf.size_stack, my_data_elf.prio); + if(my_thread_id<0) return -1; + */ - if ( !external_ehcmodule ) + if (!external_ehcmodule) { #ifdef DEBUG_MLOAD - gprintf( "before mload_init\n" ); + gprintf("before mload_init\n"); #endif - if ( mload_init() < 0 ) return -1; + if (mload_init() < 0) return -1; #ifdef DEBUG_MLOAD - gprintf( "after mload_init\n" ); + gprintf("after mload_init\n"); #endif - if ( IOS_GetRevision() == 4 ) + if (IOS_GetRevision() == 4) { #ifdef DEBUG_MLOAD - gprintf( "Loading ehcmodule v4\n" ); + gprintf("Loading ehcmodule v4\n"); #endif - mload_elf( ( void * ) ehcmodule_frag_v4_bin, &my_data_elf ); + mload_elf((void *) ehcmodule_frag_v4_bin, &my_data_elf); } - else if ( IOS_GetRevision() == 65535 ) + else if (IOS_GetRevision() == 65535) { #ifdef DEBUG_MLOAD - gprintf( "Loading ehcmodule v5\n" ); + gprintf("Loading ehcmodule v5\n"); #endif - mload_elf( ( void * ) ehcmodule_frag_v5_bin, &my_data_elf ); + mload_elf((void *) ehcmodule_frag_v5_bin, &my_data_elf); } else { return -2; } -// mload_elf((void *) ehcmodule, &my_data_elf); + // mload_elf((void *) ehcmodule, &my_data_elf); #ifdef DEBUG_MLOAD - gprintf( "before mload_run_thread\n" ); + gprintf("before mload_run_thread\n"); #endif - my_thread_id = mload_run_thread( my_data_elf.start, my_data_elf.stack, my_data_elf.size_stack, my_data_elf.prio ); - if ( my_thread_id < 0 ) return -1; + my_thread_id = mload_run_thread(my_data_elf.start, my_data_elf.stack, my_data_elf.size_stack, my_data_elf.prio); + if (my_thread_id < 0) return -1; //if(mload_module(ehcmodule, size_ehcmodule)<0) return -1; } else { //if(mload_module(external_ehcmodule, size_external_ehcmodule)<0) return -1; - if ( mload_init() < 0 ) return -1; - mload_elf( ( void * ) external_ehcmodule, &my_data_elf ); - my_thread_id = mload_run_thread( my_data_elf.start, my_data_elf.stack, my_data_elf.size_stack, my_data_elf.prio ); - if ( my_thread_id < 0 ) return -1; + if (mload_init() < 0) return -1; + mload_elf((void *) external_ehcmodule, &my_data_elf); + my_thread_id = mload_run_thread(my_data_elf.start, my_data_elf.stack, my_data_elf.size_stack, my_data_elf.prio); + if (my_thread_id < 0) return -1; } - usleep( 350*1000 ); - + usleep(350 * 1000); // Test for IOS @@ -198,72 +180,72 @@ int load_ehc_module() #endif is_ios = mload_get_IOS_base(); - switch ( is_ios ) + switch (is_ios) { case 36: - memcpy( ios_36, dip_plugin, 4 ); // copy the entry_point - memcpy( dip_plugin, ios_36, 4*10 ); // copy the adresses from the array + 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 ); + 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_seek(0x20209040, SEEK_SET); + mload_write(ios_36, 4); break; case 37: - memcpy( ios_37, dip_plugin, 4 ); // copy the entry_point - memcpy( dip_plugin, ios_37, 4*10 ); // copy the adresses from the array + memcpy(ios_37, dip_plugin, 4); // copy the entry_point + memcpy(dip_plugin, ios_37, 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 ); + mload_seek(0x1377E000, SEEK_SET); // copy dip_plugin in the starlet + mload_write(dip_plugin, size_dip_plugin); // enables DIP plugin - mload_seek( 0x20209030, SEEK_SET ); - mload_write( ios_37, 4 ); + mload_seek(0x20209030, SEEK_SET); + mload_write(ios_37, 4); break; case 38: - memcpy( ios_38, dip_plugin, 4 ); // copy the entry_point - memcpy( dip_plugin, ios_38, 4*10 ); // copy the adresses from the array + 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 ); + 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_seek(0x20208030, SEEK_SET); + mload_write(ios_38, 4); break; case 57: - memcpy( ios_57, dip_plugin, 4 ); // copy the entry_point - memcpy( dip_plugin, ios_57, 4*10 ); // copy the adresses from the array + memcpy(ios_57, dip_plugin, 4); // copy the entry_point + memcpy(dip_plugin, ios_57, 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 ); + 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_57, 4 ); + mload_seek(0x20208030, SEEK_SET); + mload_write(ios_57, 4); break; case 60: - memcpy( ios_60, dip_plugin, 4 ); // copy the entry_point - memcpy( dip_plugin, ios_60, 4*10 ); // copy the adresses from the array + memcpy(ios_60, dip_plugin, 4); // copy the entry_point + memcpy(dip_plugin, ios_60, 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 ); + 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_60, 4 ); + mload_seek(0x20208030, SEEK_SET); + mload_write(ios_60, 4); break; } @@ -280,26 +262,26 @@ int load_ehc_module() #define IOCTL_FFS_MODE 0x80 -int load_fatffs_module( u8 *discid ) +int load_fatffs_module(u8 *discid) { static char fs[] ATTRIBUTE_ALIGN( 32 ) = "fat"; s32 hid = -1, fd = -1; - static char file_name[256] ALIGNED( 0x20 ) = "SD:"; + static char file_name[256] ALIGNED( 0x20 ) = "SD:"; int n; char *p; s32 ret; p = &file_name[0]; - if ( mload_init() < 0 ) return -1; + if (mload_init() < 0) return -1; - mload_elf( ( void * ) fatffs_module_bin, &my_data_elf ); - my_thread_id = mload_run_thread( my_data_elf.start, my_data_elf.stack, my_data_elf.size_stack, my_data_elf.prio ); - if ( my_thread_id < 0 ) return -1; + mload_elf((void *) fatffs_module_bin, &my_data_elf); + my_thread_id = mload_run_thread(my_data_elf.start, my_data_elf.stack, my_data_elf.size_stack, my_data_elf.prio); + if (my_thread_id < 0) return -1; global_mount &= ~0xc; - if ( discid ) + if (discid) { sd_ok = ud_ok = 1; @@ -309,155 +291,177 @@ int load_fatffs_module( u8 *discid ) sd_ok = ud_ok = 0; - if ( !p ) return -1; + if (!p) return -1; global_mount &= ~0xf; // change 'ud:' by 'usb:' - if ( p[0] == 'U' ) {global_mount |= 2; file_name[0] = 'U'; file_name[1] = 'S'; file_name[2] = 'B'; memcpy( file_name + 3, ( void * )p + 2, 253 );} - else {global_mount |= 1; memcpy( file_name, ( void * ) p, 256 );} + if (p[0] == 'U') + { + global_mount |= 2; + file_name[0] = 'U'; + file_name[1] = 'S'; + file_name[2] = 'B'; + memcpy(file_name + 3, (void *) p + 2, 253); + } + else + { + global_mount |= 1; + memcpy(file_name, (void *) p, 256); + } // copy filename to dip_plugin filename area - mload_seek( *( ( u32 * ) ( dip_plugin + 14*4 ) ), SEEK_SET ); // offset 14 (filename Address - 256 bytes) - mload_write( file_name, sizeof( file_name ) ); + mload_seek(*((u32 *) (dip_plugin + 14 * 4)), SEEK_SET); // offset 14 (filename Address - 256 bytes) + mload_write(file_name, sizeof(file_name)); mload_close(); - } else { - if ( ( global_mount & 3 ) == 0 ) return 0; - if ( global_mount & 1 ) p[0] = 's'; - if ( global_mount & 2 ) p[0] = 'u'; + if ((global_mount & 3) == 0) return 0; + if (global_mount & 1) p[0] = 's'; + if (global_mount & 2) p[0] = 'u'; } - usleep( 350*1000 ); + usleep(350 * 1000); /* Create heap */ - if ( hid < 0 ) + if (hid < 0) { - hid = iosCreateHeap( 0x100 ); - if ( hid < 0 ) - return -1; + hid = iosCreateHeap(0x100); + if (hid < 0) return -1; } /* Open USB device */ - fd = IOS_Open( fs, 0 ); + fd = IOS_Open(fs, 0); - if ( fd < 0 ) + if (fd < 0) { - if ( hid >= 0 ) + if (hid >= 0) { - iosDestroyHeap( hid ); + iosDestroyHeap(hid); hid = -1; } return -1; } n = 30; // try 20 times - while ( n > 0 ) + while (n > 0) { - if ( ( global_mount & 10 ) == 2 ) {ret = IOS_IoctlvFormat( hid, fd, IOCTL_FAT_MOUNTUSB, ":" ); if ( ret == 0 ) global_mount |= 8;} - else {ret = IOS_IoctlvFormat( hid, fd, IOCTL_FAT_MOUNTSD, ":" ); if ( ret == 0 ) {global_mount |= 4;}} + if ((global_mount & 10) == 2) + { + ret = IOS_IoctlvFormat(hid, fd, IOCTL_FAT_MOUNTUSB, ":"); + if (ret == 0) global_mount |= 8; + } + else + { + ret = IOS_IoctlvFormat(hid, fd, IOCTL_FAT_MOUNTSD, ":"); + if (ret == 0) + { + global_mount |= 4; + } + } - if ( ( global_mount & 7 ) == 3 && ret == 0 ) - {ret = IOS_IoctlvFormat( hid, fd, IOCTL_FAT_MOUNTSD, ":" ); if ( ret == 0 ) global_mount |= 4;} + if ((global_mount & 7) == 3 && ret == 0) + { + ret = IOS_IoctlvFormat(hid, fd, IOCTL_FAT_MOUNTSD, ":"); + if (ret == 0) global_mount |= 4; + } - if ( ( global_mount & 3 ) == ( ( global_mount >> 2 ) & 3 ) && ( global_mount & 3 ) ) {ret = 0; break;} + if ((global_mount & 3) == ((global_mount >> 2) & 3) && (global_mount & 3)) + { + ret = 0; + break; + } else ret = -1; //ret=IOS_IoctlvFormat(hid, fd, IOCTL_FAT_MOUNTSD, ":"); //if(ret==0) break; - usleep( 500*1000 ); + usleep(500 * 1000); n--; } - if ( fd >= 0 ) + if (fd >= 0) { - IOS_Close( fd ); + IOS_Close(fd); fd = -1; } - if ( hid >= 0 ) + if (hid >= 0) { - iosDestroyHeap( hid ); + iosDestroyHeap(hid); hid = -1; } - if ( n == 0 ) return -1; + if (n == 0) return -1; return 0; } - -int enable_ffs( int mode ) +int enable_ffs(int mode) { static char fs[] ATTRIBUTE_ALIGN( 32 ) = "fat"; s32 hid = -1, fd = -1; s32 ret; /* Create heap */ - if ( hid < 0 ) + if (hid < 0) { - hid = iosCreateHeap( 0x100 ); - if ( hid < 0 ) - return -1; + hid = iosCreateHeap(0x100); + if (hid < 0) return -1; } /* Open USB device */ - fd = IOS_Open( fs, 0 ); + fd = IOS_Open(fs, 0); - if ( fd < 0 ) + if (fd < 0) { - if ( hid >= 0 ) + if (hid >= 0) { - iosDestroyHeap( hid ); + iosDestroyHeap(hid); hid = -1; } return -1; } + ret = IOS_IoctlvFormat(hid, fd, IOCTL_FFS_MODE, "i:", mode); - ret = IOS_IoctlvFormat( hid, fd, IOCTL_FFS_MODE, "i:", mode ); - - - if ( fd >= 0 ) + if (fd >= 0) { - IOS_Close( fd ); + IOS_Close(fd); fd = -1; } - if ( hid >= 0 ) + if (hid >= 0) { - iosDestroyHeap( hid ); + iosDestroyHeap(hid); hid = -1; } - - return ret; } -void enable_ES_ioctlv_vector( void ) +void enable_ES_ioctlv_vector(void) { - patch_datas[0] = *( ( u32 * ) ( dip_plugin + 16 * 4 ) ); - mload_set_ES_ioctlv_vector( ( void * ) patch_datas[0] ); + patch_datas[0] = *((u32 *) (dip_plugin + 16 * 4)); + mload_set_ES_ioctlv_vector((void *) patch_datas[0]); } -void Set_DIP_BCA_Datas( u8 *bca_data ) +void Set_DIP_BCA_Datas(u8 *bca_data) { // write in dip_plugin bca data area - mload_seek( *( ( u32 * ) ( dip_plugin + 15*4 ) ), SEEK_SET ); // offset 15 (bca_data area) - mload_write( bca_data, 64 ); + mload_seek(*((u32 *) (dip_plugin + 15 * 4)), SEEK_SET); // offset 15 (bca_data area) + mload_write(bca_data, 64); mload_close(); } -u8 *search_for_ehcmodule_cfg( u8 *p, int size ) +u8 *search_for_ehcmodule_cfg(u8 *p, int size) { int n; - for ( n = 0; n < size; n++ ) + for (n = 0; n < size; n++) { - if ( !memcmp( ( void * ) &p[n], "EHC_CFG", 8 ) && p[n+8] == 0x12 && p[n+9] == 0x34 && p[n+10] == 0x00 && p[n+11] == 0x01 ) + if (!memcmp((void *) &p[n], "EHC_CFG", 8) && p[n + 8] == 0x12 && p[n + 9] == 0x34 && p[n + 10] == 0x00 && p[n + + 11] == 0x01) { return &p[n]; } @@ -472,40 +476,38 @@ void test_and_patch_for_port1() u8 * ehc_data = NULL; - if ( IOS_GetRevision() == 4 ) + if (IOS_GetRevision() == 4) { - ehc_data = search_for_ehcmodule_cfg( ( void * ) ehcmodule_frag_v4_bin, ehcmodule_frag_v4_bin_size ); + ehc_data = search_for_ehcmodule_cfg((void *) ehcmodule_frag_v4_bin, ehcmodule_frag_v4_bin_size); } - else if ( IOS_GetRevision() == 65535 ) + else if (IOS_GetRevision() == 65535) { - ehc_data = search_for_ehcmodule_cfg( ( void * ) ehcmodule_frag_v5_bin, ehcmodule_frag_v5_bin_size ); + ehc_data = search_for_ehcmodule_cfg((void *) ehcmodule_frag_v5_bin, ehcmodule_frag_v5_bin_size); } - if ( ehc_data ) + if (ehc_data) { ehc_data += 12; use_port1 = ehc_data[0]; } - - if ( use_port1 ) - // release port 0 and use port 1 + if (use_port1) + // release port 0 and use port 1 { u32 dat = 0; u32 addr; // get EHCI base registers - mload_getw( ( void * ) 0x0D040000, &addr ); + mload_getw((void *) 0x0D040000, &addr); addr &= 0xff; addr += 0x0D040000; - - mload_getw( ( void * ) ( addr + 0x44 ), &dat ); - if ( ( dat & 0x2001 ) == 1 ) mload_setw( ( void * ) ( addr + 0x44 ), 0x2000 ); - mload_getw( ( void * ) ( addr + 0x48 ), &dat ); - if ( ( dat & 0x2000 ) == 0x2000 ) mload_setw( ( void * ) ( addr + 0x48 ), 0x1001 ); + mload_getw((void *) (addr + 0x44), &dat); + if ((dat & 0x2001) == 1) mload_setw((void *) (addr + 0x44), 0x2000); + mload_getw((void *) (addr + 0x48), &dat); + if ((dat & 0x2000) == 0x2000) mload_setw((void *) (addr + 0x48), 0x1001); } } ////////////////////////////////// diff --git a/source/mload/mload_modules.h b/source/mload/mload_modules.h index be986acb..12267763 100644 --- a/source/mload/mload_modules.h +++ b/source/mload/mload_modules.h @@ -15,14 +15,14 @@ extern "C" extern int use_port1; int load_ehc_module(); - int load_fatffs_module( u8 *discid ); + int load_fatffs_module(u8 *discid); - void enable_ES_ioctlv_vector( void ); - void Set_DIP_BCA_Datas( u8 *bca_data ); + void enable_ES_ioctlv_vector(void); + void Set_DIP_BCA_Datas(u8 *bca_data); void test_and_patch_for_port1(); - int enable_ffs( int mode ); + int enable_ffs(int mode); #ifdef __cplusplus } diff --git a/source/network/HTML_Stream.cpp b/source/network/HTML_Stream.cpp index 1f63a7b6..ffac2d61 100644 --- a/source/network/HTML_Stream.cpp +++ b/source/network/HTML_Stream.cpp @@ -1,30 +1,30 @@ /*************************************************************************** -* Copyright (C) 2010 -* 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. -* -* HTML_Stream Class -* -* for WiiXplorer 2010 -***************************************************************************/ + * Copyright (C) 2010 + * 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. + * + * HTML_Stream Class + * + * for WiiXplorer 2010 + ***************************************************************************/ #include #include #include @@ -35,7 +35,6 @@ #define htmlstringcompare(text, cmp, pos) strncasecmp((const char*) &text[pos], (const char*) cmp, strlen((const char*) cmp)) - HTML_Stream::HTML_Stream() { HTML_File = NULL; @@ -43,50 +42,44 @@ HTML_Stream::HTML_Stream() filesize = 0; } -HTML_Stream::HTML_Stream( const char * url ) +HTML_Stream::HTML_Stream(const char * url) { HTML_File = NULL; position = 0; filesize = 0; - LoadLink( url ); + LoadLink(url); } HTML_Stream::~HTML_Stream() { - if ( HTML_File ) - free( HTML_File ); + if (HTML_File) free(HTML_File); } -bool HTML_Stream::LoadLink( const char * url ) +bool HTML_Stream::LoadLink(const char * url) { - if ( !IsNetworkInit() ) - return false; + if (!IsNetworkInit()) return false; - struct block file = downloadfile( url ); + struct block file = downloadfile(url); - if ( !file.data || !file.size ) - return false; + if (!file.data || !file.size) return false; - if ( HTML_File ) - free( HTML_File ); + if (HTML_File) free(HTML_File); - HTML_File = ( char * ) file.data; + HTML_File = (char *) file.data; filesize = file.size; position = 0; return true; } -const char * HTML_Stream::FindStringStart( const char * string ) +const char * HTML_Stream::FindStringStart(const char * string) { - if ( !HTML_File ) - return NULL; + if (!HTML_File) return NULL; - while ( ( u32 ) position < filesize ) + while ((u32) position < filesize) { - if ( htmlstringcompare( HTML_File, string, position ) == 0 ) - break; + if (htmlstringcompare( HTML_File, string, position ) == 0) break; position++; } @@ -94,56 +87,52 @@ const char * HTML_Stream::FindStringStart( const char * string ) return &HTML_File[position]; } -const char * HTML_Stream::FindStringEnd( const char * string ) +const char * HTML_Stream::FindStringEnd(const char * string) { - if ( !HTML_File ) - return NULL; + if (!HTML_File) return NULL; - while ( ( u32 ) position < filesize ) + while ((u32) position < filesize) { - if ( htmlstringcompare( HTML_File, string, position ) == 0 ) - break; + if (htmlstringcompare( HTML_File, string, position ) == 0) break; position++; } - if ( ( u32 ) position >= filesize ) + if ((u32) position >= filesize) { return NULL; } - position += strlen( string ); + position += strlen(string); return &HTML_File[position]; } -char * HTML_Stream::CopyString( const char * stopat ) +char * HTML_Stream::CopyString(const char * stopat) { - if ( !stopat || !HTML_File ) - return NULL; + if (!stopat || !HTML_File) return NULL; u32 blocksize = 1024; u32 counter = 0; u32 allocatedsize = 0; - char * outtext = ( char* ) malloc( blocksize ); - if ( !outtext ) - return NULL; + char * outtext = (char*) malloc(blocksize); + if (!outtext) return NULL; allocatedsize = blocksize; - memset( outtext, 0, blocksize ); + memset(outtext, 0, blocksize); - while ( ( htmlstringcompare( HTML_File, stopat, position ) != 0 ) && ( position + strlen( stopat ) < filesize ) ) + while ((htmlstringcompare( HTML_File, stopat, position ) != 0) && (position + strlen(stopat) < filesize)) { - if ( counter > blocksize ) + if (counter > blocksize) { blocksize += 1024; - char * tmpblock = ( char* ) realloc( outtext, blocksize ); - if ( !tmpblock ) + char * tmpblock = (char*) realloc(outtext, blocksize); + if (!tmpblock) { - free( outtext ); + free(outtext); outtext = NULL; - free( tmpblock ); + free(tmpblock); return NULL; } @@ -156,17 +145,16 @@ char * HTML_Stream::CopyString( const char * stopat ) } outtext[counter] = '\0'; - outtext = ( char* ) realloc( outtext, counter + 1 ); + outtext = (char*) realloc(outtext, counter + 1); return outtext; } -int HTML_Stream::Seek( u32 pos, int origin ) +int HTML_Stream::Seek(u32 pos, int origin) { - if ( !HTML_File ) - return -1; + if (!HTML_File) return -1; - switch ( origin ) + switch (origin) { case SEEK_SET: position = pos; @@ -184,8 +172,7 @@ int HTML_Stream::Seek( u32 pos, int origin ) void HTML_Stream::Rewind() { - if ( !HTML_File ) - return; + if (!HTML_File) return; position = 0; } diff --git a/source/network/HTML_Stream.h b/source/network/HTML_Stream.h index d2647938..c2b30603 100644 --- a/source/network/HTML_Stream.h +++ b/source/network/HTML_Stream.h @@ -1,30 +1,30 @@ /*************************************************************************** -* Copyright (C) 2010 -* 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. -* -* HTML_Stream Class -* -* for WiiXplorer 2010 -***************************************************************************/ + * Copyright (C) 2010 + * 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. + * + * HTML_Stream Class + * + * for WiiXplorer 2010 + ***************************************************************************/ #ifndef ___HTML_STREAM_H_ #define ___HTML_STREAM_H_ @@ -36,25 +36,25 @@ class HTML_Stream //!Constructor HTML_Stream(); //!\param url from where to the HTML file - HTML_Stream( const char * url ); + HTML_Stream(const char * url); //!Destructor ~HTML_Stream(); //!Load url - bool LoadLink( const char * url ); + bool LoadLink(const char * url); //! Find start of a string from current position in the html //!\param string to find - const char * FindStringStart( const char * string ); + const char * FindStringStart(const char * string); //! Find end of a string from current position in the html //!\param string to find - const char * FindStringEnd( const char * string ); + const char * FindStringEnd(const char * string); //!CopyString from current position in html till stopat string //!\param stopat string before which to stop copying (e.g. ) //!\param outtext variable is allocated with malloc and must be set 0 before - char * CopyString( const char * stopat ); + char * CopyString(const char * stopat); //!Seek position in file //!\param position seeked //!\param seek origin (SEEK_SET, SEEK_CUR, SEEK_END) - int Seek( u32 pos, int origin ); + int Seek(u32 pos, int origin); //!Rewind to the start of the html void Rewind(); //!Get current position diff --git a/source/network/URL_List.cpp b/source/network/URL_List.cpp index 446480fe..b2b54b4d 100644 --- a/source/network/URL_List.cpp +++ b/source/network/URL_List.cpp @@ -10,21 +10,20 @@ #include "URL_List.h" - -URL_List::URL_List( const char * url ) +URL_List::URL_List(const char * url) { Links = NULL; urlcount = 0; - if ( !IsNetworkInit() ) + if (!IsNetworkInit()) { urlcount = -1; return; } - struct block file = downloadfile( url ); + struct block file = downloadfile(url); - if ( !file.data || !file.size ) + if (!file.data || !file.size) { urlcount = -2; return; @@ -33,26 +32,26 @@ URL_List::URL_List( const char * url ) u32 cnt = 0; char temp[1024]; - Links = ( Link_Info * ) malloc( sizeof( Link_Info ) ); - if ( !Links ) + Links = (Link_Info *) malloc(sizeof(Link_Info)); + if (!Links) { - free( file.data ); + free(file.data); urlcount = -3; return; } - memset( &Links[urlcount], 0, sizeof( Link_Info ) ); + memset(&Links[urlcount], 0, sizeof(Link_Info)); - while ( cnt < file.size ) + while (cnt < file.size) { - if ( file.data[cnt] == '"' && file.data[cnt-1] == '=' && file.data[cnt-2] == 'f' - && file.data[cnt-3] == 'e' && file.data[cnt-4] == 'r' && file.data[cnt-5] == 'h' ) + if (file.data[cnt] == '"' && file.data[cnt - 1] == '=' && file.data[cnt - 2] == 'f' && file.data[cnt - 3] + == 'e' && file.data[cnt - 4] == 'r' && file.data[cnt - 5] == 'h') { u32 cnt2 = 0; cnt++; - while ( file.data[cnt] != '"' && cnt2 < 1024 ) + while (file.data[cnt] != '"' && cnt2 < 1024) { temp[cnt2] = file.data[cnt]; cnt2++; @@ -60,76 +59,74 @@ URL_List::URL_List( const char * url ) } temp[cnt2] = '\0'; - Links = ( Link_Info * ) realloc( Links, ( urlcount + 1 ) * sizeof( Link_Info ) ); + Links = (Link_Info *) realloc(Links, (urlcount + 1) * sizeof(Link_Info)); - if ( !Links ) + if (!Links) { - for ( int i = 0; i == urlcount; i++ ) + for (int i = 0; i == urlcount; i++) { delete Links[i].URL; Links[i].URL = NULL; } - free( Links ); + free(Links); Links = NULL; - free( file.data ); + free(file.data); urlcount = -4; break; } - memset( &( Links[urlcount] ), 0, sizeof( Link_Info ) ); + memset(&(Links[urlcount]), 0, sizeof(Link_Info)); - Links[urlcount].URL = new char[cnt2+1]; + Links[urlcount].URL = new char[cnt2 + 1]; - if ( !Links[urlcount].URL ) + if (!Links[urlcount].URL) { - for ( int i = 0; i == urlcount; i++ ) + for (int i = 0; i == urlcount; i++) { delete Links[i].URL; Links[i].URL = NULL; } - free( Links ); + free(Links); Links = NULL; - free( file.data ); + free(file.data); urlcount = -5; break; } - snprintf( Links[urlcount].URL, cnt2 + 1, "%s", temp ); + snprintf(Links[urlcount].URL, cnt2 + 1, "%s", temp); - if ( strncmp( Links[urlcount].URL, "http://", strlen( "http://" ) ) != 0 ) + if (strncmp(Links[urlcount].URL, "http://", strlen("http://")) != 0) Links[urlcount].direct = false; - else - Links[urlcount].direct = true; + else Links[urlcount].direct = true; urlcount++; } cnt++; } - free( file.data ); + free(file.data); } URL_List::~URL_List() { - for ( int i = 0; i == urlcount; i++ ) + for (int i = 0; i == urlcount; i++) { delete Links[i].URL; Links[i].URL = NULL; } - if ( Links != NULL ) + if (Links != NULL) { - free( Links ); + free(Links); Links = NULL; } } -char * URL_List::GetURL( int ind ) +char * URL_List::GetURL(int ind) { - if ( ind > urlcount || ind < 0 || !Links || urlcount <= 0 ) + if (ind > urlcount || ind < 0 || !Links || urlcount <= 0) return NULL; - else - return Links[ind].URL; + else return Links[ind].URL; } int URL_List::GetURLCount() @@ -137,14 +134,14 @@ int URL_List::GetURLCount() return urlcount; } -static int ListCompare( const void *a, const void *b ) +static int ListCompare(const void *a, const void *b) { - Link_Info *ab = ( Link_Info* ) a; - Link_Info *bb = ( Link_Info* ) b; + Link_Info *ab = (Link_Info*) a; + Link_Info *bb = (Link_Info*) b; - return stricmp( ( char * ) ab->URL, ( char * ) bb->URL ); + return stricmp((char *) ab->URL, (char *) bb->URL); } void URL_List::SortList() { - qsort( Links, urlcount, sizeof( Link_Info ), ListCompare ); + qsort(Links, urlcount, sizeof(Link_Info), ListCompare); } diff --git a/source/network/URL_List.h b/source/network/URL_List.h index 08cd2977..a78f579f 100644 --- a/source/network/URL_List.h +++ b/source/network/URL_List.h @@ -11,8 +11,8 @@ typedef struct { - char *URL; - bool direct; + char *URL; + bool direct; } Link_Info; class URL_List @@ -20,14 +20,14 @@ class URL_List public: //!Constructor //!\param url from where to get the list of links - URL_List( const char *url ); + URL_List(const char *url); //!Destructor ~URL_List(); //! Get the a filepath of the list //!\param list index - char * GetURL( int index ); + char * GetURL(int index); //! Is it a direct URL or just a file or path under the main url - bool IsDirectURL( int index ); + bool IsDirectURL(int index); //! Get the number of links counted int GetURLCount(); //! Sort list diff --git a/source/network/dns.c b/source/network/dns.c index dd3bbf5e..ab189f17 100644 --- a/source/network/dns.c +++ b/source/network/dns.c @@ -8,24 +8,22 @@ * @param char* The domain name to resolve * @return u32 The ipaddress represented by four bytes inside an u32 (in network order) */ -u32 getipbyname( char *domain ) +u32 getipbyname(char *domain) { //Care should be taken when using net_gethostbyname, //it returns a static buffer which makes it not threadsafe //TODO: implement some locking mechanism to make below code atomic - struct hostent *host = net_gethostbyname( domain ); + struct hostent *host = net_gethostbyname(domain); - if ( host == NULL ) + if (host == NULL) { return 0; } - u32 *ip = ( u32* )host->h_addr_list[0]; + u32 *ip = (u32*) host->h_addr_list[0]; return *ip; } - - //Defines how many DNS entries should be cached by getipbynamecached() #define MAX_DNS_CACHE_ENTRIES 20 @@ -37,7 +35,7 @@ struct dnsentry char *domain; u32 ip; struct dnsentry *nextnode; -} ; +}; static struct dnsentry *firstdnsentry = NULL; static int dnsentrycount = 0; @@ -46,22 +44,20 @@ static int dnsentrycount = 0; * Performs the same function as getipbyname(), * except that it will prevent extremely expensive net_gethostbyname() calls by caching the result */ -u32 getipbynamecached( char *domain ) +u32 getipbynamecached(char *domain) { //Search if this domainname is already cached struct dnsentry *node = firstdnsentry; struct dnsentry *previousnode = NULL; - while ( node != NULL ) + while (node != NULL) { - if ( strcmp( node->domain, domain ) == 0 ) + if (strcmp(node->domain, domain) == 0) { //DNS node found in the cache, move it to the front of the list - if ( previousnode != NULL ) - previousnode->nextnode = node->nextnode; + if (previousnode != NULL) previousnode->nextnode = node->nextnode; - if ( node != firstdnsentry ) - node->nextnode = firstdnsentry; + if (node != firstdnsentry) node->nextnode = firstdnsentry; firstdnsentry = node; return node->ip; @@ -70,47 +66,47 @@ u32 getipbynamecached( char *domain ) previousnode = node; node = node->nextnode; } - u32 ip = getipbyname( domain ); + u32 ip = getipbyname(domain); //No cache of this domain could be found, create a cache node and add it to the front of the cache - struct dnsentry *newnode = malloc( sizeof( struct dnsentry ) ); - if ( newnode == NULL ) + struct dnsentry *newnode = malloc(sizeof(struct dnsentry)); + if (newnode == NULL) { return ip; } newnode->ip = ip; - newnode->domain = malloc( strlen( domain ) + 1 ); - if ( newnode->domain == NULL ) + newnode->domain = malloc(strlen(domain) + 1); + if (newnode->domain == NULL) { - free( newnode ); + free(newnode); return ip; } - strcpy( newnode->domain, domain ); + strcpy(newnode->domain, domain); newnode->nextnode = firstdnsentry; firstdnsentry = newnode; dnsentrycount++; //If the cache grows too big delete the last (and probably least important) node of the list - if ( dnsentrycount > MAX_DNS_CACHE_ENTRIES ) + if (dnsentrycount > MAX_DNS_CACHE_ENTRIES) { struct dnsentry *node = firstdnsentry; struct dnsentry *previousnode = NULL; //Fetch the last two elements of the list - while ( node->nextnode != NULL ) + while (node->nextnode != NULL) { previousnode = node; node = node->nextnode; } - if ( node == NULL ) + if (node == NULL) { - printf( "Configuration error, MAX_DNS_ENTRIES reached while the list is empty\n" ); - exit( 1 ); + printf("Configuration error, MAX_DNS_ENTRIES reached while the list is empty\n"); + exit(1); } - else if ( previousnode == NULL ) + else if (previousnode == NULL) { firstdnsentry = NULL; } @@ -119,8 +115,8 @@ u32 getipbynamecached( char *domain ) previousnode->nextnode = NULL; } - free( node->domain ); - free( node ); + free(node->domain); + free(node); dnsentrycount--; } diff --git a/source/network/dns.h b/source/network/dns.h index 5e6dc9bf..f979550f 100644 --- a/source/network/dns.h +++ b/source/network/dns.h @@ -7,14 +7,13 @@ #include #include //usleep - #ifdef __cplusplus extern "C" { #endif - u32 getipbyname( char *domain ); - u32 getipbynamecached( char *domain ); + u32 getipbyname(char *domain); + u32 getipbynamecached(char *domain); #ifdef __cplusplus } diff --git a/source/network/http.c b/source/network/http.c index a107c9ce..b624ef7d 100644 --- a/source/network/http.c +++ b/source/network/http.c @@ -7,25 +7,25 @@ extern char incommingIP[50]; * Emptyblock is a statically defined variable for functions to return if they are unable * to complete a request */ -const struct block emptyblock = {0, NULL}; +const struct block emptyblock = { 0, NULL }; //The maximum amount of bytes to send per net_write() call //#define NET_BUFFER_SIZE 1024 #define NET_BUFFER_SIZE 3600 // Write our message to the server -static s32 send_message( s32 server, char *msg ) +static s32 send_message(s32 server, char *msg) { s32 bytes_transferred = 0; - s32 remaining = strlen( msg ); - while ( remaining ) + s32 remaining = strlen(msg); + while (remaining) { - if ( ( bytes_transferred = net_write( server, msg, remaining > NET_BUFFER_SIZE ? NET_BUFFER_SIZE : remaining ) ) > 0 ) + if ((bytes_transferred = net_write(server, msg, remaining > NET_BUFFER_SIZE ? NET_BUFFER_SIZE : remaining)) > 0) { remaining -= bytes_transferred; - usleep ( 20 * 1000 ); + usleep(20 * 1000); } - else if ( bytes_transferred < 0 ) + else if (bytes_transferred < 0) { return bytes_transferred; } @@ -44,24 +44,24 @@ static s32 send_message( s32 server, char *msg ) * @param u32 the port to connect to on the server * @return s32 The connection to the server (negative number if connection could not be established) */ -static s32 server_connect( u32 ipaddress, u32 socket_port ) +static s32 server_connect(u32 ipaddress, u32 socket_port) { //Initialize socket - s32 connection = net_socket( AF_INET, SOCK_STREAM, IPPROTO_IP ); - if ( connection < 0 ) return connection; + s32 connection = net_socket(AF_INET, SOCK_STREAM, IPPROTO_IP); + if (connection < 0) return connection; struct sockaddr_in connect_addr; - memset( &connect_addr, 0, sizeof( connect_addr ) ); + memset(&connect_addr, 0, sizeof(connect_addr)); connect_addr.sin_family = AF_INET; connect_addr.sin_port = socket_port; connect_addr.sin_addr.s_addr = ipaddress; - sprintf( incommingIP, "%s", inet_ntoa( connect_addr.sin_addr ) ); + sprintf(incommingIP, "%s", inet_ntoa(connect_addr.sin_addr)); //Attemt to open the socket - if ( net_connect( connection, ( struct sockaddr* )&connect_addr, sizeof( connect_addr ) ) == -1 ) + if (net_connect(connection, (struct sockaddr*) &connect_addr, sizeof(connect_addr)) == -1) { - net_close( connection ); + net_close(connection); return -1; } return connection; @@ -82,14 +82,14 @@ static s32 server_connect( u32 ipaddress, u32 socket_port ) * @param s32 connection The connection identifier to suck the response out of * @return block A 'block' struct (see http.h) in which the buffer is located */ -struct block read_message( s32 connection ) +struct block read_message(s32 connection) { //Create a block of memory to put in the response struct block buffer; - buffer.data = malloc( HTTP_BUFFER_SIZE ); + buffer.data = malloc(HTTP_BUFFER_SIZE); buffer.size = HTTP_BUFFER_SIZE; - if ( buffer.data == NULL ) + if (buffer.data == NULL) { return emptyblock; } @@ -97,14 +97,14 @@ struct block read_message( s32 connection ) //The offset variable always points to the first byte of memory that is free in the buffer u32 offset = 0; - while ( 1 ) + while (1) { //Fill the buffer with a new batch of bytes from the connection, //starting from where we left of in the buffer till the end of the buffer - s32 bytes_read = net_read( connection, buffer.data + offset, buffer.size - offset ); + s32 bytes_read = net_read(connection, buffer.data + offset, buffer.size - offset); //Anything below 0 is an error in the connection - if ( bytes_read < 0 ) + if (bytes_read < 0) { //printf("Connection error from net_read() Errorcode: %i\n", bytes_read); return emptyblock; @@ -112,7 +112,7 @@ struct block read_message( s32 connection ) //No more bytes were read into the buffer, //we assume this means the HTTP response is done - if ( bytes_read == 0 ) + if (bytes_read == 0) { break; } @@ -121,12 +121,12 @@ struct block read_message( s32 connection ) //Check if we have enough buffer left over, //if not expand it with an additional HTTP_BUFFER_GROWTH worth of bytes - if ( offset >= buffer.size ) + if (offset >= buffer.size) { buffer.size += HTTP_BUFFER_GROWTH; - buffer.data = realloc( buffer.data, buffer.size ); + buffer.data = realloc(buffer.data, buffer.size); - if ( buffer.data == NULL ) + if (buffer.data == NULL) { return emptyblock; } @@ -137,7 +137,7 @@ struct block read_message( s32 connection ) buffer.size = offset; //Shrink the size of the buffer so the data fits exactly in it - buffer.data = realloc( buffer.data, buffer.size ); + buffer.data = realloc(buffer.data, buffer.size); return buffer; } @@ -146,75 +146,73 @@ struct block read_message( s32 connection ) * Downloads the contents of a URL to memory * This method is not threadsafe (because networking is not threadsafe on the Wii) */ -struct block downloadfile( const char *url ) +struct block downloadfile(const char *url) { //Check if the url starts with "http://", if not it is not considered a valid url - if ( strncmp( url, "http://", strlen( "http://" ) ) != 0 ) + if (strncmp(url, "http://", strlen("http://")) != 0) { //printf("URL '%s' doesn't start with 'http://'\n", url); return emptyblock; } //Locate the path part of the url by searching for '/' past "http://" - char *path = strchr( url + strlen( "http://" ), '/' ); + char *path = strchr(url + strlen("http://"), '/'); //At the very least the url has to end with '/', ending with just a domain is invalid - if ( path == NULL ) + if (path == NULL) { //printf("URL '%s' has no PATH part\n", url); return emptyblock; } //Extract the domain part out of the url - int domainlength = path - url - strlen( "http://" ); + int domainlength = path - url - strlen("http://"); - if ( domainlength == 0 ) + if (domainlength == 0) { //printf("No domain part in URL '%s'\n", url); return emptyblock; } char domain[domainlength + 1]; - strlcpy( domain, url + strlen( "http://" ), domainlength + 1 ); + strlcpy(domain, url + strlen("http://"), domainlength + 1); //Parsing of the URL is done, start making an actual connection - u32 ipaddress = getipbynamecached( domain ); + u32 ipaddress = getipbynamecached(domain); - if ( ipaddress == 0 ) + if (ipaddress == 0) { //printf("\ndomain %s could not be resolved", domain); return emptyblock; } + s32 connection = server_connect(ipaddress, 80); - s32 connection = server_connect( ipaddress, 80 ); - - if ( connection < 0 ) + if (connection < 0) { //printf("Error establishing connection"); return emptyblock; } //Form a nice request header to send to the webserver - char* headerformat = "GET %s HTTP/1.0\r\nHost: %s\r\nReferer: %s\r\nUser-Agent: USBLoaderGX r%s\r\n\r\n";; - char header[strlen( headerformat ) + strlen( path ) + strlen( domain ) + strlen( domain )]; - sprintf( header, headerformat, path, domain, domain, GetRev() ); + char* headerformat = "GET %s HTTP/1.0\r\nHost: %s\r\nReferer: %s\r\nUser-Agent: USBLoaderGX r%s\r\n\r\n"; + ; + char header[strlen(headerformat) + strlen(path) + strlen(domain) + strlen(domain)]; + sprintf(header, headerformat, path, domain, domain, GetRev()); //Do the request and get the response - send_message( connection, header ); - struct block response = read_message( connection ); - net_close( connection ); + send_message(connection, header); + struct block response = read_message(connection); + net_close(connection); //Search for the 4-character sequence \r\n\r\n in the response which signals the start of the http payload (file) unsigned char *filestart = NULL; u32 filesize = 0; int i; - for ( i = 3; i < response.size; i++ ) + for (i = 3; i < response.size; i++) { - if ( response.data[i] == '\n' && - response.data[i-1] == '\r' && - response.data[i-2] == '\n' && - response.data[i-3] == '\r' ) + if (response.data[i] == '\n' && response.data[i - 1] == '\r' && response.data[i - 2] == '\n' && response.data[i + - 3] == '\r') { filestart = response.data + i + 1; filesize = response.size - i - 1; @@ -222,42 +220,42 @@ struct block downloadfile( const char *url ) } } - if ( filestart == NULL ) + if (filestart == NULL) { //printf("HTTP Response was without a file\n"); - free( response.data ); + free(response.data); return emptyblock; } //Copy the file part of the response into a new memoryblock to return struct block file; - file.data = malloc( filesize ); + file.data = malloc(filesize); file.size = filesize; - if ( file.data == NULL ) + if (file.data == NULL) { //printf("No more memory to copy file from HTTP response\n"); - free( response.data ); + free(response.data); return emptyblock; } - memcpy( file.data, filestart, filesize ); + memcpy(file.data, filestart, filesize); //Dispose of the original response - free( response.data ); + free(response.data); return file; } -s32 GetConnection( char * domain ) +s32 GetConnection(char * domain) { - u32 ipaddress = getipbynamecached( domain ); - if ( ipaddress == 0 ) + u32 ipaddress = getipbynamecached(domain); + if (ipaddress == 0) { return -1; } - s32 connection = server_connect( ipaddress, 80 ); + s32 connection = server_connect(ipaddress, 80); return connection; } diff --git a/source/network/http.h b/source/network/http.h index 6eb3f3de..1998b32a 100644 --- a/source/network/http.h +++ b/source/network/http.h @@ -18,14 +18,14 @@ extern "C" */ struct block { - u32 size; - unsigned char *data; + u32 size; + unsigned char *data; }; extern const struct block emptyblock; - struct block downloadfile( const char *url ); - s32 GetConnection( char * domain ); + struct block downloadfile(const char *url); + s32 GetConnection(char * domain); #ifdef __cplusplus } diff --git a/source/network/networkops.cpp b/source/network/networkops.cpp index 2c6433e6..23c9f991 100644 --- a/source/network/networkops.cpp +++ b/source/network/networkops.cpp @@ -43,16 +43,16 @@ static bool networkHalt = true; /**************************************************************************** * Initialize_Network ***************************************************************************/ -void Initialize_Network( void ) +void Initialize_Network(void) { - if ( networkinitialized ) return; + if (networkinitialized) return; s32 result; - result = if_config( IP, NULL, NULL, true ); + result = if_config(IP, NULL, NULL, true); - if ( result < 0 ) + if (result < 0) { networkinitialized = false; return; @@ -67,7 +67,7 @@ void Initialize_Network( void ) /**************************************************************************** * Check if network was initialised ***************************************************************************/ -bool IsNetworkInit( void ) +bool IsNetworkInit(void) { return networkinitialized; } @@ -75,7 +75,7 @@ bool IsNetworkInit( void ) /**************************************************************************** * Get network IP ***************************************************************************/ -char * GetNetworkIP( void ) +char * GetNetworkIP(void) { return IP; } @@ -83,7 +83,7 @@ char * GetNetworkIP( void ) /**************************************************************************** * Get incomming IP ***************************************************************************/ -char * GetIncommingIP( void ) +char * GetIncommingIP(void) { return incommingIP; } @@ -94,24 +94,23 @@ char * GetIncommingIP( void ) bool ShutdownWC24() { bool onlinefix = IsNetworkInit(); - if ( onlinefix ) + if (onlinefix) { s32 kd_fd, ret; STACK_ALIGN( u8, kd_buf, 0x20, 32 ); - kd_fd = IOS_Open( "/dev/net/kd/request", 0 ); - if ( kd_fd >= 0 ) + kd_fd = IOS_Open("/dev/net/kd/request", 0); + if (kd_fd >= 0) { - ret = IOS_Ioctl( kd_fd, 7, NULL, 0, kd_buf, 0x20 ); - if ( ret >= 0 ) - onlinefix = false; // fixed no IOS reload needed - IOS_Close( kd_fd ); + ret = IOS_Ioctl(kd_fd, 7, NULL, 0, kd_buf, 0x20); + if (ret >= 0) onlinefix = false; // fixed no IOS reload needed + IOS_Close(kd_fd); } } return onlinefix; } -s32 network_request( const char * request, char * filename ) +s32 network_request(const char * request, char * filename) { char buf[1024]; char *ptr = NULL; @@ -120,64 +119,58 @@ s32 network_request( const char * request, char * filename ) s32 ret; /* Send request */ - ret = net_send( connection, request, strlen( request ), 0 ); - if ( ret < 0 ) - return ret; + ret = net_send(connection, request, strlen(request), 0); + if (ret < 0) return ret; /* Clear buffer */ - memset( buf, 0, sizeof( buf ) ); + memset(buf, 0, sizeof(buf)); /* Read HTTP header */ - for ( cnt = 0; !strstr( buf, "\r\n\r\n" ); cnt++ ) - if ( net_recv( connection, buf + cnt, 1, 0 ) <= 0 ) - return -1; + for (cnt = 0; !strstr(buf, "\r\n\r\n"); cnt++) + if (net_recv(connection, buf + cnt, 1, 0) <= 0) return -1; /* HTTP request OK? */ - if ( !strstr( buf, "HTTP/1.1 200 OK" ) ) - return -1; + if (!strstr(buf, "HTTP/1.1 200 OK")) return -1; - if ( filename ) + if (filename) { /* Get filename */ - ptr = strstr( buf, "filename=\"" ); + ptr = strstr(buf, "filename=\""); - if ( ptr ) + if (ptr) { - ptr += sizeof( "filename=\"" ) - 1; + 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'; + filename[cnt + 1] = '\0'; } } } /* Retrieve content size */ - ptr = strstr( buf, "Content-Length:" ); - if ( !ptr ) - return -1; + ptr = strstr(buf, "Content-Length:"); + if (!ptr) return -1; - sscanf( ptr, "Content-Length: %u", &size ); + sscanf(ptr, "Content-Length: %u", &size); return size; } -s32 network_read( u8 *buf, u32 len ) +s32 network_read(u8 *buf, u32 len) { u32 read = 0; s32 ret = -1; /* Data to be read */ - while ( read < len ) + while (read < len) { /* Read network data */ - ret = net_read( connection, buf + read, len - read ); - if ( ret < 0 ) - return ret; + ret = net_read(connection, buf + read, len - read); + if (ret < 0) return ret; /* Read finished */ - if ( !ret ) - break; + if (!ret) break; /* Increment read variable */ read += ret; @@ -189,46 +182,46 @@ s32 network_read( u8 *buf, u32 len ) /**************************************************************************** * Download request ***************************************************************************/ -s32 download_request( const char * url, char * filename ) +s32 download_request(const char * url, char * filename) { //Check if the url starts with "http://", if not it is not considered a valid url - if ( strncmp( url, "http://", strlen( "http://" ) ) != 0 ) + if (strncmp(url, "http://", strlen("http://")) != 0) { return -1; } //Locate the path part of the url by searching for '/' past "http://" - char *path = strchr( url + strlen( "http://" ), '/' ); + char *path = strchr(url + strlen("http://"), '/'); //At the very least the url has to end with '/', ending with just a domain is invalid - if ( path == NULL ) + if (path == NULL) { return -1; } //Extract the domain part out of the url - int domainlength = path - url - strlen( "http://" ); + int domainlength = path - url - strlen("http://"); - if ( domainlength == 0 ) + if (domainlength == 0) { return -1; } char domain[domainlength + 1]; - strlcpy( domain, url + strlen( "http://" ), domainlength + 1 ); + strlcpy(domain, url + strlen("http://"), domainlength + 1); - connection = GetConnection( domain ); - if ( connection < 0 ) + connection = GetConnection(domain); + if (connection < 0) { return -1; } //Form a nice request header to send to the webserver - char header[strlen( path )+strlen( domain )+strlen( url )+100]; - sprintf( header, "GET %s HTTP/1.1\r\nHost: %s\r\nReferer: %s\r\nConnection: close\r\n\r\n", path, domain, url ); + char header[strlen(path) + strlen(domain) + strlen(url) + 100]; + sprintf(header, "GET %s HTTP/1.1\r\nHost: %s\r\nReferer: %s\r\nConnection: close\r\n\r\n", path, domain, url); - s32 filesize = network_request( header, filename ); + s32 filesize = network_request(header, filename); return filesize; } @@ -236,11 +229,11 @@ s32 download_request( const char * url, char * filename ) void CloseConnection() { - net_close( connection ); + net_close(connection); - if ( waitforanswer ) + if (waitforanswer) { - net_close( socket ); + net_close(socket); waitforanswer = false; } } @@ -251,17 +244,16 @@ void CloseConnection() int NetworkWait() { - if ( !checkincomming ) - return -3; + if (!checkincomming) return -3; struct sockaddr_in sin; struct sockaddr_in client_address; - socklen_t addrlen = sizeof( client_address ); + socklen_t addrlen = sizeof(client_address); //Open socket - socket = net_socket( AF_INET, SOCK_STREAM, IPPROTO_IP ); + socket = net_socket(AF_INET, SOCK_STREAM, IPPROTO_IP); - if ( socket == INVALID_SOCKET ) + if (socket == INVALID_SOCKET) { return socket; } @@ -270,26 +262,26 @@ int NetworkWait() sin.sin_port = htons( PORT ); sin.sin_addr.s_addr = htonl( INADDR_ANY ); - if ( net_bind( socket, ( struct sockaddr* )&sin, sizeof( sin ) ) < 0 ) + if (net_bind(socket, (struct sockaddr*) &sin, sizeof(sin)) < 0) { - net_close( socket ); + net_close(socket); return -1; } - if ( net_listen( socket, 3 ) < 0 ) + if (net_listen(socket, 3) < 0) { - net_close( socket ); + net_close(socket); return -1; } - connection = net_accept( socket, ( struct sockaddr* ) & client_address, &addrlen ); + connection = net_accept(socket, (struct sockaddr*) &client_address, &addrlen); - sprintf( incommingIP, "%s", inet_ntoa( client_address.sin_addr ) ); + sprintf(incommingIP, "%s", inet_ntoa(client_address.sin_addr)); - if ( connection < 0 ) + if (connection < 0) { - net_close( connection ); - net_close( socket ); + net_close(connection); + net_close(socket); return -4; } @@ -298,15 +290,15 @@ int NetworkWait() unsigned char haxx[9]; //skip haxx - net_read( connection, &haxx, 8 ); + net_read(connection, &haxx, 8); wiiloadVersion[0] = haxx[4]; wiiloadVersion[1] = haxx[5]; - net_read( connection, &infilesize, 4 ); + net_read(connection, &infilesize, 4); - if ( haxx[4] > 0 || haxx[5] > 4 ) + if (haxx[4] > 0 || haxx[5] > 4) { - net_read( connection, &uncfilesize, 4 ); // Compressed protocol, read another 4 bytes + net_read(connection, &uncfilesize, 4); // Compressed protocol, read another 4 bytes } waitforanswer = true; checkincomming = false; @@ -321,13 +313,12 @@ int NetworkWait() ***************************************************************************/ int CheckUpdate() { - if ( !networkinitialized ) - return -1; + if (!networkinitialized) return -1; int revnumber = 0; - int currentrev = atoi( GetRev() ); + int currentrev = atoi(GetRev()); - if ( Settings.beta_upgrades ) + if (Settings.beta_upgrades) { revnumber = CheckForBetaUpdate(); } @@ -336,25 +327,24 @@ int CheckUpdate() #ifdef FULLCHANNEL 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]; - u8 i; - if ( file.data != NULL ) + u8 i; + if (file.data != NULL) { - for ( i = 0; i < 9 || i < file.size; i++ ) + for (i = 0; i < 9 || i < file.size; i++) revtxt[i] = file.data[i]; revtxt[i] = 0; - revnumber = atoi( revtxt ); - free( file.data ); + revnumber = atoi(revtxt); + free(file.data); } } - if ( revnumber > currentrev ) + if (revnumber > currentrev) return revnumber; - else - return -1; + else return -1; } /**************************************************************************** @@ -365,12 +355,11 @@ void HaltNetworkThread() networkHalt = true; checkincomming = false; - if ( waitforanswer ) - CloseConnection(); + if (waitforanswer) CloseConnection(); // wait for thread to finish - while ( !LWP_ThreadIsSuspended( networkthread ) ) - usleep( 100 ); + while (!LWP_ThreadIsSuspended(networkthread)) + usleep(100); } /**************************************************************************** @@ -379,7 +368,7 @@ void HaltNetworkThread() void ResumeNetworkThread() { networkHalt = false; - LWP_ResumeThread( networkthread ); + LWP_ResumeThread(networkthread); } /**************************************************************************** @@ -392,27 +381,25 @@ void ResumeNetworkWait() waitforanswer = true; infilesize = 0; connection = -1; - LWP_ResumeThread( networkthread ); + LWP_ResumeThread(networkthread); } /********************************************************************************* * Networkthread for background network initialize and update check with idle prio *********************************************************************************/ -static void * networkinitcallback( void *arg ) +static void * networkinitcallback(void *arg) { - while ( 1 ) + while (1) { - if ( !checkincomming && networkHalt ) - LWP_SuspendThread( networkthread ); + if (!checkincomming && networkHalt) LWP_SuspendThread(networkthread); Initialize_Network(); - if ( networkinitialized == true && updatechecked == false ) + if (networkinitialized == true && updatechecked == false) { - if ( CheckUpdate() > 0 ) - updateavailable = true; + if (CheckUpdate() > 0) updateavailable = true; //suspend thread updatechecked = true; @@ -420,8 +407,7 @@ static void * networkinitcallback( void *arg ) checkincomming = false; } - if ( checkincomming ) - NetworkWait(); + if (checkincomming) NetworkWait(); } return NULL; } @@ -431,7 +417,7 @@ static void * networkinitcallback( void *arg ) ***************************************************************************/ void InitNetworkThread() { - LWP_CreateThread ( &networkthread, networkinitcallback, NULL, NULL, 16384, 0 ); + LWP_CreateThread(&networkthread, networkinitcallback, NULL, NULL, 16384, 0); } /**************************************************************************** @@ -439,6 +425,6 @@ void InitNetworkThread() ***************************************************************************/ void ShutdownNetworkThread() { - LWP_JoinThread ( networkthread, NULL ); + LWP_JoinThread(networkthread, NULL); networkthread = LWP_THREAD_NULL; } diff --git a/source/network/networkops.h b/source/network/networkops.h index b71387f6..7d36e8a7 100644 --- a/source/network/networkops.h +++ b/source/network/networkops.h @@ -9,15 +9,14 @@ #define _NETWORKOPS_H_ #define NETWORKBLOCKSIZE 5*1024 //5KB - -void Initialize_Network( void ); -bool IsNetworkInit( void ); -char * GetNetworkIP( void ); -char * GetIncommingIP( void ); +void Initialize_Network(void); +bool IsNetworkInit(void); +char * GetNetworkIP(void); +char * GetIncommingIP(void); bool ShutdownWC24(); -s32 network_request( const char * request, char * filename ); -s32 network_read( u8 *buf, u32 len ); -s32 download_request( const char * url, char * filename = NULL ); +s32 network_request(const char * request, char * filename); +s32 network_read(u8 *buf, u32 len); +s32 download_request(const char * url, char * filename = NULL); void CloseConnection(); int CheckUpdate(); diff --git a/source/network/update.cpp b/source/network/update.cpp index 7edefeb9..9ddb23d3 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 @@ -41,39 +41,38 @@ int CheckForBetaUpdate() { int revnumber = 0; - HTML_Stream HTML( "http://code.google.com/p/usbloader-gui/downloads/list" ); + HTML_Stream HTML("http://code.google.com/p/usbloader-gui/downloads/list"); const char * HTML_Pos = NULL; do { - HTML_Pos = HTML.FindStringEnd( "href='" ); - char * tmpLink = HTML.CopyString( "'\"" ); - if ( tmpLink ) + HTML_Pos = HTML.FindStringEnd("href='"); + char * tmpLink = HTML.CopyString("'\""); + if (tmpLink) { - char *fileext = strrchr( tmpLink, '.' ); - if ( fileext ) + char *fileext = strrchr(tmpLink, '.'); + if (fileext) { - if ( strcasecmp( fileext, ".dol" ) == 0 ) + if (strcasecmp(fileext, ".dol") == 0) { char revtxt[80]; - char *filename = strrchr( tmpLink, '/' ) + 2; + char *filename = strrchr(tmpLink, '/') + 2; u8 n = 0; - for ( n = 0; n < strlen( filename ) - 2; n++ ) + for (n = 0; n < strlen(filename) - 2; n++) revtxt[n] = filename[n]; revtxt[n] = 0; - int fileRev = atoi( revtxt ); + int fileRev = atoi(revtxt); - if ( fileRev > revnumber ) + if (fileRev > revnumber) { revnumber = fileRev; } } } - free( tmpLink ); + free(tmpLink); } - } - while ( HTML_Pos != NULL ); + } while (HTML_Pos != NULL); return revnumber; } diff --git a/source/network/update.h b/source/network/update.h index 5ab60317..68c67c01 100644 --- a/source/network/update.h +++ b/source/network/update.h @@ -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.h -* -* 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.h + * + * Update operations + * for Wii-Xplorer 2009 + ***************************************************************************/ #ifndef _UPDATEOPS_H_ #define _UPDATEOPS_H_ diff --git a/source/patches/codehandler.h b/source/patches/codehandler.h index 73715fd2..7cf81098 100644 --- a/source/patches/codehandler.h +++ b/source/patches/codehandler.h @@ -1,278 +1,247 @@ /* - This file was autogenerated by raw2c. -Visit http://www.devkitpro.org -*/ + This file was autogenerated by raw2c. + Visit http://www.devkitpro.org + */ -const unsigned char codehandler[] = -{ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x27, 0x74, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 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, 0x55, 0x3a, 0xa0, 0x00, 0x00, 0x3a, 0xc0, 0x00, 0x19, 0x3a, 0xe0, 0x00, 0xd0, - 0x3f, 0x00, 0xcd, 0x00, 0x63, 0xf2, 0x27, 0x74, 0x80, 0x01, 0x00, 0xac, 0x90, 0x12, 0x00, 0x04, - 0x92, 0xb8, 0x64, 0x3c, 0x48, 0x00, 0x04, 0x2d, 0x41, 0x82, 0x05, 0xa4, 0x2c, 0x1d, 0x00, 0x04, - 0x40, 0x80, 0x00, 0x10, 0x2c, 0x1d, 0x00, 0x01, 0x41, 0x80, 0x05, 0x94, 0x48, 0x00, 0x03, 0x4c, - 0x41, 0x82, 0x04, 0xf0, 0x2c, 0x1d, 0x00, 0x06, 0x41, 0x82, 0x00, 0x8c, 0x2c, 0x1d, 0x00, 0x07, - 0x41, 0x82, 0x03, 0x30, 0x2c, 0x1d, 0x00, 0x08, 0x41, 0x82, 0x05, 0x80, 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, 0x28, 0x2c, 0x1d, 0x00, 0x40, 0x41, 0x82, 0x03, 0x40, 0x2c, 0x1d, 0x00, 0x41, - 0x41, 0x82, 0x03, 0x58, 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, 0x0c, 0x48, 0x00, 0x05, 0x10, - 0x80, 0x72, 0x00, 0x00, 0x48, 0x00, 0x04, 0x29, 0x48, 0x00, 0x05, 0x04, 0x48, 0x00, 0x05, 0x89, - 0x48, 0x00, 0x04, 0xfc, 0x38, 0x80, 0x00, 0x01, 0x90, 0x92, 0x00, 0x00, 0x48, 0x00, 0x04, 0xf0, - 0x48, 0x00, 0x04, 0x09, 0x3a, 0x00, 0x00, 0xa0, 0x63, 0xec, 0x27, 0x98, 0x48, 0x00, 0x03, 0x14, - 0x38, 0x60, 0x01, 0x20, 0x63, 0xec, 0x27, 0x98, 0x48, 0x00, 0x03, 0xc9, 0x48, 0x00, 0x04, 0xd0, - 0x2f, 0x1d, 0x00, 0x10, 0x2e, 0x9d, 0x00, 0x44, 0x63, 0xe4, 0x1a, 0xb4, 0x3c, 0x60, 0x80, 0x00, - 0x60, 0x63, 0x03, 0x00, 0x48, 0x00, 0x05, 0x09, 0x38, 0x63, 0x0a, 0x00, 0x48, 0x00, 0x05, 0x01, - 0x38, 0x63, 0x06, 0x00, 0x48, 0x00, 0x04, 0xf9, 0x63, 0xec, 0x27, 0x88, 0x92, 0xac, 0x00, 0x00, - 0x92, 0xac, 0x00, 0x04, 0x92, 0xac, 0x00, 0x08, 0x63, 0xe4, 0x27, 0x98, 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, 0x14, - 0x55, 0x29, 0x05, 0xa8, 0x91, 0x24, 0x00, 0x18, 0x41, 0x96, 0x04, 0x54, 0x41, 0x9a, 0x00, 0x08, - 0x39, 0x8c, 0x00, 0x04, 0x38, 0x60, 0x00, 0x04, 0x48, 0x00, 0x03, 0x09, 0x40, 0x99, 0x00, 0x10, - 0x39, 0x8c, 0x00, 0x04, 0x38, 0x60, 0x00, 0x04, 0x48, 0x00, 0x02, 0xf9, 0x63, 0xe4, 0x27, 0x88, - 0x80, 0x64, 0x00, 0x00, 0x80, 0x84, 0x00, 0x04, 0x7c, 0x72, 0xfb, 0xa6, 0x7c, 0x95, 0xfb, 0xa6, - 0x48, 0x00, 0x04, 0x1c, 0x7c, 0x32, 0x43, 0xa6, 0x7c, 0x3a, 0x02, 0xa6, 0x7c, 0x73, 0x43, 0xa6, - 0x7c, 0x7b, 0x02, 0xa6, 0x54, 0x63, 0x05, 0xa8, 0x90, 0x60, 0x27, 0xb0, 0x54, 0x63, 0x06, 0x1e, - 0x60, 0x63, 0x20, 0x00, 0x7c, 0x7b, 0x03, 0xa6, 0x3c, 0x60, 0x80, 0x00, 0x60, 0x63, 0x1a, 0xe8, - 0x7c, 0x7a, 0x03, 0xa6, 0x4c, 0x00, 0x00, 0x64, 0x3c, 0x60, 0x80, 0x00, 0x60, 0x63, 0x27, 0x98, - 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, 0x3c, 0xa0, 0x80, 0x00, - 0x60, 0xa5, 0x1b, 0x70, 0x3f, 0xe0, 0xd0, 0x04, 0x63, 0xff, 0x00, 0xa0, 0x93, 0xe5, 0x00, 0x00, - 0x7c, 0x00, 0x28, 0x6c, 0x7c, 0x00, 0x04, 0xac, 0x7c, 0x00, 0x2f, 0xac, 0x4c, 0x00, 0x01, 0x2c, - 0xd0, 0x04, 0x00, 0xa0, 0x3b, 0xff, 0x00, 0x04, 0x3f, 0xff, 0x00, 0x20, 0x57, 0xf0, 0x01, 0x4b, - 0x41, 0x82, 0xff, 0xdc, 0x3f, 0xe0, 0x80, 0x00, 0x63, 0xe5, 0x27, 0x88, 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, 0x27, 0x74, 0x90, 0xa4, 0x00, 0x00, - 0x38, 0x60, 0x00, 0x11, 0x48, 0x00, 0x01, 0xb9, 0x4b, 0xff, 0xfc, 0x71, 0x7c, 0x20, 0x00, 0xa6, - 0x54, 0x21, 0x07, 0xfa, 0x54, 0x21, 0x04, 0x5e, 0x7c, 0x20, 0x01, 0x24, 0x63, 0xe1, 0x27, 0x98, - 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, 0x00, 0x64, - 0x92, 0xb2, 0x00, 0x00, 0x48, 0x00, 0x02, 0x54, 0x2e, 0x9d, 0x00, 0x02, 0x38, 0x60, 0x00, 0x08, - 0x63, 0xec, 0x27, 0x7c, 0x48, 0x00, 0x00, 0xfd, 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, 0x08, 0x48, 0x00, 0x01, 0x21, 0x38, 0x60, 0x00, 0x04, - 0x63, 0xec, 0x27, 0x7c, 0x48, 0x00, 0x00, 0xbd, 0x82, 0x0c, 0x00, 0x00, 0x3d, 0x80, 0x80, 0x00, - 0x61, 0x8c, 0x28, 0xb8, 0x48, 0x00, 0x00, 0x1c, 0x48, 0x00, 0x01, 0x01, 0x38, 0x60, 0x00, 0x08, - 0x63, 0xec, 0x27, 0x7c, 0x48, 0x00, 0x00, 0x9d, 0x82, 0x0c, 0x00, 0x04, 0x81, 0x8c, 0x00, 0x00, - 0x63, 0xfb, 0x27, 0x84, 0x3a, 0x20, 0x0f, 0x80, 0x48, 0x00, 0x02, 0x39, 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, 0x27, 0x7c, 0x4b, 0xff, 0xff, 0x55, - 0x80, 0xac, 0x00, 0x04, 0x81, 0x8c, 0x00, 0x00, 0x63, 0xfb, 0x27, 0x84, 0x62, 0xb1, 0xf8, 0x00, - 0x7e, 0x0c, 0x28, 0x50, 0x48, 0x00, 0x00, 0xed, 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, 0x27, 0x98, 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, 0xfa, 0x50, 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, 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, 0x3d, 0xe0, 0x80, 0x00, 0x61, 0xef, 0x28, 0xb8, - 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, 0xac, - 0x41, 0x82, 0x02, 0x50, 0x2c, 0x0a, 0x00, 0x05, 0x41, 0x80, 0x02, 0xd4, 0x41, 0xa2, 0x04, 0xe0, - 0x2c, 0x0a, 0x00, 0x07, 0x41, 0xa0, 0x05, 0x0c, 0x48, 0x00, 0x05, 0xf0, 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, 0xc8, 0x35, 0x29, 0xff, 0xff, 0x41, 0x80, 0x04, 0xc0, 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, 0x51, 0x08, 0x08, 0x3c, 0x40, 0x9e, 0x00, 0x78, 0x41, 0x8d, 0x04, 0xb8, - 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, 0x40, 0x41, 0x94, 0xfe, 0x3c, 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, 0x0c, 0x40, 0xbe, 0xfe, 0x08, 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, 0x80, 0x7e, 0x0c, 0x21, 0x2e, 0x4b, 0xff, 0xfd, 0x78, 0x40, 0x90, 0x00, 0x0c, - 0x7c, 0x86, 0x23, 0x78, 0x4b, 0xff, 0xfd, 0x6c, 0x7c, 0x90, 0x23, 0x78, 0x4b, 0xff, 0xfd, 0x64, - 0x54, 0x89, 0x1e, 0x78, 0x39, 0x29, 0x00, 0x40, 0x2c, 0x05, 0x00, 0x02, 0x41, 0x80, 0x00, 0x48, - 0x54, 0x6b, 0x50, 0x03, 0x41, 0x82, 0x00, 0x14, 0x41, 0x81, 0x00, 0x08, 0x48, 0x00, 0x00, 0x10, - 0x41, 0xbe, 0xfd, 0x40, 0x48, 0x00, 0x00, 0x08, 0x40, 0xbe, 0xfd, 0x38, 0x2c, 0x05, 0x00, 0x03, - 0x41, 0x81, 0x00, 0x10, 0x41, 0xa2, 0x00, 0x10, 0x7d, 0xe7, 0x48, 0x2e, 0x4b, 0xff, 0xfd, 0x24, - 0x7d, 0xe7, 0x49, 0x2e, 0x7c, 0x64, 0x07, 0x34, 0x54, 0x84, 0x1a, 0x78, 0x7d, 0xef, 0x22, 0x14, - 0x4b, 0xff, 0xfd, 0x10, 0x40, 0xbe, 0xfd, 0x0c, 0x7c, 0xa7, 0x4a, 0x14, 0x40, 0x92, 0x00, 0x14, - 0x54, 0x64, 0x04, 0x3e, 0x91, 0xe5, 0x00, 0x00, 0x90, 0x85, 0x00, 0x04, 0x4b, 0xff, 0xfc, 0xf4, - 0x81, 0x25, 0x00, 0x04, 0x2c, 0x09, 0x00, 0x00, 0x41, 0xa2, 0xfc, 0xe8, 0x39, 0x29, 0xff, 0xff, - 0x91, 0x25, 0x00, 0x04, 0x81, 0xe5, 0x00, 0x00, 0x4b, 0xff, 0xfc, 0xd8, 0x40, 0xbe, 0xfc, 0xd4, - 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, 0x40, 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, 0x8c, 0x2c, 0x05, 0x00, 0x0a, 0x41, 0x81, 0xfb, 0x84, - 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, 0x64, - 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, 0x44, - 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, 0x1c, 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, 0xc4, 0x54, 0x6b, 0xe4, 0x3e, 0x4b, 0xff, 0xfb, 0xbc, - 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, 0x6c, 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, 0x50, 0x57, 0x44, 0x00, 0x3a, 0x7c, 0x8c, 0x20, 0x50, 0x50, 0x85, 0x01, 0xba, - 0x50, 0x65, 0x07, 0xfe, 0x90, 0xac, 0x00, 0x00, 0x4b, 0xff, 0xfa, 0x38, 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, 0x28, 0x55, 0x8c, 0x84, 0x3e, 0x57, 0x44, 0x84, 0x3e, 0x57, 0x5a, 0x04, 0x3e, - 0x7c, 0x0c, 0x20, 0x00, 0x41, 0x80, 0xfb, 0xa8, 0x7c, 0x0c, 0xd0, 0x00, 0x40, 0x80, 0xfb, 0xa0, - 0x4b, 0xff, 0xf9, 0xe0, 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, 0xac, 0x2c, 0x0b, 0x00, 0x00, 0x41, 0x82, 0x01, 0x38, - 0x2c, 0x05, 0x00, 0x01, 0x41, 0x82, 0x00, 0x18, 0x2c, 0x05, 0x00, 0x02, 0x41, 0x82, 0x00, 0x14, - 0x2c, 0x05, 0x00, 0x03, 0x41, 0x82, 0x00, 0x70, 0x4b, 0xff, 0xf9, 0x80, 0x54, 0xcc, 0x00, 0x0c, - 0x54, 0x97, 0x46, 0x3e, 0x54, 0x98, 0xc4, 0x3e, 0x54, 0x84, 0x06, 0x3e, 0x40, 0x9e, 0x00, 0xfc, - 0x56, 0xf9, 0x06, 0x31, 0x7d, 0x9a, 0x63, 0x78, 0x7f, 0x43, 0xd2, 0x14, 0x57, 0x5a, 0x00, 0x3a, - 0x41, 0x82, 0x00, 0x18, 0x7e, 0xf7, 0x07, 0x74, 0x7e, 0xf7, 0x00, 0xd0, 0x1f, 0x37, 0x00, 0x02, - 0x3b, 0x39, 0x00, 0x04, 0x7f, 0x59, 0xd0, 0x50, 0x2c, 0x17, 0x00, 0x00, 0x41, 0x82, 0x00, 0x1c, - 0x3b, 0x20, 0x00, 0x00, 0x7e, 0xe9, 0x03, 0xa6, 0xa3, 0x7a, 0x00, 0x04, 0x7f, 0x79, 0xca, 0x78, - 0x3b, 0x5a, 0x00, 0x02, 0x42, 0x00, 0xff, 0xf4, 0x7c, 0x18, 0xc8, 0x00, 0x40, 0x82, 0x00, 0xac, - 0x4b, 0xff, 0xfe, 0x90, 0x51, 0x08, 0x08, 0x3c, 0x40, 0x9e, 0x00, 0x9c, 0x54, 0x77, 0xb0, 0x03, - 0x41, 0x81, 0x00, 0x88, 0x41, 0x80, 0x00, 0x8c, 0x54, 0x7e, 0x06, 0x3e, 0x1f, 0xde, 0x00, 0x02, - 0x54, 0x97, 0x00, 0x1e, 0x6e, 0xf8, 0x80, 0x00, 0x2c, 0x18, 0x00, 0x00, 0x40, 0x82, 0x00, 0x08, - 0x62, 0xf7, 0x30, 0x00, 0x54, 0x98, 0x80, 0x1e, 0x1f, 0x3e, 0x00, 0x04, 0x7f, 0x19, 0xc0, 0x50, - 0x3b, 0x20, 0x00, 0x00, 0x1f, 0x59, 0x00, 0x04, 0x7f, 0x6f, 0xd0, 0x2e, 0x7f, 0x57, 0xd0, 0x2e, - 0x3b, 0x39, 0x00, 0x01, 0x7c, 0x17, 0xc0, 0x40, 0x41, 0x81, 0x00, 0x34, 0x7c, 0x19, 0xf0, 0x00, - 0x41, 0x81, 0x00, 0x14, 0x7c, 0x1a, 0xd8, 0x00, 0x41, 0x82, 0xff, 0xdc, 0x3a, 0xf7, 0x00, 0x04, - 0x4b, 0xff, 0xff, 0xd0, 0x80, 0x6f, 0xff, 0xf8, 0x60, 0x63, 0x03, 0x00, 0x90, 0x6f, 0xff, 0xf8, - 0x92, 0xef, 0xff, 0xfc, 0x7e, 0xf0, 0xbb, 0x78, 0x48, 0x00, 0x00, 0x1c, 0x80, 0x6f, 0xff, 0xf8, - 0x60, 0x63, 0x01, 0x00, 0x90, 0x6f, 0xff, 0xf8, 0x61, 0x08, 0x00, 0x01, 0x48, 0x00, 0x00, 0x08, - 0x7c, 0x90, 0x23, 0x78, 0x54, 0x64, 0x06, 0x3e, 0x1c, 0x84, 0x00, 0x08, 0x7d, 0xe4, 0x7a, 0x14, - 0x4b, 0xff, 0xf8, 0x70, 0x40, 0x92, 0x00, 0x0c, 0x39, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x14, - 0x54, 0x69, 0x06, 0xff, 0x54, 0x65, 0x67, 0xfe, 0x7d, 0x08, 0x4c, 0x30, 0x55, 0x17, 0xff, 0xff, - 0x40, 0x82, 0x00, 0x08, 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, 0xf8, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +const unsigned char codehandler[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x27, 0x74, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 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, 0x55, 0x3a, 0xa0, 0x00, 0x00, 0x3a, + 0xc0, 0x00, 0x19, 0x3a, 0xe0, 0x00, 0xd0, 0x3f, 0x00, 0xcd, 0x00, 0x63, 0xf2, 0x27, 0x74, 0x80, 0x01, 0x00, + 0xac, 0x90, 0x12, 0x00, 0x04, 0x92, 0xb8, 0x64, 0x3c, 0x48, 0x00, 0x04, 0x2d, 0x41, 0x82, 0x05, 0xa4, 0x2c, + 0x1d, 0x00, 0x04, 0x40, 0x80, 0x00, 0x10, 0x2c, 0x1d, 0x00, 0x01, 0x41, 0x80, 0x05, 0x94, 0x48, 0x00, 0x03, + 0x4c, 0x41, 0x82, 0x04, 0xf0, 0x2c, 0x1d, 0x00, 0x06, 0x41, 0x82, 0x00, 0x8c, 0x2c, 0x1d, 0x00, 0x07, 0x41, + 0x82, 0x03, 0x30, 0x2c, 0x1d, 0x00, 0x08, 0x41, 0x82, 0x05, 0x80, 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, 0x28, 0x2c, 0x1d, 0x00, + 0x40, 0x41, 0x82, 0x03, 0x40, 0x2c, 0x1d, 0x00, 0x41, 0x41, 0x82, 0x03, 0x58, 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, 0x0c, 0x48, + 0x00, 0x05, 0x10, 0x80, 0x72, 0x00, 0x00, 0x48, 0x00, 0x04, 0x29, 0x48, 0x00, 0x05, 0x04, 0x48, 0x00, 0x05, + 0x89, 0x48, 0x00, 0x04, 0xfc, 0x38, 0x80, 0x00, 0x01, 0x90, 0x92, 0x00, 0x00, 0x48, 0x00, 0x04, 0xf0, 0x48, + 0x00, 0x04, 0x09, 0x3a, 0x00, 0x00, 0xa0, 0x63, 0xec, 0x27, 0x98, 0x48, 0x00, 0x03, 0x14, 0x38, 0x60, 0x01, + 0x20, 0x63, 0xec, 0x27, 0x98, 0x48, 0x00, 0x03, 0xc9, 0x48, 0x00, 0x04, 0xd0, 0x2f, 0x1d, 0x00, 0x10, 0x2e, + 0x9d, 0x00, 0x44, 0x63, 0xe4, 0x1a, 0xb4, 0x3c, 0x60, 0x80, 0x00, 0x60, 0x63, 0x03, 0x00, 0x48, 0x00, 0x05, + 0x09, 0x38, 0x63, 0x0a, 0x00, 0x48, 0x00, 0x05, 0x01, 0x38, 0x63, 0x06, 0x00, 0x48, 0x00, 0x04, 0xf9, 0x63, + 0xec, 0x27, 0x88, 0x92, 0xac, 0x00, 0x00, 0x92, 0xac, 0x00, 0x04, 0x92, 0xac, 0x00, 0x08, 0x63, 0xe4, 0x27, + 0x98, 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, 0x14, 0x55, + 0x29, 0x05, 0xa8, 0x91, 0x24, 0x00, 0x18, 0x41, 0x96, 0x04, 0x54, 0x41, 0x9a, 0x00, 0x08, 0x39, 0x8c, 0x00, + 0x04, 0x38, 0x60, 0x00, 0x04, 0x48, 0x00, 0x03, 0x09, 0x40, 0x99, 0x00, 0x10, 0x39, 0x8c, 0x00, 0x04, 0x38, + 0x60, 0x00, 0x04, 0x48, 0x00, 0x02, 0xf9, 0x63, 0xe4, 0x27, 0x88, 0x80, 0x64, 0x00, 0x00, 0x80, 0x84, 0x00, + 0x04, 0x7c, 0x72, 0xfb, 0xa6, 0x7c, 0x95, 0xfb, 0xa6, 0x48, 0x00, 0x04, 0x1c, 0x7c, 0x32, 0x43, 0xa6, 0x7c, + 0x3a, 0x02, 0xa6, 0x7c, 0x73, 0x43, 0xa6, 0x7c, 0x7b, 0x02, 0xa6, 0x54, 0x63, 0x05, 0xa8, 0x90, 0x60, 0x27, + 0xb0, 0x54, 0x63, 0x06, 0x1e, 0x60, 0x63, 0x20, 0x00, 0x7c, 0x7b, 0x03, 0xa6, 0x3c, 0x60, 0x80, 0x00, 0x60, + 0x63, 0x1a, 0xe8, 0x7c, 0x7a, 0x03, 0xa6, 0x4c, 0x00, 0x00, 0x64, 0x3c, 0x60, 0x80, 0x00, 0x60, 0x63, 0x27, + 0x98, 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, 0x3c, 0xa0, 0x80, 0x00, 0x60, 0xa5, 0x1b, 0x70, 0x3f, 0xe0, 0xd0, 0x04, 0x63, 0xff, 0x00, + 0xa0, 0x93, 0xe5, 0x00, 0x00, 0x7c, 0x00, 0x28, 0x6c, 0x7c, 0x00, 0x04, 0xac, 0x7c, 0x00, 0x2f, 0xac, 0x4c, + 0x00, 0x01, 0x2c, 0xd0, 0x04, 0x00, 0xa0, 0x3b, 0xff, 0x00, 0x04, 0x3f, 0xff, 0x00, 0x20, 0x57, 0xf0, 0x01, + 0x4b, 0x41, 0x82, 0xff, 0xdc, 0x3f, 0xe0, 0x80, 0x00, 0x63, 0xe5, 0x27, 0x88, 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, 0x27, 0x74, 0x90, 0xa4, 0x00, 0x00, 0x38, 0x60, 0x00, + 0x11, 0x48, 0x00, 0x01, 0xb9, 0x4b, 0xff, 0xfc, 0x71, 0x7c, 0x20, 0x00, 0xa6, 0x54, 0x21, 0x07, 0xfa, 0x54, + 0x21, 0x04, 0x5e, 0x7c, 0x20, 0x01, 0x24, 0x63, 0xe1, 0x27, 0x98, 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, 0x00, 0x64, 0x92, 0xb2, 0x00, 0x00, 0x48, 0x00, 0x02, 0x54, 0x2e, 0x9d, 0x00, 0x02, 0x38, + 0x60, 0x00, 0x08, 0x63, 0xec, 0x27, 0x7c, 0x48, 0x00, 0x00, 0xfd, 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, 0x08, 0x48, 0x00, 0x01, 0x21, 0x38, 0x60, 0x00, 0x04, 0x63, 0xec, 0x27, 0x7c, 0x48, + 0x00, 0x00, 0xbd, 0x82, 0x0c, 0x00, 0x00, 0x3d, 0x80, 0x80, 0x00, 0x61, 0x8c, 0x28, 0xb8, 0x48, 0x00, 0x00, + 0x1c, 0x48, 0x00, 0x01, 0x01, 0x38, 0x60, 0x00, 0x08, 0x63, 0xec, 0x27, 0x7c, 0x48, 0x00, 0x00, 0x9d, 0x82, + 0x0c, 0x00, 0x04, 0x81, 0x8c, 0x00, 0x00, 0x63, 0xfb, 0x27, 0x84, 0x3a, 0x20, 0x0f, 0x80, 0x48, 0x00, 0x02, + 0x39, 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, 0x27, 0x7c, 0x4b, + 0xff, 0xff, 0x55, 0x80, 0xac, 0x00, 0x04, 0x81, 0x8c, 0x00, 0x00, 0x63, 0xfb, 0x27, 0x84, 0x62, 0xb1, 0xf8, + 0x00, 0x7e, 0x0c, 0x28, 0x50, 0x48, 0x00, 0x00, 0xed, 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, 0x27, 0x98, 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, 0xfa, 0x50, 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, 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, 0x3d, 0xe0, 0x80, 0x00, 0x61, + 0xef, 0x28, 0xb8, 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, 0xac, 0x41, 0x82, 0x02, 0x50, 0x2c, 0x0a, 0x00, 0x05, 0x41, 0x80, 0x02, 0xd4, 0x41, 0xa2, 0x04, + 0xe0, 0x2c, 0x0a, 0x00, 0x07, 0x41, 0xa0, 0x05, 0x0c, 0x48, 0x00, 0x05, 0xf0, 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, 0xc8, 0x35, 0x29, 0xff, 0xff, 0x41, 0x80, 0x04, + 0xc0, 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, 0x51, 0x08, 0x08, 0x3c, 0x40, + 0x9e, 0x00, 0x78, 0x41, 0x8d, 0x04, 0xb8, 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, 0x40, 0x41, 0x94, 0xfe, + 0x3c, 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, 0x0c, 0x40, 0xbe, 0xfe, 0x08, 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, 0x80, 0x7e, 0x0c, 0x21, 0x2e, 0x4b, 0xff, 0xfd, 0x78, 0x40, + 0x90, 0x00, 0x0c, 0x7c, 0x86, 0x23, 0x78, 0x4b, 0xff, 0xfd, 0x6c, 0x7c, 0x90, 0x23, 0x78, 0x4b, 0xff, 0xfd, + 0x64, 0x54, 0x89, 0x1e, 0x78, 0x39, 0x29, 0x00, 0x40, 0x2c, 0x05, 0x00, 0x02, 0x41, 0x80, 0x00, 0x48, 0x54, + 0x6b, 0x50, 0x03, 0x41, 0x82, 0x00, 0x14, 0x41, 0x81, 0x00, 0x08, 0x48, 0x00, 0x00, 0x10, 0x41, 0xbe, 0xfd, + 0x40, 0x48, 0x00, 0x00, 0x08, 0x40, 0xbe, 0xfd, 0x38, 0x2c, 0x05, 0x00, 0x03, 0x41, 0x81, 0x00, 0x10, 0x41, + 0xa2, 0x00, 0x10, 0x7d, 0xe7, 0x48, 0x2e, 0x4b, 0xff, 0xfd, 0x24, 0x7d, 0xe7, 0x49, 0x2e, 0x7c, 0x64, 0x07, + 0x34, 0x54, 0x84, 0x1a, 0x78, 0x7d, 0xef, 0x22, 0x14, 0x4b, 0xff, 0xfd, 0x10, 0x40, 0xbe, 0xfd, 0x0c, 0x7c, + 0xa7, 0x4a, 0x14, 0x40, 0x92, 0x00, 0x14, 0x54, 0x64, 0x04, 0x3e, 0x91, 0xe5, 0x00, 0x00, 0x90, 0x85, 0x00, + 0x04, 0x4b, 0xff, 0xfc, 0xf4, 0x81, 0x25, 0x00, 0x04, 0x2c, 0x09, 0x00, 0x00, 0x41, 0xa2, 0xfc, 0xe8, 0x39, + 0x29, 0xff, 0xff, 0x91, 0x25, 0x00, 0x04, 0x81, 0xe5, 0x00, 0x00, 0x4b, 0xff, 0xfc, 0xd8, 0x40, 0xbe, 0xfc, + 0xd4, 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, 0x40, 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, 0x8c, 0x2c, 0x05, 0x00, 0x0a, 0x41, 0x81, 0xfb, 0x84, 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, 0x64, 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, 0x44, 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, 0x1c, 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, 0xc4, 0x54, 0x6b, 0xe4, 0x3e, 0x4b, 0xff, 0xfb, + 0xbc, 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, 0x6c, 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, 0x50, 0x57, 0x44, 0x00, + 0x3a, 0x7c, 0x8c, 0x20, 0x50, 0x50, 0x85, 0x01, 0xba, 0x50, 0x65, 0x07, 0xfe, 0x90, 0xac, 0x00, 0x00, 0x4b, + 0xff, 0xfa, 0x38, 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, 0x28, 0x55, 0x8c, 0x84, 0x3e, 0x57, 0x44, 0x84, 0x3e, 0x57, 0x5a, 0x04, 0x3e, 0x7c, + 0x0c, 0x20, 0x00, 0x41, 0x80, 0xfb, 0xa8, 0x7c, 0x0c, 0xd0, 0x00, 0x40, 0x80, 0xfb, 0xa0, 0x4b, 0xff, 0xf9, + 0xe0, 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, 0xac, 0x2c, + 0x0b, 0x00, 0x00, 0x41, 0x82, 0x01, 0x38, 0x2c, 0x05, 0x00, 0x01, 0x41, 0x82, 0x00, 0x18, 0x2c, 0x05, 0x00, + 0x02, 0x41, 0x82, 0x00, 0x14, 0x2c, 0x05, 0x00, 0x03, 0x41, 0x82, 0x00, 0x70, 0x4b, 0xff, 0xf9, 0x80, 0x54, + 0xcc, 0x00, 0x0c, 0x54, 0x97, 0x46, 0x3e, 0x54, 0x98, 0xc4, 0x3e, 0x54, 0x84, 0x06, 0x3e, 0x40, 0x9e, 0x00, + 0xfc, 0x56, 0xf9, 0x06, 0x31, 0x7d, 0x9a, 0x63, 0x78, 0x7f, 0x43, 0xd2, 0x14, 0x57, 0x5a, 0x00, 0x3a, 0x41, + 0x82, 0x00, 0x18, 0x7e, 0xf7, 0x07, 0x74, 0x7e, 0xf7, 0x00, 0xd0, 0x1f, 0x37, 0x00, 0x02, 0x3b, 0x39, 0x00, + 0x04, 0x7f, 0x59, 0xd0, 0x50, 0x2c, 0x17, 0x00, 0x00, 0x41, 0x82, 0x00, 0x1c, 0x3b, 0x20, 0x00, 0x00, 0x7e, + 0xe9, 0x03, 0xa6, 0xa3, 0x7a, 0x00, 0x04, 0x7f, 0x79, 0xca, 0x78, 0x3b, 0x5a, 0x00, 0x02, 0x42, 0x00, 0xff, + 0xf4, 0x7c, 0x18, 0xc8, 0x00, 0x40, 0x82, 0x00, 0xac, 0x4b, 0xff, 0xfe, 0x90, 0x51, 0x08, 0x08, 0x3c, 0x40, + 0x9e, 0x00, 0x9c, 0x54, 0x77, 0xb0, 0x03, 0x41, 0x81, 0x00, 0x88, 0x41, 0x80, 0x00, 0x8c, 0x54, 0x7e, 0x06, + 0x3e, 0x1f, 0xde, 0x00, 0x02, 0x54, 0x97, 0x00, 0x1e, 0x6e, 0xf8, 0x80, 0x00, 0x2c, 0x18, 0x00, 0x00, 0x40, + 0x82, 0x00, 0x08, 0x62, 0xf7, 0x30, 0x00, 0x54, 0x98, 0x80, 0x1e, 0x1f, 0x3e, 0x00, 0x04, 0x7f, 0x19, 0xc0, + 0x50, 0x3b, 0x20, 0x00, 0x00, 0x1f, 0x59, 0x00, 0x04, 0x7f, 0x6f, 0xd0, 0x2e, 0x7f, 0x57, 0xd0, 0x2e, 0x3b, + 0x39, 0x00, 0x01, 0x7c, 0x17, 0xc0, 0x40, 0x41, 0x81, 0x00, 0x34, 0x7c, 0x19, 0xf0, 0x00, 0x41, 0x81, 0x00, + 0x14, 0x7c, 0x1a, 0xd8, 0x00, 0x41, 0x82, 0xff, 0xdc, 0x3a, 0xf7, 0x00, 0x04, 0x4b, 0xff, 0xff, 0xd0, 0x80, + 0x6f, 0xff, 0xf8, 0x60, 0x63, 0x03, 0x00, 0x90, 0x6f, 0xff, 0xf8, 0x92, 0xef, 0xff, 0xfc, 0x7e, 0xf0, 0xbb, + 0x78, 0x48, 0x00, 0x00, 0x1c, 0x80, 0x6f, 0xff, 0xf8, 0x60, 0x63, 0x01, 0x00, 0x90, 0x6f, 0xff, 0xf8, 0x61, + 0x08, 0x00, 0x01, 0x48, 0x00, 0x00, 0x08, 0x7c, 0x90, 0x23, 0x78, 0x54, 0x64, 0x06, 0x3e, 0x1c, 0x84, 0x00, + 0x08, 0x7d, 0xe4, 0x7a, 0x14, 0x4b, 0xff, 0xf8, 0x70, 0x40, 0x92, 0x00, 0x0c, 0x39, 0x00, 0x00, 0x00, 0x48, + 0x00, 0x00, 0x14, 0x54, 0x69, 0x06, 0xff, 0x54, 0x65, 0x67, 0xfe, 0x7d, 0x08, 0x4c, 0x30, 0x55, 0x17, 0xff, + 0xff, 0x40, 0x82, 0x00, 0x08, 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, 0xf8, + 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; -const int codehandler_size = sizeof( codehandler ); +const int codehandler_size = sizeof(codehandler); diff --git a/source/patches/codehandleronly.h b/source/patches/codehandleronly.h index 7fc7c52b..62d12278 100644 --- a/source/patches/codehandleronly.h +++ b/source/patches/codehandleronly.h @@ -1,181 +1,161 @@ /* - This file was autogenerated by raw2c. -Visit http://www.devkitpro.org -*/ + This file was autogenerated by raw2c. + Visit http://www.devkitpro.org + */ -const unsigned char codehandleronly[] = -{ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x21, 0x60, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 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, - 0x7f, 0xa8, 0x02, 0xa6, 0x3d, 0xe0, 0x80, 0x00, 0x61, 0xef, 0x22, 0xa8, 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, 0x4c, 0x7f, 0xa8, 0x03, 0xa6, 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, 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, 0xac, 0x41, 0x82, 0x02, 0x50, - 0x2c, 0x0a, 0x00, 0x05, 0x41, 0x80, 0x02, 0xd4, 0x41, 0xa2, 0x04, 0xe0, 0x2c, 0x0a, 0x00, 0x07, - 0x41, 0xa0, 0x05, 0x0c, 0x48, 0x00, 0x05, 0xf0, 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, 0xc8, - 0x35, 0x29, 0xff, 0xff, 0x41, 0x80, 0x04, 0xc0, 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, - 0x51, 0x08, 0x08, 0x3c, 0x40, 0x9e, 0x00, 0x78, 0x41, 0x8d, 0x04, 0xb8, 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, 0x40, - 0x41, 0x94, 0xfe, 0x3c, 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, 0x0c, 0x40, 0xbe, 0xfe, 0x08, 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, 0x80, - 0x7e, 0x0c, 0x21, 0x2e, 0x4b, 0xff, 0xfd, 0x78, 0x40, 0x90, 0x00, 0x0c, 0x7c, 0x86, 0x23, 0x78, - 0x4b, 0xff, 0xfd, 0x6c, 0x7c, 0x90, 0x23, 0x78, 0x4b, 0xff, 0xfd, 0x64, 0x54, 0x89, 0x1e, 0x78, - 0x39, 0x29, 0x00, 0x40, 0x2c, 0x05, 0x00, 0x02, 0x41, 0x80, 0x00, 0x48, 0x54, 0x6b, 0x50, 0x03, - 0x41, 0x82, 0x00, 0x14, 0x41, 0x81, 0x00, 0x08, 0x48, 0x00, 0x00, 0x10, 0x41, 0xbe, 0xfd, 0x40, - 0x48, 0x00, 0x00, 0x08, 0x40, 0xbe, 0xfd, 0x38, 0x2c, 0x05, 0x00, 0x03, 0x41, 0x81, 0x00, 0x10, - 0x41, 0xa2, 0x00, 0x10, 0x7d, 0xe7, 0x48, 0x2e, 0x4b, 0xff, 0xfd, 0x24, 0x7d, 0xe7, 0x49, 0x2e, - 0x7c, 0x64, 0x07, 0x34, 0x54, 0x84, 0x1a, 0x78, 0x7d, 0xef, 0x22, 0x14, 0x4b, 0xff, 0xfd, 0x10, - 0x40, 0xbe, 0xfd, 0x0c, 0x7c, 0xa7, 0x4a, 0x14, 0x40, 0x92, 0x00, 0x14, 0x54, 0x64, 0x04, 0x3e, - 0x91, 0xe5, 0x00, 0x00, 0x90, 0x85, 0x00, 0x04, 0x4b, 0xff, 0xfc, 0xf4, 0x81, 0x25, 0x00, 0x04, - 0x2c, 0x09, 0x00, 0x00, 0x41, 0xa2, 0xfc, 0xe8, 0x39, 0x29, 0xff, 0xff, 0x91, 0x25, 0x00, 0x04, - 0x81, 0xe5, 0x00, 0x00, 0x4b, 0xff, 0xfc, 0xd8, 0x40, 0xbe, 0xfc, 0xd4, 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, 0x40, - 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, 0x8c, 0x2c, 0x05, 0x00, 0x0a, 0x41, 0x81, 0xfb, 0x84, 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, 0x64, 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, 0x44, 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, 0x1c, 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, 0xc4, 0x54, 0x6b, 0xe4, 0x3e, 0x4b, 0xff, 0xfb, 0xbc, 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, 0x6c, 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, 0x50, - 0x57, 0x44, 0x00, 0x3a, 0x7c, 0x8c, 0x20, 0x50, 0x50, 0x85, 0x01, 0xba, 0x50, 0x65, 0x07, 0xfe, - 0x90, 0xac, 0x00, 0x00, 0x4b, 0xff, 0xfa, 0x38, 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, 0x28, - 0x55, 0x8c, 0x84, 0x3e, 0x57, 0x44, 0x84, 0x3e, 0x57, 0x5a, 0x04, 0x3e, 0x7c, 0x0c, 0x20, 0x00, - 0x41, 0x80, 0xfb, 0xa8, 0x7c, 0x0c, 0xd0, 0x00, 0x40, 0x80, 0xfb, 0xa0, 0x4b, 0xff, 0xf9, 0xe0, - 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, 0xac, 0x2c, 0x0b, 0x00, 0x00, 0x41, 0x82, 0x01, 0x38, 0x2c, 0x05, 0x00, 0x01, - 0x41, 0x82, 0x00, 0x18, 0x2c, 0x05, 0x00, 0x02, 0x41, 0x82, 0x00, 0x14, 0x2c, 0x05, 0x00, 0x03, - 0x41, 0x82, 0x00, 0x70, 0x4b, 0xff, 0xf9, 0x40, 0x54, 0xcc, 0x00, 0x0c, 0x54, 0x97, 0x46, 0x3e, - 0x54, 0x98, 0xc4, 0x3e, 0x54, 0x84, 0x06, 0x3e, 0x40, 0x9e, 0x00, 0xfc, 0x56, 0xf9, 0x06, 0x31, - 0x7d, 0x9a, 0x63, 0x78, 0x7f, 0x43, 0xd2, 0x14, 0x57, 0x5a, 0x00, 0x3a, 0x41, 0x82, 0x00, 0x18, - 0x7e, 0xf7, 0x07, 0x74, 0x7e, 0xf7, 0x00, 0xd0, 0x1f, 0x37, 0x00, 0x02, 0x3b, 0x39, 0x00, 0x04, - 0x7f, 0x59, 0xd0, 0x50, 0x2c, 0x17, 0x00, 0x00, 0x41, 0x82, 0x00, 0x1c, 0x3b, 0x20, 0x00, 0x00, - 0x7e, 0xe9, 0x03, 0xa6, 0xa3, 0x7a, 0x00, 0x04, 0x7f, 0x79, 0xca, 0x78, 0x3b, 0x5a, 0x00, 0x02, - 0x42, 0x00, 0xff, 0xf4, 0x7c, 0x18, 0xc8, 0x00, 0x40, 0x82, 0x00, 0xac, 0x4b, 0xff, 0xfe, 0x90, - 0x51, 0x08, 0x08, 0x3c, 0x40, 0x9e, 0x00, 0x9c, 0x54, 0x77, 0xb0, 0x03, 0x41, 0x81, 0x00, 0x88, - 0x41, 0x80, 0x00, 0x8c, 0x54, 0x7e, 0x06, 0x3e, 0x1f, 0xde, 0x00, 0x02, 0x54, 0x97, 0x00, 0x1e, - 0x6e, 0xf8, 0x80, 0x00, 0x2c, 0x18, 0x00, 0x00, 0x40, 0x82, 0x00, 0x08, 0x62, 0xf7, 0x30, 0x00, - 0x54, 0x98, 0x80, 0x1e, 0x1f, 0x3e, 0x00, 0x04, 0x7f, 0x19, 0xc0, 0x50, 0x3b, 0x20, 0x00, 0x00, - 0x1f, 0x59, 0x00, 0x04, 0x7f, 0x6f, 0xd0, 0x2e, 0x7f, 0x57, 0xd0, 0x2e, 0x3b, 0x39, 0x00, 0x01, - 0x7c, 0x17, 0xc0, 0x40, 0x41, 0x81, 0x00, 0x34, 0x7c, 0x19, 0xf0, 0x00, 0x41, 0x81, 0x00, 0x14, - 0x7c, 0x1a, 0xd8, 0x00, 0x41, 0x82, 0xff, 0xdc, 0x3a, 0xf7, 0x00, 0x04, 0x4b, 0xff, 0xff, 0xd0, - 0x80, 0x6f, 0xff, 0xf8, 0x60, 0x63, 0x03, 0x00, 0x90, 0x6f, 0xff, 0xf8, 0x92, 0xef, 0xff, 0xfc, - 0x7e, 0xf0, 0xbb, 0x78, 0x48, 0x00, 0x00, 0x1c, 0x80, 0x6f, 0xff, 0xf8, 0x60, 0x63, 0x01, 0x00, - 0x90, 0x6f, 0xff, 0xf8, 0x61, 0x08, 0x00, 0x01, 0x48, 0x00, 0x00, 0x08, 0x7c, 0x90, 0x23, 0x78, - 0x54, 0x64, 0x06, 0x3e, 0x1c, 0x84, 0x00, 0x08, 0x7d, 0xe4, 0x7a, 0x14, 0x4b, 0xff, 0xf8, 0x70, - 0x40, 0x92, 0x00, 0x0c, 0x39, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x14, 0x54, 0x69, 0x06, 0xff, - 0x54, 0x65, 0x67, 0xfe, 0x7d, 0x08, 0x4c, 0x30, 0x55, 0x17, 0xff, 0xff, 0x40, 0x82, 0x00, 0x08, - 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, 0xf8, 0x30, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 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 unsigned char codehandleronly[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x21, 0x60, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 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, 0x7f, 0xa8, 0x02, 0xa6, 0x3d, 0xe0, 0x80, 0x00, 0x61, + 0xef, 0x22, 0xa8, 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, 0x4c, 0x7f, 0xa8, 0x03, 0xa6, 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, 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, 0xac, 0x41, 0x82, 0x02, 0x50, 0x2c, + 0x0a, 0x00, 0x05, 0x41, 0x80, 0x02, 0xd4, 0x41, 0xa2, 0x04, 0xe0, 0x2c, 0x0a, 0x00, 0x07, 0x41, 0xa0, 0x05, + 0x0c, 0x48, 0x00, 0x05, 0xf0, 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, 0xc8, 0x35, 0x29, 0xff, 0xff, 0x41, 0x80, 0x04, 0xc0, 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, 0x51, 0x08, 0x08, 0x3c, 0x40, 0x9e, 0x00, 0x78, 0x41, 0x8d, 0x04, 0xb8, 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, 0x40, 0x41, 0x94, 0xfe, 0x3c, 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, 0x0c, 0x40, 0xbe, 0xfe, 0x08, 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, + 0x80, 0x7e, 0x0c, 0x21, 0x2e, 0x4b, 0xff, 0xfd, 0x78, 0x40, 0x90, 0x00, 0x0c, 0x7c, 0x86, 0x23, 0x78, 0x4b, + 0xff, 0xfd, 0x6c, 0x7c, 0x90, 0x23, 0x78, 0x4b, 0xff, 0xfd, 0x64, 0x54, 0x89, 0x1e, 0x78, 0x39, 0x29, 0x00, + 0x40, 0x2c, 0x05, 0x00, 0x02, 0x41, 0x80, 0x00, 0x48, 0x54, 0x6b, 0x50, 0x03, 0x41, 0x82, 0x00, 0x14, 0x41, + 0x81, 0x00, 0x08, 0x48, 0x00, 0x00, 0x10, 0x41, 0xbe, 0xfd, 0x40, 0x48, 0x00, 0x00, 0x08, 0x40, 0xbe, 0xfd, + 0x38, 0x2c, 0x05, 0x00, 0x03, 0x41, 0x81, 0x00, 0x10, 0x41, 0xa2, 0x00, 0x10, 0x7d, 0xe7, 0x48, 0x2e, 0x4b, + 0xff, 0xfd, 0x24, 0x7d, 0xe7, 0x49, 0x2e, 0x7c, 0x64, 0x07, 0x34, 0x54, 0x84, 0x1a, 0x78, 0x7d, 0xef, 0x22, + 0x14, 0x4b, 0xff, 0xfd, 0x10, 0x40, 0xbe, 0xfd, 0x0c, 0x7c, 0xa7, 0x4a, 0x14, 0x40, 0x92, 0x00, 0x14, 0x54, + 0x64, 0x04, 0x3e, 0x91, 0xe5, 0x00, 0x00, 0x90, 0x85, 0x00, 0x04, 0x4b, 0xff, 0xfc, 0xf4, 0x81, 0x25, 0x00, + 0x04, 0x2c, 0x09, 0x00, 0x00, 0x41, 0xa2, 0xfc, 0xe8, 0x39, 0x29, 0xff, 0xff, 0x91, 0x25, 0x00, 0x04, 0x81, + 0xe5, 0x00, 0x00, 0x4b, 0xff, 0xfc, 0xd8, 0x40, 0xbe, 0xfc, 0xd4, 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, 0x40, 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, 0x8c, 0x2c, 0x05, 0x00, + 0x0a, 0x41, 0x81, 0xfb, 0x84, 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, + 0x64, 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, 0x44, 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, + 0x1c, 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, 0xc4, 0x54, 0x6b, 0xe4, 0x3e, 0x4b, 0xff, 0xfb, 0xbc, 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, 0x6c, 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, 0x50, 0x57, 0x44, 0x00, 0x3a, 0x7c, 0x8c, 0x20, 0x50, 0x50, 0x85, 0x01, + 0xba, 0x50, 0x65, 0x07, 0xfe, 0x90, 0xac, 0x00, 0x00, 0x4b, 0xff, 0xfa, 0x38, 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, 0x28, 0x55, 0x8c, 0x84, + 0x3e, 0x57, 0x44, 0x84, 0x3e, 0x57, 0x5a, 0x04, 0x3e, 0x7c, 0x0c, 0x20, 0x00, 0x41, 0x80, 0xfb, 0xa8, 0x7c, + 0x0c, 0xd0, 0x00, 0x40, 0x80, 0xfb, 0xa0, 0x4b, 0xff, 0xf9, 0xe0, 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, 0xac, 0x2c, 0x0b, 0x00, 0x00, 0x41, 0x82, 0x01, 0x38, 0x2c, + 0x05, 0x00, 0x01, 0x41, 0x82, 0x00, 0x18, 0x2c, 0x05, 0x00, 0x02, 0x41, 0x82, 0x00, 0x14, 0x2c, 0x05, 0x00, + 0x03, 0x41, 0x82, 0x00, 0x70, 0x4b, 0xff, 0xf9, 0x40, 0x54, 0xcc, 0x00, 0x0c, 0x54, 0x97, 0x46, 0x3e, 0x54, + 0x98, 0xc4, 0x3e, 0x54, 0x84, 0x06, 0x3e, 0x40, 0x9e, 0x00, 0xfc, 0x56, 0xf9, 0x06, 0x31, 0x7d, 0x9a, 0x63, + 0x78, 0x7f, 0x43, 0xd2, 0x14, 0x57, 0x5a, 0x00, 0x3a, 0x41, 0x82, 0x00, 0x18, 0x7e, 0xf7, 0x07, 0x74, 0x7e, + 0xf7, 0x00, 0xd0, 0x1f, 0x37, 0x00, 0x02, 0x3b, 0x39, 0x00, 0x04, 0x7f, 0x59, 0xd0, 0x50, 0x2c, 0x17, 0x00, + 0x00, 0x41, 0x82, 0x00, 0x1c, 0x3b, 0x20, 0x00, 0x00, 0x7e, 0xe9, 0x03, 0xa6, 0xa3, 0x7a, 0x00, 0x04, 0x7f, + 0x79, 0xca, 0x78, 0x3b, 0x5a, 0x00, 0x02, 0x42, 0x00, 0xff, 0xf4, 0x7c, 0x18, 0xc8, 0x00, 0x40, 0x82, 0x00, + 0xac, 0x4b, 0xff, 0xfe, 0x90, 0x51, 0x08, 0x08, 0x3c, 0x40, 0x9e, 0x00, 0x9c, 0x54, 0x77, 0xb0, 0x03, 0x41, + 0x81, 0x00, 0x88, 0x41, 0x80, 0x00, 0x8c, 0x54, 0x7e, 0x06, 0x3e, 0x1f, 0xde, 0x00, 0x02, 0x54, 0x97, 0x00, + 0x1e, 0x6e, 0xf8, 0x80, 0x00, 0x2c, 0x18, 0x00, 0x00, 0x40, 0x82, 0x00, 0x08, 0x62, 0xf7, 0x30, 0x00, 0x54, + 0x98, 0x80, 0x1e, 0x1f, 0x3e, 0x00, 0x04, 0x7f, 0x19, 0xc0, 0x50, 0x3b, 0x20, 0x00, 0x00, 0x1f, 0x59, 0x00, + 0x04, 0x7f, 0x6f, 0xd0, 0x2e, 0x7f, 0x57, 0xd0, 0x2e, 0x3b, 0x39, 0x00, 0x01, 0x7c, 0x17, 0xc0, 0x40, 0x41, + 0x81, 0x00, 0x34, 0x7c, 0x19, 0xf0, 0x00, 0x41, 0x81, 0x00, 0x14, 0x7c, 0x1a, 0xd8, 0x00, 0x41, 0x82, 0xff, + 0xdc, 0x3a, 0xf7, 0x00, 0x04, 0x4b, 0xff, 0xff, 0xd0, 0x80, 0x6f, 0xff, 0xf8, 0x60, 0x63, 0x03, 0x00, 0x90, + 0x6f, 0xff, 0xf8, 0x92, 0xef, 0xff, 0xfc, 0x7e, 0xf0, 0xbb, 0x78, 0x48, 0x00, 0x00, 0x1c, 0x80, 0x6f, 0xff, + 0xf8, 0x60, 0x63, 0x01, 0x00, 0x90, 0x6f, 0xff, 0xf8, 0x61, 0x08, 0x00, 0x01, 0x48, 0x00, 0x00, 0x08, 0x7c, + 0x90, 0x23, 0x78, 0x54, 0x64, 0x06, 0x3e, 0x1c, 0x84, 0x00, 0x08, 0x7d, 0xe4, 0x7a, 0x14, 0x4b, 0xff, 0xf8, + 0x70, 0x40, 0x92, 0x00, 0x0c, 0x39, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x14, 0x54, 0x69, 0x06, 0xff, 0x54, + 0x65, 0x67, 0xfe, 0x7d, 0x08, 0x4c, 0x30, 0x55, 0x17, 0xff, 0xff, 0x40, 0x82, 0x00, 0x08, 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, 0xf8, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 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 codehandleronly_size = sizeof( codehandleronly ); +const int codehandleronly_size = sizeof(codehandleronly); diff --git a/source/patches/dolpatcher.c b/source/patches/dolpatcher.c index 66407226..f5153ea8 100644 --- a/source/patches/dolpatcher.c +++ b/source/patches/dolpatcher.c @@ -1,16 +1,16 @@ #include #include -bool PatchDOL( u8 * Address, int Size, const u8 * SearchPattern, int SearchSize, const u8 * PatchData, int PatchSize ) +bool PatchDOL(u8 * Address, int Size, const u8 * SearchPattern, int SearchSize, const u8 * PatchData, int PatchSize) { u8 * Addr = Address; u8 * Addr_end = Address + Size; - while ( Addr <= Addr_end - SearchSize ) + while (Addr <= Addr_end - SearchSize) { - if ( memcmp( Addr, SearchPattern, SearchSize ) == 0 ) + if (memcmp(Addr, SearchPattern, SearchSize) == 0) { - memcpy( Addr, PatchData, PatchSize ); + memcpy(Addr, PatchData, PatchSize); return true; } Addr += 4; diff --git a/source/patches/dolpatcher.h b/source/patches/dolpatcher.h index df7c1ccf..09eb3190 100644 --- a/source/patches/dolpatcher.h +++ b/source/patches/dolpatcher.h @@ -3,6 +3,6 @@ #include -bool PatchDOL( u8 * Address, int Size, const u8 * SearchPattern, int SearchSize, const u8 * PatchData, int PatchSize ); +bool PatchDOL(u8 * Address, int Size, const u8 * SearchPattern, int SearchSize, const u8 * PatchData, int PatchSize); #endif diff --git a/source/patches/dvd_broadway.c b/source/patches/dvd_broadway.c index 7b355b6e..3b629991 100644 --- a/source/patches/dvd_broadway.c +++ b/source/patches/dvd_broadway.c @@ -93,83 +93,82 @@ static char __di_fs[] ATTRIBUTE_ALIGN( 32 ) = "/dev/di"; extern u32 __IPC_ClntInit(); -static __inline__ lwp_node* __lwp_queue_head( lwp_queue *queue ) +static __inline__ lwp_node* __lwp_queue_head(lwp_queue *queue) { - return ( lwp_node* )queue; + return (lwp_node*) queue; } -static __inline__ lwp_node* __lwp_queue_tail( lwp_queue *queue ) +static __inline__ lwp_node* __lwp_queue_tail(lwp_queue *queue) { - return ( lwp_node* )&queue->perm_null; + return (lwp_node*) &queue->perm_null; } - -static __inline__ void __lwp_queue_init_empty( lwp_queue *queue ) +static __inline__ void __lwp_queue_init_empty(lwp_queue *queue) { - queue->first = __lwp_queue_tail( queue ); + queue->first = __lwp_queue_tail(queue); queue->perm_null = NULL; - queue->last = __lwp_queue_head( queue ); + queue->last = __lwp_queue_head(queue); } -static struct dicontext* __dvd_getcontext( dvdcallbacklow cb ) +static struct dicontext* __dvd_getcontext(dvdcallbacklow cb) { struct dicontext *ctx; - ctx = ( struct dicontext* )__lwp_queue_get( &__di_contextq ); - if ( ctx != NULL ) ctx->cb = cb; + ctx = (struct dicontext*) __lwp_queue_get(&__di_contextq); + if (ctx != NULL) ctx->cb = cb; return ctx; } -static s32 __dvd_iostransactionCB( s32 result, void *usrdata ) +static s32 __dvd_iostransactionCB(s32 result, void *usrdata) { - struct dicontext *ctx = ( struct dicontext* )usrdata; + struct dicontext *ctx = (struct dicontext*) usrdata; __dvd_reqinprogress = 0; - if ( ctx->cb != NULL ) + if (ctx->cb != NULL) { __dvd_cbinprogress = 1; - if ( result != 0 ) __dvd_readlength = 0; - ctx->cb( result ); + if (result != 0) __dvd_readlength = 0; + ctx->cb(result); __dvd_cbinprogress = 0; } - __lwp_queue_append( &__di_contextq, &ctx->node ); + __lwp_queue_append(&__di_contextq, &ctx->node); return 0; } -static s32 __dvd_ioscoverregisterCB( s32 result, void *usrdata ) +static s32 __dvd_ioscoverregisterCB(s32 result, void *usrdata) { - struct dicontext *ctx = ( struct dicontext* )usrdata; + struct dicontext *ctx = (struct dicontext*) usrdata; __dvd_reqinprogress = 0; __di_regvalcache[1] = __di_regbuffer[0]; - if ( ctx->cb != NULL ) + if (ctx->cb != NULL) { __dvd_cbinprogress = 1; - ctx->cb( result ); + ctx->cb(result); __dvd_cbinprogress = 0; } - __lwp_queue_append( &__di_contextq, &ctx->node ); + __lwp_queue_append(&__di_contextq, &ctx->node); return 0; } -static s32 __dvd_ioscovercloseCB( s32 result, void *usrdata ) +static s32 __dvd_ioscovercloseCB(s32 result, void *usrdata) { - struct dicontext *ctx = ( struct dicontext* )usrdata; + struct dicontext *ctx = (struct dicontext*) usrdata; __dvd_reqinprogress = 0; - if ( ctx->cb != NULL ) + if (ctx->cb != NULL) { __dvd_cbinprogress = 1; - ctx->cb( result ); + ctx->cb(result); __dvd_cbinprogress = 0; } - __lwp_queue_append( &__di_contextq, &ctx->node ); + __lwp_queue_append(&__di_contextq, &ctx->node); return 0; } @@ -181,45 +180,45 @@ s32 bwDVD_LowInit() lwp_queue inactives; struct dicontext *ctx; - if ( __dvd_lowinitcalled == 0 ) + if (__dvd_lowinitcalled == 0) { ret = __IPC_ClntInit(); - if ( ret < 0 ) return ret; + if (ret < 0) return ret; - ipclo = ( ( ( u32 )IPC_GetBufferLo() + 0x1f )&~0x1f ); - ipchi = ( u32 )IPC_GetBufferHi(); - if ( ipchi >= ( ipclo + ( sizeof( struct dicommand )*DI_CMDCTX_CNT ) ) ) + 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 ) ) ); + __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 ) ); + 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 ) + __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 ); + __lwp_queue_append(&__di_contextq, &ctx->node); i++; } } - ret = IOS_Open( __di_fs, 0 ); - if ( ret < 0 ) return ret; + ret = IOS_Open(__di_fs, 0); + if (ret < 0) return ret; __dvd_fd = ret; -// __dvd_lowinitcalled = 1; + // __dvd_lowinitcalled = 1; // printf("DVD_LowInit(%d)\n",ret); } return 0; } -s32 bwDVD_LowInquiry( dvddrvinfo *info, dvdcallbacklow cb ) +s32 bwDVD_LowInquiry(dvddrvinfo *info, dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; @@ -227,63 +226,65 @@ s32 bwDVD_LowInquiry( dvddrvinfo *info, dvdcallbacklow cb ) __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + 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 ); + 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 bwDVD_LowReadID(dvddiskid *diskID, dvdcallbacklow cb) { s32 ret = 0; struct dicontext *ctx; struct dicommand *cmd; -// printf("DVD_LowReadID()\n"); + // printf("DVD_LowReadID()\n"); __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + 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 ); + 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); + // printf("DVD_LowReadID(%d)\n",ret); return ret; } - -s32 bwDVD_LowRead( void *buf, u32 len, u32 offset, dvdcallbacklow cb ) +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; + 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; + ctx = __dvd_getcontext(cb); + if (ctx == NULL) return IPC_ENOMEM; cmd = ctx->cmd; - cmd->diReg[0] = ( IOCTL_DI_READ << 24 ); + 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 ); + 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 bwDVD_LowReadVideo(void *buf, u32 len, u32 offset, dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; @@ -292,21 +293,20 @@ s32 bwDVD_LowReadVideo( void *buf, u32 len, u32 offset, dvdcallbacklow cb ) __dvd_reqinprogress = 1; __dvd_readlength = len; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + ctx = __dvd_getcontext(cb); + if (ctx == NULL) return IPC_ENOMEM; cmd = ctx->cmd; - cmd->diReg[0] = ( IOCTL_DI_READ_DVDVIDEO << 24 ); + 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 ); + 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 bwDVD_LowStopLaser(dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; @@ -314,18 +314,19 @@ s32 bwDVD_LowStopLaser( dvdcallbacklow cb ) __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + 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 ); + 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 bwDVD_EnableVideo(dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; @@ -333,17 +334,18 @@ s32 bwDVD_EnableVideo( dvdcallbacklow cb ) __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + 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 ); + 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 bwDVD_LowSeek(u32 offset, dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; @@ -351,41 +353,48 @@ s32 bwDVD_LowSeek( u32 offset, dvdcallbacklow cb ) __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + ctx = __dvd_getcontext(cb); + if (ctx == NULL) return IPC_ENOMEM; cmd = ctx->cmd; - cmd->diReg[0] = ( IOCTL_DI_SEEK << 24 ); + 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 ); + 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 bwDVD_LowOffset(u64 offset, dvdcallbacklow cb) { s32 ret; //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; struct dicontext *ctx; struct dicommand *cmd; __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + ctx = __dvd_getcontext(cb); + if (ctx == NULL) return IPC_ENOMEM; cmd = ctx->cmd; - cmd->diReg[0] = ( IOCTL_DI_OFFSET << 24 ); + cmd->diReg[0] = (IOCTL_DI_OFFSET << 24); cmd->diReg[1] = 0; - if ( off.off32[0] ) cmd->diReg[1] = 1; + 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 ); + 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 bwDVD_LowPrepareCoverRegister(dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; @@ -393,56 +402,60 @@ s32 bwDVD_LowPrepareCoverRegister( dvdcallbacklow cb ) __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + 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 ); + 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 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; + 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; + ctx = __dvd_getcontext(cb); + if (ctx == NULL) return IPC_ENOMEM; cmd = ctx->cmd; - cmd->diReg[0] = ( IOCTL_DI_OPENPART << 24 ); + 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[0].len = sizeof(struct dicommand); __di_iovector[1].data = eticket; - if ( eticket == NULL ) __di_iovector[1].len = 0; + 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; + 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 ); + ret = IOS_IoctlvAsync(__dvd_fd, IOCTL_DI_OPENPART, 3, 2, __di_iovector, __dvd_iostransactionCB, ctx); return ret; } -s32 bwDVD_LowClosePartition( dvdcallbacklow cb ) +s32 bwDVD_LowClosePartition(dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; @@ -450,17 +463,18 @@ s32 bwDVD_LowClosePartition( dvdcallbacklow cb ) __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + 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 ); + 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 bwDVD_LowUnencryptedRead(void *buf, u32 len, u32 offset, dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; @@ -469,19 +483,20 @@ s32 bwDVD_LowUnencryptedRead( void *buf, u32 len, u32 offset, dvdcallbacklow cb __dvd_reqinprogress = 1; __dvd_readlength = len; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + ctx = __dvd_getcontext(cb); + if (ctx == NULL) return IPC_ENOMEM; cmd = ctx->cmd; - cmd->diReg[0] = ( IOCTL_DI_UNENCREAD << 24 ); + 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 ); + 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 bwDVD_LowWaitCoverClose(dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; @@ -489,12 +504,13 @@ s32 bwDVD_LowWaitCoverClose( dvdcallbacklow cb ) __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + 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 ); + 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; } @@ -505,40 +521,41 @@ s32 bwDVD_LowResetNotify() struct dicontext *ctx; struct dicommand *cmd; - if ( __dvd_cbinprogress == 1 ) return -1; + if (__dvd_cbinprogress == 1) return -1; - ctx = __dvd_getcontext( NULL ); - if ( ctx == NULL ) return IPC_ENOMEM; + 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 ); + 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 bwDVD_LowReset(dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; struct dicommand *cmd; -// printf("DVD_LowReset()\n"); + // printf("DVD_LowReset()\n"); __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + ctx = __dvd_getcontext(cb); + if (ctx == NULL) return IPC_ENOMEM; cmd = ctx->cmd; - cmd->diReg[0] = ( IOCTL_DI_RESET << 24 ); + 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 ); + ret = IOS_IoctlAsync(__dvd_fd, IOCTL_DI_RESET, cmd->diReg, sizeof(struct dicommand), NULL, 0, + __dvd_iostransactionCB, ctx); -// printf("DVD_LowReset(%d)\n",ret); + // printf("DVD_LowReset(%d)\n",ret); return ret; } -s32 bwDVD_LowStopMotor( u8 stop1, u8 stop2, dvdcallbacklow cb ) +s32 bwDVD_LowStopMotor(u8 stop1, u8 stop2, dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; @@ -546,20 +563,21 @@ s32 bwDVD_LowStopMotor( u8 stop1, u8 stop2, dvdcallbacklow cb ) __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + 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 ); + 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 bwDVD_LowRequestError(dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; @@ -567,18 +585,18 @@ s32 bwDVD_LowRequestError( dvdcallbacklow cb ) __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + 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 ); + 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 bwDVD_SetDecryption(s32 mode, dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; @@ -586,19 +604,20 @@ s32 bwDVD_SetDecryption( s32 mode, dvdcallbacklow cb ) __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + ctx = __dvd_getcontext(cb); + if (ctx == NULL) return IPC_ENOMEM; cmd = ctx->cmd; - cmd->diReg[0] = ( IOCTL_DI_SETCRYPTMODE << 24 ); + 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 ); + 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 bwDVD_SetOffset(u32 offset, dvdcallbacklow cb) { s32 ret; struct dicontext *ctx; @@ -606,13 +625,14 @@ s32 bwDVD_SetOffset( u32 offset, dvdcallbacklow cb ) __dvd_reqinprogress = 1; - ctx = __dvd_getcontext( cb ); - if ( ctx == NULL ) return IPC_ENOMEM; + ctx = __dvd_getcontext(cb); + if (ctx == NULL) return IPC_ENOMEM; cmd = ctx->cmd; - cmd->diReg[0] = ( IOCTL_DI_SETOFFBASE << 24 ); + 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 ); + 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 f91f35b0..eaf41e21 100644 --- a/source/patches/dvd_broadway.h +++ b/source/patches/dvd_broadway.h @@ -31,21 +31,22 @@ extern "C" { #endif /* __cplusplus */ - typedef void ( *dvdcallbacklow )( s32 result ); + 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 ); + 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 } diff --git a/source/patches/fst.c b/source/patches/fst.c index 08505087..7ff2cc25 100644 --- a/source/patches/fst.c +++ b/source/patches/fst.c @@ -19,7 +19,6 @@ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ - #include #include #include @@ -75,29 +74,28 @@ extern const u32 wpadbuttonsdown2hooks[4]; void SetCheatFilepath(const char * path) { - CheatFilepath = path; + CheatFilepath = path; } void SetBCAFilepath(const char * path) { - BCAFilepath = path; + BCAFilepath = path; } //static vu32 dvddone = 0; //--------------------------------------------------------------------------------- -void app_loadgameconfig( char *discid ) +void app_loadgameconfig(char *discid) //--------------------------------------------------------------------------------- { - if(!CheatFilepath) - return; + if (!CheatFilepath) return; gameconfsize = 0; - if ( gameconf == NULL ) + if (gameconf == NULL) { - gameconf = (u32*) malloc( 65536 ); - if ( gameconf == NULL ) + gameconf = (u32*) malloc(65536); + if (gameconf == NULL) { //TODO for oggzee //print_status("Out of memory"); @@ -125,29 +123,29 @@ void app_loadgameconfig( char *discid ) //tempgameconfsize = defaultgameconfig_size + 1; char filepath[200]; - snprintf( filepath, sizeof( filepath ), "%s/gameconfig.txt", CheatFilepath ); + snprintf(filepath, sizeof(filepath), "%s/gameconfig.txt", CheatFilepath); - fp = fopen( filepath, "rb" ); + fp = fopen(filepath, "rb"); - if ( !fp ) + if (!fp) { - snprintf( filepath, sizeof( filepath ), "SD:/gameconfig.txt" ); - fp = fopen( filepath, "rb" ); - if ( !fp ) + snprintf(filepath, sizeof(filepath), "SD:/gameconfig.txt"); + fp = fopen(filepath, "rb"); + if (!fp) { - snprintf( filepath, sizeof( filepath ), "USB:/gameconfig.txt" ); - fp = fopen( filepath, "rb" ); + snprintf(filepath, sizeof(filepath), "USB:/gameconfig.txt"); + fp = fopen(filepath, "rb"); } } - if ( fp ) + if (fp) { - fseek( fp, 0, SEEK_END ); - filesize = ftell( fp ); - fseek( fp, 0, SEEK_SET ); + fseek(fp, 0, SEEK_END); + filesize = ftell(fp); + fseek(fp, 0, SEEK_SET); - tempgameconf = (u8*) malloc( filesize ); - if ( tempgameconf == NULL ) + tempgameconf = (u8*) malloc(filesize); + if (tempgameconf == NULL) { //TODO for oggzee //print_status("Out of memory"); @@ -155,9 +153,9 @@ void app_loadgameconfig( char *discid ) return; } - ret = fread( ( void* )tempgameconf, 1, filesize, fp ); - fclose( fp ); - if ( ret != filesize ) + ret = fread((void*) tempgameconf, 1, filesize, fp); + fclose(fp); + if (ret != filesize) { //TODO for oggzee //print_status("Error reading gameconfig.txt"); @@ -173,78 +171,78 @@ void app_loadgameconfig( char *discid ) // Remove non-ASCII characters numnonascii = 0; - for ( i = 0; i < tempgameconfsize; i++ ) + for (i = 0; i < tempgameconfsize; i++) { - if ( tempgameconf[i] < 9 || tempgameconf[i] > 126 ) + if (tempgameconf[i] < 9 || tempgameconf[i] > 126) numnonascii++; - else - tempgameconf[i-numnonascii] = tempgameconf[i]; + else tempgameconf[i - numnonascii] = tempgameconf[i]; } tempgameconfsize -= numnonascii; - *( tempgameconf + tempgameconfsize ) = 0; + *(tempgameconf + tempgameconfsize) = 0; //gameconf = (tempgameconf + tempgameconfsize) + (4 - (((u32) (tempgameconf + tempgameconfsize)) % 4)); - for ( maxgameidmatch = 0; maxgameidmatch <= 6; maxgameidmatch++ ) + for (maxgameidmatch = 0; maxgameidmatch <= 6; maxgameidmatch++) { i = 0; - while ( i < tempgameconfsize ) + while (i < tempgameconfsize) { maxgameidmatch2 = -1; - while ( maxgameidmatch != maxgameidmatch2 ) + while (maxgameidmatch != maxgameidmatch2) { - while ( i != tempgameconfsize && tempgameconf[i] != ':' ) i++; - if ( i == tempgameconfsize ) break; - while ( ( tempgameconf[i] != 10 && tempgameconf[i] != 13 ) && ( i != 0 ) ) i--; - if ( i != 0 ) i++; + while (i != tempgameconfsize && tempgameconf[i] != ':') + i++; + if (i == tempgameconfsize) break; + while ((tempgameconf[i] != 10 && tempgameconf[i] != 13) && (i != 0)) + i--; + if (i != 0) i++; parsebufpos = 0; gameidmatch = 0; - while ( tempgameconf[i] != ':' ) + while (tempgameconf[i] != ':') { - if ( tempgameconf[i] == '?' ) + if (tempgameconf[i] == '?') { parsebuffer[parsebufpos] = discid[parsebufpos]; parsebufpos++; gameidmatch--; i++; } - else if ( tempgameconf[i] != 0 && tempgameconf[i] != ' ' ) + else if (tempgameconf[i] != 0 && tempgameconf[i] != ' ') parsebuffer[parsebufpos++] = tempgameconf[i++]; - else if ( tempgameconf[i] == ' ' ) + else if (tempgameconf[i] == ' ') break; - else - i++; - if ( parsebufpos == 8 ) break; + else i++; + if (parsebufpos == 8) break; } parsebuffer[parsebufpos] = 0; - if ( strncasecmp( "DEFAULT", parsebuffer, strlen( parsebuffer ) ) == 0 && strlen( parsebuffer ) == 7 ) + if (strncasecmp("DEFAULT", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 7) { gameidmatch = 0; goto idmatch; } - if ( strncmp( discid, parsebuffer, strlen( parsebuffer ) ) == 0 ) + if (strncmp(discid, parsebuffer, strlen(parsebuffer)) == 0) { - gameidmatch += strlen( parsebuffer ); -idmatch: - if ( gameidmatch > maxgameidmatch2 ) + gameidmatch += strlen(parsebuffer); + idmatch: if (gameidmatch > maxgameidmatch2) { maxgameidmatch2 = gameidmatch; } } - while ( ( i != tempgameconfsize ) && ( tempgameconf[i] != 10 && tempgameconf[i] != 13 ) ) i++; + while ((i != tempgameconfsize) && (tempgameconf[i] != 10 && tempgameconf[i] != 13)) + i++; } - while ( i != tempgameconfsize && tempgameconf[i] != ':' ) + while (i != tempgameconfsize && tempgameconf[i] != ':') { parsebufpos = 0; - while ( ( i != tempgameconfsize ) && ( tempgameconf[i] != 10 && tempgameconf[i] != 13 ) ) + while ((i != tempgameconfsize) && (tempgameconf[i] != 10 && tempgameconf[i] != 13)) { - if ( tempgameconf[i] != 0 && tempgameconf[i] != ' ' && tempgameconf[i] != '(' && tempgameconf[i] != ':' ) + if (tempgameconf[i] != 0 && tempgameconf[i] != ' ' && tempgameconf[i] != '(' && tempgameconf[i] + != ':') parsebuffer[parsebufpos++] = tempgameconf[i++]; - else if ( tempgameconf[i] == ' ' || tempgameconf[i] == '(' || tempgameconf[i] == ':' ) + else if (tempgameconf[i] == ' ' || tempgameconf[i] == '(' || tempgameconf[i] == ':') break; - else - i++; - if ( parsebufpos == 17 ) break; + else i++; + if (parsebufpos == 17) break; } parsebuffer[parsebufpos] = 0; //if (!autobootcheck) @@ -255,345 +253,348 @@ idmatch: // if (ret == 2) // addtocodelist(codeaddr, codeval); //} - if ( strncasecmp( "codeliststart", parsebuffer, strlen( parsebuffer ) ) == 0 && strlen( parsebuffer ) == 13 ) + if (strncasecmp("codeliststart", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) + == 13) { - sscanf( ( char * )( tempgameconf + i ), " = %x", ( unsigned int * )&codelist ); + sscanf((char *) (tempgameconf + i), " = %x", (unsigned int *) &codelist); } - if ( strncasecmp( "codelistend", parsebuffer, strlen( parsebuffer ) ) == 0 && strlen( parsebuffer ) == 11 ) + if (strncasecmp("codelistend", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 11) { - sscanf( ( char * )( tempgameconf + i ), " = %x", ( unsigned int * )&codelistend ); + sscanf((char *) (tempgameconf + i), " = %x", (unsigned int *) &codelistend); } /* - if (strncasecmp("hooktype", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 8) + if (strncasecmp("hooktype", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 8) + { + if (hookset == 1) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + if (temp >= 0 && temp <= 7) + config_bytes[2] = temp; + } + } + */ + if (strncasecmp("poke", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 4) { - if (hookset == 1) + ret = sscanf((char *) tempgameconf + i, "( %x , %x", &codeaddr, &codeval); + if (ret == 2) { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - if (temp >= 0 && temp <= 7) - config_bytes[2] = temp; - } - } - */ - if ( strncasecmp( "poke", parsebuffer, strlen( parsebuffer ) ) == 0 && strlen( parsebuffer ) == 4 ) - { - ret = sscanf( ( char * )tempgameconf + i, "( %x , %x", &codeaddr, &codeval ); - if ( ret == 2 ) - { - *( gameconf + ( gameconfsize / 4 ) ) = 0; + *(gameconf + (gameconfsize / 4)) = 0; gameconfsize += 4; - *( gameconf + ( gameconfsize / 4 ) ) = 0; + *(gameconf + (gameconfsize / 4)) = 0; gameconfsize += 8; - *( gameconf + ( gameconfsize / 4 ) ) = codeaddr; + *(gameconf + (gameconfsize / 4)) = codeaddr; gameconfsize += 4; - *( gameconf + ( gameconfsize / 4 ) ) = codeval; + *(gameconf + (gameconfsize / 4)) = codeval; gameconfsize += 4; - DCFlushRange( ( void * ) ( gameconf + ( gameconfsize / 4 ) - 5 ), 20 ); + DCFlushRange((void *) (gameconf + (gameconfsize / 4) - 5), 20); } } - if ( strncasecmp( "pokeifequal", parsebuffer, strlen( parsebuffer ) ) == 0 && strlen( parsebuffer ) == 11 ) + if (strncasecmp("pokeifequal", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 11) { - ret = sscanf( ( char * )( tempgameconf + i ), "( %x , %x , %x , %x", &codeaddr, &codeval, &codeaddr2, &codeval2 ); - if ( ret == 4 ) + ret = sscanf((char *) (tempgameconf + i), "( %x , %x , %x , %x", &codeaddr, &codeval, + &codeaddr2, &codeval2); + if (ret == 4) { - *( gameconf + ( gameconfsize / 4 ) ) = 0; + *(gameconf + (gameconfsize / 4)) = 0; gameconfsize += 4; - *( gameconf + ( gameconfsize / 4 ) ) = codeaddr; + *(gameconf + (gameconfsize / 4)) = codeaddr; gameconfsize += 4; - *( gameconf + ( gameconfsize / 4 ) ) = codeval; + *(gameconf + (gameconfsize / 4)) = codeval; gameconfsize += 4; - *( gameconf + ( gameconfsize / 4 ) ) = codeaddr2; + *(gameconf + (gameconfsize / 4)) = codeaddr2; gameconfsize += 4; - *( gameconf + ( gameconfsize / 4 ) ) = codeval2; + *(gameconf + (gameconfsize / 4)) = codeval2; gameconfsize += 4; - DCFlushRange( ( void * ) ( gameconf + ( gameconfsize / 4 ) - 5 ), 20 ); + DCFlushRange((void *) (gameconf + (gameconfsize / 4) - 5), 20); } } - if ( strncasecmp( "searchandpoke", parsebuffer, strlen( parsebuffer ) ) == 0 && strlen( parsebuffer ) == 13 ) + if (strncasecmp("searchandpoke", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) + == 13) { - ret = sscanf( ( char * )( tempgameconf + i ), "( %x%n", &codeval, &tempoffset ); - if ( ret == 1 ) + ret = sscanf((char *) (tempgameconf + i), "( %x%n", &codeval, &tempoffset); + if (ret == 1) { gameconfsize += 4; temp = 0; - while ( ret == 1 ) + while (ret == 1) { - *( gameconf + ( gameconfsize / 4 ) ) = codeval; + *(gameconf + (gameconfsize / 4)) = codeval; gameconfsize += 4; temp++; i += tempoffset; - ret = sscanf( ( char * )( tempgameconf + i ), " %x%n", &codeval, &tempoffset ); + ret = sscanf((char *) (tempgameconf + i), " %x%n", &codeval, &tempoffset); } - *( gameconf + ( gameconfsize / 4 ) - temp - 1 ) = temp; - ret = sscanf( ( char * )( tempgameconf + i ), " , %x , %x , %x , %x", &codeaddr, &codeaddr2, &codeoffset, &codeval2 ); - if ( ret == 4 ) + *(gameconf + (gameconfsize / 4) - temp - 1) = temp; + ret = sscanf((char *) (tempgameconf + i), " , %x , %x , %x , %x", &codeaddr, &codeaddr2, + &codeoffset, &codeval2); + if (ret == 4) { - *( gameconf + ( gameconfsize / 4 ) ) = codeaddr; + *(gameconf + (gameconfsize / 4)) = codeaddr; gameconfsize += 4; - *( gameconf + ( gameconfsize / 4 ) ) = codeaddr2; + *(gameconf + (gameconfsize / 4)) = codeaddr2; gameconfsize += 4; - *( gameconf + ( gameconfsize / 4 ) ) = codeoffset; + *(gameconf + (gameconfsize / 4)) = codeoffset; gameconfsize += 4; - *( gameconf + ( gameconfsize / 4 ) ) = codeval2; + *(gameconf + (gameconfsize / 4)) = codeval2; gameconfsize += 4; - DCFlushRange( ( void * ) ( gameconf + ( gameconfsize / 4 ) - temp - 5 ), temp * 4 + 20 ); + DCFlushRange((void *) (gameconf + (gameconfsize / 4) - temp - 5), temp * 4 + 20); } - else - gameconfsize -= temp * 4 + 4; + else gameconfsize -= temp * 4 + 4; } } /* - if (strncasecmp("hook", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 4) - { - ret = sscanf(tempgameconf + i, "( %x %x %x %x %x %x %x %x", customhook, customhook + 1, customhook + 2, customhook + 3, customhook + 4, customhook + 5, customhook + 6, customhook + 7); - if (ret >= 3) - { - if (hookset != 1) - configwarn |= 4; - config_bytes[2] = 0x08; - customhooksize = ret * 4; - } - } - if (strncasecmp("002fix", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 6) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - if (temp >= 0 && temp <= 0x1) - fakeiosversion = temp; - } - if (strncasecmp("switchios", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 9) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - if (temp >= 0 && temp <= 1) - willswitchios = temp; - } - if (strncasecmp("videomode", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 9) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - { - if (temp == 0) - { - if (config_bytes[1] != 0x00) - configwarn |= 1; - config_bytes[1] = 0x00; - } - else if (temp == 1) - { - if (config_bytes[1] != 0x03) - configwarn |= 1; - config_bytes[1] = 0x03; - } - else if (temp == 2) - { - if (config_bytes[1] != 0x01) - configwarn |= 1; - config_bytes[1] = 0x01; - } - else if (temp == 3) - { - if (config_bytes[1] != 0x02) - configwarn |= 1; - config_bytes[1] = 0x02; - } - } - } - if (strncasecmp("language", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 8) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - { - if (temp == 0) - { - if (config_bytes[0] != 0xCD) - configwarn |= 2; - config_bytes[0] = 0xCD; - } - else if (temp > 0 && temp <= 10) - { - if (config_bytes[0] != temp-1) - configwarn |= 2; - config_bytes[0] = temp-1; - } - } - } - if (strncasecmp("diagnostic", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 10) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - { - if (temp == 0 || temp == 1) - diagcreate = temp; - } - } - if (strncasecmp("vidtv", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 5) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - if (temp >= 0 && temp <= 1) - vipatchon = temp; - } - if (strncasecmp("fwritepatch", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 11) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - if (temp >= 0 && temp <= 1) - applyfwritepatch = temp; - } - if (strncasecmp("dumpmaindol", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 11) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - if (temp >= 0 && temp <= 1) - dumpmaindol = temp; - } - */ + if (strncasecmp("hook", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 4) + { + ret = sscanf(tempgameconf + i, "( %x %x %x %x %x %x %x %x", customhook, customhook + 1, customhook + 2, customhook + 3, customhook + 4, customhook + 5, customhook + 6, customhook + 7); + if (ret >= 3) + { + if (hookset != 1) + configwarn |= 4; + config_bytes[2] = 0x08; + customhooksize = ret * 4; + } + } + if (strncasecmp("002fix", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 6) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + if (temp >= 0 && temp <= 0x1) + fakeiosversion = temp; + } + if (strncasecmp("switchios", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 9) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + if (temp >= 0 && temp <= 1) + willswitchios = temp; + } + if (strncasecmp("videomode", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 9) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + { + if (temp == 0) + { + if (config_bytes[1] != 0x00) + configwarn |= 1; + config_bytes[1] = 0x00; + } + else if (temp == 1) + { + if (config_bytes[1] != 0x03) + configwarn |= 1; + config_bytes[1] = 0x03; + } + else if (temp == 2) + { + if (config_bytes[1] != 0x01) + configwarn |= 1; + config_bytes[1] = 0x01; + } + else if (temp == 3) + { + if (config_bytes[1] != 0x02) + configwarn |= 1; + config_bytes[1] = 0x02; + } + } + } + if (strncasecmp("language", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 8) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + { + if (temp == 0) + { + if (config_bytes[0] != 0xCD) + configwarn |= 2; + config_bytes[0] = 0xCD; + } + else if (temp > 0 && temp <= 10) + { + if (config_bytes[0] != temp-1) + configwarn |= 2; + config_bytes[0] = temp-1; + } + } + } + if (strncasecmp("diagnostic", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 10) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + { + if (temp == 0 || temp == 1) + diagcreate = temp; + } + } + if (strncasecmp("vidtv", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 5) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + if (temp >= 0 && temp <= 1) + vipatchon = temp; + } + if (strncasecmp("fwritepatch", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 11) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + if (temp >= 0 && temp <= 1) + applyfwritepatch = temp; + } + if (strncasecmp("dumpmaindol", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 11) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + if (temp >= 0 && temp <= 1) + dumpmaindol = temp; + } + */ } /*else - { + { - if (strncasecmp("autoboot", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 8) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - if (temp >= 0 && temp <= 1) - autoboot = temp; - } - if (strncasecmp("autobootwait", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 12) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - if (temp >= 0 && temp <= 255) - autobootwait = temp; - } - if (strncasecmp("autoboothbc", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 11) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - if (temp >= 0 && temp <= 1) - autoboothbc = temp; - } - if (strncasecmp("autobootocarina", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 15) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - if (temp >= 0 && temp <= 1) - config_bytes[4] = temp; - } - if (strncasecmp("autobootdebugger", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 16) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - if (temp >= 0 && temp <= 1) - config_bytes[7] = temp; - } - if (strncasecmp("rebootermenuitem", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 16) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - if (temp >= 0 && temp <= 1) - rebooterasmenuitem = temp; - } - if (strncasecmp("startupios", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 10) - { - ret = sscanf(tempgameconf + i, " = %u", &temp); - if (ret == 1) - if (temp >= 0 && temp <= 255) - { - sdio_Shutdown(); - IOS_ReloadIOS(temp); - detectIOScapabilities(); - sd_init(); - startupiosloaded = 1; - } - } + if (strncasecmp("autoboot", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 8) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + if (temp >= 0 && temp <= 1) + autoboot = temp; + } + if (strncasecmp("autobootwait", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 12) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + if (temp >= 0 && temp <= 255) + autobootwait = temp; + } + if (strncasecmp("autoboothbc", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 11) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + if (temp >= 0 && temp <= 1) + autoboothbc = temp; + } + if (strncasecmp("autobootocarina", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 15) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + if (temp >= 0 && temp <= 1) + config_bytes[4] = temp; + } + if (strncasecmp("autobootdebugger", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 16) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + if (temp >= 0 && temp <= 1) + config_bytes[7] = temp; + } + if (strncasecmp("rebootermenuitem", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 16) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + if (temp >= 0 && temp <= 1) + rebooterasmenuitem = temp; + } + if (strncasecmp("startupios", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 10) + { + ret = sscanf(tempgameconf + i, " = %u", &temp); + if (ret == 1) + if (temp >= 0 && temp <= 255) + { + sdio_Shutdown(); + IOS_ReloadIOS(temp); + detectIOScapabilities(); + sd_init(); + startupiosloaded = 1; + } + } - }*/ - if ( tempgameconf[i] != ':' ) + }*/ + if (tempgameconf[i] != ':') { - while ( ( i != tempgameconfsize ) && ( tempgameconf[i] != 10 && tempgameconf[i] != 13 ) ) i++; - if ( i != tempgameconfsize ) i++; + while ((i != tempgameconfsize) && (tempgameconf[i] != 10 && tempgameconf[i] != 13)) + i++; + if (i != tempgameconfsize) i++; } } - if ( i != tempgameconfsize ) while ( ( tempgameconf[i] != 10 && tempgameconf[i] != 13 ) && ( i != 0 ) ) i--; + if (i != tempgameconfsize) while ((tempgameconf[i] != 10 && tempgameconf[i] != 13) && (i != 0)) + i--; } } - free( tempgameconf ); + free(tempgameconf); //tempcodelist = ((u8 *) gameconf) + gameconfsize; } u8 *code_buf = NULL; int code_size = 0; -int ocarina_load_code( u8 *id ) +int ocarina_load_code(u8 *id) { - if ( debuggerselect == 0x00 ) - codelist = ( u8 * ) 0x800022A8; - else - codelist = ( u8 * ) 0x800028B8; - codelistend = ( u8 * ) 0x80003000; + if (debuggerselect == 0x00) + codelist = (u8 *) 0x800022A8; + else codelist = (u8 *) 0x800028B8; + codelistend = (u8 *) 0x80003000; - - app_loadgameconfig( ( char * )id ); + app_loadgameconfig((char *) id); char filepath[150]; - gprintf( "Ocarina: Searching codes..." ); - gprintf( "\n" ); + gprintf("Ocarina: Searching codes..."); + gprintf("\n"); - sprintf( filepath, "%s%s", CheatFilepath, ( char * ) id ); - filepath[strlen( CheatFilepath )+6] = 0x2E; - filepath[strlen( CheatFilepath )+7] = 0x67; - filepath[strlen( CheatFilepath )+8] = 0x63; - filepath[strlen( CheatFilepath )+9] = 0x74; - filepath[strlen( CheatFilepath )+10] = 0; + sprintf(filepath, "%s%s", CheatFilepath, (char *) id); + filepath[strlen(CheatFilepath) + 6] = 0x2E; + filepath[strlen(CheatFilepath) + 7] = 0x67; + filepath[strlen(CheatFilepath) + 8] = 0x63; + filepath[strlen(CheatFilepath) + 9] = 0x74; + filepath[strlen(CheatFilepath) + 10] = 0; - FILE * fp = fopen( filepath, "rb" ); - if ( !fp ) + FILE * fp = fopen(filepath, "rb"); + if (!fp) { - gprintf( "Ocarina: No codes found" ); - printf( "\n" ); + gprintf("Ocarina: No codes found"); + printf("\n"); return 0; } - fseek( fp, 0, SEEK_END ); - u32 filesize = ftell( fp ); - rewind( fp ); + fseek(fp, 0, SEEK_END); + u32 filesize = ftell(fp); + rewind(fp); - code_buf = ( u8* ) malloc( filesize ); - if ( !code_buf ) + code_buf = (u8*) malloc(filesize); + if (!code_buf) { - gprintf( "Ocarina: No codes found\n" ); - fclose( fp ); + gprintf("Ocarina: No codes found\n"); + fclose(fp); return 0; } - code_size = fread( code_buf, 1, filesize, fp ); + code_size = fread(code_buf, 1, filesize, fp); - fclose( fp ); + fclose(fp); - if ( code_size <= 0 ) + if (code_size <= 0) { - gprintf( "Ocarina: could not read file.\n" ); - free( code_buf ); + gprintf("Ocarina: could not read file.\n"); + free(code_buf); code_buf = NULL; code_size = 0; return 0; } - if ( code_size > ( s32 )codelistend - ( s32 )codelist ) + if (code_size > (s32) codelistend - (s32) codelist) { - gprintf( "Ocarina: Too many codes found\n" ); - free( code_buf ); + gprintf("Ocarina: Too many codes found\n"); + free(code_buf); code_buf = NULL; code_size = 0; return 0; } - gprintf( "Ocarina: Codes found.\n" ); + gprintf("Ocarina: Codes found.\n"); return code_size; } @@ -604,143 +605,141 @@ void app_pokevalues() { u32 i, *codeaddr, *codeaddr2, *addrfound = NULL; - if ( gameconfsize != 0 ) + if (gameconfsize != 0) { - for ( i = 0; i < gameconfsize / 4; i++ ) + for (i = 0; i < gameconfsize / 4; i++) { - if ( *( gameconf + i ) == 0 ) + if (*(gameconf + i) == 0) { - if ( ( ( u32 * ) ( *( gameconf + i + 1 ) ) ) == NULL || - *( ( u32 * ) ( *( gameconf + i + 1 ) ) ) == *( gameconf + i + 2 ) ) + if (((u32 *) (*(gameconf + i + 1))) == NULL || *((u32 *) (*(gameconf + i + 1))) == *(gameconf + i + 2)) { - *( ( u32 * ) ( *( gameconf + i + 3 ) ) ) = *( gameconf + i + 4 ); - DCFlushRange( ( void * ) *( gameconf + i + 3 ), 4 ); + *((u32 *) (*(gameconf + i + 3))) = *(gameconf + i + 4); + DCFlushRange((void *) *(gameconf + i + 3), 4); } i += 4; } else { - codeaddr = ( u32 * ) * ( gameconf + i + *( gameconf + i ) + 1 ); - codeaddr2 = ( u32 * ) * ( gameconf + i + *( gameconf + i ) + 2 ); - if ( codeaddr == 0 && addrfound != NULL ) + codeaddr = (u32 *) *(gameconf + i + *(gameconf + i) + 1); + codeaddr2 = (u32 *) *(gameconf + i + *(gameconf + i) + 2); + if (codeaddr == 0 && addrfound != NULL) codeaddr = addrfound; - else if ( codeaddr == 0 && codeaddr2 != 0 ) - codeaddr = ( u32 * ) ( ( ( ( u32 ) codeaddr2 ) >> 28 ) << 28 ); - else if ( codeaddr == 0 && codeaddr2 == 0 ) + else if (codeaddr == 0 && codeaddr2 != 0) + codeaddr = (u32 *) ((((u32) codeaddr2) >> 28) << 28); + else if (codeaddr == 0 && codeaddr2 == 0) { - i += *( gameconf + i ) + 4; + i += *(gameconf + i) + 4; continue; } - if ( codeaddr2 == 0 ) - codeaddr2 = codeaddr + *( gameconf + i ); + if (codeaddr2 == 0) codeaddr2 = codeaddr + *(gameconf + i); addrfound = NULL; - while ( codeaddr <= ( codeaddr2 - *( gameconf + i ) ) ) + while (codeaddr <= (codeaddr2 - *(gameconf + i))) { - if ( memcmp( codeaddr, gameconf + i + 1, ( *( gameconf + i ) ) * 4 ) == 0 ) + if (memcmp(codeaddr, gameconf + i + 1, (*(gameconf + i)) * 4) == 0) { - *( codeaddr + ( ( *( gameconf + i + *( gameconf + i ) + 3 ) ) / 4 ) ) = *( gameconf + i + *( gameconf + i ) + 4 ); - if ( addrfound == NULL ) addrfound = codeaddr; + *(codeaddr + ((*(gameconf + i + *(gameconf + i) + 3)) / 4)) = *(gameconf + i + *(gameconf + i) + + 4); + if (addrfound == NULL) addrfound = codeaddr; } codeaddr++; } - i += *( gameconf + i ) + 4; + i += *(gameconf + i) + 4; } } } } - //--------------------------------------------------------------------------------- void load_handler() //--------------------------------------------------------------------------------- { - if ( hooktype != 0x00 ) + if (hooktype != 0x00) { - if ( debuggerselect == 0x01 ) + if (debuggerselect == 0x01) { /*switch(gecko_channel) - { - case 0: // Slot A + { + case 0: // Slot A - memset((void*)0x80001800,0,codehandlerslota_size); - memcpy((void*)0x80001800,codehandlerslota,codehandlerslota_size); - if (pausedstartoption == 0x01) - *(u32*)0x80002798 = 1; - memcpy((void*)0x80001CDE, &codelist, 2); - memcpy((void*)0x80001CE2, ((u8*) &codelist) + 2, 2); - memcpy((void*)0x80001F7E, &codelist, 2); - memcpy((void*)0x80001F82, ((u8*) &codelist) + 2, 2); - DCFlushRange((void*)0x80001800,codehandlerslota_size); - break; + memset((void*)0x80001800,0,codehandlerslota_size); + memcpy((void*)0x80001800,codehandlerslota,codehandlerslota_size); + if (pausedstartoption == 0x01) + *(u32*)0x80002798 = 1; + memcpy((void*)0x80001CDE, &codelist, 2); + memcpy((void*)0x80001CE2, ((u8*) &codelist) + 2, 2); + memcpy((void*)0x80001F7E, &codelist, 2); + memcpy((void*)0x80001F82, ((u8*) &codelist) + 2, 2); + DCFlushRange((void*)0x80001800,codehandlerslota_size); + break; - case 1: // slot B - */ - memset( ( void* )0x80001800, 0, codehandler_size ); - memcpy( ( void* )0x80001800, codehandler, codehandler_size ); + case 1: // slot B + */ + memset((void*) 0x80001800, 0, codehandler_size); + memcpy((void*) 0x80001800, codehandler, codehandler_size); //TODO for oggzee: Consider adding an option for paused start, debugging related //if (pausedstartoption == 0x01) // *(u32*)0x80002798 = 1; - memcpy( ( void* )0x80001CDE, &codelist, 2 ); - memcpy( ( void* )0x80001CE2, ( ( u8* ) &codelist ) + 2, 2 ); - memcpy( ( void* )0x80001F5A, &codelist, 2 ); - memcpy( ( void* )0x80001F5E, ( ( u8* ) &codelist ) + 2, 2 ); - DCFlushRange( ( void* )0x80001800, codehandler_size ); + memcpy((void*) 0x80001CDE, &codelist, 2); + memcpy((void*) 0x80001CE2, ((u8*) &codelist) + 2, 2); + memcpy((void*) 0x80001F5A, &codelist, 2); + memcpy((void*) 0x80001F5E, ((u8*) &codelist) + 2, 2); + DCFlushRange((void*) 0x80001800, codehandler_size); /* break; - case 2: - memset((void*)0x80001800,0,codehandler_size); - memcpy((void*)0x80001800,codehandler,codehandler_size); - if (pausedstartoption == 0x01) - *(u32*)0x80002798 = 1; - memcpy((void*)0x80001CDE, &codelist, 2); - memcpy((void*)0x80001CE2, ((u8*) &codelist) + 2, 2); - memcpy((void*)0x80001F5A, &codelist, 2); - memcpy((void*)0x80001F5E, ((u8*) &codelist) + 2, 2); - DCFlushRange((void*)0x80001800,codehandler_size); - break; - }*/ + case 2: + memset((void*)0x80001800,0,codehandler_size); + memcpy((void*)0x80001800,codehandler,codehandler_size); + if (pausedstartoption == 0x01) + *(u32*)0x80002798 = 1; + memcpy((void*)0x80001CDE, &codelist, 2); + memcpy((void*)0x80001CE2, ((u8*) &codelist) + 2, 2); + memcpy((void*)0x80001F5A, &codelist, 2); + memcpy((void*)0x80001F5E, ((u8*) &codelist) + 2, 2); + DCFlushRange((void*)0x80001800,codehandler_size); + break; + }*/ } else { - memset( ( void* )0x80001800, 0, codehandleronly_size ); - memcpy( ( void* )0x80001800, codehandleronly, codehandleronly_size ); - memcpy( ( void* )0x80001906, &codelist, 2 ); - memcpy( ( void* )0x8000190A, ( ( u8* ) &codelist ) + 2, 2 ); - DCFlushRange( ( void* )0x80001800, codehandleronly_size ); + memset((void*) 0x80001800, 0, codehandleronly_size); + memcpy((void*) 0x80001800, codehandleronly, codehandleronly_size); + memcpy((void*) 0x80001906, &codelist, 2); + memcpy((void*) 0x8000190A, ((u8*) &codelist) + 2, 2); + DCFlushRange((void*) 0x80001800, codehandleronly_size); } // Load multidol handler - memset( ( void* )0x80001000, 0, multidol_size ); - memcpy( ( void* )0x80001000, multidol, multidol_size ); - DCFlushRange( ( void* )0x80001000, multidol_size ); - switch ( hooktype ) + memset((void*) 0x80001000, 0, multidol_size); + memcpy((void*) 0x80001000, multidol, multidol_size); + DCFlushRange((void*) 0x80001000, multidol_size); + switch (hooktype) { case 0x01: - memcpy( ( void* )0x8000119C, viwiihooks, 12 ); - memcpy( ( void* )0x80001198, viwiihooks + 3, 4 ); + memcpy((void*) 0x8000119C, viwiihooks, 12); + memcpy((void*) 0x80001198, viwiihooks + 3, 4); break; case 0x02: - memcpy( ( void* )0x8000119C, kpadhooks, 12 ); - memcpy( ( void* )0x80001198, kpadhooks + 3, 4 ); + memcpy((void*) 0x8000119C, kpadhooks, 12); + memcpy((void*) 0x80001198, kpadhooks + 3, 4); break; case 0x03: - memcpy( ( void* )0x8000119C, joypadhooks, 12 ); - memcpy( ( void* )0x80001198, joypadhooks + 3, 4 ); + memcpy((void*) 0x8000119C, joypadhooks, 12); + memcpy((void*) 0x80001198, joypadhooks + 3, 4); break; case 0x04: - memcpy( ( void* )0x8000119C, gxdrawhooks, 12 ); - memcpy( ( void* )0x80001198, gxdrawhooks + 3, 4 ); + memcpy((void*) 0x8000119C, gxdrawhooks, 12); + memcpy((void*) 0x80001198, gxdrawhooks + 3, 4); break; case 0x05: - memcpy( ( void* )0x8000119C, gxflushhooks, 12 ); - memcpy( ( void* )0x80001198, gxflushhooks + 3, 4 ); + memcpy((void*) 0x8000119C, gxflushhooks, 12); + memcpy((void*) 0x80001198, gxflushhooks + 3, 4); break; case 0x06: - memcpy( ( void* )0x8000119C, ossleepthreadhooks, 12 ); - memcpy( ( void* )0x80001198, ossleepthreadhooks + 3, 4 ); + memcpy((void*) 0x8000119C, ossleepthreadhooks, 12); + memcpy((void*) 0x80001198, ossleepthreadhooks + 3, 4); break; case 0x07: - memcpy( ( void* )0x8000119C, axnextframehooks, 12 ); - memcpy( ( void* )0x80001198, axnextframehooks + 3, 4 ); + memcpy((void*) 0x8000119C, axnextframehooks, 12); + memcpy((void*) 0x80001198, axnextframehooks + 3, 4); break; case 0x08: //if (customhooksize == 16) @@ -758,29 +757,29 @@ void load_handler() //memcpy((void*)0x80001198,wpadbuttonsdown2hooks+3,4); break; } - DCFlushRange( ( void* )0x80001198, 16 ); + DCFlushRange((void*) 0x80001198, 16); } - memcpy( ( void * )0x80001800, ( void* )0x80000000, 6 ); + memcpy((void *) 0x80001800, (void*) 0x80000000, 6); } int ocarina_do_code() { - if ( !code_buf ) + if (!code_buf) { return 0; } - memset( ( void * )0x80001800, 0, 0x1800 ); + memset((void *) 0x80001800, 0, 0x1800); load_handler(); - memset( codelist, 0, ( u32 )codelistend - ( u32 )codelist ); + memset(codelist, 0, (u32) codelistend - (u32) codelist); //Copy the codes - if ( code_size > 0 ) + if (code_size > 0) { - memcpy( codelist, code_buf, code_size ); - DCFlushRange( codelist, ( u32 )codelistend - ( u32 )codelist ); - free( code_buf ); + memcpy(codelist, code_buf, code_size); + DCFlushRange(codelist, (u32) codelistend - (u32) codelist); + free(code_buf); code_buf = NULL; } @@ -795,68 +794,67 @@ int ocarina_do_code() return 1; } -u32 do_bca_code( u8 *gameid ) +u32 do_bca_code(u8 *gameid) { - if(!BCAFilepath) - return 0; + if (!BCAFilepath) return 0; - if ( IOS_GetVersion() == 222 || IOS_GetVersion() == 223 ) + if (IOS_GetVersion() == 222 || IOS_GetVersion() == 223) { FILE *fp; u32 filesize; char filepath[150]; - memset( filepath, 0, 150 ); + memset(filepath, 0, 150); u8 bcaCode[64] ATTRIBUTE_ALIGN( 32 ); - sprintf( filepath, "%s%6s", BCAFilepath, gameid ); - filepath[strlen( BCAFilepath )+6] = '.'; - filepath[strlen( BCAFilepath )+7] = 'b'; - filepath[strlen( BCAFilepath )+8] = 'c'; - filepath[strlen( BCAFilepath )+9] = 'a'; + sprintf(filepath, "%s%6s", BCAFilepath, gameid); + filepath[strlen(BCAFilepath) + 6] = '.'; + filepath[strlen(BCAFilepath) + 7] = 'b'; + filepath[strlen(BCAFilepath) + 8] = 'c'; + filepath[strlen(BCAFilepath) + 9] = 'a'; - fp = fopen( filepath, "rb" ); - if ( !fp ) + fp = fopen(filepath, "rb"); + if (!fp) { - memset( filepath, 0, 150 ); - sprintf( filepath, "%s%3s", BCAFilepath, gameid + 1 ); - filepath[strlen( BCAFilepath )+3] = '.'; - filepath[strlen( BCAFilepath )+4] = 'b'; - filepath[strlen( BCAFilepath )+5] = 'c'; - filepath[strlen( BCAFilepath )+6] = 'a'; - fp = fopen( filepath, "rb" ); + memset(filepath, 0, 150); + sprintf(filepath, "%s%3s", BCAFilepath, gameid + 1); + filepath[strlen(BCAFilepath) + 3] = '.'; + filepath[strlen(BCAFilepath) + 4] = 'b'; + filepath[strlen(BCAFilepath) + 5] = 'c'; + filepath[strlen(BCAFilepath) + 6] = 'a'; + fp = fopen(filepath, "rb"); - if ( !fp ) + if (!fp) { // Set default bcaCode - memset( bcaCode, 0, 64 ); + memset(bcaCode, 0, 64); bcaCode[0x33] = 1; } } - if ( fp ) + if (fp) { u32 ret = 0; - fseek( fp, 0, SEEK_END ); - filesize = ftell( fp ); + fseek(fp, 0, SEEK_END); + filesize = ftell(fp); - if ( filesize == 64 ) + if (filesize == 64) { - fseek( fp, 0, SEEK_SET ); - ret = fread( bcaCode, 1, 64, fp ); + fseek(fp, 0, SEEK_SET); + ret = fread(bcaCode, 1, 64, fp); } - fclose( fp ); + fclose(fp); - if ( ret != 64 ) + if (ret != 64) { // Set default bcaCode - memset( bcaCode, 0, 64 ); + 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_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 9c89c925..290e2af5 100644 --- a/source/patches/fst.h +++ b/source/patches/fst.h @@ -26,13 +26,13 @@ extern "C" { #endif -//u32 do_fst(u32 fstlocation); -//u32 do_sd_code(char *filename); + //u32 do_fst(u32 fstlocation); + //u32 do_sd_code(char *filename); #define MAX_GCT_SIZE 2056 - u32 do_bca_code( u8 *gameid ); - int ocarina_load_code( u8 *id ); + u32 do_bca_code(u8 *gameid); + int ocarina_load_code(u8 *id); int ocarina_do_code(); void SetCheatFilepath(const char * path); void SetBCAFilepath(const char * path); diff --git a/source/patches/fwrite_patch.h b/source/patches/fwrite_patch.h index cd180104..026f2796 100644 --- a/source/patches/fwrite_patch.h +++ b/source/patches/fwrite_patch.h @@ -1,16 +1,9 @@ -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 -}; +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 }; unsigned int fwrite_patch_bin_len = 136; diff --git a/source/patches/gamepatches.c b/source/patches/gamepatches.c index e1c21bc6..89831429 100644 --- a/source/patches/gamepatches.c +++ b/source/patches/gamepatches.c @@ -6,56 +6,71 @@ #include "gecko.h" /** Anti 002 fix for IOS 249 rev > 12 thanks to WiiPower **/ -bool Anti_002_fix( u8 * Address, int Size ) +bool Anti_002_fix(u8 * Address, int Size) { - u8 SearchPattern[12] = { 0x2C, 0x00, 0x00, 0x00, 0x48, 0x00, 0x02, 0x14, 0x3C, 0x60, 0x80, 0x00 }; - u8 PatchData[12] = { 0x2C, 0x00, 0x00, 0x00, 0x40, 0x82, 0x02, 0x14, 0x3C, 0x60, 0x80, 0x00 }; - return PatchDOL( Address, Size, ( const u8 * ) &SearchPattern, sizeof( SearchPattern ), ( const u8 * ) &PatchData, sizeof( PatchData ) ); + u8 SearchPattern[12] = { 0x2C, 0x00, 0x00, 0x00, 0x48, 0x00, 0x02, 0x14, 0x3C, 0x60, 0x80, 0x00 }; + u8 PatchData[12] = { 0x2C, 0x00, 0x00, 0x00, 0x40, 0x82, 0x02, 0x14, 0x3C, 0x60, 0x80, 0x00 }; + return PatchDOL(Address, Size, (const u8 *) &SearchPattern, sizeof(SearchPattern), (const u8 *) &PatchData, + sizeof(PatchData)); } /** Thanks to WiiPower **/ -bool NSMBPatch( u8 * Address, int Size ) +bool NSMBPatch(u8 * 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 (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 ) + 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 }; - return PatchDOL( Address, Size, ( const u8 * ) &SearchPattern, sizeof( SearchPattern ), ( const u8 * ) &PatchData, sizeof( PatchData ) ); + 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 }; + return PatchDOL(Address, Size, (const u8 *) &SearchPattern, sizeof(SearchPattern), (const u8 *) &PatchData, + sizeof(PatchData)); } - else if ( memcmp( "SMN", ( char * )0x80000000, 3 ) == 0 ) + else if (memcmp("SMN", (char *) 0x80000000, 3) == 0) { - u8 SearchPattern[4] = { 0x7A, 0x6B, 0x6F, 0x6A }; - 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 }; - return PatchDOL( Address, Size, ( const u8 * ) &SearchPattern, sizeof( SearchPattern ), ( const u8 * ) &PatchData, sizeof( PatchData ) ); + u8 SearchPattern[4] = { 0x7A, 0x6B, 0x6F, 0x6A }; + 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 }; + return PatchDOL(Address, Size, (const u8 *) &SearchPattern, sizeof(SearchPattern), (const u8 *) &PatchData, + sizeof(PatchData)); } return false; } bool PoPPatch() { - if ( memcmp( "SPX", ( char * )0x80000000, 3 ) == 0 || memcmp( "RPW", ( char * )0x80000000, 3 ) == 0 ) + if (memcmp("SPX", (char *) 0x80000000, 3) == 0 || memcmp("RPW", (char *) 0x80000000, 3) == 0) { - WIP_Code * CodeList = malloc( 5 * sizeof( WIP_Code ) ); - CodeList[0].offset = 0x007AAC6A; CodeList[0].srcaddress = 0x7A6B6F6A; CodeList[0].dstaddress = 0x6F6A7A6B; - CodeList[1].offset = 0x007AAC75; CodeList[1].srcaddress = 0x7C7A6939; CodeList[1].dstaddress = 0x69397C7A; - CodeList[2].offset = 0x007AAC82; CodeList[2].srcaddress = 0x7376686B; CodeList[2].dstaddress = 0x686B7376; - CodeList[3].offset = 0x007AAC92; CodeList[3].srcaddress = 0x80717570; CodeList[3].dstaddress = 0x75708071; - CodeList[4].offset = 0x007AAC9D; CodeList[4].srcaddress = 0x82806F3F; CodeList[4].dstaddress = 0x6F3F8280; + WIP_Code * CodeList = malloc(5 * sizeof(WIP_Code)); + CodeList[0].offset = 0x007AAC6A; + CodeList[0].srcaddress = 0x7A6B6F6A; + CodeList[0].dstaddress = 0x6F6A7A6B; + CodeList[1].offset = 0x007AAC75; + CodeList[1].srcaddress = 0x7C7A6939; + CodeList[1].dstaddress = 0x69397C7A; + CodeList[2].offset = 0x007AAC82; + CodeList[2].srcaddress = 0x7376686B; + CodeList[2].dstaddress = 0x686B7376; + CodeList[3].offset = 0x007AAC92; + CodeList[3].srcaddress = 0x80717570; + CodeList[3].dstaddress = 0x75708071; + CodeList[4].offset = 0x007AAC9D; + CodeList[4].srcaddress = 0x82806F3F; + CodeList[4].dstaddress = 0x6F3F8280; - if ( set_wip_list( CodeList, 5 ) == false ) + if (set_wip_list(CodeList, 5) == false) { - free( CodeList ); + free(CodeList); CodeList = NULL; } } return false; } - - /** Insert the individual gamepatches above with the patterns and patch data **/ /** Following is only the VideoPatcher **/ @@ -93,73 +108,47 @@ static GXRModeObj* vmodes[] = #endif -static GXRModeObj* PAL2NTSC[] = -{ - &TVMpal480IntDf, &TVNtsc480IntDf, - &TVPal264Ds, &TVNtsc240Ds, - &TVPal264DsAa, &TVNtsc240DsAa, - &TVPal264Int, &TVNtsc240Int, - &TVPal264IntAa, &TVNtsc240IntAa, - &TVPal524IntAa, &TVNtsc480IntAa, - &TVPal528Int, &TVNtsc480IntAa, - &TVPal528IntDf, &TVNtsc480IntDf, - &TVPal574IntDfScale, &TVNtsc480IntDf, - &TVEurgb60Hz240Ds, &TVNtsc240Ds, - &TVEurgb60Hz240DsAa, &TVNtsc240DsAa, - &TVEurgb60Hz240Int, &TVNtsc240Int, - &TVEurgb60Hz240IntAa, &TVNtsc240IntAa, - &TVEurgb60Hz480Int, &TVNtsc480IntAa, - &TVEurgb60Hz480IntDf, &TVNtsc480IntDf, - &TVEurgb60Hz480IntAa, &TVNtsc480IntAa, - &TVEurgb60Hz480Prog, &TVNtsc480Prog, - &TVEurgb60Hz480ProgSoft, &TVNtsc480Prog, - &TVEurgb60Hz480ProgAa, &TVNtsc480Prog, - 0, 0 -}; +static GXRModeObj* PAL2NTSC[] = { &TVMpal480IntDf, &TVNtsc480IntDf, &TVPal264Ds, &TVNtsc240Ds, &TVPal264DsAa, + &TVNtsc240DsAa, &TVPal264Int, &TVNtsc240Int, &TVPal264IntAa, &TVNtsc240IntAa, &TVPal524IntAa, &TVNtsc480IntAa, + &TVPal528Int, &TVNtsc480IntAa, &TVPal528IntDf, &TVNtsc480IntDf, &TVPal574IntDfScale, &TVNtsc480IntDf, + &TVEurgb60Hz240Ds, &TVNtsc240Ds, &TVEurgb60Hz240DsAa, &TVNtsc240DsAa, &TVEurgb60Hz240Int, &TVNtsc240Int, + &TVEurgb60Hz240IntAa, &TVNtsc240IntAa, &TVEurgb60Hz480Int, &TVNtsc480IntAa, &TVEurgb60Hz480IntDf, + &TVNtsc480IntDf, &TVEurgb60Hz480IntAa, &TVNtsc480IntAa, &TVEurgb60Hz480Prog, &TVNtsc480Prog, + &TVEurgb60Hz480ProgSoft, &TVNtsc480Prog, &TVEurgb60Hz480ProgAa, &TVNtsc480Prog, 0, 0 }; -static GXRModeObj* NTSC2PAL[] = -{ - &TVNtsc240Ds, &TVPal264Ds, - &TVNtsc240DsAa, &TVPal264DsAa, - &TVNtsc240Int, &TVPal264Int, - &TVNtsc240IntAa, &TVPal264IntAa, - &TVNtsc480IntDf, &TVPal528IntDf, - &TVNtsc480IntAa, &TVPal524IntAa, - &TVNtsc480Prog, &TVPal528IntDf, - 0, 0 -}; +static GXRModeObj* NTSC2PAL[] = { &TVNtsc240Ds, &TVPal264Ds, &TVNtsc240DsAa, &TVPal264DsAa, &TVNtsc240Int, + &TVPal264Int, &TVNtsc240IntAa, &TVPal264IntAa, &TVNtsc480IntDf, &TVPal528IntDf, &TVNtsc480IntAa, + &TVPal524IntAa, &TVNtsc480Prog, &TVPal528IntDf, 0, 0 }; -static GXRModeObj* NTSC2PAL60[] = -{ - &TVNtsc240Ds, &TVEurgb60Hz240Ds, - &TVNtsc240DsAa, &TVEurgb60Hz240DsAa, - &TVNtsc240Int, &TVEurgb60Hz240Int, - &TVNtsc240IntAa, &TVEurgb60Hz240IntAa, - &TVNtsc480IntDf, &TVEurgb60Hz480IntDf, - &TVNtsc480IntAa, &TVEurgb60Hz480IntAa, - &TVNtsc480Prog, &TVEurgb60Hz480Prog, - 0, 0 -}; +static GXRModeObj* NTSC2PAL60[] = { &TVNtsc240Ds, &TVEurgb60Hz240Ds, &TVNtsc240DsAa, &TVEurgb60Hz240DsAa, + &TVNtsc240Int, &TVEurgb60Hz240Int, &TVNtsc240IntAa, &TVEurgb60Hz240IntAa, &TVNtsc480IntDf, + &TVEurgb60Hz480IntDf, &TVNtsc480IntAa, &TVEurgb60Hz480IntAa, &TVNtsc480Prog, &TVEurgb60Hz480Prog, 0, 0 }; -static bool compare_videomodes( GXRModeObj* mode1, GXRModeObj* mode2 ) +static bool compare_videomodes(GXRModeObj* mode1, GXRModeObj* mode2) { - if ( mode1->viTVMode != mode2->viTVMode || mode1->fbWidth != mode2->fbWidth || mode1->efbHeight != mode2->efbHeight || mode1->xfbHeight != mode2->xfbHeight || - mode1->viXOrigin != mode2->viXOrigin || mode1->viYOrigin != mode2->viYOrigin || mode1->viWidth != mode2->viWidth || mode1->viHeight != mode2->viHeight || - mode1->xfbMode != mode2->xfbMode || mode1->field_rendering != mode2->field_rendering || mode1->aa != mode2->aa || mode1->sample_pattern[0][0] != mode2->sample_pattern[0][0] || - mode1->sample_pattern[1][0] != mode2->sample_pattern[1][0] || mode1->sample_pattern[2][0] != mode2->sample_pattern[2][0] || - mode1->sample_pattern[3][0] != mode2->sample_pattern[3][0] || mode1->sample_pattern[4][0] != mode2->sample_pattern[4][0] || - mode1->sample_pattern[5][0] != mode2->sample_pattern[5][0] || mode1->sample_pattern[6][0] != mode2->sample_pattern[6][0] || - mode1->sample_pattern[7][0] != mode2->sample_pattern[7][0] || mode1->sample_pattern[8][0] != mode2->sample_pattern[8][0] || - mode1->sample_pattern[9][0] != mode2->sample_pattern[9][0] || mode1->sample_pattern[10][0] != mode2->sample_pattern[10][0] || - mode1->sample_pattern[11][0] != mode2->sample_pattern[11][0] || mode1->sample_pattern[0][1] != mode2->sample_pattern[0][1] || - mode1->sample_pattern[1][1] != mode2->sample_pattern[1][1] || mode1->sample_pattern[2][1] != mode2->sample_pattern[2][1] || - mode1->sample_pattern[3][1] != mode2->sample_pattern[3][1] || mode1->sample_pattern[4][1] != mode2->sample_pattern[4][1] || - mode1->sample_pattern[5][1] != mode2->sample_pattern[5][1] || mode1->sample_pattern[6][1] != mode2->sample_pattern[6][1] || - mode1->sample_pattern[7][1] != mode2->sample_pattern[7][1] || mode1->sample_pattern[8][1] != mode2->sample_pattern[8][1] || - mode1->sample_pattern[9][1] != mode2->sample_pattern[9][1] || mode1->sample_pattern[10][1] != mode2->sample_pattern[10][1] || - mode1->sample_pattern[11][1] != mode2->sample_pattern[11][1] || mode1->vfilter[0] != mode2->vfilter[0] || - mode1->vfilter[1] != mode2->vfilter[1] || mode1->vfilter[2] != mode2->vfilter[2] || mode1->vfilter[3] != mode2->vfilter[3] || mode1->vfilter[4] != mode2->vfilter[4] || - mode1->vfilter[5] != mode2->vfilter[5] || mode1->vfilter[6] != mode2->vfilter[6] ) + if (mode1->viTVMode != mode2->viTVMode || mode1->fbWidth != mode2->fbWidth || mode1->efbHeight != mode2->efbHeight + || mode1->xfbHeight != mode2->xfbHeight || mode1->viXOrigin != mode2->viXOrigin || mode1->viYOrigin + != mode2->viYOrigin || mode1->viWidth != mode2->viWidth || mode1->viHeight != mode2->viHeight + || mode1->xfbMode != mode2->xfbMode || mode1->field_rendering != mode2->field_rendering || mode1->aa + != mode2->aa || mode1->sample_pattern[0][0] != mode2->sample_pattern[0][0] || mode1->sample_pattern[1][0] + != mode2->sample_pattern[1][0] || mode1->sample_pattern[2][0] != mode2->sample_pattern[2][0] + || mode1->sample_pattern[3][0] != mode2->sample_pattern[3][0] || mode1->sample_pattern[4][0] + != mode2->sample_pattern[4][0] || mode1->sample_pattern[5][0] != mode2->sample_pattern[5][0] + || mode1->sample_pattern[6][0] != mode2->sample_pattern[6][0] || mode1->sample_pattern[7][0] + != mode2->sample_pattern[7][0] || mode1->sample_pattern[8][0] != mode2->sample_pattern[8][0] + || mode1->sample_pattern[9][0] != mode2->sample_pattern[9][0] || mode1->sample_pattern[10][0] + != mode2->sample_pattern[10][0] || mode1->sample_pattern[11][0] != mode2->sample_pattern[11][0] + || mode1->sample_pattern[0][1] != mode2->sample_pattern[0][1] || mode1->sample_pattern[1][1] + != mode2->sample_pattern[1][1] || mode1->sample_pattern[2][1] != mode2->sample_pattern[2][1] + || mode1->sample_pattern[3][1] != mode2->sample_pattern[3][1] || mode1->sample_pattern[4][1] + != mode2->sample_pattern[4][1] || mode1->sample_pattern[5][1] != mode2->sample_pattern[5][1] + || mode1->sample_pattern[6][1] != mode2->sample_pattern[6][1] || mode1->sample_pattern[7][1] + != mode2->sample_pattern[7][1] || mode1->sample_pattern[8][1] != mode2->sample_pattern[8][1] + || mode1->sample_pattern[9][1] != mode2->sample_pattern[9][1] || mode1->sample_pattern[10][1] + != mode2->sample_pattern[10][1] || mode1->sample_pattern[11][1] != mode2->sample_pattern[11][1] + || mode1->vfilter[0] != mode2->vfilter[0] || mode1->vfilter[1] != mode2->vfilter[1] || mode1->vfilter[2] + != mode2->vfilter[2] || mode1->vfilter[3] != mode2->vfilter[3] || mode1->vfilter[4] != mode2->vfilter[4] + || mode1->vfilter[5] != mode2->vfilter[5] || mode1->vfilter[6] != mode2->vfilter[6]) { return false; } @@ -169,8 +158,7 @@ static bool compare_videomodes( GXRModeObj* mode1, GXRModeObj* mode2 ) } } - -static void patch_videomode( GXRModeObj* mode1, GXRModeObj* mode2 ) +static void patch_videomode(GXRModeObj* mode1, GXRModeObj* mode2) { mode1->viTVMode = mode2->viTVMode; mode1->fbWidth = mode2->fbWidth; @@ -216,25 +204,25 @@ static void patch_videomode( GXRModeObj* mode1, GXRModeObj* mode2 ) mode1->vfilter[6] = mode2->vfilter[6]; } -static bool Search_and_patch_Video_Modes( u8 * Address, u32 Size, GXRModeObj* Table[] ) +static bool Search_and_patch_Video_Modes(u8 * Address, u32 Size, GXRModeObj* Table[]) { - u8 *Addr = ( u8 * )Address; + u8 *Addr = (u8 *) Address; bool found = 0; u32 i; - while ( Size >= sizeof( GXRModeObj ) ) + while (Size >= sizeof(GXRModeObj)) { - for ( i = 0; Table[i]; i += 2 ) + for (i = 0; Table[i]; i += 2) { - if ( compare_videomodes( Table[i], ( GXRModeObj* )Addr ) ) + if (compare_videomodes(Table[i], (GXRModeObj*) Addr)) { found = 1; - patch_videomode( ( GXRModeObj* )Addr, Table[i+1] ); - Addr += ( sizeof( GXRModeObj ) - 4 ); - Size -= ( sizeof( GXRModeObj ) - 4 ); + patch_videomode((GXRModeObj*) Addr, Table[i + 1]); + Addr += (sizeof(GXRModeObj) - 4); + Size -= (sizeof(GXRModeObj) - 4); break; } } @@ -243,20 +231,19 @@ static bool Search_and_patch_Video_Modes( u8 * Address, u32 Size, GXRModeObj* Ta Size -= 4; } - return found; } -void VideoModePatcher( u8 * dst, int len, u8 videoSelected ) +void VideoModePatcher(u8 * dst, int len, u8 videoSelected) { GXRModeObj** table = NULL; - if ( videoSelected == 5 ) // patch + if (videoSelected == 5) // patch { - switch ( CONF_GetVideo() ) + switch (CONF_GetVideo()) { case CONF_VIDEO_PAL: - if ( CONF_GetEuRGB60() > 0 ) + if (CONF_GetEuRGB60() > 0) { table = NTSC2PAL60; } @@ -268,149 +255,153 @@ void VideoModePatcher( u8 * dst, int len, u8 videoSelected ) case CONF_VIDEO_MPAL: - - table = NTSC2PAL; break; - default: table = PAL2NTSC; break; } - Search_and_patch_Video_Modes( dst, len, table ); + Search_and_patch_Video_Modes(dst, len, table); } } //giantpune's magic super patch to return to channels -bool PatchReturnTo( void *Address, int Size, u32 id ) { - if( !id )return 0; +bool PatchReturnTo(void *Address, int Size, u32 id) +{ + if (!id) return 0; //new __OSLoadMenu() (SM2.0 and higher) - u8 SearchPattern[ 12 ] = { 0x38, 0x80, 0x00, 0x02, 0x38, 0x60, 0x00, 0x01, 0x38, 0xa0, 0x00, 0x00 }; + u8 SearchPattern[12] = { 0x38, 0x80, 0x00, 0x02, 0x38, 0x60, 0x00, 0x01, 0x38, 0xa0, 0x00, 0x00 }; //old _OSLoadMenu() (used in launch games) - u8 SearchPatternB[ 12 ] = { 0x38, 0xC0, 0x00, 0x02, 0x38, 0xA0, 0x00, 0x01, 0x38, 0xE0, 0x00, 0x00 }; + u8 SearchPatternB[12] = { 0x38, 0xC0, 0x00, 0x02, 0x38, 0xA0, 0x00, 0x01, 0x38, 0xE0, 0x00, 0x00 }; //identifier for the safe place - u8 SearchPattern2[ 12 ] = { 0x4D, 0x65, 0x74, 0x72, 0x6F, 0x77, 0x65, 0x72, 0x6B, 0x73, 0x20, 0x54 }; - + u8 SearchPattern2[12] = { 0x4D, 0x65, 0x74, 0x72, 0x6F, 0x77, 0x65, 0x72, 0x6B, 0x73, 0x20, 0x54 }; int found = 0; int patched = 0; u8 oldSDK = 0; - u32 ad[ 4 ] = { 0, 0, 0, 0 }; + u32 ad[4] = { 0, 0, 0, 0 }; void *Addr = Address; - void *Addr_end = Address+Size; + void *Addr_end = Address + Size; - while (Addr <= Addr_end - 12 ) { - //find a safe place or the patch to hang out - if ( ! ad[ 3 ] && memcmp( Addr, SearchPattern2, 12 )==0 ) { - ad[ 3 ] = (u32)Addr + 0x30; - //gprintf("found a safe place @ %08x\n", ad[ 3 ]); - //hexdump( Addr, 0x50 ); - } - //find __OSLaunchMenu() and remember some addresses in it - else if ( memcmp( Addr, SearchPattern, 12 )==0 ) { - ad[ found++ ] = (u32)Addr; - } - else if ( ad[ 0 ] && memcmp( Addr, SearchPattern, 8 )==0 ) //after the first match is found, only search the first 8 bytes for the other 2 - { - if( !ad[ 1 ] ) ad[ found++ ] = (u32)Addr; - else if( !ad[ 2 ] ) ad[ found++ ] = (u32)Addr; - if( found >= 3 )break; - } - Addr += 4; + while (Addr <= Addr_end - 12) + { + //find a safe place or the patch to hang out + if (!ad[3] && memcmp(Addr, SearchPattern2, 12) == 0) + { + ad[3] = (u32) Addr + 0x30; + //gprintf("found a safe place @ %08x\n", ad[ 3 ]); + //hexdump( Addr, 0x50 ); + } + //find __OSLaunchMenu() and remember some addresses in it + else if (memcmp(Addr, SearchPattern, 12) == 0) + { + ad[found++] = (u32) Addr; + } + else if (ad[0] && memcmp(Addr, SearchPattern, 8) == 0) //after the first match is found, only search the first 8 bytes for the other 2 + { + if (!ad[1]) + ad[found++] = (u32) Addr; + else if (!ad[2]) ad[found++] = (u32) Addr; + if (found >= 3) break; + } + Addr += 4; } //check for the older-ass version of the SDK - if( found < 3 && ad[ 3 ] ) + if (found < 3 && ad[3]) { - Addr = Address; - ad[ 0 ] = 0; ad[ 1 ] = 0; - ad[ 2 ] = 0; - found = 0; - oldSDK = 1; + Addr = Address; + ad[0] = 0; + ad[1] = 0; + ad[2] = 0; + found = 0; + oldSDK = 1; - while (Addr <= Addr_end - 12 ) { - //find __OSLaunchMenu() and remember some addresses in it - if ( memcmp( Addr, SearchPatternB, 12 )==0 ) { - ad[ found++ ] = (u32)Addr; - } - else if ( ad[ 0 ] && memcmp( Addr, SearchPatternB, 8 ) == 0 ) //after the first match is found, only search the first 8 bytes for the other 2 - { - if( !ad[ 1 ] ) ad[ found++ ] = (u32)Addr; - else if( !ad[ 2 ] ) ad[ found++ ] = (u32)Addr; - if( found >= 3 )break; - } - Addr += 4; - } + while (Addr <= Addr_end - 12) + { + //find __OSLaunchMenu() and remember some addresses in it + if (memcmp(Addr, SearchPatternB, 12) == 0) + { + ad[found++] = (u32) Addr; + } + else if (ad[0] && memcmp(Addr, SearchPatternB, 8) == 0) //after the first match is found, only search the first 8 bytes for the other 2 + { + if (!ad[1]) + ad[found++] = (u32) Addr; + else if (!ad[2]) ad[found++] = (u32) Addr; + if (found >= 3) break; + } + Addr += 4; + } } //if the function is found and if it is not too far into the main.dol - if( found == 3 && ( ad[ 2 ] - ad[ 3 ] < 0x1000001 ) && ad[ 3 ] ) + if (found == 3 && (ad[2] - ad[3] < 0x1000001) && ad[3]) { - //gprintf("patch __OSLaunchMenu( 0x00010001, 0x%08x )\n", id); - u32 nop = 0x60000000; + //gprintf("patch __OSLaunchMenu( 0x00010001, 0x%08x )\n", id); + u32 nop = 0x60000000; - //the magic that writes the TID to the registers - u8 jump[ 20 ] = { 0x3C, 0x60, 0x00, 0x01, 0x60, 0x63, 0x00, 0x01, - 0x3C, 0x80, 0x4A, 0x4F, 0x60, 0x84, 0x44, 0x49, - 0x4E, 0x80, 0x00, 0x20 }; - if( oldSDK ) - { - jump[ 1 ] = 0xA0; //3CA00001 60A50001 - jump[ 5 ] = 0xA5; //3CC04A4F 60C64449 - jump[ 9 ] = 0xC0; - jump[ 13 ] = 0xC6; - } - //patch the thing to use the new TID - jump[ 10 ] = (u8)( id >> 24 ); - jump[ 11 ] = (u8)( id >> 16 ); - jump[ 14 ] = (u8)( id >> 8 ); - jump[ 15 ] = (u8)id; + //the magic that writes the TID to the registers + u8 jump[20] = { 0x3C, 0x60, 0x00, 0x01, 0x60, 0x63, 0x00, 0x01, 0x3C, 0x80, 0x4A, 0x4F, 0x60, 0x84, 0x44, 0x49, + 0x4E, 0x80, 0x00, 0x20 }; + if (oldSDK) + { + jump[1] = 0xA0; //3CA00001 60A50001 + jump[5] = 0xA5; //3CC04A4F 60C64449 + jump[9] = 0xC0; + jump[13] = 0xC6; + } + //patch the thing to use the new TID + jump[10] = (u8) (id >> 24); + jump[11] = (u8) (id >> 16); + jump[14] = (u8) (id >> 8); + jump[15] = (u8) id; - void* addr = (u32*)ad[ 3 ]; + void* addr = (u32*) ad[3]; - //write new stuff to memory main.dol in a unused part of the main.dol - memcpy( addr, jump, sizeof( jump ) ); + //write new stuff to memory main.dol in a unused part of the main.dol + memcpy(addr, jump, sizeof(jump)); - //ES_GetTicketViews() - u32 newval = ( ad[ 3 ] - ad[ 0 ] ); - newval &= 0x03FFFFFC; - newval |= 0x48000001; - addr = (u32*)ad[ 0 ]; - memcpy( addr, &newval, sizeof( u32 ) ); - memcpy( addr + 4, &nop, sizeof( u32 ) ); - //gprintf("\t%p -> %08x\n", addr, newval ); + //ES_GetTicketViews() + u32 newval = (ad[3] - ad[0]); + newval &= 0x03FFFFFC; + newval |= 0x48000001; + addr = (u32*) ad[0]; + memcpy(addr, &newval, sizeof(u32)); + memcpy(addr + 4, &nop, sizeof(u32)); + //gprintf("\t%p -> %08x\n", addr, newval ); - //ES_GetTicketViews() again - newval = ( ad[ 3 ] - ad[ 1 ] ); - newval &= 0x03FFFFFC; - newval |= 0x48000001; - addr = (u32*)ad[ 1 ]; - memcpy( addr, &newval, sizeof( u32 ) ); - memcpy( addr + 4, &nop, sizeof( u32 ) ); - //gprintf("\t%p -> %08x\n", addr, newval ); + //ES_GetTicketViews() again + newval = (ad[3] - ad[1]); + newval &= 0x03FFFFFC; + newval |= 0x48000001; + addr = (u32*) ad[1]; + memcpy(addr, &newval, sizeof(u32)); + memcpy(addr + 4, &nop, sizeof(u32)); + //gprintf("\t%p -> %08x\n", addr, newval ); - //ES_LaunchTitle() - newval = ( ad[ 3 ] - ad[ 2 ] ); - newval &= 0x03FFFFFC; - newval |= 0x48000001; - addr = (u32*)ad[ 2 ]; - memcpy( addr, &newval, sizeof( u32 ) ); - memcpy( addr + 4, &nop, sizeof( u32 ) ); - //gprintf("\t%p -> %08x\n", addr, newval ); + //ES_LaunchTitle() + newval = (ad[3] - ad[2]); + newval &= 0x03FFFFFC; + newval |= 0x48000001; + addr = (u32*) ad[2]; + memcpy(addr, &newval, sizeof(u32)); + memcpy(addr + 4, &nop, sizeof(u32)); + //gprintf("\t%p -> %08x\n", addr, newval ); - patched = 1; + patched = 1; } else { - gprintf("not patched\n"); - gprintf("found %d addresses\n", found); - int i; - for( i = 0; i< 4; i++) - gprintf("ad[ %d ]: %08x\n", i, ad[ i ] ); - gprintf("offset : %08x\n", ad[ 2 ] - ad[ 3 ] ); + gprintf("not patched\n"); + gprintf("found %d addresses\n", found); + int i; + for (i = 0; i < 4; i++) + gprintf("ad[ %d ]: %08x\n", i, ad[i]); + gprintf("offset : %08x\n", ad[2] - ad[3]); } return patched; diff --git a/source/patches/gamepatches.h b/source/patches/gamepatches.h index a5769157..696c0051 100644 --- a/source/patches/gamepatches.h +++ b/source/patches/gamepatches.h @@ -3,11 +3,11 @@ #include -bool Anti_002_fix( u8 * Address, int Size ); -bool NSMBPatch( u8 * Address, int Size ); +bool Anti_002_fix(u8 * Address, int Size); +bool NSMBPatch(u8 * Address, int Size); bool PoPPatch(); -bool Search_and_patch_Video_Modes( u8 * Address, u32 Size, GXRModeObj* Table[] ); -void VideoModePatcher( u8 * dst, int len, u8 videoSelected ); -bool PatchReturnTo( void *Address, int Size, u32 id ); +bool Search_and_patch_Video_Modes(u8 * Address, u32 Size, GXRModeObj* Table[]); +void VideoModePatcher(u8 * dst, int len, u8 videoSelected); +bool PatchReturnTo(void *Address, int Size, u32 id); #endif diff --git a/source/patches/geckomenu.h b/source/patches/geckomenu.h index 45068415..d86fd2c9 100644 --- a/source/patches/geckomenu.h +++ b/source/patches/geckomenu.h @@ -22,7 +22,6 @@ #ifndef __GECKOMENU_H__ #define __GECKOMENU_H__ - #define ROOTMENU 0 #define ABOUTMENU 1 #define CONFIGMENU 2 @@ -32,7 +31,7 @@ #define config_itemcount 9 #define rebooter_itemcount 6 -u32 currentmenu; // 0 ROOT +u32 currentmenu; // 0 ROOT u32 rootmenu_item; u32 menufreeze; u32 langselect; @@ -48,13 +47,12 @@ u32 regionfreeselect; u32 nocopyselect; u32 buttonskipselect; -u32 doprogress( u32 progstate, u32 noelements ); -void drawmenu( u32 menuid ); -void drawselected( u32 menuidpos ); +u32 doprogress(u32 progstate, u32 noelements); +void drawmenu(u32 menuid); +void drawselected(u32 menuidpos); void processwpad(); -void clearscreen( u32 *framebuffer, u16 xscreen, u16 yscreen, u16 width, u16 height, u32 color ); -void drawicon( u32 *framebuffer, u16 xscreen, u16 yscreen, u16 width, u16 height, u32 gicon ); -u32 CvtRGB ( u8 r1, u8 g1, u8 b1, u8 r2, u8 g2, u8 b2 ); - +void clearscreen(u32 *framebuffer, u16 xscreen, u16 yscreen, u16 width, u16 height, u32 color); +void drawicon(u32 *framebuffer, u16 xscreen, u16 yscreen, u16 width, u16 height, u32 gicon); +u32 CvtRGB(u8 r1, u8 g1, u8 b1, u8 r2, u8 g2, u8 b2); #endif // __GECKOLOAD_H__ diff --git a/source/patches/kenobiwii.h b/source/patches/kenobiwii.h index 6a173005..7d6c4f94 100644 --- a/source/patches/kenobiwii.h +++ b/source/patches/kenobiwii.h @@ -1,265 +1,235 @@ /* - This file was autogenerated by raw2c. -Visit http://www.devkitpro.org -*/ + This file was autogenerated by raw2c. + 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 +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 }; -const int kenobiwii_size = sizeof( kenobiwii ); +const int kenobiwii_size = sizeof(kenobiwii); diff --git a/source/patches/multidol.c b/source/patches/multidol.c index 2a52520e..1061858b 100644 --- a/source/patches/multidol.c +++ b/source/patches/multidol.c @@ -1,37 +1,31 @@ /* - This file was autogenerated by raw2c. -Visit http://www.devkitpro.org -*/ + This file was autogenerated by raw2c. + Visit http://www.devkitpro.org + */ -const unsigned char multidol[] = -{ - 0x7f, 0xe8, 0x03, 0xa6, 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, 0x3c, 0x60, 0x80, 0x00, 0x60, 0x63, 0x18, 0xa8, - 0x3c, 0xe0, 0x80, 0x00, 0x60, 0xe7, 0x11, 0x98, 0x3e, 0x60, 0x80, 0x00, 0x62, 0x73, 0x11, 0x88, - 0x3e, 0x40, 0x4e, 0x80, 0x62, 0x52, 0x00, 0x20, 0x81, 0xc7, 0x00, 0x04, 0x81, 0xe7, 0x00, 0x08, - 0x82, 0x07, 0x00, 0x0c, 0x82, 0x27, 0x00, 0x00, 0x3c, 0x80, 0x80, 0x00, 0x3c, 0xa0, 0x81, 0x33, - 0x38, 0x84, 0xff, 0xfc, 0x84, 0xc4, 0x00, 0x04, 0x7c, 0x04, 0x28, 0x00, 0x40, 0x80, 0x00, 0x4c, - 0x7c, 0x06, 0x70, 0x00, 0x40, 0x82, 0xff, 0xf0, 0x84, 0xc4, 0x00, 0x04, 0x7c, 0x06, 0x78, 0x00, - 0x40, 0x82, 0xff, 0xe0, 0x84, 0xc4, 0x00, 0x04, 0x7c, 0x06, 0x80, 0x00, 0x40, 0x82, 0xff, 0xd4, - 0x84, 0xc4, 0x00, 0x04, 0x7c, 0x06, 0x88, 0x00, 0x40, 0x82, 0xff, 0xc8, 0x84, 0xc4, 0x00, 0x04, - 0x7c, 0x04, 0x28, 0x00, 0x40, 0x80, 0x00, 0x14, 0x7c, 0x06, 0x90, 0x00, 0x40, 0x82, 0xff, 0xf0, - 0x48, 0x00, 0x00, 0xad, 0x4b, 0xff, 0xff, 0xb0, 0x3c, 0x60, 0x80, 0x00, 0x60, 0x63, 0x10, 0x00, - 0x3e, 0x60, 0x80, 0x00, 0x62, 0x73, 0x11, 0x90, 0x3c, 0xe0, 0x80, 0x00, 0x60, 0xe7, 0x11, 0xa8, - 0x81, 0xc7, 0x00, 0x04, 0x81, 0xe7, 0x00, 0x08, 0x82, 0x07, 0x00, 0x0c, 0x82, 0x27, 0x00, 0x00, - 0x3c, 0x80, 0x80, 0x00, 0x3c, 0xa0, 0x81, 0x40, 0x38, 0x84, 0xff, 0xfc, 0x84, 0xc4, 0x00, 0x04, - 0x7c, 0x04, 0x28, 0x00, 0x40, 0x80, 0x00, 0x38, 0x7c, 0x06, 0x70, 0x00, 0x40, 0x82, 0xff, 0xf0, - 0x84, 0xc4, 0x00, 0x04, 0x7c, 0x06, 0x78, 0x00, 0x40, 0x82, 0xff, 0xe0, 0x84, 0xc4, 0x00, 0x04, - 0x7c, 0x06, 0x80, 0x00, 0x40, 0x82, 0xff, 0xd4, 0x84, 0xc4, 0x00, 0x04, 0x7c, 0x06, 0x88, 0x00, - 0x40, 0x82, 0xff, 0xc8, 0x48, 0x00, 0x00, 0x39, 0x4b, 0xff, 0xff, 0xc4, 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, 0x48, 0x00, 0x07, 0x50, 0x7e, 0x44, 0x18, 0x50, - 0x3c, 0xc0, 0x48, 0x00, 0x52, 0x46, 0x01, 0xba, 0x90, 0xc4, 0x00, 0x00, 0x90, 0xd3, 0x00, 0x00, - 0x90, 0x93, 0x00, 0x04, 0x7c, 0x00, 0x20, 0xac, 0x7c, 0x00, 0x04, 0xac, 0x7c, 0x00, 0x27, 0xac, - 0x4c, 0x00, 0x01, 0x2c, 0x4e, 0x80, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0xc7, 0x00, 0x4c, 0x7c, 0xe3, 0x3b, 0x78, - 0x38, 0x87, 0x00, 0x34, 0x38, 0xa7, 0x00, 0x38, 0x4e, 0x80, 0x04, 0x20, 0x7c, 0x00, 0x04, 0xac, - 0x4c, 0x00, 0x01, 0x2c, 0x7f, 0xe9, 0x03, 0xa6 -}; -const int multidol_size = sizeof( multidol ); +const unsigned char multidol[] = { 0x7f, 0xe8, 0x03, 0xa6, 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, 0x3c, 0x60, 0x80, 0x00, 0x60, 0x63, 0x18, 0xa8, 0x3c, 0xe0, + 0x80, 0x00, 0x60, 0xe7, 0x11, 0x98, 0x3e, 0x60, 0x80, 0x00, 0x62, 0x73, 0x11, 0x88, 0x3e, 0x40, 0x4e, 0x80, + 0x62, 0x52, 0x00, 0x20, 0x81, 0xc7, 0x00, 0x04, 0x81, 0xe7, 0x00, 0x08, 0x82, 0x07, 0x00, 0x0c, 0x82, 0x27, + 0x00, 0x00, 0x3c, 0x80, 0x80, 0x00, 0x3c, 0xa0, 0x81, 0x33, 0x38, 0x84, 0xff, 0xfc, 0x84, 0xc4, 0x00, 0x04, + 0x7c, 0x04, 0x28, 0x00, 0x40, 0x80, 0x00, 0x4c, 0x7c, 0x06, 0x70, 0x00, 0x40, 0x82, 0xff, 0xf0, 0x84, 0xc4, + 0x00, 0x04, 0x7c, 0x06, 0x78, 0x00, 0x40, 0x82, 0xff, 0xe0, 0x84, 0xc4, 0x00, 0x04, 0x7c, 0x06, 0x80, 0x00, + 0x40, 0x82, 0xff, 0xd4, 0x84, 0xc4, 0x00, 0x04, 0x7c, 0x06, 0x88, 0x00, 0x40, 0x82, 0xff, 0xc8, 0x84, 0xc4, + 0x00, 0x04, 0x7c, 0x04, 0x28, 0x00, 0x40, 0x80, 0x00, 0x14, 0x7c, 0x06, 0x90, 0x00, 0x40, 0x82, 0xff, 0xf0, + 0x48, 0x00, 0x00, 0xad, 0x4b, 0xff, 0xff, 0xb0, 0x3c, 0x60, 0x80, 0x00, 0x60, 0x63, 0x10, 0x00, 0x3e, 0x60, + 0x80, 0x00, 0x62, 0x73, 0x11, 0x90, 0x3c, 0xe0, 0x80, 0x00, 0x60, 0xe7, 0x11, 0xa8, 0x81, 0xc7, 0x00, 0x04, + 0x81, 0xe7, 0x00, 0x08, 0x82, 0x07, 0x00, 0x0c, 0x82, 0x27, 0x00, 0x00, 0x3c, 0x80, 0x80, 0x00, 0x3c, 0xa0, + 0x81, 0x40, 0x38, 0x84, 0xff, 0xfc, 0x84, 0xc4, 0x00, 0x04, 0x7c, 0x04, 0x28, 0x00, 0x40, 0x80, 0x00, 0x38, + 0x7c, 0x06, 0x70, 0x00, 0x40, 0x82, 0xff, 0xf0, 0x84, 0xc4, 0x00, 0x04, 0x7c, 0x06, 0x78, 0x00, 0x40, 0x82, + 0xff, 0xe0, 0x84, 0xc4, 0x00, 0x04, 0x7c, 0x06, 0x80, 0x00, 0x40, 0x82, 0xff, 0xd4, 0x84, 0xc4, 0x00, 0x04, + 0x7c, 0x06, 0x88, 0x00, 0x40, 0x82, 0xff, 0xc8, 0x48, 0x00, 0x00, 0x39, 0x4b, 0xff, 0xff, 0xc4, 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, 0x48, 0x00, 0x07, 0x50, 0x7e, 0x44, 0x18, 0x50, 0x3c, 0xc0, 0x48, 0x00, + 0x52, 0x46, 0x01, 0xba, 0x90, 0xc4, 0x00, 0x00, 0x90, 0xd3, 0x00, 0x00, 0x90, 0x93, 0x00, 0x04, 0x7c, 0x00, + 0x20, 0xac, 0x7c, 0x00, 0x04, 0xac, 0x7c, 0x00, 0x27, 0xac, 0x4c, 0x00, 0x01, 0x2c, 0x4e, 0x80, 0x00, 0x20, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0xc7, + 0x00, 0x4c, 0x7c, 0xe3, 0x3b, 0x78, 0x38, 0x87, 0x00, 0x34, 0x38, 0xa7, 0x00, 0x38, 0x4e, 0x80, 0x04, 0x20, + 0x7c, 0x00, 0x04, 0xac, 0x4c, 0x00, 0x01, 0x2c, 0x7f, 0xe9, 0x03, 0xa6 }; +const int multidol_size = sizeof(multidol); diff --git a/source/patches/multidol.h b/source/patches/multidol.h index 6984bc32..11d1f8a4 100644 --- a/source/patches/multidol.h +++ b/source/patches/multidol.h @@ -1,7 +1,7 @@ /* - This file was autogenerated by raw2c. -Visit http://www.devkitpro.org -*/ + This file was autogenerated by raw2c. + Visit http://www.devkitpro.org + */ //--------------------------------------------------------------------------------- #ifndef _multidol_h_ diff --git a/source/patches/patchcode.c b/source/patches/patchcode.c index 6397c1cc..b3f652ce 100644 --- a/source/patches/patchcode.c +++ b/source/patches/patchcode.c @@ -37,231 +37,138 @@ extern const char * CheatFilepath; -extern void patchhook( u32 address, u32 len ); -extern void patchhook2( u32 address, u32 len ); -extern void patchhook3( u32 address, u32 len ); +extern void patchhook(u32 address, u32 len); +extern void patchhook2(u32 address, u32 len); +extern void patchhook3(u32 address, u32 len); -extern void multidolpatchone( u32 address, u32 len ); -extern void multidolpatchtwo( u32 address, u32 len ); +extern void multidolpatchone(u32 address, u32 len); +extern void multidolpatchtwo(u32 address, u32 len); -extern void regionfreejap( u32 address, u32 len ); -extern void regionfreeusa( u32 address, u32 len ); -extern void regionfreepal( u32 address, u32 len ); +extern void regionfreejap(u32 address, u32 len); +extern void regionfreeusa(u32 address, u32 len); +extern void regionfreepal(u32 address, u32 len); -extern void removehealthcheck( u32 address, u32 len ); +extern void removehealthcheck(u32 address, u32 len); -extern void copyflagcheck1( u32 address, u32 len ); -extern void copyflagcheck2( u32 address, u32 len ); -extern void copyflagcheck3( u32 address, u32 len ); -extern void copyflagcheck4( u32 address, u32 len ); -extern void copyflagcheck5( u32 address, u32 len ); +extern void copyflagcheck1(u32 address, u32 len); +extern void copyflagcheck2(u32 address, u32 len); +extern void copyflagcheck3(u32 address, u32 len); +extern void copyflagcheck4(u32 address, u32 len); +extern void copyflagcheck5(u32 address, u32 len); -extern void patchupdatecheck( u32 address, u32 len ); +extern void patchupdatecheck(u32 address, u32 len); -extern void movedvdhooks( u32 address, u32 len ); +extern void movedvdhooks(u32 address, u32 len); -extern void multidolhook( u32 address ); -extern void langvipatch( u32 address, u32 len, u8 langbyte ); -extern void vipatch( u32 address, u32 len ); +extern void multidolhook(u32 address); +extern void langvipatch(u32 address, u32 len, u8 langbyte); +extern void vipatch(u32 address, u32 len); -static const u32 multidolpatch1[2] = -{ - 0x3C03FFB4, 0x28004F43 -}; +static const u32 multidolpatch1[2] = { 0x3C03FFB4, 0x28004F43 }; -static const u32 healthcheckhook[2] = -{ - 0x41810010, 0x881D007D -}; +static const u32 healthcheckhook[2] = { 0x41810010, 0x881D007D }; -static const u32 updatecheckhook[3] = -{ - 0x80650050, 0x80850054, 0xA0A50058 -}; +static const u32 updatecheckhook[3] = { 0x80650050, 0x80850054, 0xA0A50058 }; -static const u32 multidolpatch2[2] = -{ - 0x3F608000, 0x807B0018 -}; +static const u32 multidolpatch2[2] = { 0x3F608000, 0x807B0018 }; -static const u32 recoveryhooks[3] = -{ - 0xA00100AC, 0x5400073E, 0x2C00000F -}; +static const u32 recoveryhooks[3] = { 0xA00100AC, 0x5400073E, 0x2C00000F }; -static const u32 nocopyflag1[3] = -{ - 0x540007FF, 0x4182001C, 0x80630068 -}; +static const u32 nocopyflag1[3] = { 0x540007FF, 0x4182001C, 0x80630068 }; -static const u32 nocopyflag2[3] = -{ - 0x540007FF, 0x41820024, 0x387E12E2 -}; +static const u32 nocopyflag2[3] = { 0x540007FF, 0x41820024, 0x387E12E2 }; // this one is for the GH3 and VC saves //static const u32 nocopyflag3[5] = { // 0x2C030000, 0x40820010, 0x88010020, 0x28000002, 0x41820234 //}; -static const u32 nocopyflag3[5] = -{ - 0x2C030000, 0x41820200, 0x48000058, 0x38610100 -}; +static const u32 nocopyflag3[5] = { 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 -}; +static const u32 nocopyflag4[4] = { 0x80010008, 0x2C000000, 0x4182000C, 0x3BE00001 }; -static const u32 nocopyflag5[3] = -{ - 0x801D0024, 0x540007FF, 0x41820024 -}; +static const u32 nocopyflag5[3] = { 0x801D0024, 0x540007FF, 0x41820024 }; -static const u32 movedvdpatch[3] = -{ - 0x2C040000, 0x41820120, 0x3C608109 -}; +static const u32 movedvdpatch[3] = { 0x2C040000, 0x41820120, 0x3C608109 }; -static const u32 regionfreehooks[5] = -{ - 0x7C600774, 0x2C000001, 0x41820030, 0x40800010, 0x2C000000 -}; +static const u32 regionfreehooks[5] = { 0x7C600774, 0x2C000001, 0x41820030, 0x40800010, 0x2C000000 }; -static const u32 cIOScode[16] = -{ - 0x7f06c378, 0x7f25cb78, 0x387e02c0, 0x4cc63182 -}; +static const u32 cIOScode[16] = { 0x7f06c378, 0x7f25cb78, 0x387e02c0, 0x4cc63182 }; -static const u32 cIOSblock[16] = -{ - 0x2C1800F9, 0x40820008, 0x3B000024 -}; +static const u32 cIOSblock[16] = { 0x2C1800F9, 0x40820008, 0x3B000024 }; -static const u32 fwritepatch[8] = -{ - 0x9421FFD0, 0x7C0802A6, 0x90010034, 0xBF210014, 0x7C9B2378, 0x7CDC3378, 0x7C7A1B78, 0x7CB92B78 // bushing fwrite -}; +static const u32 fwritepatch[8] = { 0x9421FFD0, 0x7C0802A6, 0x90010034, 0xBF210014, 0x7C9B2378, 0x7CDC3378, 0x7C7A1B78, + 0x7CB92B78 // bushing fwrite + }; -static const u32 vipatchcode[3] = -{ - 0x4182000C, 0x4180001C, 0x48000018 -}; +static const u32 vipatchcode[3] = { 0x4182000C, 0x4180001C, 0x48000018 }; -const u32 viwiihooks[4] = -{ - 0x7CE33B78, 0x38870034, 0x38A70038, 0x38C7004C -}; +const u32 viwiihooks[4] = { 0x7CE33B78, 0x38870034, 0x38A70038, 0x38C7004C }; -const u32 kpadhooks[4] = -{ - 0x9A3F005E, 0x38AE0080, 0x389FFFFC, 0x7E0903A6 -}; +const u32 kpadhooks[4] = { 0x9A3F005E, 0x38AE0080, 0x389FFFFC, 0x7E0903A6 }; -const u32 kpadoldhooks[6] = -{ - 0x801D0060, 0x901E0060, 0x801D0064, 0x901E0064, 0x801D0068, 0x901E0068 -}; +const u32 kpadoldhooks[6] = { 0x801D0060, 0x901E0060, 0x801D0064, 0x901E0064, 0x801D0068, 0x901E0068 }; -const u32 joypadhooks[4] = -{ - 0x3AB50001, 0x3A73000C, 0x2C150004, 0x3B18000C -}; +const u32 joypadhooks[4] = { 0x3AB50001, 0x3A73000C, 0x2C150004, 0x3B18000C }; -const u32 gxdrawhooks[4] = -{ - 0x3CA0CC01, 0x38000061, 0x3C804500, 0x98058000 -}; +const u32 gxdrawhooks[4] = { 0x3CA0CC01, 0x38000061, 0x3C804500, 0x98058000 }; -const u32 gxflushhooks[4] = -{ - 0x90010014, 0x800305FC, 0x2C000000, 0x41820008 -}; +const u32 gxflushhooks[4] = { 0x90010014, 0x800305FC, 0x2C000000, 0x41820008 }; -const u32 ossleepthreadhooks[4] = -{ - 0x90A402E0, 0x806502E4, 0x908502E4, 0x2C030000 -}; +const u32 ossleepthreadhooks[4] = { 0x90A402E0, 0x806502E4, 0x908502E4, 0x2C030000 }; -const u32 axnextframehooks[4] = -{ - 0x3800000E, 0x7FE3FB78, 0xB0050000, 0x38800080 -}; +const u32 axnextframehooks[4] = { 0x3800000E, 0x7FE3FB78, 0xB0050000, 0x38800080 }; -const u32 wpadbuttonsdownhooks[4] = -{ - 0x7D6B4A14, 0x816B0010, 0x7D635B78, 0x4E800020 -}; +const u32 wpadbuttonsdownhooks[4] = { 0x7D6B4A14, 0x816B0010, 0x7D635B78, 0x4E800020 }; -const u32 wpadbuttonsdown2hooks[4] = -{ - 0x7D6B4A14, 0x800B0010, 0x7C030378, 0x4E800020 -}; +const u32 wpadbuttonsdown2hooks[4] = { 0x7D6B4A14, 0x800B0010, 0x7C030378, 0x4E800020 }; -const u32 multidolhooks[4] = -{ - 0x7C0004AC, 0x4C00012C, 0x7FE903A6, 0x4E800420 -}; +const u32 multidolhooks[4] = { 0x7C0004AC, 0x4C00012C, 0x7FE903A6, 0x4E800420 }; -const u32 multidolchanhooks[4] = -{ - 0x4200FFF4, 0x48000004, 0x38800000, 0x4E800020 -}; +const u32 multidolchanhooks[4] = { 0x4200FFF4, 0x48000004, 0x38800000, 0x4E800020 }; -const u32 langpatch[3] = -{ - 0x7C600775, 0x40820010, 0x38000000 -}; +const u32 langpatch[3] = { 0x7C600775, 0x40820010, 0x38000000 }; -static const u32 oldpatch002[3] = -{ - 0x2C000000, 0x40820214, 0x3C608000 -}; +static const u32 oldpatch002[3] = { 0x2C000000, 0x40820214, 0x3C608000 }; -static const u32 newpatch002[3] = -{ - 0x2C000000, 0x48000214, 0x3C608000 -}; +static const u32 newpatch002[3] = { 0x2C000000, 0x48000214, 0x3C608000 }; //--------------------------------------------------------------------------------- -bool dogamehooks( void *addr, u32 len ) +bool dogamehooks(void *addr, u32 len) //--------------------------------------------------------------------------------- { - if(!CheatFilepath) - return false; + if (!CheatFilepath) return false; //this is temporary since the screen freezes without a file loaded char filepath[150]; char GameId[10]; - memcpy( GameId, ( u8 * ) 0x80000000, 6 ); + memcpy(GameId, (u8 *) 0x80000000, 6); GameId[6] = 0; - sprintf( filepath, "%s%s.gct", CheatFilepath, GameId ); + sprintf(filepath, "%s%s.gct", CheatFilepath, GameId); - if ( !checkfile( filepath ) ) - return false; + if (!checkfile(filepath)) return false; //TODO for oggzee: when using Ocarina check if a hook as patched hooktype = 1; // TODO for oggzee: Create an option for hooktype /* - 0 No Hook - 1 VBI - 2 KPAD read - 3 Joypad Hook - 4 GXDraw Hook - 5 GXFlush Hook - 6 OSSleepThread Hook - 7 AXNextFrame Hook - */ + 0 No Hook + 1 VBI + 2 KPAD read + 3 Joypad Hook + 4 GXDraw Hook + 5 GXFlush Hook + 6 OSSleepThread Hook + 7 AXNextFrame Hook + */ void *addr_start = addr; void *addr_end = addr + len; bool hookpatched = false; - while ( addr_start < addr_end ) + while (addr_start < addr_end) { - switch ( hooktype ) + switch (hooktype) { case 0x00: @@ -269,104 +176,104 @@ bool dogamehooks( void *addr, u32 len ) break; case 0x01: - if ( memcmp( addr_start, viwiihooks, sizeof( viwiihooks ) ) == 0 ) + if (memcmp(addr_start, viwiihooks, sizeof(viwiihooks)) == 0) { - patchhook( ( u32 )addr_start, len ); + patchhook((u32) addr_start, len); hookpatched = true; } - if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + if (memcmp(addr_start, multidolhooks, sizeof(multidolhooks)) == 0) { - multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + multidolhook((u32) addr_start + sizeof(multidolhooks) - 4); hookpatched = true; } break; case 0x02: - if ( memcmp( addr_start, kpadhooks, sizeof( kpadhooks ) ) == 0 ) + if (memcmp(addr_start, kpadhooks, sizeof(kpadhooks)) == 0) { - patchhook( ( u32 )addr_start, len ); + patchhook((u32) addr_start, len); hookpatched = true; } - if ( memcmp( addr_start, kpadoldhooks, sizeof( kpadoldhooks ) ) == 0 ) + if (memcmp(addr_start, kpadoldhooks, sizeof(kpadoldhooks)) == 0) { - patchhook( ( u32 )addr_start, len ); + patchhook((u32) addr_start, len); hookpatched = true; } - if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + if (memcmp(addr_start, multidolhooks, sizeof(multidolhooks)) == 0) { - multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + multidolhook((u32) addr_start + sizeof(multidolhooks) - 4); hookpatched = true; } break; case 0x03: - if ( memcmp( addr_start, joypadhooks, sizeof( joypadhooks ) ) == 0 ) + if (memcmp(addr_start, joypadhooks, sizeof(joypadhooks)) == 0) { - patchhook( ( u32 )addr_start, len ); + patchhook((u32) addr_start, len); hookpatched = true; } - if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + if (memcmp(addr_start, multidolhooks, sizeof(multidolhooks)) == 0) { - multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + multidolhook((u32) addr_start + sizeof(multidolhooks) - 4); hookpatched = true; } break; case 0x04: - if ( memcmp( addr_start, gxdrawhooks, sizeof( gxdrawhooks ) ) == 0 ) + if (memcmp(addr_start, gxdrawhooks, sizeof(gxdrawhooks)) == 0) { - patchhook( ( u32 )addr_start, len ); + patchhook((u32) addr_start, len); hookpatched = true; } - if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + if (memcmp(addr_start, multidolhooks, sizeof(multidolhooks)) == 0) { - multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + multidolhook((u32) addr_start + sizeof(multidolhooks) - 4); hookpatched = true; } break; case 0x05: - if ( memcmp( addr_start, gxflushhooks, sizeof( gxflushhooks ) ) == 0 ) + if (memcmp(addr_start, gxflushhooks, sizeof(gxflushhooks)) == 0) { - patchhook( ( u32 )addr_start, len ); + patchhook((u32) addr_start, len); hookpatched = true; } - if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + if (memcmp(addr_start, multidolhooks, sizeof(multidolhooks)) == 0) { - multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + multidolhook((u32) addr_start + sizeof(multidolhooks) - 4); hookpatched = true; } break; case 0x06: - if ( memcmp( addr_start, ossleepthreadhooks, sizeof( ossleepthreadhooks ) ) == 0 ) + if (memcmp(addr_start, ossleepthreadhooks, sizeof(ossleepthreadhooks)) == 0) { - patchhook( ( u32 )addr_start, len ); + patchhook((u32) addr_start, len); hookpatched = true; } - if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + if (memcmp(addr_start, multidolhooks, sizeof(multidolhooks)) == 0) { - multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + multidolhook((u32) addr_start + sizeof(multidolhooks) - 4); hookpatched = true; } break; case 0x07: - if ( memcmp( addr_start, axnextframehooks, sizeof( axnextframehooks ) ) == 0 ) + if (memcmp(addr_start, axnextframehooks, sizeof(axnextframehooks)) == 0) { - patchhook( ( u32 )addr_start, len ); + patchhook((u32) addr_start, len); hookpatched = true; } - if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + if (memcmp(addr_start, multidolhooks, sizeof(multidolhooks)) == 0) { - multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + multidolhook((u32) addr_start + sizeof(multidolhooks) - 4); hookpatched = true; } break; @@ -378,9 +285,9 @@ bool dogamehooks( void *addr, u32 len ) // patchhook((u32)addr_start, len); // hookpatched = true; //} - if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + if (memcmp(addr_start, multidolhooks, sizeof(multidolhooks)) == 0) { - multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + multidolhook((u32) addr_start + sizeof(multidolhooks) - 4); hookpatched = true; } break; @@ -392,78 +299,77 @@ bool dogamehooks( void *addr, u32 len ) // 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; - } -} -*/ -void langpatcher( void *addr, u32 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; + } + } + */ +void langpatcher(void *addr, u32 len) { void *addr_start = addr; void *addr_end = addr + len; - while ( addr_start < addr_end ) + while (addr_start < addr_end) { - if ( memcmp( addr_start, langpatch, sizeof( langpatch ) ) == 0 ) + if (memcmp(addr_start, langpatch, sizeof(langpatch)) == 0) { - if ( configbytes[0] != 0xCD ) + if (configbytes[0] != 0xCD) { - langvipatch( ( u32 )addr_start, len, configbytes[0] ); + 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) - { + while(addr_start < addr_end) + { - if(memcmp(addr_start, fwritepatch, sizeof(fwritepatch))==0) { + if(memcmp(addr_start, fwritepatch, sizeof(fwritepatch))==0) { - memcpy(addr_start,fwrite_patch_bin,fwrite_patch_bin_len); - // apply patch - } - addr_start += 4; - } -} -*/ -void vidolpatcher( void *addr, u32 len ) + memcpy(addr_start,fwrite_patch_bin,fwrite_patch_bin_len); + // apply patch + } + addr_start += 4; + } + } + */ +void vidolpatcher(void *addr, u32 len) { void *addr_start = addr; void *addr_end = addr + len; - while ( addr_start < addr_end ) + while (addr_start < addr_end) { - if ( memcmp( addr_start, vipatchcode, sizeof( vipatchcode ) ) == 0 ) + if (memcmp(addr_start, vipatchcode, sizeof(vipatchcode)) == 0) { - vipatch( ( u32 )addr_start, len ); + vipatch((u32) addr_start, len); } addr_start += 4; } } - diff --git a/source/patches/patchcode.h b/source/patches/patchcode.h index a769c333..4eb9d9b9 100644 --- a/source/patches/patchcode.h +++ b/source/patches/patchcode.h @@ -26,17 +26,17 @@ extern "C" { #endif -// Globals + // Globals u32 hooktype; int patched; u8 configbytes[2]; u32 regionfree; -// Function prototypes - bool dogamehooks( void *addr, u32 len ); - void langpatcher( void *addr, u32 len ); - void vidolpatcher( void *addr, u32 len ); - void patchdebug( void *addr, u32 len ); + // Function prototypes + bool dogamehooks(void *addr, u32 len); + void langpatcher(void *addr, u32 len); + void vidolpatcher(void *addr, u32 len); + void patchdebug(void *addr, u32 len); #ifdef __cplusplus } diff --git a/source/patches/ppc.h b/source/patches/ppc.h index 7448cb7b..000df8d3 100644 --- a/source/patches/ppc.h +++ b/source/patches/ppc.h @@ -1,5 +1,4 @@ - /* Condition Register Bit Fields */ #define cr0 0 @@ -11,7 +10,6 @@ #define cr6 6 #define cr7 7 - /* General Purpose Registers */ #define r0 0 diff --git a/source/patches/wip.c b/source/patches/wip.c index 059b166a..6e3471a7 100644 --- a/source/patches/wip.c +++ b/source/patches/wip.c @@ -12,12 +12,11 @@ static u32 CodesCount = 0; static u32 ProcessedLength = 0; static u32 Counter = 0; -void do_wip_code( u8 * dst, u32 len ) +void do_wip_code(u8 * dst, u32 len) { - if ( !CodeList ) - return; + if (!CodeList) return; - if ( Counter < 3 ) + if (Counter < 3) { Counter++; return; @@ -27,24 +26,23 @@ void do_wip_code( u8 * dst, u32 len ) int n = 0; int offset = 0; - for ( i = 0; i < CodesCount; i++ ) + for (i = 0; i < CodesCount; i++) { - for ( n = 0; n < 4; n++ ) + for (n = 0; n < 4; n++) { offset = CodeList[i].offset + n - ProcessedLength; - if ( offset < 0 || offset >= len ) - continue; + if (offset < 0 || offset >= len) continue; - if ( dst[offset] == ( ( u8 * )&CodeList[i].srcaddress )[n] ) + if (dst[offset] == ((u8 *) &CodeList[i].srcaddress)[n]) { - dst[offset] = ( ( u8 * ) & CodeList[i].dstaddress )[n]; - gprintf( "WIP: %08X Address Patched.\n", CodeList[i].offset + n ); + dst[offset] = ((u8 *) &CodeList[i].dstaddress)[n]; + gprintf("WIP: %08X Address Patched.\n", CodeList[i].offset + n); } else { - gprintf( "WIP: %08X Address does not match with WIP entrie.\n", CodeList[i].offset + n ); - gprintf( "Destination: %02X | Should be: %02X.\n", dst[offset], ( ( u8 * )&CodeList[i].srcaddress )[n] ); + gprintf("WIP: %08X Address does not match with WIP entrie.\n", CodeList[i].offset + n); + gprintf("Destination: %02X | Should be: %02X.\n", dst[offset], ((u8 *) &CodeList[i].srcaddress)[n]); } } } @@ -56,9 +54,9 @@ void do_wip_code( u8 * dst, u32 len ) //! .wip files override internal patches //! the codelist has to be freed if the set fails //! if set was successful the codelist will be freed when it's done -bool set_wip_list( WIP_Code * list, int size ) +bool set_wip_list(WIP_Code * list, int size) { - if ( !CodeList && size > 0 ) + if (!CodeList && size > 0) { CodeList = list; CodesCount = size; @@ -77,63 +75,60 @@ void wip_reset_counter() void free_wip() { - if ( CodeList ) - free( CodeList ); + if (CodeList) free(CodeList); CodeList = NULL; CodesCount = 0; Counter = 0; ProcessedLength = 0; } -int load_wip_code( u8 *gameid ) +int load_wip_code(u8 *gameid) { char filepath[150]; char GameID[8]; - memset( GameID, 0, sizeof( GameID ) ); - memcpy( GameID, gameid, 6 ); - snprintf( filepath, sizeof( filepath ), "%s%s.wip", Settings.WipCodepath, GameID ); + memset(GameID, 0, sizeof(GameID)); + memcpy(GameID, gameid, 6); + snprintf(filepath, sizeof(filepath), "%s%s.wip", Settings.WipCodepath, GameID); - FILE * fp = fopen( filepath, "rb" ); - if ( !fp ) + FILE * fp = fopen(filepath, "rb"); + if (!fp) { - memset( GameID, 0, sizeof( GameID ) ); - memcpy( GameID, gameid, 4 ); - snprintf( filepath, sizeof( filepath ), "%s%s.wip", Settings.WipCodepath, GameID ); - fp = fopen( filepath, "rb" ); + memset(GameID, 0, sizeof(GameID)); + memcpy(GameID, gameid, 4); + snprintf(filepath, sizeof(filepath), "%s%s.wip", Settings.WipCodepath, GameID); + fp = fopen(filepath, "rb"); } - if ( !fp ) + if (!fp) { - memset( GameID, 0, sizeof( GameID ) ); - memcpy( GameID, gameid, 3 ); - snprintf( filepath, sizeof( filepath ), "%s%s.wip", Settings.WipCodepath, GameID ); - fp = fopen( filepath, "rb" ); + memset(GameID, 0, sizeof(GameID)); + memcpy(GameID, gameid, 3); + snprintf(filepath, sizeof(filepath), "%s%s.wip", Settings.WipCodepath, GameID); + fp = fopen(filepath, "rb"); } - if ( !fp ) - return -1; + if (!fp) return -1; char line[255]; - gprintf( "\nLoading WIP code from %s.\n", filepath ); + gprintf("\nLoading WIP code from %s.\n", filepath); - while ( fgets( line, sizeof( line ), fp ) ) + while (fgets(line, sizeof(line), fp)) { - if ( line[0] == '#' ) continue; - if ( line[0] == ';' ) continue; - if ( line[0] == ':' ) continue; + if (line[0] == '#') continue; + if (line[0] == ';') continue; + if (line[0] == ':') continue; - if ( strlen( line ) < 26 ) continue; + if (strlen(line) < 26) continue; - u32 offset = ( u32 ) strtoul( line, NULL, 16 ); - u32 srcaddress = ( u32 ) strtoul( line + 9, NULL, 16 ); - u32 dstaddress = ( u32 ) strtoul( line + 18, NULL, 16 ); + u32 offset = (u32) strtoul(line, NULL, 16); + u32 srcaddress = (u32) strtoul(line + 9, NULL, 16); + u32 dstaddress = (u32) strtoul(line + 18, NULL, 16); - if ( !CodeList ) - CodeList = malloc( sizeof( WIP_Code ) ); + if (!CodeList) CodeList = malloc(sizeof(WIP_Code)); - WIP_Code * tmp = realloc( CodeList, ( CodesCount + 1 ) * sizeof( WIP_Code ) ); - if ( !tmp ) + WIP_Code * tmp = realloc(CodeList, (CodesCount + 1) * sizeof(WIP_Code)); + if (!tmp) { - fclose( fp ); + fclose(fp); free_wip(); return -1; } @@ -145,8 +140,8 @@ int load_wip_code( u8 *gameid ) CodeList[CodesCount].dstaddress = dstaddress; CodesCount++; } - fclose( fp ); - gprintf( "\n" ); + fclose(fp); + gprintf("\n"); return 0; } diff --git a/source/patches/wip.cpp b/source/patches/wip.cpp index c00f3047..632e0da4 100644 --- a/source/patches/wip.cpp +++ b/source/patches/wip.cpp @@ -12,12 +12,11 @@ static u32 CodesCount = 0; static u32 ProcessedLength = 0; static u32 Counter = 0; -extern "C" void do_wip_code( u8 * dst, u32 len ) +extern "C" void do_wip_code(u8 * dst, u32 len) { - if ( !CodeList ) - return; + if (!CodeList) return; - if ( Counter < 3 ) + if (Counter < 3) { Counter++; return; @@ -27,24 +26,23 @@ extern "C" void do_wip_code( u8 * dst, u32 len ) int n = 0; int offset = 0; - for ( i = 0; i < CodesCount; i++ ) + for (i = 0; i < CodesCount; i++) { - for ( n = 0; n < 4; n++ ) + for (n = 0; n < 4; n++) { offset = CodeList[i].offset + n - ProcessedLength; - if ( offset < 0 || offset >= (int) len ) - continue; + if (offset < 0 || offset >= (int) len) continue; - if ( dst[offset] == ( ( u8 * )&CodeList[i].srcaddress )[n] ) + if (dst[offset] == ((u8 *) &CodeList[i].srcaddress)[n]) { - dst[offset] = ( ( u8 * ) & CodeList[i].dstaddress )[n]; - gprintf( "WIP: %08X Address Patched.\n", CodeList[i].offset + n ); + dst[offset] = ((u8 *) &CodeList[i].dstaddress)[n]; + gprintf("WIP: %08X Address Patched.\n", CodeList[i].offset + n); } else { - gprintf( "WIP: %08X Address does not match with WIP entrie.\n", CodeList[i].offset + n ); - gprintf( "Destination: %02X | Should be: %02X.\n", dst[offset], ( ( u8 * )&CodeList[i].srcaddress )[n] ); + gprintf("WIP: %08X Address does not match with WIP entrie.\n", CodeList[i].offset + n); + gprintf("Destination: %02X | Should be: %02X.\n", dst[offset], ((u8 *) &CodeList[i].srcaddress)[n]); } } } @@ -56,9 +54,9 @@ extern "C" void do_wip_code( u8 * dst, u32 len ) //! .wip files override internal patches //! the codelist has to be freed if the set fails //! if set was successful the codelist will be freed when it's done -extern "C" bool set_wip_list( WIP_Code * list, int size ) +extern "C" bool set_wip_list(WIP_Code * list, int size) { - if ( !CodeList && size > 0 ) + if (!CodeList && size > 0) { CodeList = list; CodesCount = size; @@ -77,63 +75,60 @@ extern "C" void wip_reset_counter() extern "C" void free_wip() { - if ( CodeList ) - free( CodeList ); + if (CodeList) free(CodeList); CodeList = NULL; CodesCount = 0; Counter = 0; ProcessedLength = 0; } -extern "C" int load_wip_code( u8 *gameid ) +extern "C" int load_wip_code(u8 *gameid) { char filepath[150]; char GameID[8]; - memset( GameID, 0, sizeof( GameID ) ); - memcpy( GameID, gameid, 6 ); - snprintf( filepath, sizeof( filepath ), "%s%s.wip", Settings.WipCodepath, GameID ); + memset(GameID, 0, sizeof(GameID)); + memcpy(GameID, gameid, 6); + snprintf(filepath, sizeof(filepath), "%s%s.wip", Settings.WipCodepath, GameID); - FILE * fp = fopen( filepath, "rb" ); - if ( !fp ) + FILE * fp = fopen(filepath, "rb"); + if (!fp) { - memset( GameID, 0, sizeof( GameID ) ); - memcpy( GameID, gameid, 4 ); - snprintf( filepath, sizeof( filepath ), "%s%s.wip", Settings.WipCodepath, GameID ); - fp = fopen( filepath, "rb" ); + memset(GameID, 0, sizeof(GameID)); + memcpy(GameID, gameid, 4); + snprintf(filepath, sizeof(filepath), "%s%s.wip", Settings.WipCodepath, GameID); + fp = fopen(filepath, "rb"); } - if ( !fp ) + if (!fp) { - memset( GameID, 0, sizeof( GameID ) ); - memcpy( GameID, gameid, 3 ); - snprintf( filepath, sizeof( filepath ), "%s%s.wip", Settings.WipCodepath, GameID ); - fp = fopen( filepath, "rb" ); + memset(GameID, 0, sizeof(GameID)); + memcpy(GameID, gameid, 3); + snprintf(filepath, sizeof(filepath), "%s%s.wip", Settings.WipCodepath, GameID); + fp = fopen(filepath, "rb"); } - if ( !fp ) - return -1; + if (!fp) return -1; char line[255]; - gprintf( "\nLoading WIP code from %s.\n", filepath ); + gprintf("\nLoading WIP code from %s.\n", filepath); - while ( fgets( line, sizeof( line ), fp ) ) + while (fgets(line, sizeof(line), fp)) { - if ( line[0] == '#' ) continue; - if ( line[0] == ';' ) continue; - if ( line[0] == ':' ) continue; + if (line[0] == '#') continue; + if (line[0] == ';') continue; + if (line[0] == ':') continue; - if ( strlen( line ) < 26 ) continue; + if (strlen(line) < 26) continue; - u32 offset = ( u32 ) strtoul( line, NULL, 16 ); - u32 srcaddress = ( u32 ) strtoul( line + 9, NULL, 16 ); - u32 dstaddress = ( u32 ) strtoul( line + 18, NULL, 16 ); + u32 offset = (u32) strtoul(line, NULL, 16); + u32 srcaddress = (u32) strtoul(line + 9, NULL, 16); + u32 dstaddress = (u32) strtoul(line + 18, NULL, 16); - if ( !CodeList ) - CodeList = (WIP_Code *) malloc( sizeof( WIP_Code ) ); + if (!CodeList) CodeList = (WIP_Code *) malloc(sizeof(WIP_Code)); - WIP_Code * tmp = (WIP_Code *) realloc( CodeList, ( CodesCount + 1 ) * sizeof( WIP_Code ) ); - if ( !tmp ) + WIP_Code * tmp = (WIP_Code *) realloc(CodeList, (CodesCount + 1) * sizeof(WIP_Code)); + if (!tmp) { - fclose( fp ); + fclose(fp); free_wip(); return -1; } @@ -145,8 +140,8 @@ extern "C" int load_wip_code( u8 *gameid ) CodeList[CodesCount].dstaddress = dstaddress; CodesCount++; } - fclose( fp ); - gprintf( "\n" ); + fclose(fp); + gprintf("\n"); return 0; } diff --git a/source/patches/wip.h b/source/patches/wip.h index d270c4c5..45336fde 100644 --- a/source/patches/wip.h +++ b/source/patches/wip.h @@ -4,21 +4,22 @@ #include #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -typedef struct -{ - u32 offset; - u32 srcaddress; - u32 dstaddress; -} WIP_Code; + typedef struct + { + u32 offset; + u32 srcaddress; + u32 dstaddress; + } WIP_Code; -int load_wip_code( u8 *gameid ); -void do_wip_code( u8 * dst, u32 len ); -bool set_wip_list( WIP_Code * list, int size ); -void wip_reset_counter(); -void free_wip(); + int load_wip_code(u8 *gameid); + void do_wip_code(u8 * dst, u32 len); + bool set_wip_list(WIP_Code * list, int size); + void wip_reset_counter(); + void free_wip(); #ifdef __cplusplus } diff --git a/source/prompts/DiscBrowser.cpp b/source/prompts/DiscBrowser.cpp index 476e1d40..d8cc9cec 100644 --- a/source/prompts/DiscBrowser.cpp +++ b/source/prompts/DiscBrowser.cpp @@ -31,91 +31,91 @@ extern u8 reset; extern u8 mountMethod; /******************************************************************************** -*Disk Browser -*********************************************************************************/ -int DiscBrowse( struct discHdr * header ) + *Disk Browser + *********************************************************************************/ +int DiscBrowse(struct discHdr * header) { - gprintf( "\nDiscBrowser() started" ); + gprintf("\nDiscBrowser() started"); bool exit = false; int ret, choice; u64 offset; HaltGui(); - if ( !mountMethod ) + if (!mountMethod) { - ret = Disc_SetUSB( header->id ); - if ( ret < 0 ) + ret = Disc_SetUSB(header->id); + if (ret < 0) { ResumeGui(); - WindowPrompt( tr( "ERROR:" ), tr( "Could not set USB." ), tr( "OK" ) ); + WindowPrompt(tr( "ERROR:" ), tr( "Could not set USB." ), tr( "OK" )); return ret; } } ret = Disc_Open(); - if ( ret < 0 ) + if (ret < 0) { ResumeGui(); - WindowPrompt( tr( "ERROR:" ), tr( "Could not open Disc" ), tr( "OK" ) ); + WindowPrompt(tr( "ERROR:" ), tr( "Could not open Disc" ), tr( "OK" )); return ret; } - ret = __Disc_FindPartition( &offset ); - if ( ret < 0 ) + ret = __Disc_FindPartition(&offset); + if (ret < 0) { ResumeGui(); - WindowPrompt( tr( "ERROR:" ), tr( "Could not find a WBFS partition." ), tr( "OK" ) ); + WindowPrompt(tr( "ERROR:" ), tr( "Could not find a WBFS partition." ), tr( "OK" )); return ret; } - ret = WDVD_OpenPartition( offset ); - if ( ret < 0 ) + ret = WDVD_OpenPartition(offset); + if (ret < 0) { ResumeGui(); - WindowPrompt( tr( "ERROR:" ), tr( "Could not open WBFS partition" ), tr( "OK" ) ); + 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 ) + if (buffer == NULL) { ResumeGui(); - WindowPrompt( tr( "ERROR:" ), tr( "Not enough free memory." ), tr( "OK" ) ); + WindowPrompt(tr( "ERROR:" ), tr( "Not enough free memory." ), tr( "OK" )); return -1; } - ret = WDVD_Read( buffer, 0x20, 0x420 ); - if ( ret < 0 ) + ret = WDVD_Read(buffer, 0x20, 0x420); + if (ret < 0) { ResumeGui(); - WindowPrompt( tr( "ERROR:" ), tr( "Could not read the disc." ), tr( "OK" ) ); + WindowPrompt(tr( "ERROR:" ), tr( "Could not read the disc." ), tr( "OK" )); return ret; } void *fstbuffer = allocate_memory( buffer[2] * 4 ); - FST_ENTRY *fst = ( FST_ENTRY * )fstbuffer; + FST_ENTRY *fst = (FST_ENTRY *) fstbuffer; - if ( fst == NULL ) + if (fst == NULL) { ResumeGui(); - WindowPrompt( tr( "ERROR:" ), tr( "Not enough free memory." ), tr( "OK" ) ); - free( buffer ); + WindowPrompt(tr( "ERROR:" ), tr( "Not enough free memory." ), tr( "OK" )); + free(buffer); return -1; } - ret = WDVD_Read( fstbuffer, buffer[2] * 4, buffer[1] * 4 ); + ret = WDVD_Read(fstbuffer, buffer[2] * 4, buffer[1] * 4); - if ( ret < 0 ) + if (ret < 0) { ResumeGui(); - WindowPrompt( tr( "ERROR:" ), tr( "Could not read the disc." ), tr( "OK" ) ); - free( buffer ); - free( fstbuffer ); + WindowPrompt(tr( "ERROR:" ), tr( "Could not read the disc." ), tr( "OK" )); + free(buffer); + free(fstbuffer); return ret; } ResumeGui(); - free( buffer ); + free(buffer); WDVD_Reset(); //Disc_SetUSB(NULL); @@ -125,119 +125,116 @@ int DiscBrowse( struct discHdr * header ) u32 dolfilecount = 0; //int offsetselect[20]; - customOptionList options3( discfilecount ); + customOptionList options3(discfilecount); - for ( u32 i = 0; i < discfilecount; i++ ) + for (u32 i = 0; i < discfilecount; i++) { //don't add files that aren't .dol to the list - int len = ( strlen( fstfiles( fst, i ) ) ); - if ( fstfiles( fst, i )[len-4] == '.' && - fstfiles( fst, i )[len-3] == 'd' && - fstfiles( fst, i )[len-2] == 'o' && - fstfiles( fst, i )[len-1] == 'l' ) + int len = (strlen(fstfiles(fst, i))); + if (fstfiles(fst, i)[len - 4] == '.' && fstfiles(fst, i)[len - 3] == 'd' && fstfiles(fst, i)[len - 2] == 'o' + && fstfiles(fst, i)[len - 1] == 'l') { - options3.SetName( i, "%i", i ); - options3.SetValue( i, fstfiles( fst, i ) ); + options3.SetName(i, "%i", i); + options3.SetValue(i, fstfiles(fst, i)); //options3.SetName(i, fstfiles(fst, i)); dolfilecount++; } } - gprintf( "\n%i alt dols found", dolfilecount ); - if ( dolfilecount <= 0 ) + gprintf("\n%i alt dols found", dolfilecount); + if (dolfilecount <= 0) { - WindowPrompt( tr( "ERROR" ), tr( "No DOL file found on disc." ), tr( "OK" ) ); - free( fstbuffer ); + WindowPrompt(tr( "ERROR" ), tr( "No DOL file found on disc." ), tr( "OK" )); + free(fstbuffer); return -1; } - GuiSound btnSoundOver( button_over_pcm, button_over_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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sgamesettings_background.png", Settings.theme_path ); - GuiImageData settingsbg( imgPath, settings_background_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sgamesettings_background.png", Settings.theme_path); + GuiImageData settingsbg(imgPath, settings_background_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + 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 ); + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - GuiText titleTxt( get_title( header ), 28, ( GXColor ) {0, 0, 0, 255} ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( 12, 40 ); - titleTxt.SetMaxWidth( 356, SCROLL_HORIZONTAL ); + GuiText titleTxt(get_title(header), 28, ( GXColor ) + { 0, 0, 0, 255}); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(12, 40); + titleTxt.SetMaxWidth(356, SCROLL_HORIZONTAL); - GuiImage settingsbackground( &settingsbg ); - GuiButton settingsbackgroundbtn( settingsbackground.GetWidth(), settingsbackground.GetHeight() ); - settingsbackgroundbtn.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - settingsbackgroundbtn.SetPosition( 0, 0 ); - settingsbackgroundbtn.SetImage( &settingsbackground ); + GuiImage settingsbackground(&settingsbg); + GuiButton settingsbackgroundbtn(settingsbackground.GetWidth(), settingsbackground.GetHeight()); + settingsbackgroundbtn.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + settingsbackgroundbtn.SetPosition(0, 0); + settingsbackgroundbtn.SetImage(&settingsbackground); - GuiText cancelBtnTxt( tr( "Back" ), 22, THEME.prompttext ); - cancelBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); - GuiImage cancelBtnImg( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText cancelBtnTxt(tr( "Back" ), 22, THEME.prompttext); + cancelBtnTxt.SetMaxWidth(btnOutline.GetWidth() - 30); + GuiImage cancelBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - cancelBtnTxt.SetWidescreen( Settings.widescreen ); - cancelBtnImg.SetWidescreen( Settings.widescreen ); + cancelBtnTxt.SetWidescreen(Settings.widescreen); + cancelBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton cancelBtn( &cancelBtnImg, &cancelBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2, 1 ); - cancelBtn.SetScale( 0.9 ); - cancelBtn.SetLabel( &cancelBtnTxt ); - cancelBtn.SetTrigger( &trigB ); + GuiButton cancelBtn(&cancelBtnImg, &cancelBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2, 1); + cancelBtn.SetScale(0.9); + cancelBtn.SetLabel(&cancelBtnTxt); + cancelBtn.SetTrigger(&trigB); u8 scrollbaron = 0; - if ( dolfilecount > 9 ) - scrollbaron = 1; + if (dolfilecount > 9) scrollbaron = 1; - GuiCustomOptionBrowser optionBrowser3( 396, 280, &options3, Settings.theme_path, "bg_options_gamesettings.png", bg_options_settings_png, dolfilecount > 9 ? 1 : 0, 200 ); - optionBrowser3.SetPosition( 0, 90 ); - optionBrowser3.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + GuiCustomOptionBrowser optionBrowser3(396, 280, &options3, Settings.theme_path, "bg_options_gamesettings.png", + bg_options_settings_png, dolfilecount > 9 ? 1 : 0, 200); + optionBrowser3.SetPosition(0, 90); + optionBrowser3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); HaltGui(); - GuiWindow w( screenwidth, screenheight ); - w.Append( &settingsbackgroundbtn ); - w.Append( &titleTxt ); - w.Append( &cancelBtn ); - w.Append( &optionBrowser3 ); + GuiWindow w(screenwidth, screenheight); + w.Append(&settingsbackgroundbtn); + w.Append(&titleTxt); + w.Append(&cancelBtn); + w.Append(&optionBrowser3); - mainWindow->Append( &w ); + mainWindow->Append(&w); ResumeGui(); - while ( !exit ) + while (!exit) { VIDEO_WaitVSync(); - if ( shutdown == 1 ) - Sys_Shutdown(); - if ( reset == 1 ) - Sys_Reboot(); + if (shutdown == 1) Sys_Shutdown(); + if (reset == 1) Sys_Reboot(); ret = optionBrowser3.GetClickedOption(); - if ( ret > 0 ) + if (ret > 0) { char temp[100]; - strlcpy( temp, fstfiles( fst, ret ), sizeof( temp ) ); - choice = WindowPrompt( temp, tr( "Load this DOL as alternate DOL?" ), tr( "OK" ), tr( "Cancel" ) ); - if ( choice ) + strlcpy(temp, fstfiles(fst, ret), sizeof(temp)); + choice = WindowPrompt(temp, tr( "Load this DOL as alternate DOL?" ), tr( "OK" ), tr( "Cancel" )); + if (choice) { //ret = offsetselect[ret]; - strlcpy( alternatedname, temp, sizeof( alternatedname ) ); + strlcpy(alternatedname, temp, sizeof(alternatedname)); exit = true; } } - if ( cancelBtn.GetState() == STATE_CLICKED ) + if (cancelBtn.GetState() == STATE_CLICKED) { ret = 696969; exit = true; @@ -245,125 +242,124 @@ int DiscBrowse( struct discHdr * header ) } HaltGui(); - mainWindow->Remove( &w ); + mainWindow->Remove(&w); ResumeGui(); //free not needed list buffer anymore - free( fstbuffer ); + free(fstbuffer); return ret; } - -int autoSelectDol( const char *id, bool force ) +int autoSelectDol(const char *id, bool force) { - gprintf( "\nautoSelectDol() started" ); + gprintf("\nautoSelectDol() started"); char id4[10]; - sprintf( id4, "%c%c%c%c", id[0], id[1], id[2], id[3] ); + sprintf(id4, "%c%c%c%c", id[0], id[1], id[2], id[3]); -////// games that can be forced (always need alt dol) + ////// games that can be forced (always need alt dol) //Boogie - if ( strcmp( id, "RBOP69" ) == 0 ) return 675;//previous value was 657 - if ( strcmp( id, "RBOE69" ) == 0 ) return 675;//starstremr + if (strcmp(id, "RBOP69") == 0) return 675;//previous value was 657 + if (strcmp(id, "RBOE69") == 0) return 675;//starstremr //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 + 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 - if ( strcmp( id, "RMDP69" ) == 0 ) return 39;//from isostar + if (strcmp(id, "RMDP69") == 0) return 39;//from isostar //Madden NFL08 - if ( strcmp( id, "RNFP69" ) == 0 ) return 1079;//from isostar + 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 + 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 + if (strcmp(id, "RKMP5D") == 0) return 290;//from isostar + if (strcmp(id, "RKME5D") == 0) return 290;//starstremr //NBA 08 - if ( strcmp( id, "RNBX69" ) == 0 ) return 964;//from isostar + if (strcmp(id, "RNBX69") == 0) return 964;//from isostar //Pangya! Golf with Style - if ( strcmp( id, "RPYP9B" ) == 0 ) return 12490;//from isostar + if (strcmp(id, "RPYP9B") == 0) return 12490;//from isostar //Redsteel - if ( strcmp( id, "REDP41" ) == 0 ) return 1957;//from isostar - if ( strcmp( id, "REDE41" ) == 0 ) return 1957;//starstremr + if (strcmp(id, "REDP41") == 0) return 1957;//from isostar + if (strcmp(id, "REDE41") == 0) return 1957;//starstremr //SSX - if ( strcmp( id, "RSXP69" ) == 0 ) return 377;//previous value was 337 - if ( strcmp( id, "RSXE69" ) == 0 ) return 377;//previous value was 337 + 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 -///// games that can't be forced (alt dol is not always needed) - if ( !force ) + ///// 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 + 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 + 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 + 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 + 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 (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 ) +int autoSelectDolMenu(const char *id, bool force) { /* - char id4[10]; - sprintf(id4,"%c%c%c%c",id[0],id[1],id[2],id[3]); + 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; - */ + 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 ) + if (strcmp(id, "RJ8E64") == 0) { - int choice = WindowPrompt( tr( "Select a DOL" ), 0, "Fate of Atlantis", tr( "Default" ) ); - switch ( choice ) + int choice = WindowPrompt(tr( "Select a DOL" ), 0, "Fate of Atlantis", tr( "Default" )); + switch (choice) { case 1: choice = 8; //from starstremr @@ -374,10 +370,10 @@ int autoSelectDolMenu( const char *id, bool force ) } return choice; } - if ( strcmp( id, "RJ8P64" ) == 0 ) + if (strcmp(id, "RJ8P64") == 0) { - int choice = WindowPrompt( tr( "Select a DOL" ), 0, "Fate of Atlantis", tr( "Default" ) ); - switch ( choice ) + int choice = WindowPrompt(tr( "Select a DOL" ), 0, "Fate of Atlantis", tr( "Default" )); + switch (choice) { case 1: choice = 8; //from isostar @@ -390,10 +386,10 @@ int autoSelectDolMenu( const char *id, bool force ) } //Metal Slug Anthology (Metal Slug 6) - if ( strcmp( id, "RMLEH4" ) == 0 ) + if (strcmp(id, "RMLEH4") == 0) { - int choice = WindowPrompt( tr( "Select a DOL" ), 0, "Metal Slug 6", tr( "Default" ) ); - switch ( choice ) + int choice = WindowPrompt(tr( "Select a DOL" ), 0, "Metal Slug 6", tr( "Default" )); + switch (choice) { case 1: choice = 54; //from lustar @@ -404,10 +400,10 @@ int autoSelectDolMenu( const char *id, bool force ) } return choice; } - if ( strcmp( id, "RMLP7U" ) == 0 ) + if (strcmp(id, "RMLP7U") == 0) { - int choice = WindowPrompt( tr( "Select a DOL" ), 0, "Metal Slug 6", tr( "Default" ) ); - switch ( choice ) + int choice = WindowPrompt(tr( "Select a DOL" ), 0, "Metal Slug 6", tr( "Default" )); + switch (choice) { case 1: choice = 56; //from isostar @@ -420,17 +416,18 @@ int autoSelectDolMenu( const char *id, bool force ) } //Metroid Prime Trilogy - if ( strcmp( id, "R3ME01" ) == 0 ) + 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 ) + 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; @@ -447,16 +444,17 @@ int autoSelectDolMenu( const char *id, bool force ) } return choice; } - if ( strcmp( id, "R3MP01" ) == 0 ) + 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 ) + 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; @@ -475,10 +473,10 @@ int autoSelectDolMenu( const char *id, bool force ) } //Rampage: Total Destruction (M1.dol=Rampage, jarvos.dol=Rampage World Tour) - if ( strcmp( id, "RPGP5D" ) == 0 ) + if (strcmp(id, "RPGP5D") == 0) { - int choice = WindowPrompt( tr( "Select a DOL" ), 0, "Rampage", "World Tour", tr( "Default" ) ); - switch ( choice ) + int choice = WindowPrompt(tr( "Select a DOL" ), 0, "Rampage", "World Tour", tr( "Default" )); + switch (choice) { case 1: choice = 369; //from Ramzee @@ -494,10 +492,10 @@ int autoSelectDolMenu( const char *id, bool force ) } //The House Of The Dead 2 & 3 Return (only to play 2) - if ( strcmp( id, "RHDE8P" ) == 0 ) + if (strcmp(id, "RHDE8P") == 0) { - int choice = WindowPrompt( tr( "Select a DOL" ), 0, "HotD 2", tr( "Default" ) ); - switch ( choice ) + int choice = WindowPrompt(tr( "Select a DOL" ), 0, "HotD 2", tr( "Default" )); + switch (choice) { case 1: choice = 149; //from starstremr @@ -508,10 +506,10 @@ int autoSelectDolMenu( const char *id, bool force ) } return choice; } - if ( strcmp( id, "RHDP8P" ) == 0 ) + if (strcmp(id, "RHDP8P") == 0) { - int choice = WindowPrompt( tr( "Select a DOL" ), 0, "HotD 2", tr( "Default" ) ); - switch ( choice ) + int choice = WindowPrompt(tr( "Select a DOL" ), 0, "HotD 2", tr( "Default" )); + switch (choice) { case 1: choice = 149; //from isostar @@ -523,52 +521,52 @@ int autoSelectDolMenu( const char *id, bool force ) return choice; } - return -1; } - /******************************************************************************** -* Mount a DVD, get the type and ID. -*********************************************************************************/ + * Mount a DVD, get the type and ID. + *********************************************************************************/ 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 ) +static dvddiskid *g_diskID = (dvddiskid*) 0x80000000; // If you change this address, the read functions will FAIL! +void __dvd_readidcb(s32 result) { dvddone = result; } -u8 DiscMount( discHdr *header ) +u8 DiscMount(discHdr *header) { - gprintf( "\nDiscMount() " ); + gprintf("\nDiscMount() "); int ret; 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 ); + 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_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 ); + 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 ) + if (dvddone != 1) { return 0; } - return ( header->magic == 0x5D1C9EA3 ) ? 1 : 2; // Don't check gamecube magic (0xC2339F3D) + return (header->magic == 0x5D1C9EA3) ? 1 : 2; // Don't check gamecube magic (0xC2339F3D) } diff --git a/source/prompts/DiscBrowser.h b/source/prompts/DiscBrowser.h index 947c7c9f..4ea20536 100644 --- a/source/prompts/DiscBrowser.h +++ b/source/prompts/DiscBrowser.h @@ -8,9 +8,9 @@ #ifndef _DISCBROWSER_H_ #define _DISCBROWSER_H_ -int DiscBrowse( struct discHdr * header ); -int autoSelectDol( const char *id, bool force ); -int autoSelectDolMenu( const char *id, bool force ); -u8 DiscMount( struct discHdr * header ); +int DiscBrowse(struct discHdr * header); +int autoSelectDol(const char *id, bool force); +int autoSelectDolMenu(const char *id, bool force); +u8 DiscMount(struct discHdr * header); #endif diff --git a/source/prompts/ProgressWindow.cpp b/source/prompts/ProgressWindow.cpp index 85705296..712fd358 100644 --- a/source/prompts/ProgressWindow.cpp +++ b/source/prompts/ProgressWindow.cpp @@ -44,11 +44,10 @@ extern float gamesize; extern void ResumeGui(); extern void HaltGui(); - /**************************************************************************** * ProgressCallback mainly for gameinstallation. Can be used for other C app. -***************************************************************************/ -extern "C" void ProgressCallback( s64 done, s64 total ) + ***************************************************************************/ +extern "C" void ProgressCallback(s64 done, s64 total) { gameinstalldone = done; gameinstalltotal = total; @@ -57,14 +56,12 @@ extern "C" void ProgressCallback( s64 done, s64 total ) /**************************************************************************** * GameInstallProgress * GameInstallValue updating function -***************************************************************************/ + ***************************************************************************/ static void GameInstallProgress() { - if ( gameinstalltotal <= 0 ) - return; + if (gameinstalltotal <= 0) return; - if ( gameinstalldone > gameinstalltotal ) - gameinstalldone = gameinstalltotal; + if (gameinstalldone > gameinstalltotal) gameinstalldone = gameinstalltotal; static u32 expected = 300; @@ -72,50 +69,49 @@ static void GameInstallProgress() f32 speed = 0; //Elapsed time - elapsed = time( 0 ) - start; + elapsed = time(0) - start; //Calculate speed in MB/s - if ( elapsed > 0 ) - speed = KB_SIZE * gamesize * gameinstalldone / ( gameinstalltotal * elapsed ); + if (elapsed > 0) speed = KB_SIZE * gamesize * gameinstalldone / (gameinstalltotal * elapsed); - if ( gameinstalldone != gameinstalltotal ) + if (gameinstalldone != gameinstalltotal) { //Expected time - if ( elapsed ) - expected = ( expected * 3 + elapsed * gameinstalltotal / gameinstalldone ) / 4; + if (elapsed) expected = (expected * 3 + elapsed * gameinstalltotal / gameinstalldone) / 4; //Remaining time - elapsed = ( expected > elapsed ) ? ( expected - elapsed ) : 0; + elapsed = (expected > elapsed) ? (expected - elapsed) : 0; } //Calculate time values - h = elapsed / 3600; - m = ( elapsed / 60 ) % 60; - s = elapsed % 60; + h = elapsed / 3600; + m = (elapsed / 60) % 60; + s = elapsed % 60; progressDone = 100.0 * gameinstalldone / gameinstalltotal; - snprintf( progressTime, sizeof( progressTime ), "%s %d:%02d:%02d", tr( "Time left:" ), h, m, s ); - snprintf( progressSizeLeft, sizeof( progressSizeLeft ), "%.2fGB/%.2fGB", gamesize * gameinstalldone / gameinstalltotal, gamesize ); - snprintf( progressSpeed, sizeof( progressSpeed ), "%.1fMB/s", speed ); + snprintf(progressTime, sizeof(progressTime), "%s %d:%02d:%02d", tr( "Time left:" ), h, m, s); + snprintf(progressSizeLeft, sizeof(progressSizeLeft), "%.2fGB/%.2fGB", + gamesize * gameinstalldone / gameinstalltotal, gamesize); + snprintf(progressSpeed, sizeof(progressSpeed), "%.1fMB/s", speed); changed = true; } /**************************************************************************** * SetupGameInstallProgress -***************************************************************************/ -void SetupGameInstallProgress( char * title, char * game ) + ***************************************************************************/ +void SetupGameInstallProgress(char * title, char * game) { - strlcpy( progressTitle, title, sizeof( progressTitle ) ); - strlcpy( progressMsg1, game, sizeof( progressMsg1 ) ); + strlcpy(progressTitle, title, sizeof(progressTitle)); + strlcpy(progressMsg1, game, sizeof(progressMsg1)); gameinstalltotal = 1; showProgress = 1; showSize = true; showTime = true; - LWP_ResumeThread( progressthread ); - start = time( 0 ); + LWP_ResumeThread(progressthread); + start = time(0); } /**************************************************************************** @@ -125,197 +121,192 @@ void SetupGameInstallProgress( char * title, char * game ) * progress bar showing % completion, or a throbber that only shows that an * action is in progress. ***************************************************************************/ -static void ProgressWindow( const char *title, const char *msg1, const char *msg2 ) +static void ProgressWindow(const char *title, const char *msg1, const char *msg2) { - GuiWindow promptWindow( 472, 320 ); - promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - promptWindow.SetPosition( 0, -10 ); + GuiWindow promptWindow(472, 320); + promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + promptWindow.SetPosition(0, -10); char imgPath[100]; - snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", Settings.theme_path ); - GuiImageData dialogBox( imgPath, dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", Settings.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiImage dialogBoxImg( &dialogBox ); - if ( Settings.wsprompt == yes ) + GuiImage dialogBoxImg(&dialogBox); + if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen( Settings.widescreen ); + dialogBoxImg.SetWidescreen(Settings.widescreen); } - snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_outline.png", Settings.theme_path ); - GuiImageData progressbarOutline( imgPath, progressbar_outline_png ); + snprintf(imgPath, sizeof(imgPath), "%sprogressbar_outline.png", Settings.theme_path); + GuiImageData progressbarOutline(imgPath, progressbar_outline_png); - GuiImage progressbarOutlineImg( &progressbarOutline ); - if ( Settings.wsprompt == yes ) + GuiImage progressbarOutlineImg(&progressbarOutline); + if (Settings.wsprompt == yes) { - progressbarOutlineImg.SetWidescreen( Settings.widescreen ); + progressbarOutlineImg.SetWidescreen(Settings.widescreen); } - progressbarOutlineImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - progressbarOutlineImg.SetPosition( 25, 40 ); + progressbarOutlineImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + progressbarOutlineImg.SetPosition(25, 40); - snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_empty.png", Settings.theme_path ); - GuiImageData progressbarEmpty( imgPath, progressbar_empty_png ); - GuiImage progressbarEmptyImg( &progressbarEmpty ); - progressbarEmptyImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - progressbarEmptyImg.SetPosition( 25, 40 ); - progressbarEmptyImg.SetTile( 100 ); + snprintf(imgPath, sizeof(imgPath), "%sprogressbar_empty.png", Settings.theme_path); + GuiImageData progressbarEmpty(imgPath, progressbar_empty_png); + GuiImage progressbarEmptyImg(&progressbarEmpty); + progressbarEmptyImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + progressbarEmptyImg.SetPosition(25, 40); + progressbarEmptyImg.SetTile(100); - snprintf( imgPath, sizeof( imgPath ), "%sprogressbar.png", Settings.theme_path ); - GuiImageData progressbar( imgPath, progressbar_png ); - GuiImage progressbarImg( &progressbar ); - progressbarImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - progressbarImg.SetPosition( 25, 40 ); + snprintf(imgPath, sizeof(imgPath), "%sprogressbar.png", Settings.theme_path); + GuiImageData progressbar(imgPath, progressbar_png); + GuiImage progressbarImg(&progressbar); + progressbarImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + progressbarImg.SetPosition(25, 40); - GuiText titleTxt( title, 26, THEME.prompttext ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( 0, 60 ); + GuiText titleTxt(title, 26, THEME.prompttext); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0, 60); - GuiText msg1Txt( msg1, 22, THEME.prompttext ); - msg1Txt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - if ( msg2 ) - msg1Txt.SetPosition( 0, 120 ); - else - msg1Txt.SetPosition( 0, 100 ); - msg1Txt.SetMaxWidth( 430, DOTTED ); + GuiText msg1Txt(msg1, 22, THEME.prompttext); + msg1Txt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + if (msg2) + msg1Txt.SetPosition(0, 120); + else msg1Txt.SetPosition(0, 100); + msg1Txt.SetMaxWidth(430, DOTTED); - GuiText msg2Txt( msg2, 22, THEME.prompttext ); - msg2Txt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - msg2Txt.SetPosition( 0, 125 ); - msg2Txt.SetMaxWidth( 430, DOTTED ); + GuiText msg2Txt(msg2, 22, THEME.prompttext); + msg2Txt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + msg2Txt.SetPosition(0, 125); + msg2Txt.SetMaxWidth(430, DOTTED); - GuiText prsTxt( "%", 22, THEME.prompttext ); - prsTxt.SetAlignment( ALIGN_RIGHT, ALIGN_MIDDLE ); - prsTxt.SetPosition( -188, 40 ); + GuiText prsTxt("%", 22, THEME.prompttext); + prsTxt.SetAlignment(ALIGN_RIGHT, ALIGN_MIDDLE); + prsTxt.SetPosition(-188, 40); - GuiText timeTxt( ( char* ) NULL, 22, THEME.prompttext ); - timeTxt.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - timeTxt.SetPosition( 280, -50 ); + GuiText timeTxt((char*) NULL, 22, THEME.prompttext); + timeTxt.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + timeTxt.SetPosition(280, -50); - GuiText sizeTxt( ( char* ) NULL, 22, THEME.prompttext ); - sizeTxt.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - sizeTxt.SetPosition( 50, -50 ); + GuiText sizeTxt((char*) NULL, 22, THEME.prompttext); + sizeTxt.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + sizeTxt.SetPosition(50, -50); - GuiText speedTxt( ( char* ) NULL, 22, THEME.prompttext ); - speedTxt.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - speedTxt.SetPosition( 50, -74 ); + GuiText speedTxt((char*) NULL, 22, THEME.prompttext); + speedTxt.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + speedTxt.SetPosition(50, -74); - GuiText prTxt( ( char* ) NULL, 26, THEME.prompttext ); - prTxt.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - prTxt.SetPosition( 200, 40 ); + GuiText prTxt((char*) NULL, 26, THEME.prompttext); + prTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + prTxt.SetPosition(200, 40); - if ( ( Settings.wsprompt == yes ) && ( Settings.widescreen ) ) /////////////adjust for widescreen + if ((Settings.wsprompt == yes) && (Settings.widescreen)) /////////////adjust for widescreen { - progressbarOutlineImg.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - progressbarOutlineImg.SetPosition( 0, 40 ); - progressbarEmptyImg.SetPosition( 80, 40 ); - progressbarEmptyImg.SetTile( 78 ); - progressbarImg.SetPosition( 80, 40 ); - msg1Txt.SetMaxWidth( 380, DOTTED ); - msg2Txt.SetMaxWidth( 380, DOTTED ); + progressbarOutlineImg.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + progressbarOutlineImg.SetPosition(0, 40); + progressbarEmptyImg.SetPosition(80, 40); + progressbarEmptyImg.SetTile(78); + progressbarImg.SetPosition(80, 40); + msg1Txt.SetMaxWidth(380, DOTTED); + msg2Txt.SetMaxWidth(380, DOTTED); - timeTxt.SetPosition( 250, -50 ); - timeTxt.SetFontSize( 20 ); - speedTxt.SetPosition( 90, -74 ); - speedTxt.SetFontSize( 20 ); - sizeTxt.SetPosition( 90, -50 ); - sizeTxt.SetFontSize( 20 ); + timeTxt.SetPosition(250, -50); + timeTxt.SetFontSize(20); + speedTxt.SetPosition(90, -74); + speedTxt.SetFontSize(20); + sizeTxt.SetPosition(90, -50); + sizeTxt.SetFontSize(20); } - usleep( 400000 ); // wait to see if progress flag changes soon - if ( !showProgress ) - return; + usleep(400000); // wait to see if progress flag changes soon + if (!showProgress) return; - promptWindow.Append( &dialogBoxImg ); - promptWindow.Append( &progressbarEmptyImg ); - promptWindow.Append( &progressbarImg ); - promptWindow.Append( &progressbarOutlineImg ); - promptWindow.Append( &prTxt ); - promptWindow.Append( &prsTxt ); - if ( title ) - promptWindow.Append( &titleTxt ); - if ( msg1 ) - promptWindow.Append( &msg1Txt ); - if ( msg2 ) - promptWindow.Append( &msg2Txt ); - if ( showTime ) - promptWindow.Append( &timeTxt ); - if ( showSize ) + promptWindow.Append(&dialogBoxImg); + promptWindow.Append(&progressbarEmptyImg); + promptWindow.Append(&progressbarImg); + promptWindow.Append(&progressbarOutlineImg); + promptWindow.Append(&prTxt); + promptWindow.Append(&prsTxt); + if (title) promptWindow.Append(&titleTxt); + if (msg1) promptWindow.Append(&msg1Txt); + if (msg2) promptWindow.Append(&msg2Txt); + if (showTime) promptWindow.Append(&timeTxt); + if (showSize) { - promptWindow.Append( &sizeTxt ); - promptWindow.Append( &speedTxt ); + promptWindow.Append(&sizeTxt); + promptWindow.Append(&speedTxt); } HaltGui(); - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50 ); - mainWindow->SetState( STATE_DISABLED ); - mainWindow->Append( &promptWindow ); - mainWindow->ChangeFocus( &promptWindow ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); - while ( promptWindow.GetEffect() > 0 ) usleep( 100 ); - + while (promptWindow.GetEffect() > 0) + usleep(100); int tmp; - while ( showProgress ) + while (showProgress) { VIDEO_WaitVSync(); GameInstallProgress(); - if ( changed ) + if (changed) { changed = false; - tmp = static_cast( progressbarImg.GetWidth() * progressDone ); + tmp = static_cast (progressbarImg.GetWidth() * progressDone); - if ( Settings.widescreen && Settings.wsprompt == yes ) - progressbarImg.SetSkew( 0, 0, static_cast( progressbarImg.GetWidth()*progressDone*0.8 ) - progressbarImg.GetWidth(), 0, static_cast( progressbarImg.GetWidth()*progressDone*0.8 ) - progressbarImg.GetWidth(), 0, 0, 0 ); - else - progressbarImg.SetSkew( 0, 0, static_cast( progressbarImg.GetWidth()*progressDone ) - progressbarImg.GetWidth(), 0, static_cast( progressbarImg.GetWidth()*progressDone ) - progressbarImg.GetWidth(), 0, 0, 0 ); + if (Settings.widescreen && Settings.wsprompt == yes) + progressbarImg.SetSkew(0, 0, static_cast (progressbarImg.GetWidth() * progressDone * 0.8) + - progressbarImg.GetWidth(), 0, static_cast (progressbarImg.GetWidth() * progressDone + * 0.8) - progressbarImg.GetWidth(), 0, 0, 0); + else progressbarImg.SetSkew(0, 0, static_cast (progressbarImg.GetWidth() * progressDone) + - progressbarImg.GetWidth(), 0, static_cast (progressbarImg.GetWidth() * progressDone) + - progressbarImg.GetWidth(), 0, 0, 0); - prTxt.SetTextf( "%.2f", progressDone ); + prTxt.SetTextf("%.2f", progressDone); - if ( showSize ) + if (showSize) { - sizeTxt.SetText( progressSizeLeft ); - speedTxt.SetText( progressSpeed ); + sizeTxt.SetText(progressSizeLeft); + speedTxt.SetText(progressSpeed); } - if ( showTime ) - timeTxt.SetText( progressTime ); + if (showTime) timeTxt.SetText(progressTime); - if ( msg2 ) - msg2Txt.SetText( dyn_message ); + if (msg2) msg2Txt.SetText(dyn_message); } } - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - while ( promptWindow.GetEffect() > 0 ) usleep( 100 ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + while (promptWindow.GetEffect() > 0) + usleep(100); HaltGui(); - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); } /**************************************************************************** * ProgressThread - ***************************************************************************/ + ***************************************************************************/ -static void * ProgressThread ( void *arg ) +static void * ProgressThread(void *arg) { - while ( 1 ) + while (1) { - if ( !showProgress ) - LWP_SuspendThread ( progressthread ); + if (!showProgress) LWP_SuspendThread(progressthread); - ProgressWindow( progressTitle, progressMsg1, progressMsg2 ); - usleep( 100 ); + ProgressWindow(progressTitle, progressMsg1, progressMsg2); + usleep(100); } return NULL; } @@ -329,8 +320,8 @@ void ProgressStop() gameinstalltotal = -1; // wait for thread to finish - while ( !LWP_ThreadIsSuspended( progressthread ) ) - usleep( 100 ); + while (!LWP_ThreadIsSuspended(progressthread)) + usleep(100); } /**************************************************************************** @@ -339,72 +330,68 @@ 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 ) + if (total <= 0) return; - else if ( done > total ) - done = total; + else if (done > total) done = total; showSize = swSize; showTime = swTime; - if ( title ) - strlcpy( progressTitle, title, sizeof( progressTitle ) ); - if ( msg1 ) - strlcpy( progressMsg1, msg1, sizeof( progressMsg1 ) ); - if ( dynmsg2 ) - dyn_message = dynmsg2; + if (title) strlcpy(progressTitle, title, sizeof(progressTitle)); + if (msg1) strlcpy(progressMsg1, msg1, sizeof(progressMsg1)); + if (dynmsg2) dyn_message = dynmsg2; static u32 expected; u32 elapsed, h, m, s, speed = 0; - if ( !done ) + if (!done) { - start = time( 0 ); + start = time(0); expected = 300; - LWP_ResumeThread( progressthread ); + LWP_ResumeThread(progressthread); } //Elapsed time - elapsed = time( 0 ) - start; + elapsed = time(0) - start; //Calculate speed in KB/s - if ( elapsed > 0 ) - speed = done / ( elapsed * KB_SIZE ); + if (elapsed > 0) speed = done / (elapsed * KB_SIZE); - if ( done != total ) + if (done != total) { //Expected time - if ( elapsed ) - expected = ( expected * 3 + elapsed * total / done ) / 4; + if (elapsed) expected = (expected * 3 + elapsed * total / done) / 4; //Remaining time - elapsed = ( expected > elapsed ) ? ( expected - elapsed ) : 0; + elapsed = (expected > elapsed) ? (expected - elapsed) : 0; } //Calculate time values - h = elapsed / 3600; - m = ( elapsed / 60 ) % 60; - s = elapsed % 60; + h = elapsed / 3600; + m = (elapsed / 60) % 60; + s = elapsed % 60; - if ( swTime == true ) + if (swTime == true) { - snprintf( progressTime, sizeof( progressTime ), "%s %d:%02d:%02d", tr( "Time left:" ), h, m, s ); + snprintf(progressTime, sizeof(progressTime), "%s %d:%02d:%02d", tr( "Time left:" ), h, m, s); } - if ( swSize == true ) + if (swSize == true) { - if ( total < MB_SIZE ) - snprintf( progressSizeLeft, sizeof( progressSizeLeft ), "%0.2fKB/%0.2fKB", done * done / total / KB_SIZE, total / KB_SIZE ); - else if ( total > MB_SIZE && total < GB_SIZE ) - snprintf( progressSizeLeft, sizeof( progressSizeLeft ), "%0.2fMB/%0.2fMB", done * done / total / MB_SIZE, total / MB_SIZE ); - else - snprintf( progressSizeLeft, sizeof( progressSizeLeft ), "%0.2fGB/%0.2fGB", done * done / total / GB_SIZE, total / GB_SIZE ); + if (total < MB_SIZE) + snprintf(progressSizeLeft, sizeof(progressSizeLeft), "%0.2fKB/%0.2fKB", done * done / total / KB_SIZE, + total / KB_SIZE); + else if (total > MB_SIZE && total < GB_SIZE) + snprintf(progressSizeLeft, sizeof(progressSizeLeft), "%0.2fMB/%0.2fMB", done * done / total / MB_SIZE, + total / MB_SIZE); + else snprintf(progressSizeLeft, sizeof(progressSizeLeft), "%0.2fGB/%0.2fGB", done * done / total / GB_SIZE, + total / GB_SIZE); - snprintf( progressSpeed, sizeof( progressSpeed ), "%dKB/s", speed ); + snprintf(progressSpeed, sizeof(progressSpeed), "%dKB/s", speed); } showProgress = 1; @@ -419,7 +406,7 @@ void ShowProgress( const char *title, const char *msg1, char *dynmsg2, f32 done, ***************************************************************************/ void InitProgressThread() { - LWP_CreateThread( &progressthread, ProgressThread, NULL, NULL, 16384, 80 ); + LWP_CreateThread(&progressthread, ProgressThread, NULL, NULL, 16384, 80); } /**************************************************************************** @@ -429,6 +416,6 @@ void InitProgressThread() ***************************************************************************/ void ExitProgressThread() { - LWP_JoinThread( progressthread, NULL ); + LWP_JoinThread(progressthread, NULL); progressthread = LWP_THREAD_NULL; } diff --git a/source/prompts/ProgressWindow.h b/source/prompts/ProgressWindow.h index 2cb2d239..4f4f8ccc 100644 --- a/source/prompts/ProgressWindow.h +++ b/source/prompts/ProgressWindow.h @@ -10,9 +10,9 @@ void InitProgressThread(); void ExitProgressThread(); -void SetupGameInstallProgress( char * titl, char * game ); -void ShowProgress ( const char *title, const char *msg1, char *dynmsg2, - f32 done, f32 total, bool swSize = false, bool swTime = false ); +void SetupGameInstallProgress(char * titl, char * game); +void ShowProgress(const char *title, const char *msg1, char *dynmsg2, f32 done, f32 total, bool swSize = false, + bool swTime = false); void ProgressStop(); #ifdef __cplusplus @@ -20,7 +20,7 @@ extern "C" { #endif - void ProgressCallback( s64 gameinstalldone, s64 gameinstalltotal ); + void ProgressCallback(s64 gameinstalldone, s64 gameinstalltotal); #ifdef __cplusplus } diff --git a/source/prompts/PromptWindows.cpp b/source/prompts/PromptWindows.cpp index 27935366..7b0fa136 100644 --- a/source/prompts/PromptWindows.cpp +++ b/source/prompts/PromptWindows.cpp @@ -67,74 +67,73 @@ extern void HaltGui(); * Opens an on-screen numpad window, with the data entered being stored * into the specified variable. ***************************************************************************/ -int OnScreenNumpad( char * var, u32 maxlen ) +int OnScreenNumpad(char * var, u32 maxlen) { int save = -1; - GuiNumpad numpad( var, maxlen ); + GuiNumpad numpad(var, maxlen); - GuiSound btnSoundOver( button_over_pcm, button_over_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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); GuiTrigger trigB; - trigB.SetSimpleTrigger( -1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B ); + trigB.SetSimpleTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - GuiText okBtnTxt( tr( "OK" ), 22, THEME.prompttext ); - GuiImage okBtnImg( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText okBtnTxt(tr( "OK" ), 22, THEME.prompttext); + GuiImage okBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - okBtnTxt.SetWidescreen( Settings.widescreen ); - okBtnImg.SetWidescreen( Settings.widescreen ); + okBtnTxt.SetWidescreen(Settings.widescreen); + okBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton okBtn( &okBtnImg, &okBtnImg, 0, 4, 5, -15, &trigA, &btnSoundOver, btnClick2, 1 ); - okBtn.SetLabel( &okBtnTxt ); - GuiText cancelBtnTxt( tr( "Cancel" ), 22, THEME.prompttext ); - GuiImage cancelBtnImg( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiButton okBtn(&okBtnImg, &okBtnImg, 0, 4, 5, -15, &trigA, &btnSoundOver, btnClick2, 1); + okBtn.SetLabel(&okBtnTxt); + GuiText cancelBtnTxt(tr( "Cancel" ), 22, THEME.prompttext); + GuiImage cancelBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - cancelBtnTxt.SetWidescreen( Settings.widescreen ); - cancelBtnImg.SetWidescreen( Settings.widescreen ); + cancelBtnTxt.SetWidescreen(Settings.widescreen); + cancelBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton cancelBtn( &cancelBtnImg, &cancelBtnImg, 1, 4, -5, -15, &trigA, &btnSoundOver, btnClick2, 1 ); - cancelBtn.SetLabel( &cancelBtnTxt ); - cancelBtn.SetTrigger( &trigB ); + GuiButton cancelBtn(&cancelBtnImg, &cancelBtnImg, 1, 4, -5, -15, &trigA, &btnSoundOver, btnClick2, 1); + cancelBtn.SetLabel(&cancelBtnTxt); + cancelBtn.SetTrigger(&trigB); - numpad.Append( &okBtn ); - numpad.Append( &cancelBtn ); + numpad.Append(&okBtn); + numpad.Append(&cancelBtn); HaltGui(); - mainWindow->SetState( STATE_DISABLED ); - mainWindow->Append( &numpad ); - mainWindow->ChangeFocus( &numpad ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&numpad); + mainWindow->ChangeFocus(&numpad); ResumeGui(); - while ( save == -1 ) + while (save == -1) { VIDEO_WaitVSync(); - if ( okBtn.GetState() == STATE_CLICKED ) + if (okBtn.GetState() == STATE_CLICKED) save = 1; - else if ( cancelBtn.GetState() == STATE_CLICKED ) - save = 0; + else if (cancelBtn.GetState() == STATE_CLICKED) save = 0; } - if ( save == 1 ) + if (save == 1) { - snprintf( var, maxlen, "%s", numpad.kbtextstr ); + snprintf(var, maxlen, "%s", numpad.kbtextstr); } HaltGui(); - mainWindow->Remove( &numpad ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&numpad); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); - gprintf( "\t%s", ( save == 1 ? "saved" : "discarded" ) ); + gprintf("\t%s", (save == 1 ? "saved" : "discarded")); return save; } @@ -144,84 +143,87 @@ int OnScreenNumpad( char * var, u32 maxlen ) * Opens an on-screen keyboard window, with the data entered being stored * into the specified variable. ***************************************************************************/ -int OnScreenKeyboard( char * var, u32 maxlen, int min ) +int OnScreenKeyboard(char * var, u32 maxlen, int min) { int save = -1; int keyset = 0; - if ( Settings.keyset == us ) keyset = 0; - else if ( Settings.keyset == dvorak ) keyset = 1; - else if ( Settings.keyset == euro ) keyset = 2; - else if ( Settings.keyset == azerty ) keyset = 3; - else if ( Settings.keyset == qwerty ) keyset = 4; + if (Settings.keyset == us) + keyset = 0; + else if (Settings.keyset == dvorak) + keyset = 1; + else if (Settings.keyset == euro) + keyset = 2; + 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 ); + GuiKeyboard keyboard(var, maxlen, min, keyset); - GuiSound btnSoundOver( button_over_pcm, button_over_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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); GuiTrigger trigB; - trigB.SetSimpleTrigger( -1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B ); + trigB.SetSimpleTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - GuiText okBtnTxt( tr( "OK" ), 22, THEME.prompttext ); - GuiImage okBtnImg( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText okBtnTxt(tr( "OK" ), 22, THEME.prompttext); + GuiImage okBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - okBtnTxt.SetWidescreen( Settings.widescreen ); - okBtnImg.SetWidescreen( Settings.widescreen ); + okBtnTxt.SetWidescreen(Settings.widescreen); + okBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton okBtn( &okBtnImg, &okBtnImg, 0, 4, 5, 15, &trigA, &btnSoundOver, btnClick2, 1 ); - okBtn.SetLabel( &okBtnTxt ); - GuiText cancelBtnTxt( tr( "Cancel" ), 22, THEME.prompttext ); - GuiImage cancelBtnImg( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiButton okBtn(&okBtnImg, &okBtnImg, 0, 4, 5, 15, &trigA, &btnSoundOver, btnClick2, 1); + okBtn.SetLabel(&okBtnTxt); + GuiText cancelBtnTxt(tr( "Cancel" ), 22, THEME.prompttext); + GuiImage cancelBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - cancelBtnTxt.SetWidescreen( Settings.widescreen ); - cancelBtnImg.SetWidescreen( Settings.widescreen ); + cancelBtnTxt.SetWidescreen(Settings.widescreen); + cancelBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton cancelBtn( &cancelBtnImg, &cancelBtnImg, 1, 4, -5, 15, &trigA, &btnSoundOver, btnClick2, 1 ); - cancelBtn.SetLabel( &cancelBtnTxt ); - cancelBtn.SetTrigger( &trigB ); + GuiButton cancelBtn(&cancelBtnImg, &cancelBtnImg, 1, 4, -5, 15, &trigA, &btnSoundOver, btnClick2, 1); + cancelBtn.SetLabel(&cancelBtnTxt); + cancelBtn.SetTrigger(&trigB); - keyboard.Append( &okBtn ); - keyboard.Append( &cancelBtn ); + keyboard.Append(&okBtn); + keyboard.Append(&cancelBtn); HaltGui(); - mainWindow->SetState( STATE_DISABLED ); - mainWindow->Append( &keyboard ); - mainWindow->ChangeFocus( &keyboard ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&keyboard); + mainWindow->ChangeFocus(&keyboard); ResumeGui(); - while ( save == -1 ) + while (save == -1) { VIDEO_WaitVSync(); - if ( okBtn.GetState() == STATE_CLICKED ) + if (okBtn.GetState() == STATE_CLICKED) save = 1; - else if ( cancelBtn.GetState() == STATE_CLICKED ) - save = 0; + else if (cancelBtn.GetState() == STATE_CLICKED) save = 0; } - if ( save ) + if (save) { - snprintf( var, maxlen, "%s", keyboard.kbtextstr ); + snprintf(var, maxlen, "%s", keyboard.kbtextstr); } HaltGui(); - mainWindow->Remove( &keyboard ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&keyboard); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); - gprintf( "\t%s", ( save ? "saved" : "discarded" ) ); + gprintf("\t%s", (save ? "saved" : "discarded")); return save; } @@ -231,46 +233,46 @@ int OnScreenKeyboard( char * var, u32 maxlen, int min ) ***************************************************************************/ void WindowCredits() { - gprintf( "WindowCredits()\n" ); + gprintf("WindowCredits()\n"); int angle = 0; GuiSound * creditsMusic = NULL; bgMusic->Pause(); - creditsMusic = new GuiSound( credits_music_ogg, credits_music_ogg_size, 55 ); - creditsMusic->SetVolume( 60 ); - creditsMusic->SetLoop( 1 ); + creditsMusic = new GuiSound(credits_music_ogg, credits_music_ogg_size, 55); + creditsMusic->SetVolume(60); + creditsMusic->SetLoop(1); creditsMusic->Play(); bool exit = false; int i = 0; int y = 20; - GuiWindow creditsWindow( screenwidth, screenheight ); - GuiWindow creditsWindowBox( 580, 448 ); - creditsWindowBox.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); + GuiWindow creditsWindow(screenwidth, screenheight); + GuiWindow creditsWindowBox(580, 448); + creditsWindowBox.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - GuiImageData creditsBox( credits_bg_png ); - GuiImage creditsBoxImg( &creditsBox ); - creditsBoxImg.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - creditsWindowBox.Append( &creditsBoxImg ); + GuiImageData creditsBox(credits_bg_png); + GuiImage creditsBoxImg(&creditsBox); + creditsBoxImg.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + creditsWindowBox.Append(&creditsBoxImg); - GuiImageData star( little_star_png ); - GuiImage starImg( &star ); - starImg.SetWidescreen( Settings.widescreen ); //added - starImg.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - starImg.SetPosition( 505, 350 ); + GuiImageData star(little_star_png); + GuiImage starImg(&star); + starImg.SetWidescreen(Settings.widescreen); //added + starImg.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + starImg.SetPosition(505, 350); int numEntries = 21; GuiText * txt[numEntries]; - txt[i] = new GuiText( tr( "Credits" ), 26, ( GXColor ) {255, 255, 255, 255} ); - txt[i]->SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - txt[i]->SetPosition( 0, 12 ); + txt[i] = new GuiText(tr( "Credits" ), 26, ( GXColor ) + { 255, 255, 255, 255}); + txt[i]->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + txt[i]->SetPosition(0, 12); i++; - #ifdef FULLCHANNEL char svnTmp[4];//did this to hide the M after the rev# that is made by altering it //to be ready to be in a full channel @@ -279,164 +281,163 @@ void WindowCredits() snprintf( SvnRev, sizeof( SvnRev ), "Rev%sc IOS%u (Rev %u)", svnTmp, IOS_GetVersion(), IOS_GetRevision() ); #else char SvnRev[30]; - snprintf( SvnRev, sizeof( SvnRev ), "Rev%s IOS%u (Rev %u)", GetRev(), IOS_GetVersion(), IOS_GetRevision() ); + snprintf(SvnRev, sizeof(SvnRev), "Rev%s IOS%u (Rev %u)", GetRev(), IOS_GetVersion(), IOS_GetRevision()); #endif - - - - txt[i] = new GuiText( SvnRev, 16, ( GXColor ) { 255, 255, 255, 255} ); - txt[i]->SetAlignment( ALIGN_RIGHT, ALIGN_TOP ); - txt[i]->SetPosition( 0, y ); + txt[i] = new GuiText(SvnRev, 16, ( GXColor ) + { 255, 255, 255, 255}); + txt[i]->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + txt[i]->SetPosition(0, y); i++; y += 34; - txt[i] = new GuiText( "USB Loader GX", 24, ( GXColor ) {255, 255, 255, 255} ); - txt[i]->SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - txt[i]->SetPosition( 0, y ); + txt[i] = new GuiText("USB Loader GX", 24, ( GXColor ) + { 255, 255, 255, 255}); + txt[i]->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + txt[i]->SetPosition(0, y); i++; y += 26; - txt[i] = new GuiText( tr( "Official Site:" ), 20, ( GXColor ) {255, 255, 255, 255} ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 10, y ); + txt[i] = new GuiText(tr( "Official Site:" ), 20, ( GXColor ) + { 255, 255, 255, 255}); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(10, y); i++; - txt[i] = new GuiText( "http://code.google.com/p/usbloader-gui/", 20, ( GXColor ) {255, 255, 255, 255} ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 160, y ); + txt[i] = new GuiText("http://code.google.com/p/usbloader-gui/", 20, ( GXColor ) + { 255, 255, 255, 255}); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(160, y); i++; y += 26; - GuiText::SetPresets( 22, ( GXColor ) {255, 255, 255, 255}, 3000, FTGX_JUSTIFY_LEFT | FTGX_ALIGN_TOP, ALIGN_LEFT, ALIGN_TOP ); + GuiText::SetPresets(22, ( GXColor ) + { 255, 255, 255, 255}, 3000, FTGX_JUSTIFY_LEFT | FTGX_ALIGN_TOP, ALIGN_LEFT, ALIGN_TOP); - txt[i] = new GuiText( tr( "Coding:" ) ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 10, y ); + txt[i] = new GuiText(tr( "Coding:" )); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(10, y); i++; - txt[i] = new GuiText( "dimok / nIxx / giantpune / ardi" ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 160, y ); + txt[i] = new GuiText("dimok / nIxx / giantpune / ardi"); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(160, y); i++; y += 22; - txt[i] = new GuiText( "hungyip84 / DrayX7 / lustar / r-win" ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 160, y ); + txt[i] = new GuiText("hungyip84 / DrayX7 / lustar / r-win"); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(160, y); i++; y += 26; char text[100]; - txt[i] = new GuiText( tr( "Design:" ) ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 10, y ); + txt[i] = new GuiText(tr( "Design:" )); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(10, y); i++; - txt[i] = new GuiText( "cyrex / NeoRame" ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 160, y ); + txt[i] = new GuiText("cyrex / NeoRame"); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(160, y); i++; y += 26; - txt[i] = new GuiText( tr( "Big thanks to:" ) ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 10, y ); + txt[i] = new GuiText(tr( "Big thanks to:" )); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(10, y); i++; - sprintf( text, "lustar %s", tr( "for WiiTDB and hosting covers / disc images" ) ); - txt[i] = new GuiText( text ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 160, y ); + sprintf(text, "lustar %s", tr( "for WiiTDB and hosting covers / disc images" )); + txt[i] = new GuiText(text); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(160, y); i++; y += 22; - sprintf( text, "CorneliousJD %s", tr( "for hosting the update files" ) ); - txt[i] = new GuiText( text ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 160, y ); + sprintf(text, "CorneliousJD %s", tr( "for hosting the update files" )); + txt[i] = new GuiText(text); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(160, y); i++; y += 22; - sprintf( text, "Kinyo %s", tr( "and translaters for language files updates" ) ); - txt[i] = new GuiText( text ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 160, y ); + sprintf(text, "Kinyo %s", tr( "and translaters for language files updates" )); + txt[i] = new GuiText(text); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(160, y); i++; y += 22; - sprintf( text, "Deak Phreak %s", tr( "for hosting the themes" ) ); - txt[i] = new GuiText( text ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 160, y ); + sprintf(text, "Deak Phreak %s", tr( "for hosting the themes" )); + txt[i] = new GuiText(text); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(160, y); i++; y += 26; - txt[i] = new GuiText( tr( "Special thanks to:" ) ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 10, y ); + txt[i] = new GuiText(tr( "Special thanks to:" )); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(10, y); i++; y += 22; - sprintf( text, "Waninkoko, Kwiirk & Hermes %s", tr( "for the USB Loader source" ) ); - txt[i] = new GuiText( text ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 60, y ); + sprintf(text, "Waninkoko, Kwiirk & Hermes %s", tr( "for the USB Loader source" )); + txt[i] = new GuiText(text); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(60, y); i++; y += 22; - sprintf( text, "Tantric %s", tr( "for his awesome tool LibWiiGui" ) ); - txt[i] = new GuiText( text ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 60, y ); + sprintf(text, "Tantric %s", tr( "for his awesome tool LibWiiGui" )); + txt[i] = new GuiText(text); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(60, y); i++; y += 22; - sprintf( text, "Fishears/Nuke %s", tr( "for Ocarina" ) ); - txt[i] = new GuiText( text ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 60, y ); + sprintf(text, "Fishears/Nuke %s", tr( "for Ocarina" )); + txt[i] = new GuiText(text); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(60, y); i++; y += 22; - sprintf( text, "WiiPower %s", tr( "for diverse patches" ) ); - txt[i] = new GuiText( text ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 60, y ); + sprintf(text, "WiiPower %s", tr( "for diverse patches" )); + txt[i] = new GuiText(text); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(60, y); i++; y += 22; - sprintf( text, "Oggzee %s", tr( "for FAT/NTFS support" ) ); - txt[i] = new GuiText( text ); - txt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - txt[i]->SetPosition( 60, y ); + sprintf(text, "Oggzee %s", tr( "for FAT/NTFS support" )); + txt[i] = new GuiText(text); + txt[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + txt[i]->SetPosition(60, y); i++; y += 22; - for ( i = 0; i < numEntries; i++ ) - creditsWindowBox.Append( txt[i] ); + for (i = 0; i < numEntries; i++) + creditsWindowBox.Append(txt[i]); + creditsWindow.Append(&creditsWindowBox); + creditsWindow.Append(&starImg); - creditsWindow.Append( &creditsWindowBox ); - creditsWindow.Append( &starImg ); - - creditsWindow.SetEffect( EFFECT_FADE, 30 ); + creditsWindow.SetEffect(EFFECT_FADE, 30); HaltGui(); - mainWindow->SetState( STATE_DISABLED ); - mainWindow->Append( &creditsWindow ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&creditsWindow); ResumeGui(); - while ( !exit ) + while (!exit) { angle++; - if ( angle > 360 ) - angle = 0; - usleep( 12000 ); - starImg.SetAngle( angle ); - if ( ButtonsPressed() != 0 ) - exit = true; + if (angle > 360) angle = 0; + usleep(12000); + starImg.SetAngle(angle); + if (ButtonsPressed() != 0) exit = true; } @@ -444,12 +445,13 @@ void WindowCredits() delete creditsMusic; - creditsWindow.SetEffect( EFFECT_FADE, -30 ); - while ( creditsWindow.GetEffect() > 0 ) usleep( 50 ); + creditsWindow.SetEffect(EFFECT_FADE, -30); + while (creditsWindow.GetEffect() > 0) + usleep(50); HaltGui(); - mainWindow->Remove( &creditsWindow ); - mainWindow->SetState( STATE_DEFAULT ); - for ( i = 0; i < numEntries; i++ ) + mainWindow->Remove(&creditsWindow); + mainWindow->SetState(STATE_DEFAULT); + for (i = 0; i < numEntries; i++) { delete txt[i]; txt[i] = NULL; @@ -465,53 +467,54 @@ void WindowCredits() ***************************************************************************/ int WindowScreensaver() { - gprintf( "WindowScreenSaver()\n" ); + gprintf("WindowScreenSaver()\n"); int i = 0; bool exit = false; char imgPath[100];//uncomment for themable screensaver /* initialize random seed: */ - srand ( time( NULL ) ); + srand(time(NULL)); - snprintf( imgPath, sizeof( imgPath ), "%sscreensaver.png", Settings.theme_path );//uncomment for themable screensaver - GuiImageData GXlogo( imgPath, gxlogo_png );//uncomment for themable screensaver + snprintf(imgPath, sizeof(imgPath), "%sscreensaver.png", Settings.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 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 ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&screensaverWindow); ResumeGui(); - while ( !exit ) + while (!exit) { i++; - if ( IsWpadConnected() ) + if (IsWpadConnected()) { exit = true; } /* Set position only every 400000th loop */ - if ( ( i % 8000000 ) == 0 ) + if ((i % 8000000) == 0) { /* Set random position */ - GXlogoImg.SetPosition( ( rand() % 345 ), ( rand() % 305 ) ); + GXlogoImg.SetPosition((rand() % 345), (rand() % 305)); } } HaltGui(); - mainWindow->Remove( &screensaverWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&screensaverWindow); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); return 1; } @@ -526,294 +529,283 @@ int WindowScreensaver() * If title/subtitle or one of the buttons is not needed give him a 0 on that * place. ***************************************************************************/ -int WindowPrompt( const char *title, const char *msg, const char *btn1Label, - const char *btn2Label, const char *btn3Label, - const char *btn4Label, int wait ) +int WindowPrompt(const char *title, const char *msg, const char *btn1Label, const char *btn2Label, + const char *btn3Label, const char *btn4Label, int wait) { int choice = -1; int count = wait; - gprintf( "WindowPrompt( %s, %s, %s, %s, %s, %s, %i ): ", title, msg, btn1Label, btn2Label, btn3Label, btn4Label, wait ); + gprintf("WindowPrompt( %s, %s, %s, %s, %s, %s, %i ): ", title, msg, btn1Label, btn2Label, btn3Label, btn4Label, + wait); + GuiWindow promptWindow(472, 320); + promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + promptWindow.SetPosition(0, -10); - 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 ); + 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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", Settings.theme_path ); - GuiImageData dialogBox( imgPath, dialogue_box_png ); - + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", Settings.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - GuiImage dialogBoxImg( &dialogBox ); - if ( Settings.wsprompt == yes ) + GuiImage dialogBoxImg(&dialogBox); + if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen( Settings.widescreen ); + dialogBoxImg.SetWidescreen(Settings.widescreen); } - GuiText titleTxt( title, 26, THEME.prompttext ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( 0, 55 ); - GuiText msgTxt( msg, 22, THEME.prompttext ); - msgTxt.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - msgTxt.SetPosition( 0, -40 ); - msgTxt.SetMaxWidth( 430 ); + GuiText titleTxt(title, 26, THEME.prompttext); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0, 55); + GuiText msgTxt(msg, 22, THEME.prompttext); + msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + msgTxt.SetPosition(0, -40); + msgTxt.SetMaxWidth(430); - GuiText btn1Txt( btn1Label, 22, THEME.prompttext ); - GuiImage btn1Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn1Txt(btn1Label, 22, THEME.prompttext); + GuiImage btn1Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn1Txt.SetWidescreen( Settings.widescreen ); - btn1Img.SetWidescreen( Settings.widescreen ); + btn1Txt.SetWidescreen(Settings.widescreen); + btn1Img.SetWidescreen(Settings.widescreen); } - GuiButton btn1( &btn1Img, &btn1Img, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 1 ); - btn1.SetLabel( &btn1Txt ); - btn1.SetState( STATE_SELECTED ); + GuiButton btn1(&btn1Img, &btn1Img, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 1); + btn1.SetLabel(&btn1Txt); + btn1.SetState(STATE_SELECTED); - GuiText btn2Txt( btn2Label, 22, THEME.prompttext ); - GuiImage btn2Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn2Txt(btn2Label, 22, THEME.prompttext); + GuiImage btn2Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn2Txt.SetWidescreen( Settings.widescreen ); - btn2Img.SetWidescreen( Settings.widescreen ); + btn2Txt.SetWidescreen(Settings.widescreen); + btn2Img.SetWidescreen(Settings.widescreen); } - GuiButton btn2( &btn2Img, &btn2Img, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 1 ); - btn2.SetLabel( &btn2Txt ); - if ( !btn3Label && !btn4Label ) - btn2.SetTrigger( &trigB ); + GuiButton btn2(&btn2Img, &btn2Img, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 1); + btn2.SetLabel(&btn2Txt); + if (!btn3Label && !btn4Label) btn2.SetTrigger(&trigB); - GuiText btn3Txt( btn3Label, 22, THEME.prompttext ); - GuiImage btn3Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn3Txt(btn3Label, 22, THEME.prompttext); + GuiImage btn3Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn3Txt.SetWidescreen( Settings.widescreen ); - btn3Img.SetWidescreen( Settings.widescreen ); + btn3Txt.SetWidescreen(Settings.widescreen); + btn3Img.SetWidescreen(Settings.widescreen); } - GuiButton btn3( &btn3Img, &btn3Img, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 1 ); - btn3.SetLabel( &btn3Txt ); - if ( !btn4Label ) - btn3.SetTrigger( &trigB ); + GuiButton btn3(&btn3Img, &btn3Img, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 1); + btn3.SetLabel(&btn3Txt); + if (!btn4Label) btn3.SetTrigger(&trigB); - GuiText btn4Txt( btn4Label, 22, THEME.prompttext ); - GuiImage btn4Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn4Txt(btn4Label, 22, THEME.prompttext); + GuiImage btn4Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn4Txt.SetWidescreen( Settings.widescreen ); - btn4Img.SetWidescreen( Settings.widescreen ); + btn4Txt.SetWidescreen(Settings.widescreen); + btn4Img.SetWidescreen(Settings.widescreen); } - GuiButton btn4( &btn4Img, &btn4Img, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 1 ); - btn4.SetLabel( &btn4Txt ); - if ( btn4Label ) - btn4.SetTrigger( &trigB ); + GuiButton btn4(&btn4Img, &btn4Img, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 1); + btn4.SetLabel(&btn4Txt); + if (btn4Label) btn4.SetTrigger(&trigB); - if ( ( Settings.wsprompt == yes ) && ( Settings.widescreen ) ) /////////////adjust buttons for widescreen + if ((Settings.wsprompt == yes) && (Settings.widescreen)) /////////////adjust buttons for widescreen { - msgTxt.SetMaxWidth( 330 ); + msgTxt.SetMaxWidth(330); - if ( btn2Label && !btn3Label && !btn4Label ) + if (btn2Label && !btn3Label && !btn4Label) { - btn1.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn1.SetPosition( 70, -80 ); - btn2.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn2.SetPosition( -70, -80 ); - btn3.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn3.SetPosition( -70, -55 ); - btn4.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn4.SetPosition( 70, -55 ); + btn1.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn1.SetPosition(70, -80); + btn2.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn2.SetPosition(-70, -80); + btn3.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn3.SetPosition(-70, -55); + btn4.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn4.SetPosition(70, -55); } - else if ( btn2Label && btn3Label && !btn4Label ) + else if (btn2Label && btn3Label && !btn4Label) { - btn1.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn1.SetPosition( 70, -120 ); - btn2.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn2.SetPosition( -70, -120 ); - btn3.SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); - btn3.SetPosition( 0, -55 ); - btn4.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn4.SetPosition( 70, -55 ); + btn1.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn1.SetPosition(70, -120); + btn2.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn2.SetPosition(-70, -120); + btn3.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + btn3.SetPosition(0, -55); + btn4.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn4.SetPosition(70, -55); } - else if ( btn2Label && btn3Label && btn4Label ) + else if (btn2Label && btn3Label && btn4Label) { - btn1.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn1.SetPosition( 70, -120 ); - btn2.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn2.SetPosition( -70, -120 ); - btn3.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn3.SetPosition( 70, -55 ); - btn4.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn4.SetPosition( -70, -55 ); + btn1.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn1.SetPosition(70, -120); + btn2.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn2.SetPosition(-70, -120); + btn3.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn3.SetPosition(70, -55); + btn4.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn4.SetPosition(-70, -55); } - else if ( !btn2Label && btn3Label && btn4Label ) + else if (!btn2Label && btn3Label && btn4Label) { - btn1.SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); - btn1.SetPosition( 0, -120 ); - btn2.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn2.SetPosition( -70, -120 ); - btn3.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn3.SetPosition( 70, -55 ); - btn4.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn4.SetPosition( -70, -55 ); + btn1.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + btn1.SetPosition(0, -120); + btn2.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn2.SetPosition(-70, -120); + btn3.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn3.SetPosition(70, -55); + btn4.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn4.SetPosition(-70, -55); } else { - btn1.SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); - btn1.SetPosition( 0, -80 ); - btn2.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn2.SetPosition( 70, -120 ); - btn3.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn3.SetPosition( -70, -55 ); - btn4.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn4.SetPosition( 70, -55 ); + btn1.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + btn1.SetPosition(0, -80); + btn2.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn2.SetPosition(70, -120); + btn3.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn3.SetPosition(-70, -55); + btn4.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn4.SetPosition(70, -55); } } else { - if ( btn2Label && !btn3Label && !btn4Label ) + if (btn2Label && !btn3Label && !btn4Label) { - btn1.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn1.SetPosition( 40, -45 ); - btn2.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn2.SetPosition( -40, -45 ); - btn3.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn3.SetPosition( 50, -65 ); - btn4.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn4.SetPosition( -50, -65 ); + btn1.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn1.SetPosition(40, -45); + btn2.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn2.SetPosition(-40, -45); + btn3.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn3.SetPosition(50, -65); + btn4.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn4.SetPosition(-50, -65); } - else if ( btn2Label && btn3Label && !btn4Label ) + else if (btn2Label && btn3Label && !btn4Label) { - btn1.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn1.SetPosition( 50, -120 ); - btn2.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn2.SetPosition( -50, -120 ); - btn3.SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); - btn3.SetPosition( 0, -65 ); - btn4.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn4.SetPosition( -50, -65 ); + btn1.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn1.SetPosition(50, -120); + btn2.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn2.SetPosition(-50, -120); + btn3.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + btn3.SetPosition(0, -65); + btn4.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn4.SetPosition(-50, -65); } - else if ( btn2Label && btn3Label && btn4Label ) + else if (btn2Label && btn3Label && btn4Label) { - btn1.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn1.SetPosition( 50, -120 ); - btn2.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn2.SetPosition( -50, -120 ); - btn3.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn3.SetPosition( 50, -65 ); - btn4.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn4.SetPosition( -50, -65 ); + btn1.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn1.SetPosition(50, -120); + btn2.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn2.SetPosition(-50, -120); + btn3.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn3.SetPosition(50, -65); + btn4.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn4.SetPosition(-50, -65); } - else if ( !btn2Label && btn3Label && btn4Label ) + else if (!btn2Label && btn3Label && btn4Label) { - btn1.SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); - btn1.SetPosition( 0, -120 ); - btn2.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn2.SetPosition( -50, -120 ); - btn3.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn3.SetPosition( 50, -65 ); - btn4.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn4.SetPosition( -50, -65 ); + btn1.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + btn1.SetPosition(0, -120); + btn2.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn2.SetPosition(-50, -120); + btn3.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn3.SetPosition(50, -65); + btn4.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn4.SetPosition(-50, -65); } else { - btn1.SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); - btn1.SetPosition( 0, -45 ); - btn2.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn2.SetPosition( 50, -120 ); - btn3.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn3.SetPosition( 50, -65 ); - btn4.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn4.SetPosition( -50, -65 ); + btn1.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + btn1.SetPosition(0, -45); + btn2.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn2.SetPosition(50, -120); + btn3.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn3.SetPosition(50, -65); + btn4.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn4.SetPosition(-50, -65); } } GuiTrigger trigZ; - trigZ.SetButtonOnlyTrigger( -1, WPAD_NUNCHUK_BUTTON_Z | WPAD_CLASSIC_BUTTON_ZL, PAD_TRIGGER_Z ); + 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 ); + GuiButton screenShotBtn(0, 0); + screenShotBtn.SetPosition(0, 0); + screenShotBtn.SetTrigger(&trigZ); - promptWindow.Append( &dialogBoxImg ); - promptWindow.Append( &titleTxt ); - promptWindow.Append( &msgTxt ); - promptWindow.Append( &screenShotBtn ); + promptWindow.Append(&dialogBoxImg); + promptWindow.Append(&titleTxt); + promptWindow.Append(&msgTxt); + promptWindow.Append(&screenShotBtn); - if ( btn1Label ) - promptWindow.Append( &btn1 ); - if ( btn2Label ) - promptWindow.Append( &btn2 ); - if ( btn3Label ) - promptWindow.Append( &btn3 ); - if ( btn4Label ) - promptWindow.Append( &btn4 ); + if (btn1Label) promptWindow.Append(&btn1); + if (btn2Label) promptWindow.Append(&btn2); + if (btn3Label) promptWindow.Append(&btn3); + if (btn4Label) promptWindow.Append(&btn4); - 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 ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); - while ( choice == -1 ) + while (choice == -1) { VIDEO_WaitVSync(); - if ( shutdown == 1 ) + if (shutdown == 1) { - wiilight( 0 ); + wiilight(0); Sys_Shutdown(); } - if ( reset == 1 ) - Sys_Reboot(); - if ( btn1.GetState() == STATE_CLICKED ) + if (reset == 1) Sys_Reboot(); + if (btn1.GetState() == STATE_CLICKED) { choice = 1; } - else if ( btn2.GetState() == STATE_CLICKED ) + else if (btn2.GetState() == STATE_CLICKED) { - if ( !btn3Label ) + if (!btn3Label) choice = 0; - else - choice = 2; + else choice = 2; } - else if ( btn3.GetState() == STATE_CLICKED ) + else if (btn3.GetState() == STATE_CLICKED) { - if ( !btn4Label ) + if (!btn4Label) choice = 0; - else - choice = 3; + else choice = 3; } - else if ( btn4.GetState() == STATE_CLICKED ) + else if (btn4.GetState() == STATE_CLICKED) { choice = 0; } - else if ( screenShotBtn.GetState() == STATE_CLICKED ) - { + else if (screenShotBtn.GetState() == STATE_CLICKED) + { screenShotBtn.ResetState(); - ScreenShot(); + ScreenShot(); } - if ( count > 0 )count--; - if ( count == 0 ) choice = 1; + if (count > 0) count--; + if (count == 0) choice = 1; } - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - while ( promptWindow.GetEffect() > 0 ) usleep( 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + while (promptWindow.GetEffect() > 0) + usleep(50); HaltGui(); - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); - gprintf( " %i\n", choice ); + gprintf(" %i\n", choice); return choice; } @@ -830,51 +822,50 @@ int WindowPrompt( const char *title, const char *msg, const char *btn1Label, ***************************************************************************/ int WindowExitPrompt() { - gprintf( "WindowExitPrompt()\n" ); + gprintf("WindowExitPrompt()\n"); GuiSound * homein = NULL; - homein = new GuiSound( menuin_ogg, menuin_ogg_size, Settings.sfxvolume ); - homein->SetVolume( Settings.sfxvolume ); - homein->SetLoop( 0 ); + homein = new GuiSound(menuin_ogg, menuin_ogg_size, Settings.sfxvolume); + homein->SetVolume(Settings.sfxvolume); + homein->SetLoop(0); homein->Play(); GuiSound * homeout = NULL; - homeout = new GuiSound( menuout_ogg, menuout_ogg_size, Settings.sfxvolume ); - homeout->SetVolume( Settings.sfxvolume ); - homeout->SetLoop( 0 ); + homeout = new GuiSound(menuout_ogg, menuout_ogg_size, Settings.sfxvolume); + homeout->SetVolume(Settings.sfxvolume); + homeout->SetLoop(0); int choice = -1; char imgPath[100]; u64 oldstub = getStubDest(); loadStub(); - if ( oldstub != 0x00010001554c4e52ll && oldstub != 0x00010001554e454fll ) - Set_Stub( oldstub ); + if (oldstub != 0x00010001554c4e52ll && oldstub != 0x00010001554e454fll) Set_Stub(oldstub); - 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 ); + 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 ); + 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 ); - GuiImageData bottom( exit_bottom_png ); - GuiImageData bottomOver( exit_bottom_over_png ); - GuiImageData button( exit_button_png ); - GuiImageData wiimote( wiimote_png ); - GuiImageData close( closebutton_png ); + GuiImageData top(exit_top_png); + GuiImageData topOver(exit_top_over_png); + GuiImageData bottom(exit_bottom_png); + GuiImageData bottomOver(exit_bottom_over_png); + GuiImageData button(exit_button_png); + GuiImageData wiimote(wiimote_png); + GuiImageData close(closebutton_png); - snprintf( imgPath, sizeof( imgPath ), "%sbattery_white.png", Settings.theme_path ); - GuiImageData battery( imgPath, battery_white_png ); - snprintf( imgPath, sizeof( imgPath ), "%sbattery_bar_white.png", Settings.theme_path ); - GuiImageData batteryBar( imgPath, battery_bar_white_png ); - snprintf( imgPath, sizeof( imgPath ), "%sbattery_red.png", Settings.theme_path ); - GuiImageData batteryRed( imgPath, battery_red_png ); - snprintf( imgPath, sizeof( imgPath ), "%sbattery_bar_red.png", Settings.theme_path ); - GuiImageData batteryBarRed( imgPath, battery_bar_red_png ); + snprintf(imgPath, sizeof(imgPath), "%sbattery_white.png", Settings.theme_path); + GuiImageData battery(imgPath, battery_white_png); + snprintf(imgPath, sizeof(imgPath), "%sbattery_bar_white.png", Settings.theme_path); + GuiImageData batteryBar(imgPath, battery_bar_white_png); + snprintf(imgPath, sizeof(imgPath), "%sbattery_red.png", Settings.theme_path); + GuiImageData batteryRed(imgPath, battery_red_png); + snprintf(imgPath, sizeof(imgPath), "%sbattery_bar_red.png", Settings.theme_path); + GuiImageData batteryBarRed(imgPath, battery_bar_red_png); int i = 0, ret = 0, level; char txt[3]; @@ -883,270 +874,277 @@ int WindowExitPrompt() GuiImage * batteryBarImg[4]; GuiButton * batteryBtn[4]; - for ( i = 0; i < 4; i++ ) + for (i = 0; i < 4; i++) { - sprintf( txt, "P%d", i + 1 ); + sprintf(txt, "P%d", i + 1); - 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 ); - batteryImg[i]->SetPosition( 36, 0 ); - batteryImg[i]->SetTile( 0 ); - batteryBarImg[i] = new GuiImage( &batteryBar ); - batteryBarImg[i]->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - batteryBarImg[i]->SetPosition( 33, 0 ); + 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); + batteryImg[i]->SetPosition(36, 0); + batteryImg[i]->SetTile(0); + batteryBarImg[i] = new GuiImage(&batteryBar); + batteryBarImg[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + batteryBarImg[i]->SetPosition(33, 0); - batteryBtn[i] = new GuiButton( 40, 20 ); - batteryBtn[i]->SetLabel( batteryTxt[i] ); - batteryBtn[i]->SetImage( batteryBarImg[i] ); - batteryBtn[i]->SetIcon( batteryImg[i] ); - batteryBtn[i]->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - batteryBtn[i]->SetRumble( false ); - batteryBtn[i]->SetAlpha( 70 ); - batteryBtn[i]->SetEffect( EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_IN, 50 ); + batteryBtn[i] = new GuiButton(40, 20); + batteryBtn[i]->SetLabel(batteryTxt[i]); + batteryBtn[i]->SetImage(batteryBarImg[i]); + batteryBtn[i]->SetIcon(batteryImg[i]); + batteryBtn[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + batteryBtn[i]->SetRumble(false); + batteryBtn[i]->SetAlpha(70); + batteryBtn[i]->SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_IN, 50); } - batteryBtn[0]->SetPosition( 180, 150 ); - batteryBtn[1]->SetPosition( 284, 150 ); - batteryBtn[2]->SetPosition( 388, 150 ); - batteryBtn[3]->SetPosition( 494, 150 ); + batteryBtn[0]->SetPosition(180, 150); + batteryBtn[1]->SetPosition(284, 150); + batteryBtn[2]->SetPosition(388, 150); + batteryBtn[3]->SetPosition(494, 150); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); GuiTrigger trigHome; - trigHome.SetButtonOnlyTrigger( -1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0 ); + trigHome.SetButtonOnlyTrigger(-1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0); - GuiText titleTxt( tr( "HOME Menu" ), 36, ( GXColor ) {255, 255, 255, 255} ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( -180, 40 ); - titleTxt.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50 ); + GuiText titleTxt(tr( "HOME Menu" ), 36, ( GXColor ) + { 255, 255, 255, 255}); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(-180, 40); + titleTxt.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50); - GuiText closeTxt( tr( "Close" ), 28, ( GXColor ) {0, 0, 0, 255} ); - closeTxt.SetPosition( 10, 3 ); - GuiImage closeImg( &close ); - if ( Settings.wsprompt == yes ) + GuiText closeTxt(tr( "Close" ), 28, ( GXColor ) + { 0, 0, 0, 255}); + closeTxt.SetPosition(10, 3); + GuiImage closeImg(&close); + if (Settings.wsprompt == yes) { - closeTxt.SetWidescreen( Settings.widescreen ); - closeImg.SetWidescreen( Settings.widescreen ); + closeTxt.SetWidescreen(Settings.widescreen); + closeImg.SetWidescreen(Settings.widescreen); } - GuiButton closeBtn( close.GetWidth(), close.GetHeight() ); - closeBtn.SetImage( &closeImg ); - closeBtn.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - closeBtn.SetPosition( 190, 30 ); - closeBtn.SetLabel( &closeTxt ); - closeBtn.SetRumble( false ); - closeBtn.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50 ); + GuiButton closeBtn(close.GetWidth(), close.GetHeight()); + closeBtn.SetImage(&closeImg); + closeBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + closeBtn.SetPosition(190, 30); + closeBtn.SetLabel(&closeTxt); + closeBtn.SetRumble(false); + closeBtn.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50); - GuiImage btn1Img( &top ); - GuiImage btn1OverImg( &topOver ); - GuiButton btn1( &btn1Img, &btn1OverImg, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 0 ); - btn1.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50 ); + GuiImage btn1Img(&top); + GuiImage btn1OverImg(&topOver); + GuiButton btn1(&btn1Img, &btn1OverImg, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 0); + btn1.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50); - GuiText btn2Txt( tr( "Back to Loader" ), 28, ( GXColor ) {0, 0, 0, 255} ); - GuiImage btn2Img( &button ); - if ( Settings.wsprompt == yes ) + GuiText btn2Txt(tr( "Back to Loader" ), 28, ( GXColor ) + { 0, 0, 0, 255}); + GuiImage btn2Img(&button); + if (Settings.wsprompt == yes) { - btn2Txt.SetWidescreen( Settings.widescreen ); - btn2Img.SetWidescreen( Settings.widescreen ); + btn2Txt.SetWidescreen(Settings.widescreen); + btn2Img.SetWidescreen(Settings.widescreen); } - GuiButton btn2( &btn2Img, &btn2Img, 2, 5, -150, 0, &trigA, &btnSoundOver, btnClick2, 1 ); - btn2.SetLabel( &btn2Txt ); - btn2.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 50 ); - btn2.SetRumble( false ); - btn2.SetPosition( -150, 0 ); + GuiButton btn2(&btn2Img, &btn2Img, 2, 5, -150, 0, &trigA, &btnSoundOver, btnClick2, 1); + btn2.SetLabel(&btn2Txt); + btn2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 50); + btn2.SetRumble(false); + btn2.SetPosition(-150, 0); - - GuiText btn3Txt( tr( "Wii Menu" ), 28, ( GXColor ) {0, 0, 0, 255} ); - GuiImage btn3Img( &button ); - if ( Settings.wsprompt == yes ) + GuiText btn3Txt(tr( "Wii Menu" ), 28, ( GXColor ) + { 0, 0, 0, 255}); + GuiImage btn3Img(&button); + if (Settings.wsprompt == yes) { - btn3Txt.SetWidescreen( Settings.widescreen ); - btn3Img.SetWidescreen( Settings.widescreen ); + btn3Txt.SetWidescreen(Settings.widescreen); + btn3Img.SetWidescreen(Settings.widescreen); } - GuiButton btn3( &btn3Img, &btn3Img, 2, 5, 150, 0, &trigA, &btnSoundOver, btnClick2, 1 ); - btn3.SetLabel( &btn3Txt ); - btn3.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 50 ); - btn3.SetRumble( false ); - btn3.SetPosition( 150, 0 ); + GuiButton btn3(&btn3Img, &btn3Img, 2, 5, 150, 0, &trigA, &btnSoundOver, btnClick2, 1); + btn3.SetLabel(&btn3Txt); + btn3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 50); + btn3.SetRumble(false); + btn3.SetPosition(150, 0); - GuiImage btn4Img( &bottom ); - GuiImage btn4OverImg( &bottomOver ); - GuiButton btn4( &btn4Img, &btn4OverImg, 0, 4, 0, 0, &trigA, &btnSoundOver, btnClick2, 0 ); - btn4.SetTrigger( &trigB ); - btn4.SetTrigger( &trigHome ); - btn4.SetEffect( EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_IN, 50 ); + GuiImage btn4Img(&bottom); + GuiImage btn4OverImg(&bottomOver); + GuiButton btn4(&btn4Img, &btn4OverImg, 0, 4, 0, 0, &trigA, &btnSoundOver, btnClick2, 0); + btn4.SetTrigger(&trigB); + btn4.SetTrigger(&trigHome); + btn4.SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_IN, 50); - GuiImage wiimoteImg( &wiimote ); - if ( Settings.wsprompt == yes ) + GuiImage wiimoteImg(&wiimote); + if (Settings.wsprompt == yes) { - wiimoteImg.SetWidescreen( Settings.widescreen ); + wiimoteImg.SetWidescreen(Settings.widescreen); } - wiimoteImg.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - wiimoteImg.SetEffect( EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_IN, 50 ); - wiimoteImg.SetPosition( 50, 210 ); + wiimoteImg.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + wiimoteImg.SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_IN, 50); + wiimoteImg.SetPosition(50, 210); - promptWindow.Append( &btn2 ); - promptWindow.Append( &btn3 ); - promptWindow.Append( &btn4 ); - promptWindow.Append( &btn1 ); - promptWindow.Append( &closeBtn ); - promptWindow.Append( &titleTxt ); - promptWindow.Append( &wiimoteImg ); + promptWindow.Append(&btn2); + promptWindow.Append(&btn3); + promptWindow.Append(&btn4); + promptWindow.Append(&btn1); + promptWindow.Append(&closeBtn); + promptWindow.Append(&titleTxt); + promptWindow.Append(&wiimoteImg); - promptWindow.Append( batteryBtn[0] ); - promptWindow.Append( batteryBtn[1] ); - promptWindow.Append( batteryBtn[2] ); - promptWindow.Append( batteryBtn[3] ); + promptWindow.Append(batteryBtn[0]); + promptWindow.Append(batteryBtn[1]); + promptWindow.Append(batteryBtn[2]); + promptWindow.Append(batteryBtn[3]); HaltGui(); - mainWindow->SetState( STATE_DISABLED ); - mainWindow->Append( &promptWindow ); - mainWindow->ChangeFocus( &promptWindow ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); - while ( choice == -1 ) + while (choice == -1) { VIDEO_WaitVSync(); - for ( i = 0; i < 4; i++ ) + for (i = 0; i < 4; i++) { - if ( WPAD_Probe( i, NULL ) == WPAD_ERR_NONE ) // controller connected + if (WPAD_Probe(i, NULL) == WPAD_ERR_NONE) // controller connected { - level = ( userInput[i].wpad.battery_level / 100.0 ) * 4; - if ( level > 4 ) level = 4; + level = (userInput[i].wpad.battery_level / 100.0) * 4; + if (level > 4) level = 4; - if ( level <= 1 ) + if (level <= 1) { - batteryBarImg[i]->SetImage( &batteryBarRed ); - batteryImg[i]->SetImage( &batteryRed ); + batteryBarImg[i]->SetImage(&batteryBarRed); + batteryImg[i]->SetImage(&batteryRed); } else { - batteryBarImg[i]->SetImage( &batteryBar ); + batteryBarImg[i]->SetImage(&batteryBar); } - batteryImg[i]->SetTile( level ); + batteryImg[i]->SetTile(level); - batteryBtn[i]->SetAlpha( 255 ); + batteryBtn[i]->SetAlpha(255); } - else // controller not connected + else // controller not connected { - batteryImg[i]->SetTile( 0 ); - batteryImg[i]->SetImage( &battery ); - batteryBtn[i]->SetAlpha( 70 ); + batteryImg[i]->SetTile(0); + batteryImg[i]->SetImage(&battery); + batteryBtn[i]->SetAlpha(70); } } - - if ( shutdown == 1 ) + if (shutdown == 1) { - wiilight( 0 ); + wiilight(0); Sys_Shutdown(); } - if ( reset == 1 ) - Sys_Reboot(); - if ( btn1.GetState() == STATE_CLICKED ) + if (reset == 1) Sys_Reboot(); + if (btn1.GetState() == STATE_CLICKED) { choice = 1; - btn1.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - closeBtn.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - btn4.SetEffect( EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50 ); - btn2.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50 ); - btn3.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50 ); - titleTxt.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - wiimoteImg.SetEffect( EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50 ); + btn1.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + closeBtn.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + btn4.SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50); + btn2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50); + btn3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50); + titleTxt.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + wiimoteImg.SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50); - for ( int i = 0; i < 4; i++ ) - batteryBtn[i]->SetEffect( EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50 ); + for (int i = 0; i < 4; i++) + batteryBtn[i]->SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50); } - else if ( btn4.GetState() == STATE_SELECTED ) + else if (btn4.GetState() == STATE_SELECTED) { - wiimoteImg.SetPosition( 50, 165 ); + wiimoteImg.SetPosition(50, 165); } - else if ( btn2.GetState() == STATE_CLICKED ) + else if (btn2.GetState() == STATE_CLICKED) { - ret = WindowPrompt( tr( "Are you sure?" ), 0, tr( "Yes" ), tr( "No" ) ); - if ( ret == 1 ) + ret = WindowPrompt(tr( "Are you sure?" ), 0, tr( "Yes" ), tr( "No" )); + if (ret == 1) { choice = 2; } HaltGui(); - mainWindow->SetState( STATE_DISABLED ); - promptWindow.SetState( STATE_DEFAULT ); - mainWindow->ChangeFocus( &promptWindow ); + mainWindow->SetState(STATE_DISABLED); + promptWindow.SetState(STATE_DEFAULT); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); btn2.ResetState(); } - else if ( btn3.GetState() == STATE_CLICKED ) + else if (btn3.GetState() == STATE_CLICKED) { - ret = WindowPrompt( tr( "Are you sure?" ), 0, tr( "Yes" ), tr( "No" ) ); - if ( ret == 1 ) + ret = WindowPrompt(tr( "Are you sure?" ), 0, tr( "Yes" ), tr( "No" )); + if (ret == 1) { choice = 3; } HaltGui(); - mainWindow->SetState( STATE_DISABLED ); - promptWindow.SetState( STATE_DEFAULT ); - mainWindow->ChangeFocus( &promptWindow ); + mainWindow->SetState(STATE_DISABLED); + promptWindow.SetState(STATE_DEFAULT); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); btn3.ResetState(); } - else if ( btn4.GetState() == STATE_CLICKED ) + else if (btn4.GetState() == STATE_CLICKED) { - btn1.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - closeBtn.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - btn4.SetEffect( EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50 ); - btn2.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50 ); - btn3.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50 ); - titleTxt.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - wiimoteImg.SetEffect( EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50 ); + btn1.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + closeBtn.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + btn4.SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50); + btn2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50); + btn3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50); + titleTxt.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + wiimoteImg.SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50); - for ( int i = 0; i < 4; i++ ) - batteryBtn[i]->SetEffect( EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50 ); + for (int i = 0; i < 4; i++) + batteryBtn[i]->SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50); choice = 0; } - else if ( btn4.GetState() != STATE_SELECTED ) + else if (btn4.GetState() != STATE_SELECTED) { - wiimoteImg.SetPosition( 50, 210 ); + wiimoteImg.SetPosition(50, 210); } } homeout->Play(); - while ( btn1.GetEffect() > 0 ) usleep( 50 ); - while ( promptWindow.GetEffect() > 0 ) usleep( 50 ); + while (btn1.GetEffect() > 0) + usleep(50); + while (promptWindow.GetEffect() > 0) + usleep(50); HaltGui(); homein->Stop(); delete homein; - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); - while ( homeout->IsPlaying() > 0 ) usleep( 50 ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); + while (homeout->IsPlaying() > 0) + usleep(50); homeout->Stop(); delete homeout; ResumeGui(); 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 ); - btnFavorite->SetSoundOver( sndOver ); - btnFavorite->SetSoundClick( sndClick ); - btnFavorite->SetTrigger( trig ); + btnFavorite->SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + btnFavorite->SetPosition(xPos, -60); + btnFavorite->SetImage(img); + btnFavorite->SetSoundOver(sndOver); + btnFavorite->SetSoundClick(sndClick); + btnFavorite->SetTrigger(trig); btnFavorite->SetEffectGrow(); } -u8 SetFavorite( GuiButton *fav1, GuiButton *fav2, GuiButton *fav3, GuiButton *fav4, GuiButton *fav5, u8* gameId, u8 favorite ) +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 ) + struct Game_NUM * game_num = CFG_get_game_num(gameId); + if (game_num) { favoritevar = game_num->favorite; playcount = game_num->count; @@ -1156,18 +1154,19 @@ u8 SetFavorite( GuiButton *fav1, GuiButton *fav2, GuiButton *fav3, GuiButton *fa favoritevar = 0; playcount = 0; } - favoritevar = ( favorite == favoritevar ) ? 0 : favorite; // Press the current rank to reset the rank - CFG_save_game_num( gameId ); + 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 ) +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 ); + 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); } /**************************************************************************** @@ -1185,351 +1184,341 @@ int GameWindowPrompt() GuiSound * gameSound = NULL; - gprintf( "GameWindowPrompt()\n" ); - 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 ); + gprintf("GameWindowPrompt()\n"); + 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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf( imgPath, sizeof( imgPath ), "%sfavorite.png", Settings.theme_path ); - GuiImageData imgFavorite( imgPath, favorite_png ); - snprintf( imgPath, sizeof( imgPath ), "%snot_favorite.png", Settings.theme_path ); - GuiImageData imgNotFavorite( imgPath, not_favorite_png ); + snprintf(imgPath, sizeof(imgPath), "%sfavorite.png", Settings.theme_path); + GuiImageData imgFavorite(imgPath, favorite_png); + snprintf(imgPath, sizeof(imgPath), "%snot_favorite.png", Settings.theme_path); + GuiImageData imgNotFavorite(imgPath, not_favorite_png); - snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_left.png", Settings.theme_path ); - GuiImageData imgLeft( imgPath, startgame_arrow_left_png ); - snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_right.png", Settings.theme_path ); - GuiImageData imgRight( imgPath, startgame_arrow_right_png ); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", Settings.theme_path); + GuiImageData imgLeft(imgPath, startgame_arrow_left_png); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", Settings.theme_path); + GuiImageData imgRight(imgPath, startgame_arrow_right_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + 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 ); + 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 ); + trigR.SetButtonOnlyTrigger(-1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT); GuiTrigger trigPlus; - trigPlus.SetButtonOnlyTrigger( -1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0 ); + trigPlus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0); GuiTrigger trigMinus; - trigMinus.SetButtonOnlyTrigger( -1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0 ); + trigMinus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0); GuiTrigger trigZ; - trigZ.SetButtonOnlyTrigger( -1, WPAD_NUNCHUK_BUTTON_Z | WPAD_CLASSIC_BUTTON_ZL, PAD_TRIGGER_Z ); + 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 ); + GuiButton screenShotBtn(0, 0); + screenShotBtn.SetPosition(0, 0); + screenShotBtn.SetTrigger(&trigZ); - if ( Settings.widescreen ) - snprintf( imgPath, sizeof( imgPath ), "%swdialogue_box_startgame.png", Settings.theme_path ); - else - snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box_startgame.png", Settings.theme_path ); + if (Settings.widescreen) + snprintf(imgPath, sizeof(imgPath), "%swdialogue_box_startgame.png", Settings.theme_path); + else snprintf(imgPath, sizeof(imgPath), "%sdialogue_box_startgame.png", Settings.theme_path); - GuiImageData dialogBox( imgPath, Settings.widescreen ? wdialogue_box_startgame_png : dialogue_box_startgame_png ); - GuiImage dialogBoxImg( &dialogBox ); + GuiImageData dialogBox(imgPath, Settings.widescreen ? wdialogue_box_startgame_png : dialogue_box_startgame_png); + GuiImage dialogBoxImg(&dialogBox); - GuiTooltip nameBtnTT( tr( "Rename Game on WBFS" ) ); - if ( Settings.wsprompt == yes ) - nameBtnTT.SetWidescreen( Settings.widescreen ); - GuiText nameTxt( "", 22, THEME.prompttext ); - if ( Settings.wsprompt == yes ) - nameTxt.SetWidescreen( Settings.widescreen ); - nameTxt.SetMaxWidth( 350, SCROLL_HORIZONTAL ); - GuiButton nameBtn( 120, 50 ); - nameBtn.SetLabel( &nameTxt ); -// nameBtn.SetLabelOver(&nameTxt); - nameBtn.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - nameBtn.SetPosition( 0, -122 ); - nameBtn.SetSoundOver( &btnSoundOver ); - nameBtn.SetSoundClick( btnClick2 ); - if ( !mountMethod ) nameBtn.SetToolTip( &nameBtnTT, 24, -30, ALIGN_LEFT ); + GuiTooltip nameBtnTT(tr( "Rename Game on WBFS" )); + if (Settings.wsprompt == yes) nameBtnTT.SetWidescreen(Settings.widescreen); + GuiText nameTxt("", 22, THEME.prompttext); + if (Settings.wsprompt == yes) nameTxt.SetWidescreen(Settings.widescreen); + nameTxt.SetMaxWidth(350, SCROLL_HORIZONTAL); + GuiButton nameBtn(120, 50); + nameBtn.SetLabel(&nameTxt); + // nameBtn.SetLabelOver(&nameTxt); + nameBtn.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + nameBtn.SetPosition(0, -122); + nameBtn.SetSoundOver(&btnSoundOver); + nameBtn.SetSoundClick(btnClick2); + if (!mountMethod) nameBtn.SetToolTip(&nameBtnTT, 24, -30, ALIGN_LEFT); - if ( Settings.godmode == 1 && !mountMethod ) + if (Settings.godmode == 1 && !mountMethod) { - nameBtn.SetTrigger( &trigA ); + nameBtn.SetTrigger(&trigA); nameBtn.SetEffectGrow(); } - GuiText sizeTxt( ( char* ) NULL, 22, THEME.prompttext ); //TODO: get the size here - sizeTxt.SetAlignment( ALIGN_RIGHT, ALIGN_TOP ); - sizeTxt.SetPosition( -60, 70 ); + GuiText sizeTxt((char*) NULL, 22, THEME.prompttext); //TODO: get the size here + sizeTxt.SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + sizeTxt.SetPosition(-60, 70); -// GuiImage diskImg; + // GuiImage diskImg; GuiDiskCover diskImg; - diskImg.SetWidescreen( Settings.widescreen ); - diskImg.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - diskImg.SetAngle( angle ); + diskImg.SetWidescreen(Settings.widescreen); + diskImg.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + diskImg.SetAngle(angle); GuiDiskCover diskImg2; - diskImg2.SetWidescreen( Settings.widescreen ); - diskImg2.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - diskImg2.SetPosition( 0, -20 ); - diskImg2.SetAngle( angle ); - diskImg2.SetBeta( 180 ); + diskImg2.SetWidescreen(Settings.widescreen); + diskImg2.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + diskImg2.SetPosition(0, -20); + diskImg2.SetAngle(angle); + diskImg2.SetBeta(180); - GuiText playcntTxt( ( char* ) NULL, 18, THEME.info ); - playcntTxt.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - playcntTxt.SetPosition( -115, 45 ); + GuiText playcntTxt((char*) NULL, 18, THEME.info); + playcntTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + playcntTxt.SetPosition(-115, 45); - GuiButton btn1( 160, 160 ); - btn1.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - btn1.SetPosition( 0, -20 ); - btn1.SetImage( &diskImg ); + GuiButton btn1(160, 160); + btn1.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + btn1.SetPosition(0, -20); + btn1.SetImage(&diskImg); - btn1.SetSoundOver( &btnSoundOver ); - btn1.SetSoundClick( btnClick2 ); - btn1.SetTrigger( &trigA ); - btn1.SetState( STATE_SELECTED ); + btn1.SetSoundOver(&btnSoundOver); + btn1.SetSoundClick(btnClick2); + btn1.SetTrigger(&trigA); + btn1.SetState(STATE_SELECTED); - GuiText btn2Txt( tr( "Back" ), 22, THEME.prompttext ); - GuiImage btn2Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn2Txt(tr( "Back" ), 22, THEME.prompttext); + GuiImage btn2Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn2Txt.SetWidescreen( Settings.widescreen ); - btn2Img.SetWidescreen( Settings.widescreen ); + btn2Txt.SetWidescreen(Settings.widescreen); + btn2Img.SetWidescreen(Settings.widescreen); } - GuiButton btn2( &btn2Img, &btn2Img, 1, 5, 0, 0, &trigA, &btnSoundOver, btnClick2, 1 ); - if ( Settings.godmode == 1 && mountMethod != 2 && mountMethod != 3 ) + GuiButton btn2(&btn2Img, &btn2Img, 1, 5, 0, 0, &trigA, &btnSoundOver, btnClick2, 1); + if (Settings.godmode == 1 && mountMethod != 2 && mountMethod != 3) { - btn2.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn2.SetPosition( -50, -40 ); + btn2.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn2.SetPosition(-50, -40); } else { - btn2.SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); - btn2.SetPosition( 0, -40 ); + btn2.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + btn2.SetPosition(0, -40); } - btn2.SetLabel( &btn2Txt ); - btn2.SetTrigger( &trigB ); + btn2.SetLabel(&btn2Txt); + btn2.SetTrigger(&trigB); - GuiText btn3Txt( tr( "Settings" ), 22, THEME.prompttext ); - GuiImage btn3Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn3Txt(tr( "Settings" ), 22, THEME.prompttext); + GuiImage btn3Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn3Txt.SetWidescreen( Settings.widescreen ); - btn3Img.SetWidescreen( Settings.widescreen ); + btn3Txt.SetWidescreen(Settings.widescreen); + btn3Img.SetWidescreen(Settings.widescreen); } - GuiButton btn3( &btn3Img, &btn3Img, 0, 4, 50, -40, &trigA, &btnSoundOver, btnClick2, 1 ); - btn3.SetLabel( &btn3Txt ); + GuiButton btn3(&btn3Img, &btn3Img, 0, 4, 50, -40, &trigA, &btnSoundOver, btnClick2, 1); + btn3.SetLabel(&btn3Txt); GuiImage btnFavoriteImg1; - btnFavoriteImg1.SetWidescreen( Settings.widescreen ); + btnFavoriteImg1.SetWidescreen(Settings.widescreen); GuiImage btnFavoriteImg2; - btnFavoriteImg2.SetWidescreen( Settings.widescreen ); + btnFavoriteImg2.SetWidescreen(Settings.widescreen); GuiImage btnFavoriteImg3; - btnFavoriteImg3.SetWidescreen( Settings.widescreen ); + btnFavoriteImg3.SetWidescreen(Settings.widescreen); GuiImage btnFavoriteImg4; - btnFavoriteImg4.SetWidescreen( Settings.widescreen ); + btnFavoriteImg4.SetWidescreen(Settings.widescreen); GuiImage btnFavoriteImg5; - btnFavoriteImg5.SetWidescreen( Settings.widescreen ); + btnFavoriteImg5.SetWidescreen(Settings.widescreen); //GuiButton btnFavorite(&btnFavoriteImg,&btnFavoriteImg, 2, 5, -125, -60, &trigA, &btnSoundOver, &btnClick,1); - GuiButton btnFavorite1( imgFavorite.GetWidth(), imgFavorite.GetHeight() ); - GuiButton btnFavorite2( imgFavorite.GetWidth(), imgFavorite.GetHeight() ); - GuiButton btnFavorite3( imgFavorite.GetWidth(), imgFavorite.GetHeight() ); - GuiButton btnFavorite4( imgFavorite.GetWidth(), imgFavorite.GetHeight() ); - GuiButton btnFavorite5( imgFavorite.GetWidth(), imgFavorite.GetHeight() ); + GuiButton btnFavorite1(imgFavorite.GetWidth(), imgFavorite.GetHeight()); + GuiButton btnFavorite2(imgFavorite.GetWidth(), imgFavorite.GetHeight()); + GuiButton btnFavorite3(imgFavorite.GetWidth(), imgFavorite.GetHeight()); + 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 ) + GuiImage btnLeftImg(&imgLeft); + if (Settings.wsprompt == yes) { - btnLeftImg.SetWidescreen( Settings.widescreen ); + btnLeftImg.SetWidescreen(Settings.widescreen); } - GuiButton btnLeft( &btnLeftImg, &btnLeftImg, 0, 5, 20, 0, &trigA, &btnSoundOver, btnClick2, 1 ); - btnLeft.SetTrigger( &trigL ); - btnLeft.SetTrigger( &trigMinus ); + GuiButton btnLeft(&btnLeftImg, &btnLeftImg, 0, 5, 20, 0, &trigA, &btnSoundOver, btnClick2, 1); + btnLeft.SetTrigger(&trigL); + btnLeft.SetTrigger(&trigMinus); - GuiImage btnRightImg( &imgRight ); - if ( Settings.wsprompt == yes ) + GuiImage btnRightImg(&imgRight); + if (Settings.wsprompt == yes) { - btnRightImg.SetWidescreen( Settings.widescreen ); + btnRightImg.SetWidescreen(Settings.widescreen); } - GuiButton btnRight( &btnRightImg, &btnRightImg, 1, 5, -20, 0, &trigA, &btnSoundOver, btnClick2, 1 ); - btnRight.SetTrigger( &trigR ); - btnRight.SetTrigger( &trigPlus ); + GuiButton btnRight(&btnRightImg, &btnRightImg, 1, 5, -20, 0, &trigA, &btnSoundOver, btnClick2, 1); + btnRight.SetTrigger(&trigR); + btnRight.SetTrigger(&trigPlus); - promptWindow.Append( &dialogBoxImg ); - promptWindow.Append( &nameBtn ); - promptWindow.Append( &playcntTxt ); - promptWindow.Append( &screenShotBtn ); - promptWindow.Append( &btn2 ); - if ( !mountMethod )//stuff we don't show if it is a DVD mounted + promptWindow.Append(&dialogBoxImg); + promptWindow.Append(&nameBtn); + 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 ); + 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 ) + if (Settings.godmode == 1 && mountMethod != 2 && mountMethod != 3) { - promptWindow.Append( &btn3 ); + promptWindow.Append(&btn3); } - promptWindow.Append( &diskImg2 ); - promptWindow.Append( &btn1 ); + promptWindow.Append(&diskImg2); + promptWindow.Append(&btn1); short changed = -1; GuiImageData * diskCover = NULL; GuiImageData * diskCover2 = NULL; - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50); - while ( changed ) + while (changed) { - if ( changed == 1 ) + if (changed == 1) { - promptWindow.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 50); } - else if ( changed == 2 ) + else if (changed == 2) { - promptWindow.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 50); } - else if ( changed == 3 || changed == 4 ) + else if (changed == 3 || changed == 4) { - if ( diskCover2 ) - delete diskCover2; + if (diskCover2) delete diskCover2; diskCover2 = NULL; - if ( diskCover ) - diskCover2 = diskCover; + if (diskCover) diskCover2 = diskCover; diskCover = NULL; } //load disc image based or what game is seleted - struct discHdr * header = ( mountMethod == 1 || mountMethod == 2 ? dvdheader : gameList[gameSelected] ); - if ( Settings.gamesoundvolume > 0 ) + struct discHdr * header = (mountMethod == 1 || mountMethod == 2 ? dvdheader : gameList[gameSelected]); + if (Settings.gamesoundvolume > 0) { - if ( gameSound ) + if (gameSound) { gameSound->Stop(); delete gameSound; gameSound = NULL; } u32 gameSoundDataLen; - const u8 *gameSoundData = LoadBannerSound( header->id, &gameSoundDataLen ); - if ( gameSoundData ) + 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 ) - gameSound->SetLoop( 1 ); + gameSound = new GuiSound(gameSoundData, gameSoundDataLen, Settings.gamesoundvolume, false, true); + bgMusic->SetVolume(0); + if (Settings.gamesound == 2) gameSound->SetLoop(1); 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] ); + 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( "\t%s\n", IDFull ); - if ( diskCover ) - delete diskCover; + gprintf("\t%s\n", IDFull); + if (diskCover) delete diskCover; + snprintf(imgPath, sizeof(imgPath), "%s%s.png", Settings.disc_path, IDFull); //changed to current full id + diskCover = new GuiImageData(imgPath, 0); - - snprintf( imgPath, sizeof( imgPath ), "%s%s.png", Settings.disc_path, IDFull ); //changed to current full id - diskCover = new GuiImageData( imgPath, 0 ); - - if ( !diskCover->GetImage() ) + if (!diskCover->GetImage()) { delete diskCover; - snprintf( imgPath, sizeof( imgPath ), "%s%s.png", Settings.disc_path, ID ); //changed to current id - diskCover = new GuiImageData( imgPath, 0 ); + snprintf(imgPath, sizeof(imgPath), "%s%s.png", Settings.disc_path, ID); //changed to current id + diskCover = new GuiImageData(imgPath, 0); - - if ( !diskCover->GetImage() ) + if (!diskCover->GetImage()) { - snprintf ( ID, sizeof( ID ), "%c%c%c%c", header->id[0], header->id[1], header->id[2], header->id[3] ); + snprintf(ID, sizeof(ID), "%c%c%c%c", header->id[0], header->id[1], header->id[2], header->id[3]); delete diskCover; - snprintf( imgPath, sizeof( imgPath ), "%s%s.png", Settings.disc_path, ID ); //changed to current id - diskCover = new GuiImageData( imgPath, 0 ); - if ( !diskCover->GetImage() ) + snprintf(imgPath, sizeof(imgPath), "%s%s.png", Settings.disc_path, ID); //changed to current id + diskCover = new GuiImageData(imgPath, 0); + if (!diskCover->GetImage()) { delete diskCover; - snprintf( imgPath, sizeof( imgPath ), "%snodisc.png", Settings.theme_path ); //changed to nodisc.png - diskCover = new GuiImageData( imgPath, nodisc_png ); + snprintf(imgPath, sizeof(imgPath), "%snodisc.png", Settings.theme_path); //changed to nodisc.png + diskCover = new GuiImageData(imgPath, nodisc_png); } } } - - - if ( changed == 3 ) + if (changed == 3) { - diskImg.SetImage( diskCover2 ); - diskImg.SetBeta( 0 ); - diskImg.SetBetaRotateEffect( -90, 15 ); - diskImg2.SetImage( diskCover ); - diskImg2.SetAngle( diskImg.GetAngle() ); - diskImg2.SetBeta( 180 ); - diskImg2.SetBetaRotateEffect( -90, 15 ); - sizeTxt.SetEffect( EFFECT_FADE, -17 ); - nameTxt.SetEffect( EFFECT_FADE, -17 ); + diskImg.SetImage(diskCover2); + diskImg.SetBeta(0); + diskImg.SetBetaRotateEffect(-90, 15); + diskImg2.SetImage(diskCover); + diskImg2.SetAngle(diskImg.GetAngle()); + diskImg2.SetBeta(180); + diskImg2.SetBetaRotateEffect(-90, 15); + sizeTxt.SetEffect(EFFECT_FADE, -17); + nameTxt.SetEffect(EFFECT_FADE, -17); ResumeGui(); - while ( nameTxt.GetEffect() > 0 || diskImg.GetBetaRotateEffect() ) usleep( 50 ); + while (nameTxt.GetEffect() > 0 || diskImg.GetBetaRotateEffect()) + usleep(50); HaltGui(); - diskImg.SetImage( diskCover ); - diskImg.SetBeta( 90 ); - diskImg.SetBetaRotateEffect( -90, 15 ); - diskImg2.SetImage( diskCover2 ); - diskImg2.SetBeta( 270 ); - diskImg2.SetBetaRotateEffect( -90, 15 ); - sizeTxt.SetEffect( EFFECT_FADE, 17 ); - nameTxt.SetEffect( EFFECT_FADE, 17 ); + diskImg.SetImage(diskCover); + diskImg.SetBeta(90); + diskImg.SetBetaRotateEffect(-90, 15); + diskImg2.SetImage(diskCover2); + diskImg2.SetBeta(270); + diskImg2.SetBetaRotateEffect(-90, 15); + sizeTxt.SetEffect(EFFECT_FADE, 17); + nameTxt.SetEffect(EFFECT_FADE, 17); } - else if ( changed == 4 ) + else if (changed == 4) { - diskImg.SetImage( diskCover2 ); - diskImg.SetBeta( 0 ); - diskImg.SetBetaRotateEffect( 90, 15 ); - diskImg2.SetImage( diskCover ); - diskImg2.SetAngle( diskImg.GetAngle() ); - diskImg2.SetBeta( 180 ); - diskImg2.SetBetaRotateEffect( 90, 15 ); - sizeTxt.SetEffect( EFFECT_FADE, -17 ); - nameTxt.SetEffect( EFFECT_FADE, -17 ); + diskImg.SetImage(diskCover2); + diskImg.SetBeta(0); + diskImg.SetBetaRotateEffect(90, 15); + diskImg2.SetImage(diskCover); + diskImg2.SetAngle(diskImg.GetAngle()); + diskImg2.SetBeta(180); + diskImg2.SetBetaRotateEffect(90, 15); + sizeTxt.SetEffect(EFFECT_FADE, -17); + nameTxt.SetEffect(EFFECT_FADE, -17); ResumeGui(); - while ( nameTxt.GetEffect() > 0 || diskImg.GetBetaRotateEffect() ) usleep( 50 ); + while (nameTxt.GetEffect() > 0 || diskImg.GetBetaRotateEffect()) + usleep(50); HaltGui(); - diskImg.SetImage( diskCover ); - diskImg.SetBeta( 270 ); - diskImg.SetBetaRotateEffect( 90, 15 ); - diskImg2.SetImage( diskCover2 ); - diskImg2.SetBeta( 90 ); - diskImg2.SetBetaRotateEffect( 90, 15 ); - sizeTxt.SetEffect( EFFECT_FADE, 17 ); - nameTxt.SetEffect( EFFECT_FADE, 17 ); + diskImg.SetImage(diskCover); + diskImg.SetBeta(270); + diskImg.SetBetaRotateEffect(90, 15); + diskImg2.SetImage(diskCover2); + diskImg2.SetBeta(90); + diskImg2.SetBetaRotateEffect(90, 15); + sizeTxt.SetEffect(EFFECT_FADE, 17); + nameTxt.SetEffect(EFFECT_FADE, 17); } - else - diskImg.SetImage( diskCover ); + else diskImg.SetImage(diskCover); - if ( !mountMethod ) + if (!mountMethod) { - WBFS_GameSize( header->id, &size ); - sizeTxt.SetTextf( "%.2fGB", size ); //set size text; + 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 ) + struct Game_NUM* game_num = CFG_get_game_num(header->id); + if (game_num) { playcount = game_num->count; favoritevar = game_num->favorite; @@ -1539,56 +1528,57 @@ int GameWindowPrompt() playcount = 0; favoritevar = 0; } - playcntTxt.SetTextf( "%s: %i", tr( "Play Count" ), playcount ); - SetFavoriteImages( &btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite ); + playcntTxt.SetTextf("%s: %i", tr( "Play Count" ), playcount); + SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, + &imgFavorite, &imgNotFavorite); - nameTxt.SetPosition( 0, 1 ); + nameTxt.SetPosition(0, 1); - if ( changed != 3 && changed != 4 ) // changed==3 or changed==4 --> only Resume the GUI + if (changed != 3 && changed != 4) // changed==3 or changed==4 --> only Resume the GUI { HaltGui(); - mainWindow->SetState( STATE_DISABLED ); - mainWindow->Append( &promptWindow ); - mainWindow->ChangeFocus( &promptWindow ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); } ResumeGui(); changed = 0; - while ( choice == -1 ) + while (choice == -1) { - VIDEO_WaitVSync (); + VIDEO_WaitVSync(); - diskImg.SetSpin( btn1.GetState() == STATE_SELECTED ); - diskImg2.SetSpin( btn1.GetState() == STATE_SELECTED ); - if ( shutdown == 1 ) //for power button + 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 ); - mainWindow->SetState( STATE_DEFAULT ); - while ( promptWindow.GetEffect() > 0 ) usleep( 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + mainWindow->SetState(STATE_DEFAULT); + while (promptWindow.GetEffect() > 0) + usleep(50); HaltGui(); - mainWindow->Remove( &promptWindow ); + mainWindow->Remove(&promptWindow); ResumeGui(); - wiilight( 0 ); + wiilight(0); Sys_Shutdown(); } - if ( reset == 1 ) //for reset button - Sys_Reboot(); + if (reset == 1) //for reset button + Sys_Reboot(); - if ( gameSound ) + if (gameSound) { - if ( !gameSound->IsPlaying() ) + if (!gameSound->IsPlaying()) { - if ( Settings.gamesound == 1 ) - bgMusic->SetVolume( Settings.volume ); + if (Settings.gamesound == 1) bgMusic->SetVolume(Settings.volume); } } - if ( btn1.GetState() == STATE_CLICKED ) + if (btn1.GetState() == STATE_CLICKED) { //playcounter - struct Game_NUM* game_num = CFG_get_game_num( header->id ); - if ( game_num ) + struct Game_NUM* game_num = CFG_get_game_num(header->id); + if (game_num) { favoritevar = game_num->favorite; playcount = game_num->count; @@ -1599,369 +1589,373 @@ int GameWindowPrompt() playcount = 0; } playcount += 1; - if ( isInserted( bootDevice ) ) + if (isInserted(bootDevice)) { - CFG_save_game_num( header->id ); + CFG_save_game_num(header->id); } choice = 1; } - else if ( btn2.GetState() == STATE_CLICKED ) //back + else if (btn2.GetState() == STATE_CLICKED) //back { choice = 0; - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - mainWindow->SetState( STATE_DEFAULT ); - wiilight( 0 ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + mainWindow->SetState(STATE_DEFAULT); + wiilight(0); } - else if ( btn3.GetState() == STATE_CLICKED ) //settings + else if (btn3.GetState() == STATE_CLICKED) //settings { choice = 2; - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); } - else if ( nameBtn.GetState() == STATE_CLICKED ) //rename + else if (nameBtn.GetState() == STATE_CLICKED) //rename { choice = 3; - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); + 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 ) ) + 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 ) ) + 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 ) ) + 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 ) ) + 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 ) ) + 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 ) - { + else if (screenShotBtn.GetState() == STATE_CLICKED) + { screenShotBtn.ResetState(); - ScreenShot(); + ScreenShot(); } // 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 + else if ((btnRight.GetState() == STATE_CLICKED) && (Settings.xflip == no)) //next game { - promptWindow.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50); changed = 1; btnClick2->Play(); - gameSelected = ( gameSelected + 1 ) % gameList.size(); + gameSelected = (gameSelected + 1) % gameList.size(); btnRight.ResetState(); break; } - else if ( ( btnLeft.GetState() == STATE_CLICKED ) && ( Settings.xflip == no ) ) //previous game + else if ((btnLeft.GetState() == STATE_CLICKED) && (Settings.xflip == no)) //previous game { - promptWindow.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50); changed = 2; btnClick2->Play(); - gameSelected = ( gameSelected - 1 + gameList.size() ) % gameList.size(); + gameSelected = (gameSelected - 1 + gameList.size()) % gameList.size(); btnLeft.ResetState(); break; } - else if ( ( btnRight.GetState() == STATE_CLICKED ) && ( Settings.xflip == yes ) ) //previous game + else if ((btnRight.GetState() == STATE_CLICKED) && (Settings.xflip == yes)) //previous game { - promptWindow.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50); changed = 2; btnClick2->Play(); - gameSelected = ( gameSelected - 1 + gameList.size() ) % gameList.size(); + gameSelected = (gameSelected - 1 + gameList.size()) % gameList.size(); btnRight.ResetState(); break; } - else if ( ( btnLeft.GetState() == STATE_CLICKED ) && ( Settings.xflip == yes ) ) //next game + else if ((btnLeft.GetState() == STATE_CLICKED) && (Settings.xflip == yes)) //next game { - promptWindow.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50); changed = 1; btnClick2->Play(); - gameSelected = ( gameSelected + 1 ) % gameList.size(); + gameSelected = (gameSelected + 1) % gameList.size(); btnLeft.ResetState(); break; } - else if ( ( btnRight.GetState() == STATE_CLICKED ) && ( Settings.xflip == sysmenu ) ) //previous game + else if ((btnRight.GetState() == STATE_CLICKED) && (Settings.xflip == sysmenu)) //previous game { - promptWindow.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50); changed = 2; btnClick2->Play(); - gameSelected = ( gameSelected + 1 ) % gameList.size(); + gameSelected = (gameSelected + 1) % gameList.size(); btnRight.ResetState(); break; } - else if ( ( btnLeft.GetState() == STATE_CLICKED ) && ( Settings.xflip == sysmenu ) ) //next game + else if ((btnLeft.GetState() == STATE_CLICKED) && (Settings.xflip == sysmenu)) //next game { - promptWindow.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50); changed = 1; btnClick2->Play(); - gameSelected = ( gameSelected - 1 + gameList.size() ) % gameList.size(); + gameSelected = (gameSelected - 1 + gameList.size()) % gameList.size(); btnLeft.ResetState(); break; } - else if ( ( btnRight.GetState() == STATE_CLICKED ) && ( Settings.xflip == wtf ) ) //previous game + else if ((btnRight.GetState() == STATE_CLICKED) && (Settings.xflip == wtf)) //previous game { - promptWindow.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50); changed = 1; btnClick2->Play(); - gameSelected = ( gameSelected - 1 + gameList.size() ) % gameList.size(); + gameSelected = (gameSelected - 1 + gameList.size()) % gameList.size(); btnRight.ResetState(); break; } - else if ( ( btnLeft.GetState() == STATE_CLICKED ) && ( Settings.xflip == wtf ) ) //next game + else if ((btnLeft.GetState() == STATE_CLICKED) && (Settings.xflip == wtf)) //next game { - promptWindow.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50); changed = 2; btnClick2->Play(); - gameSelected = ( gameSelected + 1 ) % gameList.size(); + gameSelected = (gameSelected + 1) % gameList.size(); btnLeft.ResetState(); break; } - else if ( ( btnRight.GetState() == STATE_CLICKED ) && ( Settings.xflip == disk3d ) ) //next game + else if ((btnRight.GetState() == STATE_CLICKED) && (Settings.xflip == disk3d)) //next game { -// diskImg.SetBetaRotateEffect(45, 90); + // diskImg.SetBetaRotateEffect(45, 90); changed = 3; btnClick2->Play(); - gameSelected = ( gameSelected + 1 ) % gameList.size(); + gameSelected = (gameSelected + 1) % gameList.size(); btnRight.ResetState(); break; } - else if ( ( btnLeft.GetState() == STATE_CLICKED ) && ( Settings.xflip == disk3d ) ) //previous game + else if ((btnLeft.GetState() == STATE_CLICKED) && (Settings.xflip == disk3d)) //previous game { -// diskImg.SetBetaRotateEffect(-45, 90); -// promptWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 1/*50*/); + // diskImg.SetBetaRotateEffect(-45, 90); + // promptWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 1/*50*/); changed = 4; btnClick2->Play(); - gameSelected = ( gameSelected - 1 + gameList.size() ) % gameList.size(); + gameSelected = (gameSelected - 1 + gameList.size()) % gameList.size(); btnLeft.ResetState(); break; } } - - while ( promptWindow.GetEffect() > 0 ) usleep( 50 ); + while (promptWindow.GetEffect() > 0) + usleep(50); HaltGui(); - if ( changed != 3 && changed != 4 ) // changed==3 or changed==4 --> only Halt the GUI + if (changed != 3 && changed != 4) // changed==3 or changed==4 --> only Halt the GUI { - mainWindow->Remove( &promptWindow ); + mainWindow->Remove(&promptWindow); ResumeGui(); } } delete diskCover; delete diskCover2; - if ( gameSound ) + if (gameSound) { gameSound->Stop(); delete gameSound; gameSound = NULL; } - bgMusic->SetVolume( Settings.volume ); + bgMusic->SetVolume(Settings.volume); - gprintf( "\tret: %i\n", choice ); + gprintf("\tret: %i\n", choice); return choice; } /**************************************************************************** * DiscWait ***************************************************************************/ -int -DiscWait( const char *title, const char *msg, const char *btn1Label, const char *btn2Label, int IsDeviceWait ) +int DiscWait(const char *title, const char *msg, const char *btn1Label, const char *btn2Label, int IsDeviceWait) { int i = 30, ret = 0; u32 cover = 0; - 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 ); + 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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", Settings.theme_path ); - GuiImageData dialogBox( imgPath, dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", Settings.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - GuiImage dialogBoxImg( &dialogBox ); - if ( Settings.wsprompt == yes ) + GuiImage dialogBoxImg(&dialogBox); + if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen( Settings.widescreen ); + dialogBoxImg.SetWidescreen(Settings.widescreen); } - GuiText titleTxt( title, 26, THEME.prompttext ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( 0, 60 ); - GuiText msgTxt( msg, 22, THEME.prompttext ); - msgTxt.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - msgTxt.SetPosition( 0, -40 ); - msgTxt.SetMaxWidth( 430 ); + GuiText titleTxt(title, 26, THEME.prompttext); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0, 60); + GuiText msgTxt(msg, 22, THEME.prompttext); + msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + msgTxt.SetPosition(0, -40); + msgTxt.SetMaxWidth(430); - GuiText btn1Txt( btn1Label, 22, THEME.prompttext ); - GuiImage btn1Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn1Txt(btn1Label, 22, THEME.prompttext); + GuiImage btn1Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn1Txt.SetWidescreen( Settings.widescreen ); - btn1Img.SetWidescreen( Settings.widescreen ); + btn1Txt.SetWidescreen(Settings.widescreen); + btn1Img.SetWidescreen(Settings.widescreen); } - GuiButton btn1( &btn1Img, &btn1Img, 1, 5, 0, 0, &trigA, &btnSoundOver, btnClick2, 1 ); + GuiButton btn1(&btn1Img, &btn1Img, 1, 5, 0, 0, &trigA, &btnSoundOver, btnClick2, 1); - if ( btn2Label ) + if (btn2Label) { - btn1.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn1.SetPosition( 40, -45 ); + btn1.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn1.SetPosition(40, -45); } else { - btn1.SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); - btn1.SetPosition( 0, -45 ); + btn1.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + btn1.SetPosition(0, -45); } - btn1.SetLabel( &btn1Txt ); - btn1.SetTrigger( &trigB ); - btn1.SetState( STATE_SELECTED ); + btn1.SetLabel(&btn1Txt); + btn1.SetTrigger(&trigB); + btn1.SetState(STATE_SELECTED); - GuiText btn2Txt( btn2Label, 22, THEME.prompttext ); - GuiImage btn2Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn2Txt(btn2Label, 22, THEME.prompttext); + GuiImage btn2Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn2Txt.SetWidescreen( Settings.widescreen ); - btn2Img.SetWidescreen( Settings.widescreen ); + btn2Txt.SetWidescreen(Settings.widescreen); + btn2Img.SetWidescreen(Settings.widescreen); } - GuiButton btn2( &btn2Img, &btn2Img, 1, 4, -20, -25, &trigA, &btnSoundOver, btnClick2, 1 ); - btn2.SetLabel( &btn2Txt ); + GuiButton btn2(&btn2Img, &btn2Img, 1, 4, -20, -25, &trigA, &btnSoundOver, btnClick2, 1); + btn2.SetLabel(&btn2Txt); - if ( ( Settings.wsprompt == yes ) && ( Settings.widescreen ) ) /////////////adjust buttons for widescreen + if ((Settings.wsprompt == yes) && (Settings.widescreen)) /////////////adjust buttons for widescreen { - msgTxt.SetMaxWidth( 380 ); - if ( btn2Label ) + msgTxt.SetMaxWidth(380); + if (btn2Label) { - btn1.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn2.SetPosition( -70, -80 ); - btn1.SetPosition( 70, -80 ); + btn1.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn2.SetPosition(-70, -80); + btn1.SetPosition(70, -80); } else { - btn1.SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); - btn1.SetPosition( 0, -80 ); + btn1.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + btn1.SetPosition(0, -80); } } - GuiText timerTxt( ( char* ) NULL, 26, THEME.prompttext ); - timerTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - timerTxt.SetPosition( 0, 160 ); + GuiText timerTxt((char*) NULL, 26, THEME.prompttext); + timerTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + timerTxt.SetPosition(0, 160); - promptWindow.Append( &dialogBoxImg ); - promptWindow.Append( &titleTxt ); - promptWindow.Append( &msgTxt ); + promptWindow.Append(&dialogBoxImg); + promptWindow.Append(&titleTxt); + promptWindow.Append(&msgTxt); - if ( btn1Label ) - promptWindow.Append( &btn1 ); - if ( btn2Label ) - promptWindow.Append( &btn2 ); - if ( IsDeviceWait ) - promptWindow.Append( &timerTxt ); + if (btn1Label) promptWindow.Append(&btn1); + if (btn2Label) promptWindow.Append(&btn2); + if (IsDeviceWait) promptWindow.Append(&timerTxt); - 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 ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); - if ( IsDeviceWait ) + if (IsDeviceWait) { - while ( i >= 0 ) + while (i >= 0) { VIDEO_WaitVSync(); - timerTxt.SetTextf( "%u %s", i, tr( "seconds left" ) ); + timerTxt.SetTextf("%u %s", i, tr( "seconds left" )); /* HaltGui(); if (Settings.cios == ios222) { - ret = IOS_ReloadIOS(222); - load_ehc_module(); + ret = IOS_ReloadIOS(222); + load_ehc_module(); } else { - ret = IOS_ReloadIOS(249); + ret = IOS_ReloadIOS(249); } ResumeGui();*/ - sleep( 1 ); + sleep(1); USBDevice_deInit(); USBDevice_Init(); - ret = WBFS_Init( WBFS_DEVICE_USB ); - if ( ret >= 0 ) - break; - + ret = WBFS_Init(WBFS_DEVICE_USB); + if (ret >= 0) break; i--; } } else { - while ( !( cover & 0x2 ) ) + while (!(cover & 0x2)) { VIDEO_WaitVSync(); - if ( btn1.GetState() == STATE_CLICKED ) + if (btn1.GetState() == STATE_CLICKED) { btn1.ResetState(); break; } - ret = WDVD_GetCoverStatus( &cover ); - if ( ret < 0 ) - break; + ret = WDVD_GetCoverStatus(&cover); + if (ret < 0) break; } } - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - while ( promptWindow.GetEffect() > 0 ) usleep( 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + while (promptWindow.GetEffect() > 0) + usleep(50); HaltGui(); - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); return ret; } @@ -1969,108 +1963,104 @@ DiscWait( const char *title, const char *msg, const char *btn1Label, const char /**************************************************************************** * FormatingPartition ***************************************************************************/ -int -FormatingPartition( const char *title, partitionEntry *entry ) +int FormatingPartition(const char *title, partitionEntry *entry) { int ret; - GuiWindow promptWindow( 472, 320 ); - promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - promptWindow.SetPosition( 0, -10 ); + GuiWindow promptWindow(472, 320); + promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + promptWindow.SetPosition(0, -10); char imgPath[100]; - snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", Settings.theme_path ); - GuiImageData dialogBox( imgPath, dialogue_box_png ); - + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", Settings.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiImage dialogBoxImg( &dialogBox ); - if ( Settings.wsprompt == yes ) + GuiImage dialogBoxImg(&dialogBox); + if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen( Settings.widescreen ); + dialogBoxImg.SetWidescreen(Settings.widescreen); } - GuiText titleTxt( title, 26, THEME.prompttext ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( 0, 60 ); + GuiText titleTxt(title, 26, THEME.prompttext); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0, 60); - promptWindow.Append( &dialogBoxImg ); - promptWindow.Append( &titleTxt ); + promptWindow.Append(&dialogBoxImg); + promptWindow.Append(&titleTxt); - - 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 ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); VIDEO_WaitVSync(); - ret = WBFS_Format( entry->sector, entry->size ); + ret = WBFS_Format(entry->sector, entry->size); - - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - while ( promptWindow.GetEffect() > 0 ) usleep( 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + while (promptWindow.GetEffect() > 0) + usleep(50); HaltGui(); - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); return ret; } - /**************************************************************************** * SearchMissingImages ***************************************************************************/ -bool SearchMissingImages( int choice2 ) +bool SearchMissingImages(int choice2) { - gprintf( "\nSearchMissingImages(%i)", choice2 ); - GuiWindow promptWindow( 472, 320 ); - promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - promptWindow.SetPosition( 0, -10 ); + 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 ); + 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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", Settings.theme_path ); - GuiImageData dialogBox( imgPath, dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", Settings.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiImage dialogBoxImg( &dialogBox ); + GuiImage dialogBoxImg(&dialogBox); - if ( Settings.wsprompt == yes ) + if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen( Settings.widescreen ); + dialogBoxImg.SetWidescreen(Settings.widescreen); } - GuiText titleTxt( tr( "Checking existing artwork" ), 26, THEME.prompttext ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( 0, 60 ); + GuiText titleTxt(tr( "Checking existing artwork" ), 26, THEME.prompttext); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0, 60); char msg[20] = " "; - GuiText msgTxt( msg, 22, THEME.prompttext ); - msgTxt.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - msgTxt.SetPosition( 0, -40 ); + GuiText msgTxt(msg, 22, THEME.prompttext); + msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + msgTxt.SetPosition(0, -40); - promptWindow.Append( &dialogBoxImg ); - promptWindow.Append( &titleTxt ); - promptWindow.Append( &msgTxt ); + promptWindow.Append(&dialogBoxImg); + promptWindow.Append(&titleTxt); + promptWindow.Append(&msgTxt); - 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 ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); //make sure that all games are added to the gamelist @@ -2084,65 +2074,67 @@ bool SearchMissingImages( int choice2 ) bool found1 = false; bool found2 = false; bool found3 = false; - for ( i = 0; i < gameList.size() && cntMissFiles < 500; i++ ) + for (i = 0; i < gameList.size() && cntMissFiles < 500; i++) { struct discHdr* header = gameList[i]; - if ( choice2 != 3 ) + if (choice2 != 3) { 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(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 ); + snprintf(missingFiles[cntMissFiles], 11, "%s", filename); cntMissFiles++; } } - else if ( choice2 == 3 ) + 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(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 ); + snprintf(missingFiles[cntMissFiles], 11, "%s", filename); cntMissFiles++; } } } - if ( cntMissFiles == 0 ) + if (cntMissFiles == 0) { - msgTxt.SetText( tr( "No file missing!" ) ); - sleep( 1 ); + msgTxt.SetText(tr( "No file missing!" )); + sleep(1); } - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - while ( promptWindow.GetEffect() > 0 ) usleep( 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + while (promptWindow.GetEffect() > 0) + usleep(50); HaltGui(); - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); gameList.FilterList(); ResumeGui(); - gprintf( " = %i", cntMissFiles ); - if ( cntMissFiles > 0 ) //&& !IsNetworkInit()) { + gprintf(" = %i", cntMissFiles); + if (cntMissFiles > 0) //&& !IsNetworkInit()) { { NetworkInitPrompt(); } - if ( cntMissFiles == 0 ) + if (cntMissFiles == 0) { return false; } @@ -2157,90 +2149,89 @@ bool SearchMissingImages( int choice2 ) bool NetworkInitPrompt() { - gprintf( "\nNetworkinitPrompt()" ); - if ( IsNetworkInit() ) - return true; + gprintf("\nNetworkinitPrompt()"); + if (IsNetworkInit()) return true; bool success = true; - GuiWindow promptWindow( 472, 320 ); - promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - promptWindow.SetPosition( 0, -10 ); + 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 ); + 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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", Settings.theme_path ); - GuiImageData dialogBox( imgPath, dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", Settings.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiImage dialogBoxImg( &dialogBox ); + GuiImage dialogBoxImg(&dialogBox); - if ( Settings.wsprompt == yes ) + if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen( Settings.widescreen ); + dialogBoxImg.SetWidescreen(Settings.widescreen); } - GuiText titleTxt( tr( "Initializing Network" ), 26, THEME.prompttext ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( 0, 60 ); + GuiText titleTxt(tr( "Initializing Network" ), 26, THEME.prompttext); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0, 60); char msg[20] = " "; - GuiText msgTxt( msg, 22, THEME.prompttext ); - msgTxt.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - msgTxt.SetPosition( 0, -40 ); + GuiText msgTxt(msg, 22, THEME.prompttext); + msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + msgTxt.SetPosition(0, -40); - GuiText btn1Txt( tr( "Cancel" ), 22, THEME.prompttext ); - GuiImage btn1Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn1Txt(tr( "Cancel" ), 22, THEME.prompttext); + GuiImage btn1Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn1Txt.SetWidescreen( Settings.widescreen ); - btn1Img.SetWidescreen( Settings.widescreen ); + btn1Txt.SetWidescreen(Settings.widescreen); + btn1Img.SetWidescreen(Settings.widescreen); } - GuiButton btn1( &btn1Img, &btn1Img, 2, 4, 0, -45, &trigA, &btnSoundOver, btnClick2, 1 ); - btn1.SetLabel( &btn1Txt ); - btn1.SetState( STATE_SELECTED ); + GuiButton btn1(&btn1Img, &btn1Img, 2, 4, 0, -45, &trigA, &btnSoundOver, btnClick2, 1); + btn1.SetLabel(&btn1Txt); + btn1.SetState(STATE_SELECTED); - if ( ( Settings.wsprompt == yes ) && ( Settings.widescreen ) ) /////////////adjust buttons for widescreen + if ((Settings.wsprompt == yes) && (Settings.widescreen)) /////////////adjust buttons for widescreen { - btn1.SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); - btn1.SetPosition( 0, -80 ); + btn1.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); + btn1.SetPosition(0, -80); } - promptWindow.Append( &dialogBoxImg ); - promptWindow.Append( &titleTxt ); - promptWindow.Append( &msgTxt ); - promptWindow.Append( &btn1 ); + promptWindow.Append(&dialogBoxImg); + promptWindow.Append(&titleTxt); + promptWindow.Append(&msgTxt); + promptWindow.Append(&btn1); - 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 ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); - while ( !IsNetworkInit() ) + while (!IsNetworkInit()) { VIDEO_WaitVSync(); Initialize_Network(); - if ( !IsNetworkInit() ) + if (!IsNetworkInit()) { - msgTxt.SetText( tr( "Could not initialize network!" ) ); - sleep( 3 ); + msgTxt.SetText(tr( "Could not initialize network!" )); + sleep(3); success = false; break; } - if ( btn1.GetState() == STATE_CLICKED ) + if (btn1.GetState() == STATE_CLICKED) { btn1.ResetState(); success = false; @@ -2248,12 +2239,13 @@ bool NetworkInitPrompt() } } - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - while ( promptWindow.GetEffect() > 0 ) usleep( 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + while (promptWindow.GetEffect() > 0) + usleep(50); HaltGui(); - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); return success; @@ -2266,108 +2258,107 @@ bool NetworkInitPrompt() * progress bar showing % completion, or a throbber that only shows that an * action is in progress. ***************************************************************************/ -int -ProgressDownloadWindow( int choice2 ) +int ProgressDownloadWindow(int choice2) { int i = 0, cntNotFound = 0; - GuiWindow promptWindow( 472, 320 ); - promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - promptWindow.SetPosition( 0, -10 ); + 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 ); + 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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", Settings.theme_path ); - GuiImageData dialogBox( imgPath, dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", Settings.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiImage dialogBoxImg( &dialogBox ); - if ( Settings.wsprompt == yes ) + GuiImage dialogBoxImg(&dialogBox); + if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen( Settings.widescreen ); + dialogBoxImg.SetWidescreen(Settings.widescreen); } - snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_outline.png", Settings.theme_path ); - GuiImageData progressbarOutline( imgPath, progressbar_outline_png ); - GuiImage progressbarOutlineImg( &progressbarOutline ); - if ( Settings.wsprompt == yes ) + snprintf(imgPath, sizeof(imgPath), "%sprogressbar_outline.png", Settings.theme_path); + GuiImageData progressbarOutline(imgPath, progressbar_outline_png); + GuiImage progressbarOutlineImg(&progressbarOutline); + if (Settings.wsprompt == yes) { - progressbarOutlineImg.SetWidescreen( Settings.widescreen ); + progressbarOutlineImg.SetWidescreen(Settings.widescreen); } - progressbarOutlineImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - progressbarOutlineImg.SetPosition( 25, 40 ); + progressbarOutlineImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + progressbarOutlineImg.SetPosition(25, 40); - snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_empty.png", Settings.theme_path ); - GuiImageData progressbarEmpty( imgPath, progressbar_empty_png ); - GuiImage progressbarEmptyImg( &progressbarEmpty ); - progressbarEmptyImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - progressbarEmptyImg.SetPosition( 25, 40 ); - progressbarEmptyImg.SetTile( 100 ); + snprintf(imgPath, sizeof(imgPath), "%sprogressbar_empty.png", Settings.theme_path); + GuiImageData progressbarEmpty(imgPath, progressbar_empty_png); + GuiImage progressbarEmptyImg(&progressbarEmpty); + progressbarEmptyImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + progressbarEmptyImg.SetPosition(25, 40); + progressbarEmptyImg.SetTile(100); - snprintf( imgPath, sizeof( imgPath ), "%sprogressbar.png", Settings.theme_path ); - GuiImageData progressbar( imgPath, progressbar_png ); - GuiImage progressbarImg( &progressbar ); - progressbarImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - progressbarImg.SetPosition( 25, 40 ); + snprintf(imgPath, sizeof(imgPath), "%sprogressbar.png", Settings.theme_path); + GuiImageData progressbar(imgPath, progressbar_png); + GuiImage progressbarImg(&progressbar); + progressbarImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + progressbarImg.SetPosition(25, 40); - GuiText titleTxt( tr( "Downloading file" ), 26, THEME.prompttext ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( 0, 60 ); + GuiText titleTxt(tr( "Downloading file" ), 26, THEME.prompttext); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0, 60); - GuiText msgTxt( ( char* ) NULL, 20, THEME.prompttext ); - msgTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - msgTxt.SetPosition( 0, 130 ); + GuiText msgTxt((char*) NULL, 20, THEME.prompttext); + msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + msgTxt.SetPosition(0, 130); - GuiText msg2Txt( ( char* ) NULL, 26, THEME.prompttext ); - msg2Txt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - msg2Txt.SetPosition( 0, 100 ); + GuiText msg2Txt((char*) NULL, 26, THEME.prompttext); + msg2Txt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + msg2Txt.SetPosition(0, 100); - GuiText prTxt( ( char* ) NULL, 26, THEME.prompttext ); - prTxt.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - prTxt.SetPosition( 0, 40 ); + GuiText prTxt((char*) NULL, 26, THEME.prompttext); + prTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + prTxt.SetPosition(0, 40); - GuiText btn1Txt( tr( "Cancel" ), 22, THEME.prompttext ); - GuiImage btn1Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn1Txt(tr( "Cancel" ), 22, THEME.prompttext); + GuiImage btn1Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn1Txt.SetWidescreen( Settings.widescreen ); - btn1Img.SetWidescreen( Settings.widescreen ); + btn1Txt.SetWidescreen(Settings.widescreen); + btn1Img.SetWidescreen(Settings.widescreen); } - GuiButton btn1( &btn1Img, &btn1Img, 2, 4, 0, -45, &trigA, &btnSoundOver, btnClick2, 1 ); - btn1.SetLabel( &btn1Txt ); - btn1.SetState( STATE_SELECTED ); + GuiButton btn1(&btn1Img, &btn1Img, 2, 4, 0, -45, &trigA, &btnSoundOver, btnClick2, 1); + btn1.SetLabel(&btn1Txt); + btn1.SetState(STATE_SELECTED); - if ( ( Settings.wsprompt == yes ) && ( Settings.widescreen ) ) /////////////adjust for widescreen + if ((Settings.wsprompt == yes) && (Settings.widescreen)) /////////////adjust for widescreen { - progressbarOutlineImg.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - progressbarOutlineImg.SetPosition( 0, 40 ); - progressbarEmptyImg.SetPosition( 80, 40 ); - progressbarEmptyImg.SetTile( 78 ); - progressbarImg.SetPosition( 80, 40 ); + progressbarOutlineImg.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + progressbarOutlineImg.SetPosition(0, 40); + progressbarEmptyImg.SetPosition(80, 40); + progressbarEmptyImg.SetTile(78); + progressbarImg.SetPosition(80, 40); } - promptWindow.Append( &dialogBoxImg ); - promptWindow.Append( &titleTxt ); - promptWindow.Append( &msgTxt ); - promptWindow.Append( &msg2Txt ); - promptWindow.Append( &progressbarEmptyImg ); - promptWindow.Append( &progressbarImg ); - promptWindow.Append( &progressbarOutlineImg ); - promptWindow.Append( &prTxt ); - promptWindow.Append( &btn1 ); + promptWindow.Append(&dialogBoxImg); + promptWindow.Append(&titleTxt); + promptWindow.Append(&msgTxt); + promptWindow.Append(&msg2Txt); + promptWindow.Append(&progressbarEmptyImg); + promptWindow.Append(&progressbarImg); + promptWindow.Append(&progressbarOutlineImg); + promptWindow.Append(&prTxt); + promptWindow.Append(&btn1); HaltGui(); - mainWindow->SetState( STATE_DISABLED ); - mainWindow->Append( &promptWindow ); - mainWindow->ChangeFocus( &promptWindow ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); int offset = 0, tries = 0; @@ -2378,82 +2369,82 @@ ProgressDownloadWindow( int choice2 ) char serverDiscCustom[100]; char server2d[100]; - snprintf( server3d, sizeof( server3d ), "http://wiitdb.com/wiitdb/artwork/cover3D/" ); - snprintf( serverDisc, sizeof( serverDisc ), "http://wiitdb.com/wiitdb/artwork/disc/" ); - snprintf( serverDiscCustom, sizeof( serverDiscCustom ), "http://wiitdb.com/wiitdb/artwork/disccustom/" ); - snprintf( server2d, sizeof( server2d ), "http://wiitdb.com/wiitdb/artwork/cover/" ); + snprintf(server3d, sizeof(server3d), "http://wiitdb.com/wiitdb/artwork/cover3D/"); + snprintf(serverDisc, sizeof(serverDisc), "http://wiitdb.com/wiitdb/artwork/disc/"); + snprintf(serverDiscCustom, sizeof(serverDiscCustom), "http://wiitdb.com/wiitdb/artwork/disccustom/"); + snprintf(server2d, sizeof(server2d), "http://wiitdb.com/wiitdb/artwork/cover/"); //check if directory exist and if not create one struct stat st; - if ( stat( Settings.covers_path, &st ) != 0 ) + if (stat(Settings.covers_path, &st) != 0) { - if ( subfoldercreate( Settings.covers_path ) != 1 ) + if (subfoldercreate(Settings.covers_path) != 1) { - WindowPrompt( tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" ) ); + WindowPrompt(tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" )); cntMissFiles = 0; } } - if ( stat( Settings.covers2d_path, &st ) != 0 ) + if (stat(Settings.covers2d_path, &st) != 0) { - if ( subfoldercreate( Settings.covers2d_path ) != 1 ) + if (subfoldercreate(Settings.covers2d_path) != 1) { - WindowPrompt( tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" ) ); + WindowPrompt(tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" )); cntMissFiles = 0; } } - if ( stat( Settings.disc_path, &st ) != 0 ) + if (stat(Settings.disc_path, &st) != 0) { - if ( subfoldercreate( Settings.disc_path ) != 1 ) + if (subfoldercreate(Settings.disc_path) != 1) { - WindowPrompt( tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" ) ); + WindowPrompt(tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" )); cntMissFiles = 0; } } //int server = 1; - while ( i < cntMissFiles ) + while (i < cntMissFiles) { tries = 0; - prTxt.SetTextf( "%i%%", 100*i / cntMissFiles ); + prTxt.SetTextf("%i%%", 100 * i / cntMissFiles); - if ( ( Settings.wsprompt == yes ) && ( Settings.widescreen ) ) + if ((Settings.wsprompt == yes) && (Settings.widescreen)) { //adjust for widescreen - progressbarImg.SetPosition( 80, 40 ); - progressbarImg.SetTile( 80*i / cntMissFiles ); + progressbarImg.SetPosition(80, 40); + progressbarImg.SetTile(80 * i / cntMissFiles); } else { - progressbarImg.SetTile( 100*i / cntMissFiles ); + progressbarImg.SetTile(100 * i / cntMissFiles); } - if ( cntMissFiles - i > 1 )msgTxt.SetTextf( "%i %s", cntMissFiles - i, tr( "files left" ) ); - else msgTxt.SetTextf( "%i %s", cntMissFiles - i, tr( "file left" ) ); - msg2Txt.SetTextf( "http://wiitdb.com : %s", missingFiles[i] ); - + if (cntMissFiles - i > 1) + msgTxt.SetTextf("%i %s", cntMissFiles - i, tr( "files left" )); + else msgTxt.SetTextf("%i %s", cntMissFiles - i, tr( "file left" )); + msg2Txt.SetTextf("http://wiitdb.com : %s", missingFiles[i]); //download cover char imgPath[100]; char URLFile[100]; char tmp[75]; - sprintf( tmp, tr( "Not Found" ) ); - struct block file = downloadfile( URLFile ); - if ( choice2 == 2 ) + sprintf(tmp, tr( "Not Found" )); + struct block file = downloadfile(URLFile); + if (choice2 == 2) { - while ( tries < serverCnt3d ) + while (tries < serverCnt3d) { //Creates URL depending from which Country the game is - switch ( missingFiles[i][3] ) + 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] ); + sprintf(URLFile, "%sZH/%s", server3d, missingFiles[i]); break; case 'K': - sprintf( URLFile, "%sKO/%s", server3d, missingFiles[i] ); + sprintf(URLFile, "%sKO/%s", server3d, missingFiles[i]); break; case 'P': case 'D': @@ -2465,25 +2456,27 @@ ProgressDownloadWindow( int choice2 ) case 'X': case 'Y': case 'Z': - sprintf( URLFile, "%s%s/%s", server3d, Settings.db_language, missingFiles[i] ); + sprintf(URLFile, "%s%s/%s", server3d, Settings.db_language, missingFiles[i]); break; case 'E': - sprintf( URLFile, "%sUS/%s", server3d, missingFiles[i] ); + sprintf(URLFile, "%sUS/%s", server3d, missingFiles[i]); break; } - sprintf( imgPath, "%s%s", Settings.covers_path, missingFiles[i] ); - file = downloadfile( URLFile ); + sprintf(imgPath, "%s%s", Settings.covers_path, missingFiles[i]); + file = downloadfile(URLFile); - if ( !( file.size == 36864 || file.size <= 1024 || file.size == 7386 || file.size <= 1174 || file.size == 4446 || file.data == NULL ) ) + if (!(file.size == 36864 || file.size <= 1024 || file.size == 7386 || file.size <= 1174 || file.size + == 4446 || file.data == NULL)) { break; } else { - sprintf( URLFile, "%sEN/%s", server3d, missingFiles[i] ); - file = downloadfile( URLFile ); - if ( !( file.size == 36864 || file.size <= 1024 || file.size == 7386 || file.size <= 1174 || file.size == 4446 || file.data == NULL ) ) + sprintf(URLFile, "%sEN/%s", server3d, missingFiles[i]); + file = downloadfile(URLFile); + if (!(file.size == 36864 || file.size <= 1024 || file.size == 7386 || file.size <= 1174 + || file.size == 4446 || file.data == NULL)) { break; } @@ -2492,90 +2485,90 @@ ProgressDownloadWindow( int choice2 ) } } - if ( choice2 == 3 ) + if (choice2 == 3) { - while ( tries < serverCntDisc ) + while (tries < serverCntDisc) { //Creates URL depending from which Country the game is - switch ( missingFiles[i][3] ) + switch (missingFiles[i][3]) { case 'J': - if ( Settings.discart == 0 ) + if (Settings.discart == 0) { - sprintf( URLFile, "%sJA/%s", serverDisc, missingFiles[i] ); + sprintf(URLFile, "%sJA/%s", serverDisc, missingFiles[i]); } - else if ( Settings.discart == 1 ) + else if (Settings.discart == 1) { - sprintf( URLFile, "%sJA/%s", serverDiscCustom, missingFiles[i] ); + 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] ); + 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] ); + 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] ); + 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] ); + 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] ); + sprintf(URLFile, "%sZH/%s", serverDisc, missingFiles[i]); } - else if ( Settings.discart == 1 ) + else if (Settings.discart == 1) { - sprintf( URLFile, "%sZH/%s", serverDiscCustom, missingFiles[i] ); + 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] ); + 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] ); + 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] ); + 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] ); + 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] ); + sprintf(URLFile, "%sKO/%s", serverDisc, missingFiles[i]); } - else if ( Settings.discart == 1 ) + else if (Settings.discart == 1) { - sprintf( URLFile, "%sKO/%s", serverDiscCustom, missingFiles[i] ); + 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] ); + 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] ); + 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] ); + 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] ); + sprintf(URLFile, "%sKO/%s", serverDisc, missingFiles[i]); } break; case 'P': @@ -2588,93 +2581,95 @@ 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] ); + 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] ); + 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] ); + 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] ); + 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] ); + 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] ); + 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] ); + sprintf(URLFile, "%sUS/%s", serverDisc, missingFiles[i]); } - else if ( Settings.discart == 1 ) + else if (Settings.discart == 1) { - sprintf( URLFile, "%sUS/%s", serverDiscCustom, missingFiles[i] ); + 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] ); + 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] ); + 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] ); + 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] ); + sprintf(URLFile, "%sUS/%s", serverDisc, missingFiles[i]); } break; } - sprintf( imgPath, "%s%s", Settings.disc_path, missingFiles[i] ); - file = downloadfile( URLFile ); - if ( !( file.size == 36864 || file.size <= 1024 || file.size == 7386 || file.size <= 1174 || file.size == 4446 || file.data == NULL ) ) + sprintf(imgPath, "%s%s", Settings.disc_path, missingFiles[i]); + file = downloadfile(URLFile); + 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] ); + sprintf(URLFile, "%sEN/%s", serverDisc, missingFiles[i]); } - else if ( Settings.discart == 1 ) + else if (Settings.discart == 1) { - sprintf( URLFile, "%sEN/%s", serverDiscCustom, missingFiles[i] ); + 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] ); + 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] ); + 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] ); + 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] ); + sprintf(URLFile, "%sEN/%s", serverDisc, missingFiles[i]); } - file = downloadfile( URLFile ); - if ( !( file.size == 36864 || file.size <= 1024 || file.size == 7386 || file.size <= 1174 || file.size == 4446 || file.data == NULL ) ) + file = downloadfile(URLFile); + if (!(file.size == 36864 || file.size <= 1024 || file.size == 7386 || file.size <= 1174 + || file.size == 4446 || file.data == NULL)) { break; } @@ -2682,22 +2677,22 @@ ProgressDownloadWindow( int choice2 ) tries++; } } - if ( choice2 == 1 ) + if (choice2 == 1) { - while ( tries < serverCnt2d ) + while (tries < serverCnt2d) { //Creates URL depending from which Country the game is - switch ( missingFiles[i][3] ) + 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] ); + sprintf(URLFile, "%sZH/%s", server2d, missingFiles[i]); break; case 'K': - sprintf( URLFile, "%sKO/%s", server2d, missingFiles[i] ); + sprintf(URLFile, "%sKO/%s", server2d, missingFiles[i]); break; case 'P': case 'D': @@ -2709,25 +2704,27 @@ ProgressDownloadWindow( int choice2 ) case 'X': case 'Y': case 'Z': - sprintf( URLFile, "%s%s/%s", server2d, Settings.db_language, missingFiles[i] ); + sprintf(URLFile, "%s%s/%s", server2d, Settings.db_language, missingFiles[i]); break; case 'E': - sprintf( URLFile, "%sUS/%s", server2d, missingFiles[i] ); + sprintf(URLFile, "%sUS/%s", server2d, missingFiles[i]); break; } - sprintf( imgPath, "%s%s", Settings.covers2d_path, missingFiles[i] ); - file = downloadfile( URLFile ); + sprintf(imgPath, "%s%s", Settings.covers2d_path, missingFiles[i]); + file = downloadfile(URLFile); - if ( !( file.size == 36864 || file.size <= 1024 || file.size == 7386 || file.size <= 1174 || file.size == 4446 || file.data == NULL ) ) + if (!(file.size == 36864 || file.size <= 1024 || file.size == 7386 || file.size <= 1174 || file.size + == 4446 || file.data == NULL)) { break; } else { - sprintf( URLFile, "%sEN/%s", server2d, missingFiles[i] ); - file = downloadfile( URLFile ); - if ( !( file.size == 36864 || file.size <= 1024 || file.size == 7386 || file.size <= 1174 || file.size == 4446 || file.data == NULL ) ) + sprintf(URLFile, "%sEN/%s", server2d, missingFiles[i]); + file = downloadfile(URLFile); + if (!(file.size == 36864 || file.size <= 1024 || file.size == 7386 || file.size <= 1174 + || file.size == 4446 || file.data == NULL)) { break; } @@ -2736,32 +2733,32 @@ ProgressDownloadWindow( int choice2 ) } } - offset++; - if ( file.size == 36864 || file.size <= 1024 || file.size <= 1174 || file.size == 7386 || file.size == 4446 || file.data == NULL ) + if (file.size == 36864 || file.size <= 1024 || file.size <= 1174 || file.size == 7386 || file.size == 4446 + || file.data == NULL) { cntNotFound++; i++; } else { - if ( file.data != NULL ) + if (file.data != NULL) { // save png to sd card FILE *pfile = NULL; - if ( ( pfile = fopen( imgPath, "wb" ) ) != NULL ) + if ((pfile = fopen(imgPath, "wb")) != NULL) { - fwrite( file.data, 1, file.size, pfile ); - fclose ( pfile ); + fwrite(file.data, 1, file.size, pfile); + fclose(pfile); } - free( file.data ); + free(file.data); } i++; } - if ( btn1.GetState() == STATE_CLICKED ) + if (btn1.GetState() == STATE_CLICKED) { cntNotFound = cntMissFiles - i + cntNotFound; break; @@ -2823,11 +2820,11 @@ ProgressDownloadWindow( int choice2 ) } #endif HaltGui(); - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); - if ( cntNotFound != 0 ) + if (cntNotFound != 0) { return cntNotFound; } @@ -2846,28 +2843,28 @@ ProgressDownloadWindow( int choice2 ) ***************************************************************************/ #define BLOCKSIZE 1024 /*bool unzipArchive(char * zipfilepath, char * unzipfolderpath) -{ - unzFile uf = unzOpen(zipfilepath); - if (uf==NULL) - { - // printf("Cannot open %s, aborting\n",zipfilepath); - return false; - } - //printf("%s opened\n",zipfilepath); - if(chdir(unzipfolderpath)) // can't access dir - { - makedir(unzipfolderpath); // attempt to make dir - if(chdir(unzipfolderpath)) // still can't access dir - { - //printf("Error changing into %s, aborting\n", unzipfolderpath); - return false; - } - } - extractZip(uf,0,1,0); - unzCloseCurrentFile(uf); - return true -} -*/ + { + unzFile uf = unzOpen(zipfilepath); + if (uf==NULL) + { + // printf("Cannot open %s, aborting\n",zipfilepath); + return false; + } + //printf("%s opened\n",zipfilepath); + if(chdir(unzipfolderpath)) // can't access dir + { + makedir(unzipfolderpath); // attempt to make dir + if(chdir(unzipfolderpath)) // still can't access dir + { + //printf("Error changing into %s, aborting\n", unzipfolderpath); + return false; + } + } + extractZip(uf,0,1,0); + unzCloseCurrentFile(uf); + return true + } + */ #ifdef FULLCHANNEL ///////////////////this is only used if the dol is being compiled for a full channel int ProgressUpdateWindow() @@ -2951,7 +2948,8 @@ int ProgressUpdateWindow() btn1.SetLabel( &btn1Txt ); btn1.SetState( STATE_SELECTED ); - if ( ( Settings.wsprompt == yes ) && ( Settings.widescreen ) ) /////////////adjust for widescreen + if ( ( Settings.wsprompt == yes ) && ( Settings.widescreen ) ) /////////////adjust for widescreen + { progressbarOutlineImg.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); progressbarOutlineImg.SetPosition( 0, 7 ); @@ -3000,7 +2998,7 @@ int ProgressUpdateWindow() 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 + // char dolpathsuccess[150];//use coverspath as a folder for the update wad so we dont make a new folder and have to delete it snprintf( dolpath, sizeof( dolpath ), "%sULNR.wad", Settings.covers_path ); //snprintf(dolpathsuccess, sizeof(dolpathsuccess), "%sUNEO.wad", Settings.covers_path); Initialize_Network(); @@ -3058,7 +3056,8 @@ int ProgressUpdateWindow() 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 + 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 ); } @@ -3121,7 +3120,7 @@ int ProgressUpdateWindow() u32 blksize; blksize = ( u32 )( filesize - i ); if ( blksize > BLOCKSIZE ) - blksize = BLOCKSIZE; + blksize = BLOCKSIZE; ret = network_read( blockbuffer, blksize ); if ( ret != ( s32 ) blksize ) @@ -3176,7 +3175,8 @@ int ProgressUpdateWindow() int diarhea = 0; char nipple[100]; wadFile = fopen ( dolpath , "rb" ); - if ( wadFile == NULL ) //we can't open the file wad we just downloaded + if ( wadFile == NULL ) //we can't open the file wad we just downloaded + { sprintf( nipple, tr( "Unable to open the wad that was just downloaded (%s)." ), dolpath ); WindowPrompt( tr( "Error !" ), nipple, tr( "OK" ) ); @@ -3193,7 +3193,7 @@ int ProgressUpdateWindow() { diarhea = remove( dolpath ); if ( diarhea ) - WindowPrompt( tr( "Success" ), tr( "The wad file was installed. But It could not be deleted from the SD card." ), tr( "OK" ) ); + WindowPrompt( tr( "Success" ), tr( "The wad file was installed. But It could not be deleted from the SD card." ), tr( "OK" ) ); } else { @@ -3204,10 +3204,10 @@ int ProgressUpdateWindow() } if ( error ) - WindowPrompt( tr( "ERROR" ) , tr( "An Error occured" ), tr( "OK" ) ); + WindowPrompt( tr( "ERROR" ) , tr( "An Error occured" ), tr( "OK" ) ); else { - WindowPrompt( tr( "Restarting..." ), tr( "Successfully Updated thanks to www.techjawa.com" ) , 0, 0, 0, 0, 150 ); + WindowPrompt( tr( "Restarting..." ), tr( "Successfully Updated thanks to www.techjawa.com" ) , 0, 0, 0, 0, 150 ); } CloseXMLDatabase(); ExitGUIThreads(); @@ -3227,7 +3227,7 @@ int ProgressUpdateWindow() ResumeGui(); if ( failed != 0 ) - return failed; + return failed; return 1; } @@ -3235,114 +3235,114 @@ int ProgressUpdateWindow() int ProgressUpdateWindow() { - gprintf( "\nProgressUpdateWindow(not full channel)" ); + gprintf("\nProgressUpdateWindow(not full channel)"); int ret = 0, failed = 0, updatemode = -1; - GuiWindow promptWindow( 472, 320 ); - promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - promptWindow.SetPosition( 0, -10 ); + 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 ); + 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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", Settings.theme_path ); - GuiImageData dialogBox( imgPath, dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", Settings.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiImage dialogBoxImg( &dialogBox ); - if ( Settings.wsprompt == yes ) + GuiImage dialogBoxImg(&dialogBox); + if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen( Settings.widescreen ); + dialogBoxImg.SetWidescreen(Settings.widescreen); } - snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_outline.png", Settings.theme_path ); - GuiImageData progressbarOutline( imgPath, progressbar_outline_png ); - GuiImage progressbarOutlineImg( &progressbarOutline ); - if ( Settings.wsprompt == yes ) + snprintf(imgPath, sizeof(imgPath), "%sprogressbar_outline.png", Settings.theme_path); + GuiImageData progressbarOutline(imgPath, progressbar_outline_png); + GuiImage progressbarOutlineImg(&progressbarOutline); + if (Settings.wsprompt == yes) { - progressbarOutlineImg.SetWidescreen( Settings.widescreen ); + progressbarOutlineImg.SetWidescreen(Settings.widescreen); } - progressbarOutlineImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - progressbarOutlineImg.SetPosition( 25, 7 ); + progressbarOutlineImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + progressbarOutlineImg.SetPosition(25, 7); - snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_empty.png", Settings.theme_path ); - GuiImageData progressbarEmpty( imgPath, progressbar_empty_png ); - GuiImage progressbarEmptyImg( &progressbarEmpty ); - progressbarEmptyImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - progressbarEmptyImg.SetPosition( 25, 7 ); - progressbarEmptyImg.SetTile( 100 ); + snprintf(imgPath, sizeof(imgPath), "%sprogressbar_empty.png", Settings.theme_path); + GuiImageData progressbarEmpty(imgPath, progressbar_empty_png); + GuiImage progressbarEmptyImg(&progressbarEmpty); + progressbarEmptyImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + progressbarEmptyImg.SetPosition(25, 7); + progressbarEmptyImg.SetTile(100); - snprintf( imgPath, sizeof( imgPath ), "%sprogressbar.png", Settings.theme_path ); - GuiImageData progressbar( imgPath, progressbar_png ); - GuiImage progressbarImg( &progressbar ); - progressbarImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - progressbarImg.SetPosition( 25, 7 ); + snprintf(imgPath, sizeof(imgPath), "%sprogressbar.png", Settings.theme_path); + GuiImageData progressbar(imgPath, progressbar_png); + GuiImage progressbarImg(&progressbar); + progressbarImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + progressbarImg.SetPosition(25, 7); char title[50]; - sprintf( title, "%s", tr( "Checking for Updates" ) ); - GuiText titleTxt( title, 26, THEME.prompttext ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( 0, 50 ); + sprintf(title, "%s", tr( "Checking for Updates" )); + GuiText titleTxt(title, 26, THEME.prompttext); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0, 50); char msg[50]; - sprintf( msg, "%s", tr( "Initializing Network" ) ); - GuiText msgTxt( msg, 26, THEME.prompttext ); - msgTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - msgTxt.SetPosition( 0, 140 ); + sprintf(msg, "%s", tr( "Initializing Network" )); + GuiText msgTxt(msg, 26, THEME.prompttext); + msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + msgTxt.SetPosition(0, 140); char msg2[50] = " "; - GuiText msg2Txt( msg2, 26, THEME.prompttext ); - msg2Txt.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - msg2Txt.SetPosition( 0, 50 ); + GuiText msg2Txt(msg2, 26, THEME.prompttext); + msg2Txt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + msg2Txt.SetPosition(0, 50); - GuiText prTxt( ( char* ) NULL, 26, THEME.prompttext ); - prTxt.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - prTxt.SetPosition( 0, 7 ); + GuiText prTxt((char*) NULL, 26, THEME.prompttext); + prTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + prTxt.SetPosition(0, 7); - GuiText btn1Txt( tr( "Cancel" ), 22, THEME.prompttext ); - GuiImage btn1Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn1Txt(tr( "Cancel" ), 22, THEME.prompttext); + GuiImage btn1Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn1Txt.SetWidescreen( Settings.widescreen ); - btn1Img.SetWidescreen( Settings.widescreen ); + btn1Txt.SetWidescreen(Settings.widescreen); + btn1Img.SetWidescreen(Settings.widescreen); } - GuiButton btn1( &btn1Img, &btn1Img, 2, 4, 0, -40, &trigA, &btnSoundOver, btnClick2, 1 ); - btn1.SetLabel( &btn1Txt ); - btn1.SetState( STATE_SELECTED ); + GuiButton btn1(&btn1Img, &btn1Img, 2, 4, 0, -40, &trigA, &btnSoundOver, btnClick2, 1); + btn1.SetLabel(&btn1Txt); + btn1.SetState(STATE_SELECTED); - if ( ( Settings.wsprompt == yes ) && ( Settings.widescreen ) ) /////////////adjust for widescreen + if ((Settings.wsprompt == yes) && (Settings.widescreen)) /////////////adjust for widescreen { - progressbarOutlineImg.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - progressbarOutlineImg.SetPosition( 0, 7 ); - progressbarEmptyImg.SetPosition( 80, 7 ); - progressbarEmptyImg.SetTile( 78 ); - progressbarImg.SetPosition( 80, 7 ); + progressbarOutlineImg.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + progressbarOutlineImg.SetPosition(0, 7); + progressbarEmptyImg.SetPosition(80, 7); + progressbarEmptyImg.SetTile(78); + progressbarImg.SetPosition(80, 7); } - promptWindow.Append( &dialogBoxImg ); - promptWindow.Append( &titleTxt ); - promptWindow.Append( &msgTxt ); - promptWindow.Append( &msg2Txt ); - promptWindow.Append( &btn1 ); + promptWindow.Append(&dialogBoxImg); + promptWindow.Append(&titleTxt); + promptWindow.Append(&msgTxt); + promptWindow.Append(&msg2Txt); + promptWindow.Append(&btn1); - 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 ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); struct stat st; - if ( stat( Settings.update_path, &st ) != 0 ) + if (stat(Settings.update_path, &st) != 0) { - if ( subfoldercreate( Settings.update_path ) != 1 ) + if (subfoldercreate(Settings.update_path) != 1) { - WindowPrompt( tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" ) ); + WindowPrompt(tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" )); ret = -1; failed = -1; } @@ -3350,26 +3350,26 @@ int ProgressUpdateWindow() char dolpath[150]; char dolpathsuccess[150]; - snprintf( dolpath, sizeof( dolpath ), "%sbootnew.dol", Settings.update_path ); - snprintf( dolpathsuccess, sizeof( dolpathsuccess ), "%sboot.dol", Settings.update_path ); + snprintf(dolpath, sizeof(dolpath), "%sbootnew.dol", Settings.update_path); + snprintf(dolpathsuccess, sizeof(dolpathsuccess), "%sboot.dol", Settings.update_path); - while ( !IsNetworkInit() ) + while (!IsNetworkInit()) { VIDEO_WaitVSync(); Initialize_Network(); - if ( IsNetworkInit() ) + if (IsNetworkInit()) { - msgTxt.SetText( GetNetworkIP() ); + msgTxt.SetText(GetNetworkIP()); } else { - msgTxt.SetText( tr( "Could not initialize network!" ) ); + msgTxt.SetText(tr( "Could not initialize network!" )); } - if ( btn1.GetState() == STATE_CLICKED ) + if (btn1.GetState() == STATE_CLICKED) { ret = -1; failed = -1; @@ -3380,155 +3380,161 @@ int ProgressUpdateWindow() //make the URL to get XML based on our games char XMLurl[3540]; - build_XML_URL( XMLurl, sizeof( XMLurl ) ); + 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 ) + 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 ) + 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 ); + 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 ) + 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 ); + 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" ); + filesize = download_request("http://www.techjawa.com/usbloadergx/boot.dol"); } - if ( filesize > 0 ) + if (filesize > 0) { FILE * pfile; - pfile = fopen( dolpath, "wb" ); + pfile = fopen(dolpath, "wb"); u8 * blockbuffer = new unsigned char[BLOCKSIZE]; - for ( s32 i = 0; i < filesize; i += BLOCKSIZE ) + for (s32 i = 0; i < filesize; i += BLOCKSIZE) { - usleep( 100 ); - prTxt.SetTextf( "%i%%", ( 100*i / filesize ) + 1 ); - if ( ( Settings.wsprompt == yes ) && ( Settings.widescreen ) ) + usleep(100); + prTxt.SetTextf("%i%%", (100 * i / filesize) + 1); + if ((Settings.wsprompt == yes) && (Settings.widescreen)) { - progressbarImg.SetTile( 80*i / filesize ); + progressbarImg.SetTile(80 * i / filesize); } else { - progressbarImg.SetTile( 100*i / filesize ); + progressbarImg.SetTile(100 * i / filesize); } - msg2Txt.SetTextf( "%iKB/%iKB", i / 1024, filesize / 1024 ); + msg2Txt.SetTextf("%iKB/%iKB", i / 1024, filesize / 1024); - if ( btn1.GetState() == STATE_CLICKED ) + if (btn1.GetState() == STATE_CLICKED) { - fclose( pfile ); - remove( dolpath ); + fclose(pfile); + remove(dolpath); failed = -1; btn1.ResetState(); break; } u32 blksize; - blksize = ( u32 )( filesize - i ); - if ( blksize > BLOCKSIZE ) - blksize = BLOCKSIZE; + blksize = (u32) (filesize - i); + if (blksize > BLOCKSIZE) blksize = BLOCKSIZE; - ret = network_read( blockbuffer, blksize ); - if ( ret != ( s32 ) blksize ) + ret = network_read(blockbuffer, blksize); + if (ret != (s32) blksize) { failed = -1; ret = -1; - fclose( pfile ); - remove( dolpath ); + fclose(pfile); + remove(dolpath); break; } - fwrite( blockbuffer, 1, blksize, pfile ); + fwrite(blockbuffer, 1, blksize, pfile); } - fclose( pfile ); + fclose(pfile); delete blockbuffer; - if ( !failed ) + if (!failed) { //remove old - if ( checkfile( dolpathsuccess ) ) + if (checkfile(dolpathsuccess)) { - remove( dolpathsuccess ); + remove(dolpathsuccess); } //rename new to old - rename( dolpath, dolpathsuccess ); + rename(dolpath, dolpathsuccess); - if ( choice == 2 ) + 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 ) + 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 ); + 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 ) + 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 ); + 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" ) ); + msgTxt.SetTextf("%s", tr( "Updating WiiTDB.zip" )); char wiitdbpath[200]; char wiitdbpathtmp[200]; - file = downloadfile( XMLurl ); - if ( file.data != NULL ) + 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 ); + 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 + 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 ); + 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 + 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:" ) ); + msgTxt.SetTextf("%s", tr( "Updating Language Files:" )); updateLanguageFiles(); } } @@ -3545,45 +3551,48 @@ int ProgressUpdateWindow() } else { - WindowPrompt( tr( "No new updates." ), 0, tr( "OK" ) ); + 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" ) ); + msgTxt.SetTextf("%s", tr( "Updating WiiTDB.zip" )); char wiitdbpath[200]; char wiitdbpathtmp[200]; - struct block file = downloadfile( XMLurl ); - if ( file.data != NULL ) + 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 ); + 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 + 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 ); + 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 + 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..." ) ); + msgTxt.SetTextf("%s", tr( "Updating Language Files..." )); updateLanguageFiles(); ret = 1; } @@ -3595,131 +3604,129 @@ int ProgressUpdateWindow() CloseConnection(); - if ( !failed && ret >= 0 && updatemode == 1 ) + if (!failed && ret >= 0 && updatemode == 1) { - WindowPrompt( tr( "Restarting..." ), tr( "Successfully Updated thanks to www.techjawa.com" ) , 0, 0, 0, 0, 150 ); + WindowPrompt(tr( "Restarting..." ), tr( "Successfully Updated thanks to www.techjawa.com" ), 0, 0, 0, 0, 150); loadStub(); - Set_Stub_Split( 0x00010001, "UNEO" ); + 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" ) ); + WindowPrompt(tr( "Successfully Updated" ), 0, tr( "OK" )); } - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - while ( promptWindow.GetEffect() > 0 ) usleep( 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + while (promptWindow.GetEffect() > 0) + usleep(50); HaltGui(); - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); - if ( failed != 0 ) - return failed; + if (failed != 0) return failed; return 1; } #endif -int CodeDownload( const char *id ) +int CodeDownload(const char *id) { int ret = 0; - GuiWindow promptWindow( 472, 320 ); - promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - promptWindow.SetPosition( 0, -10 ); + 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 ); + 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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", Settings.theme_path ); - GuiImageData dialogBox( imgPath, dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", Settings.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiImage dialogBoxImg( &dialogBox ); - if ( Settings.wsprompt == yes ) + GuiImage dialogBoxImg(&dialogBox); + if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen( Settings.widescreen ); + dialogBoxImg.SetWidescreen(Settings.widescreen); } - - char title[50]; - sprintf( title, "%s", tr( "Code Download" ) ); - GuiText titleTxt( title, 26, THEME.prompttext ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( 0, 50 ); + sprintf(title, "%s", tr( "Code Download" )); + GuiText titleTxt(title, 26, THEME.prompttext); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0, 50); char msg[50]; - sprintf( msg, "%s", tr( "Initializing Network" ) ); - GuiText msgTxt( msg, 26, THEME.prompttext ); - msgTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - msgTxt.SetPosition( 0, 140 ); + sprintf(msg, "%s", tr( "Initializing Network" )); + GuiText msgTxt(msg, 26, THEME.prompttext); + msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + msgTxt.SetPosition(0, 140); char msg2[50] = " "; - GuiText msg2Txt( msg2, 26, THEME.prompttext ); - msg2Txt.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - msg2Txt.SetPosition( 0, 50 ); + GuiText msg2Txt(msg2, 26, THEME.prompttext); + msg2Txt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + msg2Txt.SetPosition(0, 50); - GuiText btn1Txt( tr( "Cancel" ), 22, THEME.prompttext ); - GuiImage btn1Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn1Txt(tr( "Cancel" ), 22, THEME.prompttext); + GuiImage btn1Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn1Txt.SetWidescreen( Settings.widescreen ); - btn1Img.SetWidescreen( Settings.widescreen ); + btn1Txt.SetWidescreen(Settings.widescreen); + btn1Img.SetWidescreen(Settings.widescreen); } - GuiButton btn1( &btn1Img, &btn1Img, 2, 4, 0, -40, &trigA, &btnSoundOver, btnClick2, 1 ); - btn1.SetLabel( &btn1Txt ); - btn1.SetState( STATE_SELECTED ); + GuiButton btn1(&btn1Img, &btn1Img, 2, 4, 0, -40, &trigA, &btnSoundOver, btnClick2, 1); + btn1.SetLabel(&btn1Txt); + btn1.SetState(STATE_SELECTED); - promptWindow.Append( &dialogBoxImg ); - promptWindow.Append( &titleTxt ); - promptWindow.Append( &msgTxt ); - promptWindow.Append( &msg2Txt ); - promptWindow.Append( &btn1 ); + promptWindow.Append(&dialogBoxImg); + promptWindow.Append(&titleTxt); + promptWindow.Append(&msgTxt); + promptWindow.Append(&msg2Txt); + promptWindow.Append(&btn1); - 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 ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); struct stat st; - if ( stat( Settings.TxtCheatcodespath, &st ) != 0 ) + if (stat(Settings.TxtCheatcodespath, &st) != 0) { - if ( subfoldercreate( Settings.TxtCheatcodespath ) != 1 ) + if (subfoldercreate(Settings.TxtCheatcodespath) != 1) { - WindowPrompt( tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" ) ); + WindowPrompt(tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" )); ret = -1; goto exit; } } - while ( !IsNetworkInit() ) + while (!IsNetworkInit()) { VIDEO_WaitVSync(); Initialize_Network(); - if ( IsNetworkInit() ) + if (IsNetworkInit()) { - msgTxt.SetText( GetNetworkIP() ); + msgTxt.SetText(GetNetworkIP()); } else { - msgTxt.SetText( tr( "Could not initialize network!" ) ); + msgTxt.SetText(tr( "Could not initialize network!" )); } - if ( btn1.GetState() == STATE_CLICKED ) + if (btn1.GetState() == STATE_CLICKED) { ret = -1; btn1.ResetState(); @@ -3727,56 +3734,58 @@ int CodeDownload( const char *id ) } } - if ( IsNetworkInit() && ret >= 0 ) + if (IsNetworkInit() && ret >= 0) { char txtpath[150]; - snprintf( txtpath, sizeof( txtpath ), "%s%s.txt", Settings.TxtCheatcodespath, id ); + snprintf(txtpath, sizeof(txtpath), "%s%s.txt", Settings.TxtCheatcodespath, id); char codeurl[150]; - snprintf( codeurl, sizeof( codeurl ), "http://geckocodes.org/codes/R/%s.txt", id ); + snprintf(codeurl, sizeof(codeurl), "http://geckocodes.org/codes/R/%s.txt", id); - struct block file = downloadfile( codeurl ); + struct block file = downloadfile(codeurl); - if ( file.size == 333 || file.size == 216 || file.size == 284 ) + if (file.size == 333 || file.size == 216 || file.size == 284) { - strcat( codeurl, tr( " is not on the server." ) ); + strcat(codeurl, tr( " is not on the server." )); - WindowPrompt( tr( "Error" ), codeurl, tr( "OK" ) ); + WindowPrompt(tr( "Error" ), codeurl, tr( "OK" )); ret = -1; goto exit; } - if ( file.data != NULL ) + if (file.data != NULL) { FILE * pfile; - pfile = fopen( txtpath, "wb" ); - fwrite( file.data, 1, file.size, pfile ); - fclose( pfile ); - free( file.data ); + pfile = fopen(txtpath, "wb"); + fwrite(file.data, 1, file.size, pfile); + fclose(pfile); + free(file.data); ret = 1; - strcat( txtpath, tr( " has been Saved. The text has not been verified. Some of the code may not work right with each other. If you experience trouble, open the text in a real text editor for more information." ) ); + strcat( + txtpath, + tr( " has been Saved. The text has not been verified. Some of the code may not work right with each other. If you experience trouble, open the text in a real text editor for more information." )); - WindowPrompt( 0, txtpath, tr( "OK" ) ); + WindowPrompt(0, txtpath, tr( "OK" )); } else { - strcat( codeurl, tr( " could not be downloaded." ) ); + strcat(codeurl, tr( " could not be downloaded." )); - WindowPrompt( tr( "Error" ), codeurl, tr( "OK" ) ); + WindowPrompt(tr( "Error" ), codeurl, tr( "OK" )); ret = -1; } CloseConnection(); } -exit: - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - while ( promptWindow.GetEffect() > 0 ) usleep( 50 ); + exit: promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + while (promptWindow.GetEffect() > 0) + usleep(50); HaltGui(); - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); return ret; @@ -3784,12 +3793,9 @@ exit: char * GetMissingFiles() { - return ( char * ) missingFiles; + return (char *) missingFiles; } - - - /**************************************************************************** * HBCWindowPrompt * @@ -3799,280 +3805,272 @@ char * GetMissingFiles() ***************************************************************************/ /* - - - - - SD:/APPS/FTPII/ICON.PNG*/ + + + + + SD:/APPS/FTPII/ICON.PNG*/ -int -HBCWindowPrompt( const char *name, const char *coder, const char *version, - const char *release_date, const char *long_description, const char *iconPath, u64 filesize ) +int HBCWindowPrompt(const char *name, const char *coder, const char *version, const char *release_date, + const char *long_description, const char *iconPath, u64 filesize) { int choice = -1; - - GuiWindow promptWindow( 472, 320 ); - promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - promptWindow.SetPosition( 0, 6 ); + GuiWindow promptWindow(472, 320); + promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + promptWindow.SetPosition(0, 6); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); GuiTrigger trigU; - trigU.SetButtonOnlyTrigger( -1, WPAD_BUTTON_UP | WPAD_CLASSIC_BUTTON_UP, PAD_BUTTON_UP ); + trigU.SetButtonOnlyTrigger(-1, WPAD_BUTTON_UP | WPAD_CLASSIC_BUTTON_UP, PAD_BUTTON_UP); GuiTrigger trigD; - trigD.SetButtonOnlyTrigger( -1, WPAD_BUTTON_DOWN | WPAD_CLASSIC_BUTTON_DOWN, PAD_BUTTON_DOWN ); + trigD.SetButtonOnlyTrigger(-1, WPAD_BUTTON_DOWN | WPAD_CLASSIC_BUTTON_DOWN, PAD_BUTTON_DOWN); - GuiSound btnSoundOver( button_over_pcm, button_over_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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", Settings.theme_path ); - GuiImageData dialogBox( imgPath, dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sbg_options.png", Settings.theme_path ); - GuiImageData whiteBox( imgPath, bg_options_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", Settings.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sbg_options.png", Settings.theme_path); + GuiImageData whiteBox(imgPath, bg_options_png); - snprintf( imgPath, sizeof( imgPath ), "%sscrollbar.png", Settings.theme_path ); - GuiImageData scrollbar( imgPath, scrollbar_png ); - GuiImage scrollbarImg( &scrollbar ); - scrollbarImg.SetAlignment( ALIGN_RIGHT, ALIGN_TOP ); - scrollbarImg.SetPosition( -40, 114 ); - scrollbarImg.SetSkew( 0, 0, 0, 0, 0, -120, 0, -120 ); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar.png", Settings.theme_path); + GuiImageData scrollbar(imgPath, scrollbar_png); + GuiImage scrollbarImg(&scrollbar); + scrollbarImg.SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + scrollbarImg.SetPosition(-40, 114); + scrollbarImg.SetSkew(0, 0, 0, 0, 0, -120, 0, -120); - snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_arrowdown.png", Settings.theme_path ); - GuiImageData arrowDown( imgPath, scrollbar_arrowdown_png ); - GuiImage arrowDownImg( &arrowDown ); - arrowDownImg.SetScale( .8 ); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowdown.png", Settings.theme_path); + GuiImageData arrowDown(imgPath, scrollbar_arrowdown_png); + GuiImage arrowDownImg(&arrowDown); + arrowDownImg.SetScale(.8); - snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_arrowup.png", Settings.theme_path ); - GuiImageData arrowUp( imgPath, scrollbar_arrowup_png ); - GuiImage arrowUpImg ( &arrowUp ); - arrowUpImg.SetScale( .8 ); + snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", Settings.theme_path); + GuiImageData arrowUp(imgPath, scrollbar_arrowup_png); + GuiImage arrowUpImg(&arrowUp); + arrowUpImg.SetScale(.8); - GuiButton arrowUpBtn( arrowUpImg.GetWidth(), arrowUpImg.GetHeight() ); - arrowUpBtn.SetImage( &arrowUpImg ); - arrowUpBtn.SetAlignment( ALIGN_RIGHT, ALIGN_TOP ); - arrowUpBtn.SetPosition( -25, 91 ); - arrowUpBtn.SetTrigger( &trigA ); - arrowUpBtn.SetTrigger( &trigU ); - arrowUpBtn.SetEffectOnOver( EFFECT_SCALE, 50, 130 ); - arrowUpBtn.SetSoundClick( btnClick2 ); + GuiButton arrowUpBtn(arrowUpImg.GetWidth(), arrowUpImg.GetHeight()); + arrowUpBtn.SetImage(&arrowUpImg); + arrowUpBtn.SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + arrowUpBtn.SetPosition(-25, 91); + arrowUpBtn.SetTrigger(&trigA); + arrowUpBtn.SetTrigger(&trigU); + arrowUpBtn.SetEffectOnOver(EFFECT_SCALE, 50, 130); + arrowUpBtn.SetSoundClick(btnClick2); - GuiButton arrowDownBtn( arrowDownImg.GetWidth(), arrowDownImg.GetHeight() ); - arrowDownBtn.SetImage( &arrowDownImg ); - arrowDownBtn.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - arrowDownBtn.SetPosition( -25, -27 ); - arrowDownBtn.SetTrigger( &trigA ); - arrowDownBtn.SetTrigger( &trigD ); - arrowDownBtn.SetEffectOnOver( EFFECT_SCALE, 50, 130 ); - arrowDownBtn.SetSoundClick( btnClick2 ); + GuiButton arrowDownBtn(arrowDownImg.GetWidth(), arrowDownImg.GetHeight()); + arrowDownBtn.SetImage(&arrowDownImg); + arrowDownBtn.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + arrowDownBtn.SetPosition(-25, -27); + arrowDownBtn.SetTrigger(&trigA); + arrowDownBtn.SetTrigger(&trigD); + arrowDownBtn.SetEffectOnOver(EFFECT_SCALE, 50, 130); + arrowDownBtn.SetSoundClick(btnClick2); GuiImageData *iconData = NULL; GuiImage *iconImg = NULL; - snprintf( imgPath, sizeof( imgPath ), "%s", iconPath ); + snprintf(imgPath, sizeof(imgPath), "%s", iconPath); - bool iconExist = checkfile( imgPath ); - if ( iconExist ) + bool iconExist = checkfile(imgPath); + if (iconExist) { - iconData = new GuiImageData ( iconPath, dialogue_box_png ); - iconImg = new GuiImage ( iconData ); - iconImg->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - iconImg->SetPosition( 45, 10 ); + iconData = new GuiImageData(iconPath, dialogue_box_png); + iconImg = new GuiImage(iconData); + iconImg->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + iconImg->SetPosition(45, 10); } - GuiImage dialogBoxImg( &dialogBox ); - dialogBoxImg.SetSkew( 0, -80, 0, -80, 0, 50, 0, 50 ); + GuiImage dialogBoxImg(&dialogBox); + dialogBoxImg.SetSkew(0, -80, 0, -80, 0, 50, 0, 50); - GuiImage whiteBoxImg( &whiteBox ); - whiteBoxImg.SetPosition( 0, 110 ); - whiteBoxImg.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - whiteBoxImg.SetSkew( 0, 0, 0, 0, 0, -120, 0, -120 ); + GuiImage whiteBoxImg(&whiteBox); + whiteBoxImg.SetPosition(0, 110); + whiteBoxImg.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + whiteBoxImg.SetSkew(0, 0, 0, 0, 0, -120, 0, -120); /*if (Settings.wsprompt == yes){ - dialogBoxImg.SetWidescreen(Settings.widescreen); - }*/ + dialogBoxImg.SetWidescreen(Settings.widescreen); + }*/ char tmp[510]; - GuiText nameTxt( name, 30 , THEME.prompttext ); - nameTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - nameTxt.SetPosition( 0, -15 ); - nameTxt.SetMaxWidth( 430, SCROLL_HORIZONTAL ); + GuiText nameTxt(name, 30, THEME.prompttext); + nameTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + nameTxt.SetPosition(0, -15); + nameTxt.SetMaxWidth(430, SCROLL_HORIZONTAL); + if (strcmp(coder, "")) snprintf(tmp, sizeof(tmp), tr( "Coded by: %s" ), coder); + GuiText coderTxt(tmp, 16, THEME.prompttext); + coderTxt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + coderTxt.SetPosition(180, 30); + coderTxt.SetMaxWidth(280); - if ( strcmp( coder, "" ) ) - snprintf( tmp, sizeof( tmp ), tr( "Coded by: %s" ), coder ); - GuiText coderTxt( tmp, 16, THEME.prompttext ); - coderTxt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - coderTxt.SetPosition( 180, 30 ); - coderTxt.SetMaxWidth( 280 ); - - if ( strcmp( version, "" ) ) - snprintf( tmp, sizeof( tmp ), tr( "Version: %s" ), version ); - GuiText versionTxt( tmp, 16 , THEME.prompttext ); - versionTxt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - versionTxt.SetPosition( 40, 65 ); - versionTxt.SetMaxWidth( 430 ); + if (strcmp(version, "")) snprintf(tmp, sizeof(tmp), tr( "Version: %s" ), version); + GuiText versionTxt(tmp, 16, THEME.prompttext); + versionTxt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + versionTxt.SetPosition(40, 65); + versionTxt.SetMaxWidth(430); //if (release_date) //snprintf(tmp, sizeof(tmp), tr("Released: %s"),release_date); - GuiText release_dateTxt( release_date, 16 , THEME.prompttext ); - release_dateTxt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - release_dateTxt.SetPosition( 40, 85 ); - release_dateTxt.SetMaxWidth( 430 ); + GuiText release_dateTxt(release_date, 16, THEME.prompttext); + release_dateTxt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + release_dateTxt.SetPosition(40, 85); + release_dateTxt.SetMaxWidth(430); int pagesize = 6; - Text long_descriptionTxt( long_description, 20, THEME.prompttext ); - long_descriptionTxt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - long_descriptionTxt.SetPosition( 46, 117 ); - long_descriptionTxt.SetMaxWidth( 360 ); - long_descriptionTxt.SetLinesToDraw( pagesize ); + Text long_descriptionTxt(long_description, 20, THEME.prompttext); + long_descriptionTxt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + long_descriptionTxt.SetPosition(46, 117); + long_descriptionTxt.SetMaxWidth(360); + long_descriptionTxt.SetLinesToDraw(pagesize); long_descriptionTxt.Refresh(); //convert filesize from u64 to char and put unit of measurement after it char temp2[7]; char filesizeCH[15]; f32 sizeAdjusted; - if ( filesize <= 1024.0 ) + if (filesize <= 1024.0) { sizeAdjusted = filesize; - snprintf( temp2, sizeof( temp2 ), "%.2f", sizeAdjusted ); - snprintf( filesizeCH, sizeof( filesizeCH ), "%s B", temp2 ); + snprintf(temp2, sizeof(temp2), "%.2f", sizeAdjusted); + snprintf(filesizeCH, sizeof(filesizeCH), "%s B", temp2); } - if ( filesize > 1024.0 ) + if (filesize > 1024.0) { sizeAdjusted = filesize / 1024.0; - snprintf( temp2, sizeof( temp2 ), "%.2f", sizeAdjusted ); - snprintf( filesizeCH, sizeof( filesizeCH ), "%s KB", temp2 ); + snprintf(temp2, sizeof(temp2), "%.2f", sizeAdjusted); + snprintf(filesizeCH, sizeof(filesizeCH), "%s KB", temp2); } - if ( filesize > 1048576.0 ) + if (filesize > 1048576.0) { sizeAdjusted = filesize / 1048576.0; - snprintf( temp2, sizeof( temp2 ), "%.2f", sizeAdjusted ); - snprintf( filesizeCH, sizeof( filesizeCH ), "%s MB", temp2 ); + snprintf(temp2, sizeof(temp2), "%.2f", sizeAdjusted); + snprintf(filesizeCH, sizeof(filesizeCH), "%s MB", temp2); } - GuiText filesizeTxt( filesizeCH, 16, THEME.prompttext ); - filesizeTxt.SetAlignment( ALIGN_RIGHT, ALIGN_TOP ); - filesizeTxt.SetPosition( -40, 12 ); + GuiText filesizeTxt(filesizeCH, 16, THEME.prompttext); + filesizeTxt.SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + filesizeTxt.SetPosition(-40, 12); - GuiText btn1Txt( tr( "Load" ), 22, THEME.prompttext ); - GuiImage btn1Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn1Txt(tr( "Load" ), 22, THEME.prompttext); + GuiImage btn1Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn1Txt.SetWidescreen( Settings.widescreen ); - btn1Img.SetWidescreen( Settings.widescreen ); + btn1Txt.SetWidescreen(Settings.widescreen); + btn1Img.SetWidescreen(Settings.widescreen); } - GuiButton btn1( &btn1Img, &btn1Img, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 1 ); - btn1.SetLabel( &btn1Txt ); - btn1.SetState( STATE_SELECTED ); + GuiButton btn1(&btn1Img, &btn1Img, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 1); + btn1.SetLabel(&btn1Txt); + btn1.SetState(STATE_SELECTED); - GuiText btn2Txt( tr( "Back" ), 22, THEME.prompttext ); - GuiImage btn2Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn2Txt(tr( "Back" ), 22, THEME.prompttext); + GuiImage btn2Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn2Txt.SetWidescreen( Settings.widescreen ); - btn2Img.SetWidescreen( Settings.widescreen ); + btn2Txt.SetWidescreen(Settings.widescreen); + btn2Img.SetWidescreen(Settings.widescreen); } - GuiButton btn2( &btn2Img, &btn2Img, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 1 ); - btn2.SetLabel( &btn2Txt ); - btn2.SetTrigger( &trigB ); + GuiButton btn2(&btn2Img, &btn2Img, 0, 3, 0, 0, &trigA, &btnSoundOver, btnClick2, 1); + btn2.SetLabel(&btn2Txt); + btn2.SetTrigger(&trigB); - - btn1.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - btn1.SetPosition( 40, 2 ); - btn2.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); - btn2.SetPosition( -40, 2 ); + btn1.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + btn1.SetPosition(40, 2); + btn2.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); + btn2.SetPosition(-40, 2); GuiTrigger trigZ; - trigZ.SetButtonOnlyTrigger( -1, WPAD_NUNCHUK_BUTTON_Z | WPAD_CLASSIC_BUTTON_ZL, PAD_TRIGGER_Z ); + 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 ); - promptWindow.Append( &screenShotBtn ); + GuiButton screenShotBtn(0, 0); + screenShotBtn.SetPosition(0, 0); + screenShotBtn.SetTrigger(&trigZ); + promptWindow.Append(&screenShotBtn); - promptWindow.Append( &dialogBoxImg ); - if ( strcmp( long_description, "" ) )promptWindow.Append( &whiteBoxImg ); - if ( strcmp( long_description, "" ) )promptWindow.Append( &scrollbarImg ); - if ( strcmp( long_description, "" ) )promptWindow.Append( &arrowDownBtn ); - if ( strcmp( long_description, "" ) )promptWindow.Append( &arrowUpBtn ); + promptWindow.Append(&dialogBoxImg); + if (strcmp(long_description, "")) promptWindow.Append(&whiteBoxImg); + if (strcmp(long_description, "")) promptWindow.Append(&scrollbarImg); + if (strcmp(long_description, "")) promptWindow.Append(&arrowDownBtn); + if (strcmp(long_description, "")) promptWindow.Append(&arrowUpBtn); - if ( strcmp( name, "" ) )promptWindow.Append( &nameTxt ); - if ( strcmp( version, "" ) )promptWindow.Append( &versionTxt ); - if ( strcmp( coder, "" ) )promptWindow.Append( &coderTxt ); - if ( strcmp( release_date, "" ) )promptWindow.Append( &release_dateTxt ); - if ( strcmp( long_description, "" ) )promptWindow.Append( &long_descriptionTxt ); - promptWindow.Append( &filesizeTxt ); - if ( iconExist )promptWindow.Append( iconImg ); - promptWindow.Append( &btn1 ); - promptWindow.Append( &btn2 ); + if (strcmp(name, "")) promptWindow.Append(&nameTxt); + if (strcmp(version, "")) promptWindow.Append(&versionTxt); + if (strcmp(coder, "")) promptWindow.Append(&coderTxt); + if (strcmp(release_date, "")) promptWindow.Append(&release_dateTxt); + if (strcmp(long_description, "")) promptWindow.Append(&long_descriptionTxt); + promptWindow.Append(&filesizeTxt); + if (iconExist) promptWindow.Append(iconImg); + promptWindow.Append(&btn1); + promptWindow.Append(&btn2); - - 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 ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); - while ( choice == -1 ) + while (choice == -1) { VIDEO_WaitVSync(); - if ( shutdown == 1 ) + if (shutdown == 1) { - wiilight( 0 ); + wiilight(0); Sys_Shutdown(); } - else if ( reset == 1 ) + else if (reset == 1) { - wiilight( 0 ); + wiilight(0); Sys_Reboot(); } - if ( btn1.GetState() == STATE_CLICKED ) + if (btn1.GetState() == STATE_CLICKED) choice = 1; - else if ( btn2.GetState() == STATE_CLICKED ) + else if (btn2.GetState() == STATE_CLICKED) choice = 0; - else if ( screenShotBtn.GetState() == STATE_CLICKED ) + else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf( "\n\tscreenShotBtn clicked" ); + gprintf("\n\tscreenShotBtn clicked"); screenShotBtn.ResetState(); ScreenShot(); - gprintf( "...It's easy, mmmmmmKay" ); + gprintf("...It's easy, mmmmmmKay"); } - else if ( arrowUpBtn.GetState() == STATE_CLICKED || arrowUpBtn.GetState() == STATE_HELD ) + else if (arrowUpBtn.GetState() == STATE_CLICKED || arrowUpBtn.GetState() == STATE_HELD) { long_descriptionTxt.PreviousLine(); - usleep( 6000 ); - if ( !( ( ButtonsHold() & WPAD_BUTTON_UP ) || ( ButtonsHold() & PAD_BUTTON_UP ) ) ) - arrowUpBtn.ResetState(); + usleep(6000); + if (!((ButtonsHold() & WPAD_BUTTON_UP) || (ButtonsHold() & PAD_BUTTON_UP))) arrowUpBtn.ResetState(); } - else if ( arrowDownBtn.GetState() == STATE_CLICKED || arrowDownBtn.GetState() == STATE_HELD ) + else if (arrowDownBtn.GetState() == STATE_CLICKED || arrowDownBtn.GetState() == STATE_HELD) { long_descriptionTxt.NextLine(); - usleep( 60000 ); - if ( !( ( ButtonsHold() & WPAD_BUTTON_DOWN ) || ( ButtonsHold() & PAD_BUTTON_DOWN ) ) ) - arrowDownBtn.ResetState(); + usleep(60000); + if (!((ButtonsHold() & WPAD_BUTTON_DOWN) || (ButtonsHold() & PAD_BUTTON_DOWN))) arrowDownBtn.ResetState(); } } - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - while ( promptWindow.GetEffect() > 0 ) usleep( 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + while (promptWindow.GetEffect() > 0) + usleep(50); HaltGui(); - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); return choice; } diff --git a/source/prompts/PromptWindows.h b/source/prompts/PromptWindows.h index 0a381147..0e8424c1 100644 --- a/source/prompts/PromptWindows.h +++ b/source/prompts/PromptWindows.h @@ -10,27 +10,24 @@ #include "usbloader/partition_usbloader.h" -int WindowPrompt( const char *title, const char *msg = NULL, const char * btn1Label = NULL, - const char * btn2Label = NULL, const char * btn3Label = NULL, - const char * btn4Label = NULL, int wait = -1 ); +int WindowPrompt(const char *title, const char *msg = NULL, const char * btn1Label = NULL, const char * btn2Label = + NULL, const char * btn3Label = NULL, const char * btn4Label = NULL, int wait = -1); void WindowCredits(); -int OnScreenKeyboard( char * var, u32 maxlen, int min ); -int OnScreenNumpad( char * var, u32 maxlen ); +int OnScreenKeyboard(char * var, u32 maxlen, int min); +int OnScreenNumpad(char * var, u32 maxlen); int WindowExitPrompt(); int GameWindowPrompt(); -int DiscWait( const char *title, const char *msg, const char *btn1Label, const char *btn2Label, int IsDeviceWait ); -int FormatingPartition( const char *title, partitionEntry *entry ); -bool SearchMissingImages( int choice2 ); -int ProgressDownloadWindow( int choice2 ); +int DiscWait(const char *title, const char *msg, const char *btn1Label, const char *btn2Label, int IsDeviceWait); +int FormatingPartition(const char *title, partitionEntry *entry); +bool SearchMissingImages(int choice2); +int ProgressDownloadWindow(int choice2); int ProgressUpdateWindow(); bool NetworkInitPrompt(); char * GetMissingFiles(); int WindowScreensaver(); -int CodeDownload( const char *id ); -int HBCWindowPrompt( const char *name, const char *coder, const char *version, - const char *release_date, const char *long_description, - const char *iconPath, u64 filesize ); - +int CodeDownload(const char *id); +int HBCWindowPrompt(const char *name, const char *coder, const char *version, const char *release_date, + const char *long_description, const char *iconPath, u64 filesize); #endif diff --git a/source/prompts/TitleBrowser.cpp b/source/prompts/TitleBrowser.cpp index 14ed7551..cd063db8 100644 --- a/source/prompts/TitleBrowser.cpp +++ b/source/prompts/TitleBrowser.cpp @@ -7,7 +7,6 @@ #include - #include "language/gettext.h" #include "libwiigui/gui.h" #include "libwiigui/gui_customoptionbrowser.h" @@ -36,7 +35,6 @@ extern char wiiloadVersion[2]; #include "unzip/unzip.h" #include "unzip/miniunz.h" - /*** Extern functions ***/ extern void ResumeGui(); extern void HaltGui(); @@ -48,11 +46,10 @@ extern u8 reset; extern u32 infilesize; extern wchar_t *gameFilter; - /******************************************************************************** -* TitleBrowser- opens a browser with a list of installed Titles -*********************************************************************************/ -bool TitleSelector( char output[] ) + * TitleBrowser- opens a browser with a list of installed Titles + *********************************************************************************/ +bool TitleSelector(char output[]) { gprintf("TitleSelector()\n"); @@ -64,178 +61,174 @@ bool TitleSelector( char output[] ) ISFS_Initialize();//initialize for "titles.Exists()" // Get count of titles of the good titles - num_titles = titles.SetType( 0x10001 ); + num_titles = titles.SetType(0x10001); u32 n = num_titles; //gprintf("num_titles: %u\n", num_titles ); - for ( u32 i = 0; i < n; i++ ) + for (u32 i = 0; i < n; i++) { - u64 tid = titles.Next(); - if ( !tid ) - { - break; - } + u64 tid = titles.Next(); + if (!tid) + { + break; + } - //remove ones not actually installed on the nand - if ( !titles.Exists( tid ) ) - { - num_titles--; - } + //remove ones not actually installed on the nand + if (!titles.Exists(tid)) + { + num_titles--; + } } //gprintf("num_titles: %u\n", num_titles ); //make a list of just the tids we are adding to the titlebrowser - titleList = ( u64* )memalign( 32, num_titles * sizeof( u64 ) ); - if ( !titleList ) + titleList = (u64*) memalign(32, num_titles * sizeof(u64)); + if (!titleList) { - gprintf( "TitleLister(): out of memory!\n" ); - return false; + gprintf("TitleLister(): out of memory!\n"); + return false; } - customOptionList options4( num_titles + 1 ); + customOptionList options4(num_titles + 1); //write the titles on the option browser s32 i = 0; - titles.SetType( 0x10001 ); - while ( i < num_titles ) + titles.SetType(0x10001); + while (i < num_titles) { - u64 tid = titles.Next(); - if ( !tid ) - { - gprintf( "shit happened\n" ); - break; - } + u64 tid = titles.Next(); + if (!tid) + { + gprintf("shit happened\n"); + break; + } - if ( !titles.Exists( tid ) ) - { - continue; - } + if (!titles.Exists(tid)) + { + continue; + } - char id[ 5 ]; - titles.AsciiTID( tid, ( char* )&id ); + char id[5]; + titles.AsciiTID(tid, (char*) &id); - const char* name = titles.NameOf( tid ); - //gprintf("%016llx: %s: %s\n%p\t%p\n", tid, id, name, &id, name ); + const char* name = titles.NameOf(tid); + //gprintf("%016llx: %s: %s\n%p\t%p\n", tid, id, name, &id, name ); - options4.SetName( i, "%s", id ); - options4.SetValue( i, "%s", name ? titles.NameOf( tid ) : tr( "Unknown" ) ); - titleList[ i ] = tid; - i++; + options4.SetName(i, "%s", id); + options4.SetValue(i, "%s", name ? titles.NameOf(tid) : tr( "Unknown" )); + titleList[i] = tid; + i++; } - // gprintf("i: %u\n", i ); + // gprintf("i: %u\n", i ); //hexdump( titleList, num_titles * sizeof( u64 ) ); - options4.SetName( i, " " ); - options4.SetValue( i, "%s", tr( "Clear" ) ); + options4.SetName(i, " "); + options4.SetValue(i, "%s", tr( "Clear" )); ISFS_Deinitialize(); bool exit = false; - GuiSound btnSoundOver( button_over_pcm, button_over_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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sgamesettings_background.png", Settings.theme_path ); - GuiImageData settingsbg( imgPath, settings_background_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sgamesettings_background.png", Settings.theme_path); + GuiImageData settingsbg(imgPath, settings_background_png); - GuiImage settingsbackground( &settingsbg ); - GuiButton settingsbackgroundbtn( settingsbackground.GetWidth(), settingsbackground.GetHeight() ); - settingsbackgroundbtn.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - settingsbackgroundbtn.SetPosition( 0, 0 ); - settingsbackgroundbtn.SetImage( &settingsbackground ); + GuiImage settingsbackground(&settingsbg); + GuiButton settingsbackgroundbtn(settingsbackground.GetWidth(), settingsbackground.GetHeight()); + settingsbackgroundbtn.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + settingsbackgroundbtn.SetPosition(0, 0); + settingsbackgroundbtn.SetImage(&settingsbackground); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - GuiText cancelBtnTxt( tr( "Back" ), 22, THEME.prompttext ); - cancelBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); - GuiImage cancelBtnImg( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText cancelBtnTxt(tr( "Back" ), 22, THEME.prompttext); + cancelBtnTxt.SetMaxWidth(btnOutline.GetWidth() - 30); + GuiImage cancelBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - cancelBtnTxt.SetWidescreen( Settings.widescreen ); - cancelBtnImg.SetWidescreen( Settings.widescreen ); + cancelBtnTxt.SetWidescreen(Settings.widescreen); + cancelBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton cancelBtn( &cancelBtnImg, &cancelBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2, 1 ); - cancelBtn.SetLabel( &cancelBtnTxt ); - cancelBtn.SetTrigger( &trigB ); + GuiButton cancelBtn(&cancelBtnImg, &cancelBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2, 1); + cancelBtn.SetLabel(&cancelBtnTxt); + cancelBtn.SetTrigger(&trigB); u8 scrollbaron = 0; - if ( num_titles + 1 > 9 ) - scrollbaron = 1; + if (num_titles + 1 > 9) scrollbaron = 1; - GuiCustomOptionBrowser optionBrowser4( 396, 280, &options4, Settings.theme_path, "bg_options_gamesettings.png", bg_options_settings_png, scrollbaron, 200 ); - optionBrowser4.SetPosition( 0, 90 ); - optionBrowser4.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + GuiCustomOptionBrowser optionBrowser4(396, 280, &options4, Settings.theme_path, "bg_options_gamesettings.png", + bg_options_settings_png, scrollbaron, 200); + optionBrowser4.SetPosition(0, 90); + optionBrowser4.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); 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 ); - + 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); HaltGui(); - GuiWindow w( screenwidth, screenheight ); - w.Append( &settingsbackgroundbtn ); - w.Append( &screenShotBtn ); - w.Append( &cancelBtn ); - w.Append( &optionBrowser4 ); - mainWindow->SetState( STATE_DISABLED ); - mainWindow->Append( &w ); + GuiWindow w(screenwidth, screenheight); + w.Append(&settingsbackgroundbtn); + w.Append(&screenShotBtn); + w.Append(&cancelBtn); + w.Append(&optionBrowser4); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&w); ResumeGui(); - while ( !exit ) + while (!exit) { - VIDEO_WaitVSync(); + VIDEO_WaitVSync(); - if ( shutdown == 1 ) Sys_Shutdown(); - if ( reset == 1 ) Sys_Reboot(); + if (shutdown == 1) Sys_Shutdown(); + if (reset == 1) Sys_Reboot(); - r = optionBrowser4.GetClickedOption(); + r = optionBrowser4.GetClickedOption(); - if ( r > -1 ) - { //if a click happened - if( r < num_titles ) - { - u64 tid = titleList[ r ]; - sprintf( output, "%08x", TITLE_LOWER( tid ) ); - } - else - output[ 0 ] = 0; - ret = true; - exit = true; - } + if (r > -1) + { //if a click happened + if (r < num_titles) + { + u64 tid = titleList[r]; + sprintf(output, "%08x", TITLE_LOWER( tid )); + } + else output[0] = 0; + ret = true; + exit = true; + } - else if ( cancelBtn.GetState() == STATE_CLICKED ) - { - //break the loop and end the function - exit = true; - } - else if ( screenShotBtn.GetState() == STATE_CLICKED ) - { - screenShotBtn.ResetState(); - ScreenShot(); - } + else if (cancelBtn.GetState() == STATE_CLICKED) + { + //break the loop and end the function + exit = true; + } + else if (screenShotBtn.GetState() == STATE_CLICKED) + { + screenShotBtn.ResetState(); + ScreenShot(); + } } HaltGui(); - mainWindow->SetState( STATE_DEFAULT ); - mainWindow->Remove( &w ); - free( titleList ); + mainWindow->SetState(STATE_DEFAULT); + mainWindow->Remove(&w); + free(titleList); ResumeGui(); return ret; } - int TitleBrowser() { @@ -247,484 +240,471 @@ int TitleBrowser() ISFS_Initialize();//initialize for "titles.Exists()" // Get count of titles of the good titles - num_titles = titles.SetType( 0x10001 ); + num_titles = titles.SetType(0x10001); u32 n = num_titles; - for ( u32 i = 0; i < n; i++ ) + for (u32 i = 0; i < n; i++) { - u64 tid = titles.Next(); - if ( !tid ) - { - break; - } + u64 tid = titles.Next(); + if (!tid) + { + break; + } - //remove ones not actually installed on the nand - if ( !titles.Exists( tid ) ) - { - num_titles--; - } + //remove ones not actually installed on the nand + if (!titles.Exists(tid)) + { + num_titles--; + } } // Get count of system titles - num_sys_titles = titles.SetType( 0x10002 ); + num_sys_titles = titles.SetType(0x10002); n = num_sys_titles; - for ( u32 i = 0; i < n; i++ ) + for (u32 i = 0; i < n; i++) { - u64 tid = titles.Next(); - if ( !tid ) - { - break; - } - //these can't be booted anyways - if ( TITLE_LOWER( tid ) == 0x48414741 || TITLE_LOWER( tid ) == 0x48414141 || TITLE_LOWER( tid ) == 0x48414641 ) - { - num_sys_titles--; - continue; - } + u64 tid = titles.Next(); + if (!tid) + { + break; + } + //these can't be booted anyways + if (TITLE_LOWER( tid ) == 0x48414741 || TITLE_LOWER( tid ) == 0x48414141 || TITLE_LOWER( tid ) == 0x48414641) + { + num_sys_titles--; + continue; + } - //these aren't installed on the nand - if ( !titles.Exists( tid ) ) - { - num_sys_titles--; - } + //these aren't installed on the nand + if (!titles.Exists(tid)) + { + num_sys_titles--; + } } //make a list of just the tids we are adding to the titlebrowser - titleList = ( u64* )memalign( 32, ( num_titles + num_sys_titles ) * sizeof( u64 ) ); - if ( !titleList ) + titleList = (u64*) memalign(32, (num_titles + num_sys_titles) * sizeof(u64)); + if (!titleList) { - gprintf( "TitleBrowser(): out of memory!\n" ); - return -1; + gprintf("TitleBrowser(): out of memory!\n"); + return -1; } - customOptionList options3( num_titles + num_sys_titles + 1 ); + customOptionList options3(num_titles + num_sys_titles + 1); //write the titles on the option browser u32 i = 0; - titles.SetType( 0x10001 ); + titles.SetType(0x10001); //first add the good stuff - while ( i < num_titles ) + while (i < num_titles) { - u64 tid = titles.Next(); - if ( !tid ) - { - gprintf( "shit happened3\n" ); - break; - } - gprintf("[ %u ] tid: %016llx\t%s\n", i, tid, titles.NameOf( tid ) ); + u64 tid = titles.Next(); + if (!tid) + { + gprintf("shit happened3\n"); + break; + } + gprintf("[ %u ] tid: %016llx\t%s\n", i, tid, titles.NameOf(tid)); - if ( !titles.Exists( tid ) ) - { - continue; - } + if (!titles.Exists(tid)) + { + continue; + } - char id[ 5 ]; - titles.AsciiTID( tid, ( char* )&id ); + char id[5]; + titles.AsciiTID(tid, (char*) &id); - const char* name = titles.NameOf( tid ); + const char* name = titles.NameOf(tid); - options3.SetName( i, "%s", id ); - options3.SetValue( i, "%s", name ? titles.NameOf( tid ) : tr( "Unknown" ) ); - titleList[ i ] = tid; - i++; + options3.SetName(i, "%s", id); + options3.SetValue(i, "%s", name ? titles.NameOf(tid) : tr( "Unknown" )); + titleList[i] = tid; + i++; } - titles.SetType( 0x10002 ); - while ( i < num_sys_titles + num_titles ) + titles.SetType(0x10002); + while (i < num_sys_titles + num_titles) { - u64 tid = titles.Next(); - if ( !tid ) - { - break; - } - if ( TITLE_LOWER( tid ) == 0x48414741 || TITLE_LOWER( tid ) == 0x48414141 || TITLE_LOWER( tid ) == 0x48414641 ) - continue; + u64 tid = titles.Next(); + if (!tid) + { + break; + } + if (TITLE_LOWER( tid ) == 0x48414741 || TITLE_LOWER( tid ) == 0x48414141 || TITLE_LOWER( tid ) == 0x48414641) continue; - if ( !titles.Exists( tid ) ) - { - continue; - } + if (!titles.Exists(tid)) + { + continue; + } - char id[ 5 ]; - titles.AsciiTID( tid, ( char* )&id ); - const char* name = titles.NameOf( tid ); + char id[5]; + titles.AsciiTID(tid, (char*) &id); + const char* name = titles.NameOf(tid); - options3.SetName( i, "%s", id ); - options3.SetValue( i, "%s", name ? titles.NameOf( tid ) : tr( "Unknown" ) ); - titleList[ i ] = tid; - i++; + options3.SetName(i, "%s", id); + options3.SetValue(i, "%s", name ? titles.NameOf(tid) : tr( "Unknown" )); + titleList[i] = tid; + i++; } ISFS_Deinitialize(); - - if ( i == num_titles + num_sys_titles ) + if (i == num_titles + num_sys_titles) { - options3.SetName( i, " " ); - options3.SetValue( i, "%s", tr( "Wii Settings" ) ); + options3.SetName(i, " "); + options3.SetValue(i, "%s", tr( "Wii Settings" )); } bool exit = false; int total = num_titles + num_sys_titles; - if ( IsNetworkInit() ) - ResumeNetworkWait(); + if (IsNetworkInit()) ResumeNetworkWait(); - GuiSound btnSoundOver( button_over_pcm, button_over_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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sgamesettings_background.png", Settings.theme_path ); - GuiImageData settingsbg( imgPath, settings_background_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sgamesettings_background.png", Settings.theme_path); + GuiImageData settingsbg(imgPath, settings_background_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + 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 ); + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - GuiText titleTxt( tr( "Title Launcher" ), 28, ( GXColor ) {0, 0, 0, 255} ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( 12, 40 ); - titleTxt.SetMaxWidth( 356, SCROLL_HORIZONTAL ); + GuiText titleTxt(tr( "Title Launcher" ), 28, ( GXColor ) + { 0, 0, 0, 255}); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(12, 40); + titleTxt.SetMaxWidth(356, SCROLL_HORIZONTAL); - GuiImage settingsbackground( &settingsbg ); - GuiButton settingsbackgroundbtn( settingsbackground.GetWidth(), settingsbackground.GetHeight() ); - settingsbackgroundbtn.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - settingsbackgroundbtn.SetPosition( 0, 0 ); - settingsbackgroundbtn.SetImage( &settingsbackground ); + GuiImage settingsbackground(&settingsbg); + GuiButton settingsbackgroundbtn(settingsbackground.GetWidth(), settingsbackground.GetHeight()); + settingsbackgroundbtn.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + settingsbackgroundbtn.SetPosition(0, 0); + settingsbackgroundbtn.SetImage(&settingsbackground); - GuiText cancelBtnTxt( tr( "Back" ), 22, THEME.prompttext ); - cancelBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); - GuiImage cancelBtnImg( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText cancelBtnTxt(tr( "Back" ), 22, THEME.prompttext); + cancelBtnTxt.SetMaxWidth(btnOutline.GetWidth() - 30); + GuiImage cancelBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - cancelBtnTxt.SetWidescreen( Settings.widescreen ); - cancelBtnImg.SetWidescreen( Settings.widescreen ); + cancelBtnTxt.SetWidescreen(Settings.widescreen); + cancelBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton cancelBtn( &cancelBtnImg, &cancelBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2, 1 ); - cancelBtn.SetScale( 0.9 ); - cancelBtn.SetLabel( &cancelBtnTxt ); - cancelBtn.SetTrigger( &trigB ); + GuiButton cancelBtn(&cancelBtnImg, &cancelBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2, 1); + cancelBtn.SetScale(0.9); + cancelBtn.SetLabel(&cancelBtnTxt); + cancelBtn.SetTrigger(&trigB); u8 scrollbaron = 0; - if ( total + 1 > 9 ) - scrollbaron = 1; + if (total + 1 > 9) scrollbaron = 1; - GuiCustomOptionBrowser optionBrowser3( 396, 280, &options3, Settings.theme_path, "bg_options_gamesettings.png", bg_options_settings_png, scrollbaron, 200 ); - optionBrowser3.SetPosition( 0, 90 ); - optionBrowser3.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + GuiCustomOptionBrowser optionBrowser3(396, 280, &options3, Settings.theme_path, "bg_options_gamesettings.png", + bg_options_settings_png, scrollbaron, 200); + optionBrowser3.SetPosition(0, 90); + optionBrowser3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - snprintf( imgPath, sizeof( imgPath ), "%sWifi_btn.png", Settings.theme_path ); - GuiImageData wifiImgData( imgPath, Wifi_btn_png ); - GuiImage wifiImg( &wifiImgData ); - if ( Settings.wsprompt == yes ) + snprintf(imgPath, sizeof(imgPath), "%sWifi_btn.png", Settings.theme_path); + GuiImageData wifiImgData(imgPath, Wifi_btn_png); + GuiImage wifiImg(&wifiImgData); + if (Settings.wsprompt == yes) { - wifiImg.SetWidescreen( Settings.widescreen ); + wifiImg.SetWidescreen(Settings.widescreen); } - GuiButton wifiBtn( wifiImg.GetWidth(), wifiImg.GetHeight() ); - wifiBtn.SetImage( &wifiImg ); - wifiBtn.SetPosition( 100, 400 ); + GuiButton wifiBtn(wifiImg.GetWidth(), wifiImg.GetHeight()); + wifiBtn.SetImage(&wifiImg); + wifiBtn.SetPosition(100, 400); wifiBtn.SetEffectGrow(); - wifiBtn.SetAlpha( 80 ); - wifiBtn.SetTrigger( &trigA ); + wifiBtn.SetAlpha(80); + wifiBtn.SetTrigger(&trigA); GuiTrigger trigZ; - trigZ.SetButtonOnlyTrigger( -1, WPAD_NUNCHUK_BUTTON_Z | WPAD_CLASSIC_BUTTON_ZL, PAD_TRIGGER_Z ); + 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 ); + GuiButton screenShotBtn(0, 0); + screenShotBtn.SetPosition(0, 0); + screenShotBtn.SetTrigger(&trigZ); HaltGui(); - GuiWindow w( screenwidth, screenheight ); - w.Append( &screenShotBtn ); - w.Append( &settingsbackgroundbtn ); - w.Append( &titleTxt ); - w.Append( &cancelBtn ); - w.Append( &wifiBtn ); - w.Append( &optionBrowser3 ); - mainWindow->Append( &w ); - - + GuiWindow w(screenwidth, screenheight); + w.Append(&screenShotBtn); + w.Append(&settingsbackgroundbtn); + w.Append(&titleTxt); + w.Append(&cancelBtn); + w.Append(&wifiBtn); + w.Append(&optionBrowser3); + mainWindow->Append(&w); ResumeGui(); - while ( !exit ) + while (!exit) { - VIDEO_WaitVSync(); + VIDEO_WaitVSync(); - if ( shutdown == 1 ) Sys_Shutdown(); - if ( reset == 1 ) Sys_Reboot(); + if (shutdown == 1) Sys_Shutdown(); + if (reset == 1) + Sys_Reboot(); - else if ( wifiBtn.GetState() == STATE_CLICKED ) - { - ResumeNetworkWait(); - wifiBtn.ResetState(); - } + else if (wifiBtn.GetState() == STATE_CLICKED) + { + ResumeNetworkWait(); + wifiBtn.ResetState(); + } - if ( IsNetworkInit() ) - { - wifiBtn.SetAlpha( 255 ); - } + if (IsNetworkInit()) + { + wifiBtn.SetAlpha(255); + } - ret = optionBrowser3.GetClickedOption(); + ret = optionBrowser3.GetClickedOption(); - if ( ret > -1 ) - { //if a click happened + if (ret > -1) + { //if a click happened - if ( ret < total ) - { - //set the title's name, number, ID to text - char text[ 0x100 ]; - char id[ 5 ]; - titles.AsciiTID( titleList[ ret ], ( char* )&id ); + if (ret < total) + { + //set the title's name, number, ID to text + char text[0x100]; + char id[5]; + titles.AsciiTID(titleList[ret], (char*) &id); - snprintf( text, sizeof( text ), "%s : %s", id, titles.NameOf( titleList[ ret ] ) ); + snprintf(text, sizeof(text), "%s : %s", id, titles.NameOf(titleList[ret])); - //prompt to boot selected title - if ( WindowPrompt( tr( "Boot?" ), text, tr( "OK" ), tr( "Cancel" ) ) ) - { //if they say yes - CloseXMLDatabase(); - ExitGUIThreads(); - ShutdownAudio(); - StopGX(); - WII_Initialize(); - WII_LaunchTitle( titleList[ ret ] ); - //this really shouldn't be needed because the title will be booted - exit = true; - break; - } - else - { - //if they said no to booting the title - ret = -1; - optionBrowser3.ResetState(); - } + //prompt to boot selected title + if (WindowPrompt(tr( "Boot?" ), text, tr( "OK" ), tr( "Cancel" ))) + { //if they say yes + CloseXMLDatabase(); + ExitGUIThreads(); + ShutdownAudio(); + StopGX(); + WII_Initialize(); + WII_LaunchTitle(titleList[ret]); + //this really shouldn't be needed because the title will be booted + exit = true; + break; + } + else + { + //if they said no to booting the title + ret = -1; + optionBrowser3.ResetState(); + } - } - else if ( ret == total ) - { //if they clicked to go to the wii settings - CloseXMLDatabase(); - ExitGUIThreads(); - ShutdownAudio(); - StopGX(); - WII_Initialize(); - WII_ReturnToSettings(); - } - } + } + else if (ret == total) + { //if they clicked to go to the wii settings + CloseXMLDatabase(); + ExitGUIThreads(); + ShutdownAudio(); + StopGX(); + WII_Initialize(); + WII_ReturnToSettings(); + } + } #if 0 - if ( infilesize > 0 ) - { + if ( infilesize > 0 ) + { - char filesizetxt[50]; - char temp[50]; - char filepath[100]; -// u32 read = 0; + 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 ); - 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() ); - snprintf( temp, sizeof( temp ), tr( "Load file from: %s ?" ), GetIncommingIP() ); + int choice = WindowPrompt( filesizetxt, temp, tr( "OK" ), tr( "Cancel" ) ); + gprintf( "\nchoice:%d", choice ); - int choice = WindowPrompt( filesizetxt, temp, tr( "OK" ), tr( "Cancel" ) ); - gprintf( "\nchoice:%d", choice ); + if ( choice == 1 ) + { - if ( choice == 1 ) - { + u32 read = 0; + u8 *temp = NULL; + int len = NETWORKBLOCKSIZE; + temp = ( u8 * ) malloc( infilesize ); - u32 read = 0; - u8 *temp = NULL; - int len = NETWORKBLOCKSIZE; - temp = ( u8 * ) malloc( infilesize ); + bool error = false; + u8 *ptr = temp; + gprintf( "\nrecieving shit" ); + while ( read < infilesize ) + { - bool error = false; - u8 *ptr = temp; - gprintf( "\nrecieving shit" ); - while ( read < infilesize ) - { + ShowProgress( tr( "Receiving file from:" ), GetIncommingIP(), NULL, read, infilesize, true ); - ShowProgress( tr( "Receiving file from:" ), GetIncommingIP(), NULL, read, infilesize, true ); + if ( infilesize - read < ( u32 ) len ) + len = infilesize - read; + else + len = NETWORKBLOCKSIZE; - if ( infilesize - read < ( u32 ) len ) - len = infilesize - read; - else - len = NETWORKBLOCKSIZE; + int result = network_read( ptr, len ); - 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(); - 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" ); + 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" ); - //bool installWad=0; - if ( !error ) - { - gprintf( "\nno error yet" ); + if ( uncfilesize != 0 ) // if uncfilesize == 0, it's not compressed - network_read( ( u8* ) &filename, 100 ); - gprintf( "\nfilename: %s", filename ); + { + 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; - // Do we need to unzip this thing? - if ( wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4 ) - { - gprintf( "\nusing newer wiiload version" ); + free( temp ); + temp = unc; + } + } - 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 ( !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 ); - free( temp ); - temp = unc; - } - } + sprintf( tmptxt, "%s/wad/%s", bootDevice, filename ); + if ( checkfile( tmptxt ) )remove( tmptxt ); + rename( filepath, tmptxt ); - 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 ); + //check and make sure the wad we just saved is the correct size + u32 lSize; + file = fopen( tmptxt, "rb" ); - sprintf( tmptxt, "%s/wad/%s", bootDevice, filename ); - if ( checkfile( tmptxt ) )remove( tmptxt ); - rename( filepath, tmptxt ); + // obtain file size: + fseek ( file , 0 , SEEK_END ); + lSize = ftell ( file ); - //check and make sure the wad we just saved is the correct size - u32 lSize; - file = fopen( tmptxt, "rb" ); + 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(); - // obtain file size: - fseek ( file , 0 , SEEK_END ); - lSize = ftell ( file ); + Wad_Install( 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(); + HaltGui(); + w.Append( &titleTxt ); + w.Append( &cancelBtn ); + w.Append( &wifiBtn ); + w.Append( &optionBrowser3 ); + ResumeGui(); - Wad_Install( file ); + } + if ( pick == 2 )Wad_Uninstall( file ); + } + else gprintf( "\nBad size" ); + //close that beast, we're done with it + fclose ( file ); - HaltGui(); - w.Append( &titleTxt ); - w.Append( &cancelBtn ); - w.Append( &wifiBtn ); - w.Append( &optionBrowser3 ); - ResumeGui(); + //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 ( pick == 2 )Wad_Uninstall( file ); - } - else gprintf( "\nBad size" ); - //close that beast, we're done with it - fclose ( file ); + if ( error || read != infilesize ) + { + WindowPrompt( tr( "Error:" ), tr( "No data could be read." ), 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 ( temp )free( temp ); + } - - - if ( error || read != infilesize ) - { - WindowPrompt( tr( "Error:" ), tr( "No data could be read." ), tr( "OK" ) ); - - - } - if ( temp )free( temp ); - } - - - - CloseConnection(); - ResumeNetworkWait(); - } + CloseConnection(); + ResumeNetworkWait(); + } #endif - if ( cancelBtn.GetState() == STATE_CLICKED ) - { - //break the loop and end the function - exit = true; - ret = -10; - } - else if ( screenShotBtn.GetState() == STATE_CLICKED ) - { - screenShotBtn.ResetState(); - ScreenShot(); - } + if (cancelBtn.GetState() == STATE_CLICKED) + { + //break the loop and end the function + exit = true; + ret = -10; + } + else if (screenShotBtn.GetState() == STATE_CLICKED) + { + screenShotBtn.ResetState(); + ScreenShot(); + } } CloseConnection(); - if ( IsNetworkInit() ) - HaltNetworkThread(); + if (IsNetworkInit()) HaltNetworkThread(); HaltGui(); - mainWindow->Remove( &w ); - free( titleList ); + mainWindow->Remove(&w); + free(titleList); ResumeGui(); return ret; } - - diff --git a/source/prompts/TitleBrowser.h b/source/prompts/TitleBrowser.h index c440ef91..cd15cc3c 100644 --- a/source/prompts/TitleBrowser.h +++ b/source/prompts/TitleBrowser.h @@ -9,6 +9,6 @@ #define _TITLEBROWSER_H_ int TitleBrowser(); -bool TitleSelector( char output[] ); +bool TitleSelector(char output[]); #endif diff --git a/source/prompts/filebrowser.cpp b/source/prompts/filebrowser.cpp index 2e2992c2..736e4713 100644 --- a/source/prompts/filebrowser.cpp +++ b/source/prompts/filebrowser.cpp @@ -41,31 +41,29 @@ static int curDevice = -1; static std::vector browsers; BROWSERINFO *browser = NULL; - - /**************************************************************************** * FileFilterCallbacks * return: 1-visible 0-hidden ***************************************************************************/ -int noDIRS( BROWSERENTRY *Entry, void* Args ) +int noDIRS(BROWSERENTRY *Entry, void* Args) { return !Entry->isdir; } -int noFILES( BROWSERENTRY *Entry, void* Args ) +int noFILES(BROWSERENTRY *Entry, void* Args) { return Entry->isdir; } -int noEXT( BROWSERENTRY *Entry, void* Args ) +int noEXT(BROWSERENTRY *Entry, void* Args) { - if ( !Entry->isdir ) + if (!Entry->isdir) { - char *cptr = strrchr( Entry->displayname, '.' ); - if ( cptr && cptr != Entry->displayname ) *cptr = 0; + char *cptr = strrchr(Entry->displayname, '.'); + if (cptr && cptr != Entry->displayname) *cptr = 0; } return 1; } -void ResetBrowser( BROWSERINFO *browser ); +void ResetBrowser(BROWSERINFO *browser); /**************************************************************************** * InitBrowsers() * Clears the file browser memory, and allocates one initial entry @@ -76,23 +74,23 @@ int InitBrowsers() browsers.clear(); browser = NULL; char rootdir[ROOTDIRLEN]; - for ( int i = 3; i < STD_MAX; i++ ) + for (int i = 3; i < STD_MAX; i++) { - if ( strcmp( devoptab_list[i]->name, "stdnull" ) && devoptab_list[i]->write_r != NULL ) + if (strcmp(devoptab_list[i]->name, "stdnull") && devoptab_list[i]->write_r != NULL) { - snprintf( rootdir, sizeof( rootdir ) , "%s:/", devoptab_list[i]->name ); + snprintf(rootdir, sizeof(rootdir), "%s:/", devoptab_list[i]->name); if ( DIR_ITER *dir = diropen( rootdir ) ) { - dirclose( dir ); + dirclose(dir); BROWSERINFO browser; browser.dir[0] = '\0'; - strcpy( browser.rootdir, rootdir ); - ResetBrowser( &browser ); - browsers.push_back( browser ); + strcpy(browser.rootdir, rootdir); + ResetBrowser(&browser); + browsers.push_back(browser); } } } - if ( !browsers.size() ) return -1; + if (!browsers.size()) return -1; curDevice = 0; browser = &browsers[curDevice]; return 0; @@ -101,21 +99,21 @@ int InitBrowsers() * ResetBrowser() * Clears the file browser memory, and allocates one initial entry ***************************************************************************/ -void ResetBrowser( BROWSERINFO *browser ) +void ResetBrowser(BROWSERINFO *browser) { - browser->pageIndex = 0; + 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)); - */ + // 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)); + */ } /**************************************************************************** @@ -128,42 +126,41 @@ void ResetBrowser( BROWSERINFO *browser ) * ***************************************************************************/ //int FileSortCallback(const void *f1, const void *f2) { -bool operator< ( const BROWSERENTRY &f1, const BROWSERENTRY &f2 ) +bool operator<(const BROWSERENTRY &f1, const BROWSERENTRY &f2) { /* Special case for implicit directories */ - if ( f1.filename[0] == '.' || f2.filename[0] == '.' ) + if (f1.filename[0] == '.' || f2.filename[0] == '.') { - if ( strcmp( f1.filename, "." ) == 0 ) + if (strcmp(f1.filename, ".") == 0) { return true; } - if ( strcmp( f2.filename, "." ) == 0 ) + if (strcmp(f2.filename, ".") == 0) { return false; } - if ( strcmp( f1.filename, ".." ) == 0 ) + if (strcmp(f1.filename, "..") == 0) { return true; } - if ( strcmp( f2.filename, ".." ) == 0 ) + 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 (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 ) +int ParseFilter(FILTERCASCADE *Filter, BROWSERENTRY* Entry) { - while ( Filter ) + while (Filter) { - if ( Filter->filter && Filter->filter( Entry, Filter->filter_args ) == 0 ) - return 0; + if (Filter->filter && Filter->filter(Entry, Filter->filter_args) == 0) return 0; Filter = Filter->next; } return 1; @@ -171,7 +168,7 @@ int ParseFilter( FILTERCASCADE *Filter, BROWSERENTRY* Entry ) /*************************************************************************** * Browse subdirectories **************************************************************************/ -int ParseDirectory( const char* Path, int Flags, FILTERCASCADE *Filter ) +int ParseDirectory(const char* Path, int Flags, FILTERCASCADE *Filter) { DIR_ITER *dir = NULL; char fulldir[MAXPATHLEN]; @@ -179,107 +176,101 @@ int ParseDirectory( const char* Path, int Flags, FILTERCASCADE *Filter ) 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 + if (Path) // note in this codeblock use filename temporary { - strlcpy( fulldir, Path, sizeof( fulldir ) ); - if ( *fulldir && fulldir[strlen( fulldir )-1] != '/' ) // a file + strlcpy(fulldir, Path, sizeof(fulldir)); + if (*fulldir && fulldir[strlen(fulldir) - 1] != '/') // a file { - char * chrp = strrchr( fulldir, '/' ); - if ( chrp ) chrp[1] = 0; + char * chrp = strrchr(fulldir, '/'); + if (chrp) chrp[1] = 0; } - if ( strchr( fulldir, ':' ) == NULL ) // Path has no device device + 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 + 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 + { // 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 (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 + if (getcwd(fulldir, sizeof(fulldir))) return -1; // gets the concatenated current working dir + chdir(filename); // restore the saved cwd } } - for ( i = 0; i < browsers.size(); i++ ) // searchs the browser who match the path + for (i = 0; i < browsers.size(); i++) // searchs the browser who match the path { - if ( strnicmp( fulldir, browsers[i].rootdir, strlen( browsers[i].rootdir ) - 1 /*means without trailing '/'*/ ) == 0 ) + if (strnicmp(fulldir, browsers[i].rootdir, strlen(browsers[i].rootdir) - 1 /*means without trailing '/'*/) + == 0) { browser = &browsers[curDevice]; break; } } - if ( i != browsers.size() ) // found browser + if (i != browsers.size()) // found browser { curDevice = i; browser = &browsers[curDevice]; - strcpy( browser->dir, &fulldir[strlen( browser->rootdir )] ); + strcpy(browser->dir, &fulldir[strlen(browser->rootdir)]); } - else if ( Flags & FB_TRYSTDDEV ) + 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 + 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 return -1; } - else - snprintf( fulldir, sizeof( fulldir ), "%s%s", browser->rootdir, browser->dir ); + else snprintf(fulldir, sizeof(fulldir), "%s%s", browser->rootdir, browser->dir); // reset browser - ResetBrowser( browser ); + ResetBrowser(browser); // open the directory - if ( ( dir = diropen( fulldir ) ) == NULL ) + if ((dir = diropen(fulldir)) == NULL) { - if ( Flags & FB_TRYROOTDIR ) + if (Flags & FB_TRYROOTDIR) { browser->dir[0] = 0; - if ( ( dir = diropen( browser->rootdir ) ) == NULL ) - return -1; + if ((dir = diropen(browser->rootdir)) == NULL) return -1; } - else - return -1; + else return -1; } - while ( dirnext( dir, filename, &filestat ) == 0 ) + while (dirnext(dir, filename, &filestat) == 0) { - if ( strcmp( filename, "." ) != 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 ) ); + 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 ); + 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 ); + dirclose(dir); // Sort the file list - std::sort( browser->browserList.begin(), browser->browserList.end() ); + std::sort(browser->browserList.begin(), browser->browserList.end()); return 0; } -int ParseDirectory( int Device, int Flags, FILTERCASCADE *Filter ) +int ParseDirectory(int Device, int Flags, FILTERCASCADE *Filter) { - if ( Device >= 0 && Device < ( int )browsers.size() ) + 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; + if (ParseDirectory((char*) NULL, Flags, Filter) == 0) return 0; curDevice = old_curDevice; browser = &browsers[old_curDevice]; } @@ -291,255 +282,257 @@ 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 BrowseDevice(char * Path, int Path_size, int Flags, FILTERCASCADE *Filter/*=NULL*/) { int result = -1; int i; - if ( InitBrowsers() || ParseDirectory( Path, Flags, Filter ) ) + if (InitBrowsers() || ParseDirectory(Path, Flags, Filter)) { - WindowPrompt( tr( "Error" ), 0, tr( "OK" ) ); + 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); - */ + 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 ); + 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 ); + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - GuiSound btnSoundOver( button_over_pcm, button_over_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 ); + 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 ); + 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", Settings.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 ) + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.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( Settings.widescreen ); - ExitBtnImg.SetWidescreen( Settings.widescreen ); + ExitBtnTxt.SetWidescreen(Settings.widescreen); + ExitBtnImg.SetWidescreen(Settings.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 ); + 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 ) + GuiText usbBtnTxt(browsers[(curDevice + 1) % browsers.size()].rootdir, 24, ( GXColor ) + { 0, 0, 0, 255}); + GuiImage usbBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - usbBtnTxt.SetWidescreen( Settings.widescreen ); - usbBtnImg.SetWidescreen( Settings.widescreen ); + usbBtnTxt.SetWidescreen(Settings.widescreen); + usbBtnImg.SetWidescreen(Settings.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 ); + 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 ) + GuiText okBtnTxt(tr( "OK" ), 22, THEME.prompttext); + GuiImage okBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - okBtnTxt.SetWidescreen( Settings.widescreen ); - okBtnImg.SetWidescreen( Settings.widescreen ); + okBtnTxt.SetWidescreen(Settings.widescreen); + okBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton okBtn( &okBtnImg, &okBtnImg, 0, 4, 40, -35, &trigA, &btnSoundOver, btnClick2, 1 ); - okBtn.SetLabel( &okBtnTxt ); + 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( ( char* ) 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, SCROLL_HORIZONTAL ); - 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((char*) 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, SCROLL_HORIZONTAL); + 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 ); -// 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 ); + 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 ) + 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; i < FILEBROWSERSIZE; i++ ) + for (i = 0; i < FILEBROWSERSIZE; i++) { - if ( fileBrowser.fileList[i]->GetState() == STATE_CLICKED ) + if (fileBrowser.fileList[i]->GetState() == STATE_CLICKED) { fileBrowser.fileList[i]->ResetState(); clickedIndex = browser->pageIndex + i; bool pathCanged = false; // check corresponding browser entry - if ( browser->browserList[clickedIndex].isdir ) + if (browser->browserList[clickedIndex].isdir) { /* go up to parent directory */ - if ( strcmp( browser->browserList[clickedIndex].filename, ".." ) == 0 ) + 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 + 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, "." ) ) + else if (strcmp(browser->browserList[clickedIndex].filename, ".")) { /* test new directory namelength */ - if ( ( strlen( browser->dir ) + strlen( browser->browserList[clickedIndex].filename ) - + 1/*'/'*/ ) < MAXPATHLEN ) + 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 ); + sprintf(browser->dir, "%s%s/", browser->dir, browser->browserList[clickedIndex].filename); pathCanged = true; } } - if ( pathCanged ) + if (pathCanged) { LOCK( &fileBrowser ); - ParseDirectory( ( char* )NULL, Flags, Filter ); + ParseDirectory((char*) NULL, Flags, Filter); fileBrowser.ResetState(); fileBrowser.TriggerUpdate(); - AdressText.SetTextf( "%s%s", browser->rootdir, browser->dir ); + 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 ); + AdressText.SetTextf("%s%s%s", browser->rootdir, browser->dir, + browser->browserList[clickedIndex].filename); } } } - if ( ExitBtn.GetState() == STATE_CLICKED ) + if (ExitBtn.GetState() == STATE_CLICKED) { result = 0; break; } - else if ( okBtn.GetState() == STATE_CLICKED ) + 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 ); + 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 ) + else if (usbBtn.GetState() == STATE_CLICKED) { usbBtn.ResetState(); - for ( u32 i = 1; i < browsers.size(); i++ ) + for (u32 i = 1; i < browsers.size(); i++) { LOCK( &fileBrowser ); - if ( ParseDirectory( ( curDevice + i ) % browsers.size(), Flags, Filter ) == 0 ) + if (ParseDirectory((curDevice + i) % browsers.size(), Flags, Filter) == 0) { fileBrowser.ResetState(); fileBrowser.TriggerUpdate(); - AdressText.SetTextf( "%s%s", browser->rootdir, browser->dir ); - usbBtnTxt.SetText( browsers[( curDevice+1 )%browsers.size()].rootdir ); + AdressText.SetTextf("%s%s", browser->rootdir, browser->dir); + usbBtnTxt.SetText(browsers[(curDevice + 1) % browsers.size()].rootdir); break; } } } - else if ( folderBtn.GetState() == STATE_CLICKED ) + else if (folderBtn.GetState() == STATE_CLICKED) { folderBtn.ResetState(); HaltGui(); - mainWindow->Remove( &w ); + mainWindow->Remove(&w); ResumeGui(); char newfolder[100]; char oldfolder[100]; - snprintf( newfolder, sizeof( newfolder ), "%s%s", browser->rootdir, browser->dir ); - strcpy( oldfolder, newfolder ); + 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 ) + 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] != '/' ) + unsigned int len = strlen(newfolder); + if (len > 0 && len + 1 < sizeof(newfolder) && newfolder[len - 1] != '/') { newfolder[len] = '/'; - newfolder[len+1] = '\0'; + newfolder[len + 1] = '\0'; } struct stat st; - if ( stat( newfolder, &st ) != 0 ) + 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 (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 ) + 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 ); + AdressText.SetTextf("%s%s", browser->rootdir, browser->dir); + usbBtnTxt.SetText(browsers[(curDevice + 1) % browsers.size()].rootdir); } } HaltGui(); - mainWindow->Append( &w ); + mainWindow->Append(&w); ResumeGui(); } } HaltGui(); - mainWindow->Remove( &w ); + mainWindow->Remove(&w); ResumeGui(); //} @@ -547,12 +540,12 @@ int BrowseDevice( char * Path, int Path_size, int Flags, FILTERCASCADE *Filter/* return result; } -int BrowseDevice( char * Path, int Path_size, int Flags, FILEFILTERCALLBACK Filter, void *FilterArgs ) +int BrowseDevice(char * Path, int Path_size, int Flags, FILEFILTERCALLBACK Filter, void *FilterArgs) { - if ( Filter ) + if (Filter) { - FILTERCASCADE filter = {Filter, FilterArgs, NULL}; - return BrowseDevice( Path, Path_size, Flags, &filter ); + FILTERCASCADE filter = { Filter, FilterArgs, NULL }; + return BrowseDevice(Path, Path_size, Flags, &filter); } - return BrowseDevice( Path, Path_size, Flags ); + return BrowseDevice(Path, Path_size, Flags); } diff --git a/source/prompts/filebrowser.h b/source/prompts/filebrowser.h index 06122650..39c7a9ea 100644 --- a/source/prompts/filebrowser.h +++ b/source/prompts/filebrowser.h @@ -19,46 +19,42 @@ #define MAXDISPLAY MAXPATHLEN #define ROOTDIRLEN 10 - typedef struct { - u64 offset; // DVD offset - u64 length; // file length in 64 bytes for sizes higher than 4GB - char isdir; // 0 - file, 1 - directory - char filename[MAXJOLIET + 1]; // full filename - char displayname[MAXDISPLAY + 1]; // name for browser display + u64 offset; // DVD offset + u64 length; // file length in 64 bytes for sizes higher than 4GB + char isdir; // 0 - file, 1 - directory + char filename[MAXJOLIET + 1]; // full filename + char displayname[MAXDISPLAY + 1]; // name for browser display } BROWSERENTRY; 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; + 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; } BROWSERINFO; extern BROWSERINFO *browser; - #define FB_NOFOLDER_BTN 0x0001 #define FB_NODEVICE_BTN 0x0002 #define FB_TRYROOTDIR 0x0004 #define FB_TRYSTDDEV 0x0008 #define FB_DEFAULT (FB_TRYROOTDIR | FB_TRYSTDDEV) -typedef int ( *FILEFILTERCALLBACK )( BROWSERENTRY *Entry, void* Args ); -int noDIRS( BROWSERENTRY *Entry, void* Args ); -int noFILES( BROWSERENTRY *Entry, void* Args ); -int noEXT( BROWSERENTRY *Entry, void* Args ); +typedef int (*FILEFILTERCALLBACK)(BROWSERENTRY *Entry, void* Args); +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; + FILEFILTERCALLBACK filter; + void *filter_args; + _FILTERCASCADE *next; } FILTERCASCADE; - - /**************************************************************************** * BrowseDevice * Displays a list of files on the selected path @@ -75,8 +71,8 @@ typedef struct _FILTERCASCADE * * ***************************************************************************/ -int BrowseDevice( char * Path, int Path_size, int Flags/*=FB_DEFAULT*/, FILTERCASCADE *Filter = NULL ) ; -int BrowseDevice( char * Path, int Path_size, int Flags, FILEFILTERCALLBACK Filter, void *FilterArgs = NULL ); +int BrowseDevice(char * Path, int Path_size, int Flags/*=FB_DEFAULT*/, FILTERCASCADE *Filter = NULL); +int BrowseDevice(char * Path, int Path_size, int Flags, FILEFILTERCALLBACK Filter, void *FilterArgs = NULL); #endif diff --git a/source/prompts/gameinfo.cpp b/source/prompts/gameinfo.cpp index 2fdba831..b92e281f 100644 --- a/source/prompts/gameinfo.cpp +++ b/source/prompts/gameinfo.cpp @@ -22,7 +22,6 @@ #include "usbloader/GameList.h" #include "../gecko.h" - /*** Extern variables ***/ extern u8 shutdown; extern u8 reset; @@ -33,21 +32,20 @@ extern struct gameXMLinfo gameinfo_reset; extern void ResumeGui(); extern void HaltGui(); - /**************************************************************************** -* gameinfo -***************************************************************************/ -int showGameInfo( char *ID ) + * gameinfo + ***************************************************************************/ +int showGameInfo(char *ID) { HaltGui();//put this first to try to get rid of the code dump caused by loading this window at the same time as loading images from the SD card - mainWindow->SetState( STATE_DISABLED ); + mainWindow->SetState(STATE_DISABLED); ResumeGui(); bool databaseopened = true; - if ( databaseopened ) + if (databaseopened) { - LoadGameInfoFromXML( ID, Settings.db_language ); + LoadGameInfoFromXML(ID, Settings.db_language); bool showmeminfo = false; @@ -57,20 +55,10 @@ int showGameInfo( char *ID ) int indexy = marginY; 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; + 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; int newline = 1; u8 page = 1; @@ -135,877 +123,875 @@ int showGameInfo( char *ID ) GuiText * wiitdb3Txt = NULL; GuiText * memTxt = NULL; - GuiWindow gameinfoWindow( 600, 308 ); - gameinfoWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - gameinfoWindow.SetPosition( 0, -50 ); + GuiWindow gameinfoWindow(600, 308); + gameinfoWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + gameinfoWindow.SetPosition(0, -50); - GuiWindow gameinfoWindow2( 600, 308 ); - gameinfoWindow2.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - gameinfoWindow2.SetPosition( 0, -50 ); + GuiWindow gameinfoWindow2(600, 308); + gameinfoWindow2.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + gameinfoWindow2.SetPosition(0, -50); - GuiWindow txtWindow( 350, 270 ); - txtWindow.SetAlignment( ALIGN_CENTRE, ALIGN_RIGHT ); - txtWindow.SetPosition( 95, 55 ); + GuiWindow txtWindow(350, 270); + txtWindow.SetAlignment(ALIGN_CENTRE, ALIGN_RIGHT); + txtWindow.SetPosition(95, 55); - GuiSound btnSoundOver( button_over_pcm, button_over_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); + GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sgameinfo1_png.png", Settings.theme_path ); - GuiImageData dialogBox1( imgPath, gameinfo1_png ); - snprintf( imgPath, sizeof( imgPath ), "%sgameinfo1a_png.png", Settings.theme_path ); - GuiImageData dialogBox2( imgPath, gameinfo1a_png ); - snprintf( imgPath, sizeof( imgPath ), "%sgameinfo2_png.png", Settings.theme_path ); - GuiImageData dialogBox3( imgPath, gameinfo2_png ); - snprintf( imgPath, sizeof( imgPath ), "%sgameinfo2a_png.png", Settings.theme_path ); - GuiImageData dialogBox4( imgPath, gameinfo2a_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sgameinfo1_png.png", Settings.theme_path); + GuiImageData dialogBox1(imgPath, gameinfo1_png); + snprintf(imgPath, sizeof(imgPath), "%sgameinfo1a_png.png", Settings.theme_path); + GuiImageData dialogBox2(imgPath, gameinfo1a_png); + snprintf(imgPath, sizeof(imgPath), "%sgameinfo2_png.png", Settings.theme_path); + GuiImageData dialogBox3(imgPath, gameinfo2_png); + snprintf(imgPath, sizeof(imgPath), "%sgameinfo2a_png.png", Settings.theme_path); + GuiImageData dialogBox4(imgPath, gameinfo2a_png); GuiTrigger trig1; - trig1.SetButtonOnlyTrigger( -1, WPAD_BUTTON_1 | WPAD_CLASSIC_BUTTON_X, 0 ); + trig1.SetButtonOnlyTrigger(-1, WPAD_BUTTON_1 | WPAD_CLASSIC_BUTTON_X, 0); GuiTrigger trigA; - trigA.SetButtonOnlyTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigA.SetButtonOnlyTrigger(-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 ); + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); GuiTrigger trigU; - trigU.SetButtonOnlyTrigger( -1, WPAD_BUTTON_UP | WPAD_CLASSIC_BUTTON_UP, PAD_BUTTON_UP ); + trigU.SetButtonOnlyTrigger(-1, WPAD_BUTTON_UP | WPAD_CLASSIC_BUTTON_UP, PAD_BUTTON_UP); GuiTrigger trigD; - trigD.SetButtonOnlyTrigger( -1, WPAD_BUTTON_DOWN | WPAD_CLASSIC_BUTTON_DOWN, PAD_BUTTON_DOWN ); + trigD.SetButtonOnlyTrigger(-1, WPAD_BUTTON_DOWN | WPAD_CLASSIC_BUTTON_DOWN, PAD_BUTTON_DOWN); GuiTrigger trigH; - trigH.SetButtonOnlyTrigger( -1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0 ); + trigH.SetButtonOnlyTrigger(-1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0); //buttons for changing between synopsis and other info - GuiButton backBtn( 0, 0 ); - backBtn.SetPosition( -20, -20 ); - backBtn.SetTrigger( &trigB ); - gameinfoWindow.Append( &backBtn ); + GuiButton backBtn(0, 0); + backBtn.SetPosition(-20, -20); + backBtn.SetTrigger(&trigB); + gameinfoWindow.Append(&backBtn); - GuiButton nextBtn( 0, 0 ); - nextBtn.SetPosition( 20, 20 ); - nextBtn.SetTrigger( &trigA ); - gameinfoWindow.Append( &nextBtn ); + GuiButton nextBtn(0, 0); + nextBtn.SetPosition(20, 20); + nextBtn.SetTrigger(&trigA); + gameinfoWindow.Append(&nextBtn); //buttons for scrolling the synopsis - GuiButton upBtn( 0, 0 ); - upBtn.SetPosition( 0, 0 ); - upBtn.SetTrigger( &trigU ); + GuiButton upBtn(0, 0); + upBtn.SetPosition(0, 0); + upBtn.SetTrigger(&trigU); - GuiButton dnBtn( 0, 0 ); - dnBtn.SetPosition( 0, 0 ); - dnBtn.SetTrigger( &trigD ); + GuiButton dnBtn(0, 0); + dnBtn.SetPosition(0, 0); + dnBtn.SetTrigger(&trigD); - GuiButton homeBtn( 0, 0 ); - homeBtn.SetPosition( 0, 0 ); - homeBtn.SetTrigger( &trigH ); + GuiButton homeBtn(0, 0); + homeBtn.SetPosition(0, 0); + homeBtn.SetTrigger(&trigH); // button to save the url for the zip file for poor people without wifi - GuiButton urlBtn( 0, 0 ); - urlBtn.SetPosition( 0, 0 ); - urlBtn.SetTrigger( &trig1 ); - gameinfoWindow.Append( &urlBtn ); + GuiButton urlBtn(0, 0); + urlBtn.SetPosition(0, 0); + urlBtn.SetTrigger(&trig1); + gameinfoWindow.Append(&urlBtn); char linebuf[XML_SYNOPSISLEN] = ""; char linebuf2[100] = ""; // enable icons for required accessories - for ( int i = 1; i <= XML_ELEMMAX; i++ ) + for (int i = 1; i <= XML_ELEMMAX; i++) { - if ( strcmp( gameinfo.accessoriesReq[i], "classiccontroller" ) == 0 ) - classiccontroller = 1; - if ( strcmp( gameinfo.accessoriesReq[i], "nunchuk" ) == 0 ) - nunchuk = 1; - if ( strcmp( gameinfo.accessoriesReq[i], "guitar" ) == 0 ) - guitar = 1; - if ( strcmp( gameinfo.accessoriesReq[i], "drums" ) == 0 ) - drums = 1; - if ( strcmp( gameinfo.accessoriesReq[i], "dancepad" ) == 0 ) - dancepad = 1; - if ( strcmp( gameinfo.accessoriesReq[i], "motionplus" ) == 0 ) - motionplus = 1; - if ( strcmp( gameinfo.accessoriesReq[i], "wheel" ) == 0 ) - wheel = 1; - if ( strcmp( gameinfo.accessoriesReq[i], "balanceboard" ) == 0 ) - balanceboard = 1; - if ( strcmp( gameinfo.accessoriesReq[i], "microphone" ) == 0 ) - microphone = 1; - if ( strcmp( gameinfo.accessoriesReq[i], "zapper" ) == 0 ) - zapper = 1; - if ( strcmp( gameinfo.accessoriesReq[i], "nintendods" ) == 0 ) - nintendods = 1; - if ( strcmp( gameinfo.accessoriesReq[i], "wiispeak" ) == 0 ) - wiispeak = 1; + if (strcmp(gameinfo.accessoriesReq[i], "classiccontroller") == 0) classiccontroller = 1; + if (strcmp(gameinfo.accessoriesReq[i], "nunchuk") == 0) nunchuk = 1; + if (strcmp(gameinfo.accessoriesReq[i], "guitar") == 0) guitar = 1; + if (strcmp(gameinfo.accessoriesReq[i], "drums") == 0) drums = 1; + if (strcmp(gameinfo.accessoriesReq[i], "dancepad") == 0) dancepad = 1; + if (strcmp(gameinfo.accessoriesReq[i], "motionplus") == 0) motionplus = 1; + if (strcmp(gameinfo.accessoriesReq[i], "wheel") == 0) wheel = 1; + if (strcmp(gameinfo.accessoriesReq[i], "balanceboard") == 0) balanceboard = 1; + if (strcmp(gameinfo.accessoriesReq[i], "microphone") == 0) microphone = 1; + if (strcmp(gameinfo.accessoriesReq[i], "zapper") == 0) zapper = 1; + if (strcmp(gameinfo.accessoriesReq[i], "nintendods") == 0) nintendods = 1; + if (strcmp(gameinfo.accessoriesReq[i], "wiispeak") == 0) wiispeak = 1; //if (strcmp(gameinfo.accessoriesReq[i],"vitalitysensor")==0) // vitalitysensor=1; - if ( strcmp( gameinfo.accessoriesReq[i], "gamecube" ) == 0 ) - gamecube = 1; + if (strcmp(gameinfo.accessoriesReq[i], "gamecube") == 0) gamecube = 1; } // switch icons - if ( nunchuk ) nunchukImgData = new GuiImageData( nunchukR_png ); - else nunchukImgData = new GuiImageData( nunchuk_png ); + if (nunchuk) + nunchukImgData = new GuiImageData(nunchukR_png); + else nunchukImgData = new GuiImageData(nunchuk_png); - if ( classiccontroller ) classiccontrollerImgData = new GuiImageData( classiccontrollerR_png ); - else classiccontrollerImgData = new GuiImageData( classiccontroller_png ); + if (classiccontroller) + classiccontrollerImgData = new GuiImageData(classiccontrollerR_png); + else classiccontrollerImgData = new GuiImageData(classiccontroller_png); - if ( guitar ) guitarImgData = new GuiImageData( guitarR_png ); - else guitarImgData = new GuiImageData( guitar_png ); + if (guitar) + guitarImgData = new GuiImageData(guitarR_png); + else guitarImgData = new GuiImageData(guitar_png); - if ( gamecube ) gamecubeImgData = new GuiImageData( gcncontrollerR_png ); - else gamecubeImgData = new GuiImageData( gcncontroller_png ); + if (gamecube) + gamecubeImgData = new GuiImageData(gcncontrollerR_png); + else gamecubeImgData = new GuiImageData(gcncontroller_png); - if ( wheel ) wheelImgData = new GuiImageData( wheelR_png ); - else wheelImgData = new GuiImageData( wheel_png ); + if (wheel) + wheelImgData = new GuiImageData(wheelR_png); + else wheelImgData = new GuiImageData(wheel_png); - if ( motionplus ) motionplusImgData = new GuiImageData( motionplusR_png ); - else motionplusImgData = new GuiImageData( motionplus_png ); + if (motionplus) + motionplusImgData = new GuiImageData(motionplusR_png); + else motionplusImgData = new GuiImageData(motionplus_png); - if ( drums ) drumsImgData = new GuiImageData( drumsR_png ); - else drumsImgData = new GuiImageData( drums_png ); + if (drums) + drumsImgData = new GuiImageData(drumsR_png); + else drumsImgData = new GuiImageData(drums_png); - if ( microphone ) microphoneImgData = new GuiImageData( microphoneR_png ); - else microphoneImgData = new GuiImageData( microphone_png ); + if (microphone) + microphoneImgData = new GuiImageData(microphoneR_png); + else microphoneImgData = new GuiImageData(microphone_png); - if ( zapper ) zapperImgData = new GuiImageData( zapperR_png ); - else zapperImgData = new GuiImageData( zapper_png ); + if (zapper) + zapperImgData = new GuiImageData(zapperR_png); + else zapperImgData = new GuiImageData(zapper_png); - if ( wiispeak ) wiispeakImgData = new GuiImageData( wiispeakR_png ); - else wiispeakImgData = new GuiImageData( wiispeak_png ); + if (wiispeak) + wiispeakImgData = new GuiImageData(wiispeakR_png); + else wiispeakImgData = new GuiImageData(wiispeak_png); - if ( nintendods ) nintendodsImgData = new GuiImageData( nintendodsR_png ); - else nintendodsImgData = new GuiImageData( nintendods_png ); + if (nintendods) + nintendodsImgData = new GuiImageData(nintendodsR_png); + else nintendodsImgData = new GuiImageData(nintendods_png); //if (vitalitysensor) vitalitysensorImgData = new GuiImageData(vitalitysensorR_png); //else vitalitysensorImgData = new GuiImageData(vitalitysensor_png); - if ( balanceboard ) balanceboardImgData = new GuiImageData( balanceboardR_png ); - else balanceboardImgData = new GuiImageData( balanceboard_png ); + if (balanceboard) + balanceboardImgData = new GuiImageData(balanceboardR_png); + else balanceboardImgData = new GuiImageData(balanceboard_png); - if ( dancepad ) dancepadImgData = new GuiImageData( dancepadR_png ); - else dancepadImgData = new GuiImageData( dancepad_png ); + if (dancepad) + dancepadImgData = new GuiImageData(dancepadR_png); + else dancepadImgData = new GuiImageData(dancepad_png); // look for optional accessories - for ( int i = 1; i <= XML_ELEMMAX; i++ ) + for (int i = 1; i <= XML_ELEMMAX; i++) { - if ( strcmp( gameinfo.accessories[i], "classiccontroller" ) == 0 ) - classiccontroller = 1; - if ( strcmp( gameinfo.accessories[i], "nunchuk" ) == 0 ) - nunchuk = 1; - if ( strcmp( gameinfo.accessories[i], "guitar" ) == 0 ) - guitar = 1; - if ( strcmp( gameinfo.accessories[i], "drums" ) == 0 ) - drums = 1; - if ( strcmp( gameinfo.accessories[i], "dancepad" ) == 0 ) - dancepad = 1; - if ( strcmp( gameinfo.accessories[i], "motionplus" ) == 0 ) - motionplus = 1; - if ( strcmp( gameinfo.accessories[i], "wheel" ) == 0 ) - wheel = 1; - if ( strcmp( gameinfo.accessories[i], "balanceboard" ) == 0 ) - balanceboard = 1; - if ( strcmp( gameinfo.accessories[i], "microphone" ) == 0 ) - microphone = 1; - if ( strcmp( gameinfo.accessories[i], "zapper" ) == 0 ) - zapper = 1; - if ( strcmp( gameinfo.accessories[i], "nintendods" ) == 0 ) - nintendods = 1; - if ( strcmp( gameinfo.accessories[i], "wiispeak" ) == 0 ) - wiispeak = 1; + if (strcmp(gameinfo.accessories[i], "classiccontroller") == 0) classiccontroller = 1; + if (strcmp(gameinfo.accessories[i], "nunchuk") == 0) nunchuk = 1; + if (strcmp(gameinfo.accessories[i], "guitar") == 0) guitar = 1; + if (strcmp(gameinfo.accessories[i], "drums") == 0) drums = 1; + if (strcmp(gameinfo.accessories[i], "dancepad") == 0) dancepad = 1; + if (strcmp(gameinfo.accessories[i], "motionplus") == 0) motionplus = 1; + if (strcmp(gameinfo.accessories[i], "wheel") == 0) wheel = 1; + if (strcmp(gameinfo.accessories[i], "balanceboard") == 0) balanceboard = 1; + if (strcmp(gameinfo.accessories[i], "microphone") == 0) microphone = 1; + if (strcmp(gameinfo.accessories[i], "zapper") == 0) zapper = 1; + if (strcmp(gameinfo.accessories[i], "nintendods") == 0) nintendods = 1; + if (strcmp(gameinfo.accessories[i], "wiispeak") == 0) wiispeak = 1; //if (strcmp(gameinfo.accessories[i],"vitalitysensor")==0) // vitalitysensor=1; - if ( strcmp( gameinfo.accessories[i], "gamecube" ) == 0 ) - gamecube = 1; + if (strcmp(gameinfo.accessories[i], "gamecube") == 0) gamecube = 1; } - dialogBoxImg1 = new GuiImage( &dialogBox1 ); - dialogBoxImg1->SetAlignment( 0, 3 ); - dialogBoxImg1->SetPosition( -9, 0 ); + dialogBoxImg1 = new GuiImage(&dialogBox1); + dialogBoxImg1->SetAlignment(0, 3); + dialogBoxImg1->SetPosition(-9, 0); - dialogBoxImg2 = new GuiImage( &dialogBox2 ); - dialogBoxImg2->SetAlignment( 0, 3 ); - dialogBoxImg2->SetPosition( 145, 0 ); + dialogBoxImg2 = new GuiImage(&dialogBox2); + dialogBoxImg2->SetAlignment(0, 3); + dialogBoxImg2->SetPosition(145, 0); - dialogBoxImg3 = new GuiImage( &dialogBox3 ); - dialogBoxImg3->SetAlignment( 0, 3 ); - dialogBoxImg3->SetPosition( 301, 0 ); + dialogBoxImg3 = new GuiImage(&dialogBox3); + dialogBoxImg3->SetAlignment(0, 3); + dialogBoxImg3->SetPosition(301, 0); - dialogBoxImg4 = new GuiImage( &dialogBox4 ); - dialogBoxImg4->SetAlignment( 0, 3 ); - dialogBoxImg4->SetPosition( 457, 0 ); + dialogBoxImg4 = new GuiImage(&dialogBox4); + dialogBoxImg4->SetAlignment(0, 3); + dialogBoxImg4->SetPosition(457, 0); - gameinfoWindow.Append( dialogBoxImg1 ); - gameinfoWindow.Append( dialogBoxImg2 ); - gameinfoWindow.Append( dialogBoxImg3 ); - gameinfoWindow.Append( dialogBoxImg4 ); + gameinfoWindow.Append(dialogBoxImg1); + gameinfoWindow.Append(dialogBoxImg2); + gameinfoWindow.Append(dialogBoxImg3); + gameinfoWindow.Append(dialogBoxImg4); - snprintf( imgPath, sizeof( imgPath ), "%s%s.png", Settings.covers_path, ID ); - cover = new GuiImageData( imgPath, 0 ); //load full id image - if ( !cover->GetImage() ) + snprintf(imgPath, sizeof(imgPath), "%s%s.png", Settings.covers_path, ID); + cover = new GuiImageData(imgPath, 0); //load full id image + if (!cover->GetImage()) { delete cover; - snprintf( imgPath, sizeof( imgPath ), "%snoimage.png", Settings.covers_path ); - cover = new GuiImageData( imgPath, nocover_png ); //load no image + snprintf(imgPath, sizeof(imgPath), "%snoimage.png", Settings.covers_path); + cover = new GuiImageData(imgPath, nocover_png); //load no image } delete coverImg; coverImg = NULL; - coverImg = new GuiImage( cover ); - coverImg->SetWidescreen( Settings.widescreen ); - coverImg->SetPosition( 15, 30 ); - gameinfoWindow.Append( coverImg ); + coverImg = new GuiImage(cover); + coverImg->SetWidescreen(Settings.widescreen); + coverImg->SetPosition(15, 30); + gameinfoWindow.Append(coverImg); // # of players - if ( strcmp( gameinfo.players, "" ) != 0 ) + if (strcmp(gameinfo.players, "") != 0) { - playersImgData = new GuiImageData( Wiimote1_png ); - if ( atoi( gameinfo.players ) > 1 ) + playersImgData = new GuiImageData(Wiimote1_png); + if (atoi(gameinfo.players) > 1) { - playersImgData = new GuiImageData( Wiimote2_png ); + playersImgData = new GuiImageData(Wiimote2_png); } - if ( atoi( gameinfo.players ) > 2 ) + if (atoi(gameinfo.players) > 2) { - playersImgData = new GuiImageData( Wiimote4_png ); + playersImgData = new GuiImageData(Wiimote4_png); } - playersImg = new GuiImage( playersImgData ); - playersImg->SetWidescreen( Settings.widescreen ); - playersImg->SetPosition( intputX , inputY ); - playersImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( playersImg ); - intputX += ( Settings.widescreen ? playersImg->GetWidth() * .8 : playersImg->GetWidth() ) + 5; + playersImg = new GuiImage(playersImgData); + playersImg->SetWidescreen(Settings.widescreen); + playersImg->SetPosition(intputX, inputY); + playersImg->SetAlignment(0, 4); + gameinfoWindow.Append(playersImg); + intputX += (Settings.widescreen ? playersImg->GetWidth() * .8 : playersImg->GetWidth()) + 5; } //draw the input types for this game - if ( motionplus == 1 ) + if (motionplus == 1) { - motionplusImg = new GuiImage( motionplusImgData ); - motionplusImg->SetWidescreen( Settings.widescreen ); - motionplusImg->SetPosition( intputX , inputY ); - motionplusImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( motionplusImg ); - intputX += ( Settings.widescreen ? motionplusImg->GetWidth() * .8 : motionplusImg->GetWidth() ) + 5; + motionplusImg = new GuiImage(motionplusImgData); + motionplusImg->SetWidescreen(Settings.widescreen); + motionplusImg->SetPosition(intputX, inputY); + motionplusImg->SetAlignment(0, 4); + gameinfoWindow.Append(motionplusImg); + intputX += (Settings.widescreen ? motionplusImg->GetWidth() * .8 : motionplusImg->GetWidth()) + 5; } - if ( nunchuk == 1 ) + if (nunchuk == 1) { - nunchukImg = new GuiImage( nunchukImgData ); - nunchukImg->SetWidescreen( Settings.widescreen ); - nunchukImg->SetPosition( intputX , inputY ); - nunchukImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( nunchukImg ); - intputX += ( Settings.widescreen ? nunchukImg->GetWidth() * .8 : nunchukImg->GetWidth() ) + 5; + nunchukImg = new GuiImage(nunchukImgData); + nunchukImg->SetWidescreen(Settings.widescreen); + nunchukImg->SetPosition(intputX, inputY); + nunchukImg->SetAlignment(0, 4); + gameinfoWindow.Append(nunchukImg); + intputX += (Settings.widescreen ? nunchukImg->GetWidth() * .8 : nunchukImg->GetWidth()) + 5; } - if ( classiccontroller == 1 ) + if (classiccontroller == 1) { - classiccontrollerImg = new GuiImage( classiccontrollerImgData ); - classiccontrollerImg->SetWidescreen( Settings.widescreen ); - classiccontrollerImg->SetPosition( intputX , inputY ); - classiccontrollerImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( classiccontrollerImg ); - intputX += ( Settings.widescreen ? classiccontrollerImg->GetWidth() * .8 : classiccontrollerImg->GetWidth() ) + 5; + classiccontrollerImg = new GuiImage(classiccontrollerImgData); + classiccontrollerImg->SetWidescreen(Settings.widescreen); + classiccontrollerImg->SetPosition(intputX, inputY); + classiccontrollerImg->SetAlignment(0, 4); + gameinfoWindow.Append(classiccontrollerImg); + intputX += (Settings.widescreen ? classiccontrollerImg->GetWidth() * .8 : classiccontrollerImg->GetWidth()) + + 5; } - if ( gamecube == 1 ) + if (gamecube == 1) { - gcImg = new GuiImage( gamecubeImgData ); - gcImg->SetWidescreen( Settings.widescreen ); - gcImg->SetPosition( intputX , inputY ); - gcImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( gcImg ); - intputX += ( Settings.widescreen ? gcImg->GetWidth() * .8 : gcImg->GetWidth() ) + 5; + gcImg = new GuiImage(gamecubeImgData); + gcImg->SetWidescreen(Settings.widescreen); + gcImg->SetPosition(intputX, inputY); + gcImg->SetAlignment(0, 4); + gameinfoWindow.Append(gcImg); + intputX += (Settings.widescreen ? gcImg->GetWidth() * .8 : gcImg->GetWidth()) + 5; } - if ( wheel == 1 ) + if (wheel == 1) { - wheelImg = new GuiImage( wheelImgData ); - wheelImg->SetWidescreen( Settings.widescreen ); - wheelImg->SetPosition( intputX , inputY ); - wheelImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( wheelImg ); - intputX += ( Settings.widescreen ? wheelImg->GetWidth() * .8 : wheelImg->GetWidth() ) + 5; + wheelImg = new GuiImage(wheelImgData); + wheelImg->SetWidescreen(Settings.widescreen); + wheelImg->SetPosition(intputX, inputY); + wheelImg->SetAlignment(0, 4); + gameinfoWindow.Append(wheelImg); + intputX += (Settings.widescreen ? wheelImg->GetWidth() * .8 : wheelImg->GetWidth()) + 5; } - if ( guitar == 1 ) + if (guitar == 1) { - guitarImg = new GuiImage( guitarImgData ); - guitarImg->SetWidescreen( Settings.widescreen ); - guitarImg->SetPosition( intputX , inputY ); - guitarImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( guitarImg ); - intputX += ( Settings.widescreen ? guitarImg->GetWidth() * .8 : guitarImg->GetWidth() ) + 5; + guitarImg = new GuiImage(guitarImgData); + guitarImg->SetWidescreen(Settings.widescreen); + guitarImg->SetPosition(intputX, inputY); + guitarImg->SetAlignment(0, 4); + gameinfoWindow.Append(guitarImg); + intputX += (Settings.widescreen ? guitarImg->GetWidth() * .8 : guitarImg->GetWidth()) + 5; } - if ( drums == 1 ) + if (drums == 1) { - drumsImg = new GuiImage( drumsImgData ); - drumsImg->SetWidescreen( Settings.widescreen ); - drumsImg->SetPosition( intputX , inputY ); - drumsImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( drumsImg ); - intputX += ( Settings.widescreen ? drumsImg->GetWidth() * .8 : drumsImg->GetWidth() ) + 5; + drumsImg = new GuiImage(drumsImgData); + drumsImg->SetWidescreen(Settings.widescreen); + drumsImg->SetPosition(intputX, inputY); + drumsImg->SetAlignment(0, 4); + gameinfoWindow.Append(drumsImg); + intputX += (Settings.widescreen ? drumsImg->GetWidth() * .8 : drumsImg->GetWidth()) + 5; } - if ( microphone == 1 ) + if (microphone == 1) { - microphoneImg = new GuiImage( microphoneImgData ); - microphoneImg->SetWidescreen( Settings.widescreen ); - microphoneImg->SetPosition( intputX , inputY ); - microphoneImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( microphoneImg ); - intputX += ( Settings.widescreen ? microphoneImg->GetWidth() * .8 : microphoneImg->GetWidth() ) + 5; + microphoneImg = new GuiImage(microphoneImgData); + microphoneImg->SetWidescreen(Settings.widescreen); + microphoneImg->SetPosition(intputX, inputY); + microphoneImg->SetAlignment(0, 4); + gameinfoWindow.Append(microphoneImg); + intputX += (Settings.widescreen ? microphoneImg->GetWidth() * .8 : microphoneImg->GetWidth()) + 5; } - if ( zapper == 1 ) + if (zapper == 1) { - zapperImg = new GuiImage( zapperImgData ); - zapperImg->SetWidescreen( Settings.widescreen ); - zapperImg->SetPosition( intputX , inputY ); - zapperImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( zapperImg ); - intputX += ( Settings.widescreen ? zapperImg->GetWidth() * .8 : zapperImg->GetWidth() ) + 5; + zapperImg = new GuiImage(zapperImgData); + zapperImg->SetWidescreen(Settings.widescreen); + zapperImg->SetPosition(intputX, inputY); + zapperImg->SetAlignment(0, 4); + gameinfoWindow.Append(zapperImg); + intputX += (Settings.widescreen ? zapperImg->GetWidth() * .8 : zapperImg->GetWidth()) + 5; } - if ( wiispeak == 1 ) + if (wiispeak == 1) { - wiispeakImg = new GuiImage( wiispeakImgData ); - wiispeakImg->SetWidescreen( Settings.widescreen ); - wiispeakImg->SetPosition( intputX , inputY ); - wiispeakImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( wiispeakImg ); - intputX += ( Settings.widescreen ? wiispeakImg->GetWidth() * .8 : wiispeakImg->GetWidth() ) + 5; + wiispeakImg = new GuiImage(wiispeakImgData); + wiispeakImg->SetWidescreen(Settings.widescreen); + wiispeakImg->SetPosition(intputX, inputY); + wiispeakImg->SetAlignment(0, 4); + gameinfoWindow.Append(wiispeakImg); + intputX += (Settings.widescreen ? wiispeakImg->GetWidth() * .8 : wiispeakImg->GetWidth()) + 5; } - if ( nintendods == 1 ) + if (nintendods == 1) { - nintendodsImg = new GuiImage( nintendodsImgData ); - nintendodsImg->SetWidescreen( Settings.widescreen ); - nintendodsImg->SetPosition( intputX , inputY ); - nintendodsImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( nintendodsImg ); - intputX += ( Settings.widescreen ? nintendodsImg->GetWidth() * .8 : nintendodsImg->GetWidth() ) + 5; + nintendodsImg = new GuiImage(nintendodsImgData); + nintendodsImg->SetWidescreen(Settings.widescreen); + nintendodsImg->SetPosition(intputX, inputY); + nintendodsImg->SetAlignment(0, 4); + gameinfoWindow.Append(nintendodsImg); + intputX += (Settings.widescreen ? nintendodsImg->GetWidth() * .8 : nintendodsImg->GetWidth()) + 5; } /* - if (vitalitysensor==1) { - vitalitysensorImg = new GuiImage(vitalitysensorImgData); - vitalitysensorImg->SetWidescreen(Settings.widescreen); - vitalitysensorImg->SetPosition(intputX , inputY); - vitalitysensorImg->SetAlignment(0,4); - gameinfoWindow.Append(vitalitysensorImg); - intputX += (Settings.widescreen ? vitalitysensorImg->GetWidth() * .8 : vitalitysensorImg->GetWidth())+5; - } - */ - if ( dancepad == 1 ) + if (vitalitysensor==1) { + vitalitysensorImg = new GuiImage(vitalitysensorImgData); + vitalitysensorImg->SetWidescreen(Settings.widescreen); + vitalitysensorImg->SetPosition(intputX , inputY); + vitalitysensorImg->SetAlignment(0,4); + gameinfoWindow.Append(vitalitysensorImg); + intputX += (Settings.widescreen ? vitalitysensorImg->GetWidth() * .8 : vitalitysensorImg->GetWidth())+5; + } + */ + if (dancepad == 1) { - dancepadImg = new GuiImage( dancepadImgData ); - dancepadImg->SetWidescreen( Settings.widescreen ); - dancepadImg->SetPosition( intputX , inputY ); - dancepadImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( dancepadImg ); - intputX += ( Settings.widescreen ? dancepadImg->GetWidth() * .8 : dancepadImg->GetWidth() ) + 5; + dancepadImg = new GuiImage(dancepadImgData); + dancepadImg->SetWidescreen(Settings.widescreen); + dancepadImg->SetPosition(intputX, inputY); + dancepadImg->SetAlignment(0, 4); + gameinfoWindow.Append(dancepadImg); + intputX += (Settings.widescreen ? dancepadImg->GetWidth() * .8 : dancepadImg->GetWidth()) + 5; } - if ( balanceboard == 1 ) + if (balanceboard == 1) { - balanceboardImg = new GuiImage( balanceboardImgData ); - balanceboardImg->SetWidescreen( Settings.widescreen ); - balanceboardImg->SetPosition( intputX , inputY ); - balanceboardImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( balanceboardImg ); - intputX += ( Settings.widescreen ? balanceboardImg->GetWidth() * .8 : balanceboardImg->GetWidth() ) + 5; + balanceboardImg = new GuiImage(balanceboardImgData); + balanceboardImg->SetWidescreen(Settings.widescreen); + balanceboardImg->SetPosition(intputX, inputY); + balanceboardImg->SetAlignment(0, 4); + gameinfoWindow.Append(balanceboardImg); + intputX += (Settings.widescreen ? balanceboardImg->GetWidth() * .8 : balanceboardImg->GetWidth()) + 5; } // # online players - if ( ( strcmp( gameinfo.wifiplayers, "" ) != 0 ) && ( strcmp( gameinfo.wifiplayers, "0" ) != 0 ) ) + if ((strcmp(gameinfo.wifiplayers, "") != 0) && (strcmp(gameinfo.wifiplayers, "0") != 0)) { - wifiplayersImgData = new GuiImageData( wifi1_png ); - if ( atoi( gameinfo.wifiplayers ) > 1 ) + wifiplayersImgData = new GuiImageData(wifi1_png); + if (atoi(gameinfo.wifiplayers) > 1) { - wifiplayersImgData = new GuiImageData( wifi2_png ); + wifiplayersImgData = new GuiImageData(wifi2_png); } - if ( atoi( gameinfo.wifiplayers ) > 2 ) + if (atoi(gameinfo.wifiplayers) > 2) { - wifiplayersImgData = new GuiImageData( wifi4_png ); + wifiplayersImgData = new GuiImageData(wifi4_png); } - if ( atoi( gameinfo.wifiplayers ) > 4 ) + if (atoi(gameinfo.wifiplayers) > 4) { //wifiplayersImgData= new GuiImageData(wifi6_png); - wifiplayersImgData = new GuiImageData( wifi8_png ); + wifiplayersImgData = new GuiImageData(wifi8_png); } /* - if (atoi(gameinfo.wifiplayers)>6) { - wifiplayersImgData= new GuiImageData(wifi8_png); - } - */ - if ( atoi( gameinfo.wifiplayers ) > 8 ) + 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 ) + if (atoi(gameinfo.wifiplayers) > 12) { - wifiplayersImgData = new GuiImageData( wifi16_png ); + wifiplayersImgData = new GuiImageData(wifi16_png); } - if ( atoi( gameinfo.wifiplayers ) > 16 ) + if (atoi(gameinfo.wifiplayers) > 16) { - wifiplayersImgData = new GuiImageData( wifi32_png ); + wifiplayersImgData = new GuiImageData(wifi32_png); } - wifiplayersImg = new GuiImage( wifiplayersImgData ); - wifiplayersImg->SetWidescreen( Settings.widescreen ); - wifiplayersImg->SetPosition( intputX , inputY ); - wifiplayersImg->SetAlignment( 0, 4 ); - gameinfoWindow.Append( wifiplayersImg ); - intputX += ( Settings.widescreen ? wifiplayersImg->GetWidth() * .8 : wifiplayersImg->GetWidth() ) + 5; + wifiplayersImg = new GuiImage(wifiplayersImgData); + wifiplayersImg->SetWidescreen(Settings.widescreen); + wifiplayersImg->SetPosition(intputX, inputY); + wifiplayersImg->SetAlignment(0, 4); + gameinfoWindow.Append(wifiplayersImg); + intputX += (Settings.widescreen ? wifiplayersImg->GetWidth() * .8 : wifiplayersImg->GetWidth()) + 5; } // ratings - if ( strcmp( gameinfo.ratingtype, "" ) != 0 ) + if (strcmp(gameinfo.ratingtype, "") != 0) { - if ( strcmp( gameinfo.ratingtype, "ESRB" ) == 0 ) + if (strcmp(gameinfo.ratingtype, "ESRB") == 0) { - if ( strcmp( gameinfo.ratingvalueESRB, "EC" ) == 0 ) - ratingImgData = new GuiImageData( esrb_ec_png ); - else if ( strcmp( gameinfo.ratingvalueESRB, "E" ) == 0 ) - ratingImgData = new GuiImageData( esrb_e_png ); - else if ( strcmp( gameinfo.ratingvalueESRB, "E10+" ) == 0 ) - ratingImgData = new GuiImageData( esrb_eten_png ); - else if ( strcmp( gameinfo.ratingvalueESRB, "T" ) == 0 ) - ratingImgData = new GuiImageData( esrb_t_png ); - else if ( strcmp( gameinfo.ratingvalueESRB, "M" ) == 0 ) - ratingImgData = new GuiImageData( esrb_m_png ); - else if ( strcmp( gameinfo.ratingvalueESRB, "AO" ) == 0 ) - ratingImgData = new GuiImageData( esrb_ao_png ); + if (strcmp(gameinfo.ratingvalueESRB, "EC") == 0) + ratingImgData = new GuiImageData(esrb_ec_png); + else if (strcmp(gameinfo.ratingvalueESRB, "E") == 0) + ratingImgData = new GuiImageData(esrb_e_png); + else if (strcmp(gameinfo.ratingvalueESRB, "E10+") == 0) + ratingImgData = new GuiImageData(esrb_eten_png); + else if (strcmp(gameinfo.ratingvalueESRB, "T") == 0) + ratingImgData = new GuiImageData(esrb_t_png); + else if (strcmp(gameinfo.ratingvalueESRB, "M") == 0) + ratingImgData = new GuiImageData(esrb_m_png); + else if (strcmp(gameinfo.ratingvalueESRB, "AO") == 0) + ratingImgData = new GuiImageData(esrb_ao_png); else { - ratingImgData = new GuiImageData( norating_png ); + ratingImgData = new GuiImageData(norating_png); } - } //there are 2 values here cause some countries are stupid and - else if ( strcmp( gameinfo.ratingtype, "PEGI" ) == 0 ) //can't use the same as everybody else + } //there are 2 values here cause some countries are stupid and + else if (strcmp(gameinfo.ratingtype, "PEGI") == 0) //can't use the same as everybody else { - if ( ( strcmp( gameinfo.ratingvaluePEGI, "3" ) == 0 ) || ( strcmp( gameinfo.ratingvaluePEGI, "4" ) == 0 ) ) - ratingImgData = new GuiImageData( pegi_3_png ); - else if ( ( strcmp( gameinfo.ratingvaluePEGI, "7" ) == 0 ) || ( strcmp( gameinfo.ratingvaluePEGI, "7" ) == 0 ) ) - ratingImgData = new GuiImageData( pegi_7_png ); - else if ( strcmp( gameinfo.ratingvaluePEGI, "12" ) == 0 ) - ratingImgData = new GuiImageData( pegi_12_png ); - else if ( ( strcmp( gameinfo.ratingvaluePEGI, "16" ) == 0 ) || ( strcmp( gameinfo.ratingvaluePEGI, "15" ) == 0 ) ) - ratingImgData = new GuiImageData( pegi_16_png ); - else if ( strcmp( gameinfo.ratingvaluePEGI, "18" ) == 0 ) - ratingImgData = new GuiImageData( pegi_18_png ); + if ((strcmp(gameinfo.ratingvaluePEGI, "3") == 0) || (strcmp(gameinfo.ratingvaluePEGI, "4") == 0)) + ratingImgData = new GuiImageData(pegi_3_png); + else if ((strcmp(gameinfo.ratingvaluePEGI, "7") == 0) || (strcmp(gameinfo.ratingvaluePEGI, "7") == 0)) + ratingImgData = new GuiImageData(pegi_7_png); + else if (strcmp(gameinfo.ratingvaluePEGI, "12") == 0) + ratingImgData = new GuiImageData(pegi_12_png); + else if ((strcmp(gameinfo.ratingvaluePEGI, "16") == 0) || (strcmp(gameinfo.ratingvaluePEGI, "15") == 0)) + ratingImgData = new GuiImageData(pegi_16_png); + else if (strcmp(gameinfo.ratingvaluePEGI, "18") == 0) + ratingImgData = new GuiImageData(pegi_18_png); else { - ratingImgData = new GuiImageData( norating_png ); + ratingImgData = new GuiImageData(norating_png); } } - else if ( strcmp( gameinfo.ratingtype, "CERO" ) == 0 ) + else if (strcmp(gameinfo.ratingtype, "CERO") == 0) { - if ( strcmp( gameinfo.ratingvalueCERO, "A" ) == 0 ) - ratingImgData = new GuiImageData( cero_a_png ); - else if ( strcmp( gameinfo.ratingvalueCERO, "B" ) == 0 ) - ratingImgData = new GuiImageData( cero_b_png ); - else if ( strcmp( gameinfo.ratingvalueCERO, "C" ) == 0 ) - ratingImgData = new GuiImageData( cero_c_png ); - else if ( strcmp( gameinfo.ratingvalueCERO, "D" ) == 0 ) - ratingImgData = new GuiImageData( cero_d_png ); - else if ( strcmp( gameinfo.ratingvalueCERO, "Z" ) == 0 ) - ratingImgData = new GuiImageData( cero_z_png ); + if (strcmp(gameinfo.ratingvalueCERO, "A") == 0) + ratingImgData = new GuiImageData(cero_a_png); + else if (strcmp(gameinfo.ratingvalueCERO, "B") == 0) + ratingImgData = new GuiImageData(cero_b_png); + else if (strcmp(gameinfo.ratingvalueCERO, "C") == 0) + ratingImgData = new GuiImageData(cero_c_png); + else if (strcmp(gameinfo.ratingvalueCERO, "D") == 0) + ratingImgData = new GuiImageData(cero_d_png); + else if (strcmp(gameinfo.ratingvalueCERO, "Z") == 0) + ratingImgData = new GuiImageData(cero_z_png); else { - ratingImgData = new GuiImageData( norating_png ); + ratingImgData = new GuiImageData(norating_png); } } else { - ratingImgData = new GuiImageData( norating_png ); + ratingImgData = new GuiImageData(norating_png); } - ratingImg = new GuiImage( ratingImgData ); - ratingImg->SetWidescreen( Settings.widescreen ); - ratingImg->SetPosition( -25 , inputY ); - ratingImg->SetAlignment( 1, 4 ); - gameinfoWindow.Append( ratingImg ); - intputX += ( Settings.widescreen ? ratingImg->GetWidth() * .8 : ratingImg->GetWidth() ) + 5; + ratingImg = new GuiImage(ratingImgData); + ratingImg->SetWidescreen(Settings.widescreen); + ratingImg->SetPosition(-25, inputY); + ratingImg->SetAlignment(1, 4); + gameinfoWindow.Append(ratingImg); + intputX += (Settings.widescreen ? ratingImg->GetWidth() * .8 : ratingImg->GetWidth()) + 5; } // memory info - if ( showmeminfo ) + if (showmeminfo) { 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->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - memTxt->SetPosition( 0, 0 ); - gameinfoWindow.Append( memTxt ); + strlcpy(meminfotxt, MemInfo(), sizeof(meminfotxt)); + snprintf(linebuf, sizeof(linebuf), "%s", meminfotxt); + memTxt = new GuiText(linebuf, 18, ( GXColor ) + { 0, 0, 0, 255}); + memTxt->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + memTxt->SetPosition(0, 0); + gameinfoWindow.Append(memTxt); } // title int titlefontsize = 25; - if ( strcmp( gameinfo.title, "" ) != 0 ) + if (strcmp(gameinfo.title, "") != 0) { - snprintf( linebuf, sizeof( linebuf ), "%s", gameinfo.title ); - titleTxt = new GuiText( linebuf, titlefontsize, ( GXColor ) {0, 0, 0, 255} ); - titleTxt->SetMaxWidth( 350, SCROLL_HORIZONTAL ); + snprintf(linebuf, sizeof(linebuf), "%s", gameinfo.title); + titleTxt = new GuiText(linebuf, titlefontsize, ( GXColor ) + { 0, 0, 0, 255}); + titleTxt->SetMaxWidth(350, SCROLL_HORIZONTAL); //while (titleTxt->GetWidth()>250) { titleTxt->SetFontSize(titlefontsize-=2); } - titleTxt->SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt->SetPosition( txtXOffset, 12 + titley ); - gameinfoWindow.Append( titleTxt ); + titleTxt->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt->SetPosition(txtXOffset, 12 + titley); + gameinfoWindow.Append(titleTxt); } //date - snprintf( linebuf2, sizeof( linebuf2 ), " " ); - if ( strcmp( gameinfo.day, "" ) != 0 ) + snprintf(linebuf2, sizeof(linebuf2), " "); + if (strcmp(gameinfo.day, "") != 0) { - snprintf( linebuf2, sizeof( linebuf2 ), "%s ", gameinfo.day ); + snprintf(linebuf2, sizeof(linebuf2), "%s ", gameinfo.day); } - if ( strcmp( gameinfo.month, "" ) != 0 ) + if (strcmp(gameinfo.month, "") != 0) { - switch ( atoi( gameinfo.month ) ) + switch (atoi(gameinfo.month)) { case 1: - snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Jan" ) ); + snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr( "Jan" )); break; case 2: - snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Feb" ) ); + snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr( "Feb" )); break; case 3: - snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Mar" ) ); + snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr( "Mar" )); break; case 4: - snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Apr" ) ); + snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr( "Apr" )); break; case 5: - snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "May" ) ); + snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr( "May" )); break; case 6: - snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "June" ) ); + snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr( "June" )); break; case 7: - snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "July" ) ); + snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr( "July" )); break; case 8: - snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Aug" ) ); + snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr( "Aug" )); break; case 9: - snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Sept" ) ); + snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr( "Sept" )); break; case 10: - snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Oct" ) ); + snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr( "Oct" )); break; case 11: - snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Nov" ) ); + snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr( "Nov" )); break; case 12: - snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Dec" ) ); + snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr( "Dec" )); break; } } - if ( strcmp( gameinfo.year, "" ) != 0 ) + 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} ); - if ( releasedTxt->GetWidth() > 300 ) newline = 2; - releasedTxt->SetAlignment( ALIGN_RIGHT, ALIGN_TOP ); - releasedTxt->SetPosition( -17, 12 + indexy ); - indexy += ( 20 * newline ); + snprintf(linebuf, sizeof(linebuf), "%s : %s%s", tr( "Released" ), linebuf2, gameinfo.year); + 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); + indexy += (20 * newline); newline = 1; - gameinfoWindow.Append( releasedTxt ); + gameinfoWindow.Append(releasedTxt); } //publisher - if ( strcmp( gameinfo.publisher, "" ) != 0 ) + 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} ); - if ( publisherTxt->GetWidth() > 250 ) newline = 2; - publisherTxt->SetMaxWidth( 250, WRAP ); - publisherTxt->SetAlignment( ALIGN_RIGHT, ALIGN_TOP ); - publisherTxt->SetPosition( -17, 12 + indexy ); - indexy += ( 20 * newline ); + snprintf(linebuf, sizeof(linebuf), "%s %s", tr( "Published by" ), gameinfo.publisher); + publisherTxt = new GuiText(linebuf, 16, ( GXColor ) + { 0, 0, 0, 255}); + if (publisherTxt->GetWidth() > 250) newline = 2; + publisherTxt->SetMaxWidth(250, WRAP); + publisherTxt->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + publisherTxt->SetPosition(-17, 12 + indexy); + indexy += (20 * newline); newline = 1; - gameinfoWindow.Append( publisherTxt ); + gameinfoWindow.Append(publisherTxt); } //developer - if ( strcmp( gameinfo.developer, "" ) != 0 && strcasecmp( gameinfo.developer, gameinfo.publisher ) != 0 ) + 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} ); - if ( developerTxt->GetWidth() > 250 ) newline = 2; - developerTxt->SetMaxWidth( 250, WRAP ); - developerTxt->SetAlignment( ALIGN_RIGHT, ALIGN_TOP ); - developerTxt->SetPosition( -17, 12 + indexy ); - indexy += ( 20 * newline ); + snprintf(linebuf, sizeof(linebuf), "%s %s", tr( "Developed by" ), gameinfo.developer); + developerTxt = new GuiText(linebuf, 16, ( GXColor ) + { 0, 0, 0, 255}); + if (developerTxt->GetWidth() > 250) newline = 2; + developerTxt->SetMaxWidth(250, WRAP); + developerTxt->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); + developerTxt->SetPosition(-17, 12 + indexy); + indexy += (20 * newline); newline = 1; - gameinfoWindow.Append( developerTxt ); + gameinfoWindow.Append(developerTxt); } //genre int genreY = marginY; - genreTxt = new GuiText * [gameinfo.genreCnt + 1]; - for ( int i = 1; i <= gameinfo.genreCnt; i++ ) + 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]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - genreTxt[i]->SetPosition( 205, 12 + genreY ); + snprintf(linebuf, sizeof(linebuf), "%s", gameinfo.genresplit[i]); + 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; - gameinfoWindow.Append( genreTxt[i] ); + gameinfoWindow.Append(genreTxt[i]); } //online - wifiTxt = new GuiText * [gameinfo.wifiCnt + 1]; - for ( int i = gameinfo.wifiCnt; i >= 1; i-- ) + wifiTxt = new GuiText *[gameinfo.wifiCnt + 1]; + for (int i = gameinfo.wifiCnt; i >= 1; i--) { - if ( strcmp( gameinfo.wififeatures[i], "Nintendods" ) == 0 ) + if (strcmp(gameinfo.wififeatures[i], "Nintendods") == 0) { - snprintf( linebuf, sizeof( linebuf ), "Nintendo DS" ); + snprintf(linebuf, sizeof(linebuf), "Nintendo DS"); } else { - snprintf( linebuf, sizeof( linebuf ), "%s", gameinfo.wififeatures[i] ); + snprintf(linebuf, sizeof(linebuf), "%s", gameinfo.wififeatures[i]); } - wifiTxt[i] = new GuiText( linebuf, 16, ( GXColor ) {0, 0, 0, 255} ); - wifiTxt[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - wifiTxt[i]->SetPosition( 215, 200 + wifiY ); + 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; - gameinfoWindow.Append( wifiTxt[i] ); + gameinfoWindow.Append(wifiTxt[i]); } - if ( strcmp( gameinfo.wififeatures[1], "" ) != 0 ) + if (strcmp(gameinfo.wififeatures[1], "") != 0) { - snprintf( linebuf, sizeof( linebuf ), "%s:", tr( "WiFi Features" ) ); + snprintf(linebuf, sizeof(linebuf), "%s:", tr( "WiFi Features" )); } else { - strcpy( linebuf, "" ); + strcpy(linebuf, ""); } - 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] ); + 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]); //synopsis int pagesize = 12; - if ( strcmp( gameinfo.synopsis, "" ) != 0 ) + if (strcmp(gameinfo.synopsis, "") != 0) { - snprintf( linebuf, sizeof( linebuf ), "%s", gameinfo.synopsis ); - synopsisTxt = new Text( linebuf, 16, ( GXColor ) {0, 0, 0, 255} ); - synopsisTxt->SetMaxWidth( 350 ); - synopsisTxt->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - synopsisTxt->SetPosition( 0, 0 ); - synopsisTxt->SetLinesToDraw( pagesize ); + snprintf(linebuf, sizeof(linebuf), "%s", gameinfo.synopsis); + synopsisTxt = new Text(linebuf, 16, ( GXColor ) + { 0, 0, 0, 255}); + synopsisTxt->SetMaxWidth(350); + synopsisTxt->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + synopsisTxt->SetPosition(0, 0); + synopsisTxt->SetLinesToDraw(pagesize); synopsisTxt->Refresh(); - dialogBoxImg11 = new GuiImage( &dialogBox1 ); - dialogBoxImg11->SetAlignment( 0, 3 ); - dialogBoxImg11->SetPosition( -9, 0 ); + dialogBoxImg11 = new GuiImage(&dialogBox1); + dialogBoxImg11->SetAlignment(0, 3); + dialogBoxImg11->SetPosition(-9, 0); - dialogBoxImg22 = new GuiImage( &dialogBox2 ); - dialogBoxImg22->SetAlignment( 0, 3 ); - dialogBoxImg22->SetPosition( 145, 0 ); + dialogBoxImg22 = new GuiImage(&dialogBox2); + dialogBoxImg22->SetAlignment(0, 3); + dialogBoxImg22->SetPosition(145, 0); - dialogBoxImg33 = new GuiImage( &dialogBox3 ); - dialogBoxImg33->SetAlignment( 0, 3 ); - dialogBoxImg33->SetPosition( 301, 0 ); + dialogBoxImg33 = new GuiImage(&dialogBox3); + dialogBoxImg33->SetAlignment(0, 3); + dialogBoxImg33->SetPosition(301, 0); - dialogBoxImg44 = new GuiImage( &dialogBox4 ); - dialogBoxImg44->SetAlignment( 0, 3 ); - dialogBoxImg44->SetPosition( 457, 0 ); + dialogBoxImg44 = new GuiImage(&dialogBox4); + dialogBoxImg44->SetAlignment(0, 3); + dialogBoxImg44->SetPosition(457, 0); - gameinfoWindow2.Append( dialogBoxImg11 ); - gameinfoWindow2.Append( dialogBoxImg22 ); - gameinfoWindow2.Append( dialogBoxImg33 ); - gameinfoWindow2.Append( dialogBoxImg44 ); + gameinfoWindow2.Append(dialogBoxImg11); + gameinfoWindow2.Append(dialogBoxImg22); + gameinfoWindow2.Append(dialogBoxImg33); + gameinfoWindow2.Append(dialogBoxImg44); - txtWindow.Append( synopsisTxt ); - txtWindow.Append( &upBtn ); - txtWindow.Append( &dnBtn ); - coverImg2 = new GuiImage( cover ); - coverImg2->SetWidescreen( Settings.widescreen ); - coverImg2->SetPosition( 15, 30 ); - gameinfoWindow2.Append( coverImg2 ); - gameinfoWindow2.Append( &txtWindow ); + txtWindow.Append(synopsisTxt); + txtWindow.Append(&upBtn); + txtWindow.Append(&dnBtn); + coverImg2 = new GuiImage(cover); + coverImg2->SetWidescreen(Settings.widescreen); + coverImg2->SetPosition(15, 30); + gameinfoWindow2.Append(coverImg2); + gameinfoWindow2.Append(&txtWindow); } - snprintf( linebuf, sizeof( linebuf ), "http://wiitdb.com" ); + 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->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->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} ); - wiitdb3Txt->SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); - wiitdb3Txt->SetPosition( 202, -4 ); - gameinfoWindow.Append( wiitdb3Txt ); + 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->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}); + wiitdb3Txt->SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); + wiitdb3Txt->SetPosition(202, -4); + gameinfoWindow.Append(wiitdb3Txt); - gameinfoWindow.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 100 ); + 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 ); + 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 ); + mainWindow->Append(&gameinfoWindow); + mainWindow->ChangeFocus(&gameinfoWindow); ResumeGui(); bool savedURL = false; - while ( choice == -1 ) + while (choice == -1) { VIDEO_WaitVSync(); - if ( shutdown == 1 ) + if (shutdown == 1) { - wiilight( 0 ); + wiilight(0); Sys_Shutdown(); } - else if ( reset == 1 ) + else if (reset == 1) Sys_Reboot(); - else if ( ( backBtn.GetState() == STATE_CLICKED ) || ( backBtn.GetState() == STATE_HELD ) ) + else if ((backBtn.GetState() == STATE_CLICKED) || (backBtn.GetState() == STATE_HELD)) { backBtn.ResetState(); - if ( page == 1 ) + if (page == 1) { choice = 1; - if ( synopsisTxt ) - delete synopsisTxt; + if (synopsisTxt) delete synopsisTxt; synopsisTxt = NULL; break; } - else if ( page == 2 ) + else if (page == 2) { HaltGui(); - gameinfoWindow2.Remove( &nextBtn ); - gameinfoWindow2.Remove( &backBtn ); - 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 ); + gameinfoWindow2.Remove(&nextBtn); + gameinfoWindow2.Remove(&backBtn); + 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); ResumeGui(); page = 1; } } - else if ( ( ( nextBtn.GetState() == STATE_CLICKED ) || ( nextBtn.GetState() == STATE_HELD ) ) && - ( strcmp( gameinfo.synopsis, "" ) != 0 ) ) + else if (((nextBtn.GetState() == STATE_CLICKED) || (nextBtn.GetState() == STATE_HELD)) && (strcmp( + gameinfo.synopsis, "") != 0)) { nextBtn.ResetState(); - if ( page == 1 ) + if (page == 1) { HaltGui(); - gameinfoWindow.Remove( &nextBtn ); - gameinfoWindow.Remove( &backBtn ); - 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 ); + gameinfoWindow.Remove(&nextBtn); + gameinfoWindow.Remove(&backBtn); + 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); ResumeGui(); page = 2; } else { HaltGui(); - gameinfoWindow2.Remove( &nextBtn ); - gameinfoWindow2.Remove( &backBtn ); - 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 ); + gameinfoWindow2.Remove(&nextBtn); + gameinfoWindow2.Remove(&backBtn); + 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); ResumeGui(); page = 1; } } - else if ( ( upBtn.GetState() == STATE_CLICKED || upBtn.GetState() == STATE_HELD ) && page == 2 ) + else if ((upBtn.GetState() == STATE_CLICKED || upBtn.GetState() == STATE_HELD) && page == 2) { synopsisTxt->PreviousLine(); - usleep( 60000 ); - if ( !( ( ButtonsHold() & WPAD_BUTTON_UP ) || ( ButtonsHold() & PAD_BUTTON_UP ) ) ) - upBtn.ResetState(); + usleep(60000); + if (!((ButtonsHold() & WPAD_BUTTON_UP) || (ButtonsHold() & PAD_BUTTON_UP))) upBtn.ResetState(); } - else if ( ( dnBtn.GetState() == STATE_CLICKED || dnBtn.GetState() == STATE_HELD ) && page == 2 ) + else if ((dnBtn.GetState() == STATE_CLICKED || dnBtn.GetState() == STATE_HELD) && page == 2) { synopsisTxt->NextLine(); - usleep( 60000 ); - if ( !( ( ButtonsHold() & WPAD_BUTTON_DOWN ) || ( ButtonsHold() & PAD_BUTTON_DOWN ) ) ) - dnBtn.ResetState(); + usleep(60000); + if (!((ButtonsHold() & WPAD_BUTTON_DOWN) || (ButtonsHold() & PAD_BUTTON_DOWN))) dnBtn.ResetState(); } - else if ( homeBtn.GetState() == STATE_CLICKED ) + else if (homeBtn.GetState() == STATE_CLICKED) { - if ( page == 1 ) + if (page == 1) { choice = 2; - if ( synopsisTxt ) - delete synopsisTxt; + if (synopsisTxt) delete synopsisTxt; synopsisTxt = NULL; break; } - else if ( page == 2 ) + else if (page == 2) { HaltGui(); - gameinfoWindow2.SetVisible( false ); - gameinfoWindow.SetVisible( true ); - mainWindow->Remove( &gameinfoWindow2 ); + gameinfoWindow2.SetVisible(false); + gameinfoWindow.SetVisible(true); + mainWindow->Remove(&gameinfoWindow2); ResumeGui(); page = 1; } } - else if ( urlBtn.GetState() == STATE_CLICKED && !savedURL ) + else if (urlBtn.GetState() == STATE_CLICKED && !savedURL) { - snprintf( linebuf, sizeof( linebuf ), tr( "Please wait..." ) ); - wiitdb2Txt->SetText( linebuf ); - gameinfoWindow.Append( wiitdb2Txt ); - if ( save_XML_URL() ) + 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 ); - wiitdb2Txt->SetText( linebuf ); - gameinfoWindow.Append( wiitdb2Txt ); - snprintf( linebuf, sizeof( linebuf ), tr( "Paste it into your browser to get your WiiTDB.zip." ) ); - wiitdb3Txt->SetText( linebuf ); - gameinfoWindow.Append( wiitdb3Txt ); + snprintf(linebuf, sizeof(linebuf), tr( "Your URL has been saved in %sWiiTDB_URL.txt." ), + Settings.update_path); + wiitdb2Txt->SetText(linebuf); + gameinfoWindow.Append(wiitdb2Txt); + snprintf(linebuf, sizeof(linebuf), tr( "Paste it into your browser to get your WiiTDB.zip." )); + wiitdb3Txt->SetText(linebuf); + gameinfoWindow.Append(wiitdb3Txt); savedURL = true; } else { - snprintf( linebuf, sizeof( linebuf ), tr( "Could not save." ) ); - wiitdb2Txt->SetText( linebuf ); - gameinfoWindow.Append( wiitdb2Txt ); + snprintf(linebuf, sizeof(linebuf), tr( "Could not save." )); + wiitdb2Txt->SetText(linebuf); + gameinfoWindow.Append(wiitdb2Txt); } urlBtn.ResetState(); } - else if ( screenShotBtn.GetState() == STATE_CLICKED ) + else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf( "\n\tscreenShotBtn clicked" ); + gprintf("\n\tscreenShotBtn clicked"); screenShotBtn.ResetState(); ScreenShot(); - gprintf( "...It's easy, mmmmmmKay" ); + gprintf("...It's easy, mmmmmmKay"); } } - if ( page == 1 ) + if (page == 1) { - gameinfoWindow.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 100 ); - while ( gameinfoWindow.GetEffect() > 0 ) usleep( 50 ); + gameinfoWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 100); + while (gameinfoWindow.GetEffect() > 0) + usleep(50); HaltGui(); - mainWindow->Remove( &gameinfoWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&gameinfoWindow); + mainWindow->SetState(STATE_DEFAULT); delete playersImgData; delete playersImg; @@ -1064,16 +1050,16 @@ int showGameInfo( char *ID ) delete wiitdb2Txt; delete wiitdb3Txt; delete memTxt; - if ( gameinfo.genreCnt > 0 ) + if (gameinfo.genreCnt > 0) { - for ( int i = 1; i <= gameinfo.genreCnt; i++ ) + for (int i = 1; i <= gameinfo.genreCnt; i++) { delete genreTxt[i]; } } - if ( gameinfo.wifiCnt > 0 ) + if (gameinfo.wifiCnt > 0) { - for ( int i = 0; i <= gameinfo.wifiCnt; i++ ) + for (int i = 0; i <= gameinfo.wifiCnt; i++) { delete wifiTxt[i]; } @@ -1082,15 +1068,16 @@ int showGameInfo( char *ID ) } else { - gameinfoWindow2.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 100 ); - while ( gameinfoWindow2.GetEffect() > 0 ) usleep( 50 ); + gameinfoWindow2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 100); + while (gameinfoWindow2.GetEffect() > 0) + usleep(50); HaltGui(); - mainWindow->Remove( &gameinfoWindow2 ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&gameinfoWindow2); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); } - if ( savedURL ) return 3; + if (savedURL) return 3; return choice; /* File not found */ @@ -1101,25 +1088,24 @@ int showGameInfo( char *ID ) } } -bool save_gamelist( int txt ) // save gamelist +bool save_gamelist(int txt) // save gamelist { - mainWindow->SetState( STATE_DISABLED ); + mainWindow->SetState(STATE_DISABLED); char tmp[200]; - sprintf( tmp, "%s", Settings.update_path ); + sprintf(tmp, "%s", Settings.update_path); struct stat st; - if ( stat( tmp, &st ) != 0 ) + if (stat(tmp, &st) != 0) { - mkdir( tmp, 0777 ); + mkdir(tmp, 0777); } FILE *f; - sprintf( tmp, "%sGameList.txt", Settings.update_path ); - if ( txt == 1 ) - sprintf( tmp, "%sGameList.csv", Settings.update_path ); - f = fopen( tmp, "w" ); - if ( !f ) + sprintf(tmp, "%sGameList.txt", 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 ); + sleep(1); + mainWindow->SetState(STATE_DEFAULT); return false; } //make sure that all games are added to the gamelist @@ -1129,125 +1115,125 @@ bool save_gamelist( int txt ) // save gamelist f32 freespace, used; int i; - WBFS_DiskSpace( &used, &freespace ); + WBFS_DiskSpace(&used, &freespace); - 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 ); + 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" ); + f = fopen(tmp, "w"); - if ( txt == 0 ) + 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, "# 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 < gameList.size() ; i++ ) + for (i = 0; i < gameList.size(); i++) { struct discHdr* header = gameList[i]; - WBFS_GameSize( header->id, &size ); - if ( i < 500 ) + 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, "%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" ); + fprintf(f, "\n"); } } else { - fprintf( f, "\"ID\",\"Size(GB)\",\"Name\"\n" ); + fprintf(f, "\"ID\",\"Size(GB)\",\"Name\"\n"); - for ( i = 0; i < gameList.size() ; i++ ) + for (i = 0; i < gameList.size(); i++) { struct discHdr* header = gameList[i]; - WBFS_GameSize( header->id, &size ); - if ( i < 500 ) + 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, "\"%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 ); + fclose(f); gameList.FilterList(); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->SetState(STATE_DEFAULT); return true; } - -bool save_XML_URL() // save xml url as as txt file for people without wifi +bool save_XML_URL() // save xml url as as txt file for people without wifi { char tmp[200]; - sprintf( tmp, "%s", Settings.update_path ); + sprintf(tmp, "%s", Settings.update_path); struct stat st; - if ( stat( tmp, &st ) != 0 ) + if (stat(tmp, &st) != 0) { - mkdir( tmp, 0777 ); + mkdir(tmp, 0777); } FILE *f; - sprintf( tmp, "%sWiiTDB_URL.txt", Settings.update_path ); - f = fopen( tmp, "w" ); - if ( !f ) + sprintf(tmp, "%sWiiTDB_URL.txt", Settings.update_path); + f = fopen(tmp, "w"); + if (!f) { - sleep( 1 ); + sleep(1); return false; } char XMLurl[3540]; - build_XML_URL( XMLurl, sizeof( XMLurl ) ); + 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 ); + 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); // Closing and reopening because of a write issue we are having right now - f = fopen( tmp, "w" ); - 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" ); - fprintf( f, "# Copy and paste this URL into your web browser and you should get a zip file that will work for you.\n" ); - fprintf( f, "%s\n\n\n ", XMLurl ); + f = fopen(tmp, "w"); + 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"); + fprintf(f, + "# Copy and paste this URL into your web browser and you should get a zip file that will work for you.\n"); + fprintf(f, "%s\n\n\n ", XMLurl); - fclose( f ); + fclose(f); return true; } - void MemInfoPrompt() { char meminfotxt[200]; - strlcpy( meminfotxt, MemInfo(), sizeof( meminfotxt ) ); - WindowPrompt( 0, meminfotxt, tr( "OK" ) ); + strlcpy(meminfotxt, MemInfo(), sizeof(meminfotxt)); + WindowPrompt(0, meminfotxt, tr( "OK" )); } - -void build_XML_URL( char *XMLurl, int XMLurlsize ) +void build_XML_URL(char *XMLurl, int XMLurlsize) { gameList.LoadUnfiltered(); // 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 ); + snprintf(url, sizeof(url), "http://wiitdb.com/wiitdb.zip?LANG=%s&ID=", Settings.db_language); int i; - for ( i = 0; i < gameList.size(); i++ ) + for (i = 0; i < gameList.size(); i++) { struct discHdr* header = gameList[i]; - if ( i < 500 ) + 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] ); - strncat( url, filename, 6 ); - if ( ( i != gameList.size() - 1 ) && ( i < 500 ) ) - strncat( url, ",", 1 ); + 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 != gameList.size() - 1) && (i < 500)) strncat(url, ",", 1); } } - strlcpy( XMLurl, url, XMLurlsize ); + strlcpy(XMLurl, url, XMLurlsize); gameList.FilterList(); } diff --git a/source/prompts/gameinfo.h b/source/prompts/gameinfo.h index 03bc347a..4f46670b 100644 --- a/source/prompts/gameinfo.h +++ b/source/prompts/gameinfo.h @@ -8,9 +8,9 @@ #ifndef _GAMEINFO_H_ #define _GAMEINFO_H_ -int showGameInfo( char *ID ); -void build_XML_URL( char *XMLurl, int XMLurlsize ); +int showGameInfo(char *ID); +void build_XML_URL(char *XMLurl, int XMLurlsize); bool save_XML_URL(); -bool save_gamelist( int txt ); +bool save_gamelist(int txt); void MemInfoPrompt(); #endif diff --git a/source/ramdisk/ramdisk.cpp b/source/ramdisk/ramdisk.cpp index feebf83b..9bb39e0a 100644 --- a/source/ramdisk/ramdisk.cpp +++ b/source/ramdisk/ramdisk.cpp @@ -11,9 +11,6 @@ #define NAMELENMAX 0x80 #define MAXPATHLEN 0x100 - - - class RAMDISK_PARTITION; class RAMDISK_LINK_ENTRY; class RAMDISK_DIR_ENTRY; @@ -21,9 +18,9 @@ class RAMDISK_FILE_ENTRY; class RAMDISK_BASE_ENTRY { public: - RAMDISK_BASE_ENTRY( const char *Name, RAMDISK_DIR_ENTRY *Parent ); + RAMDISK_BASE_ENTRY(const char *Name, RAMDISK_DIR_ENTRY *Parent); virtual ~RAMDISK_BASE_ENTRY(); - void Rename( const char *Name ); + void Rename(const char *Name); RAMDISK_LINK_ENTRY *IsLink(); RAMDISK_DIR_ENTRY *IsDir(); RAMDISK_FILE_ENTRY *IsFile(); @@ -32,37 +29,36 @@ class RAMDISK_BASE_ENTRY 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_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(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 *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; + 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_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; }; @@ -70,7 +66,7 @@ class RAMDISK_PARTITION : public RAMDISK_DIR_ENTRY class FILE_DATA { public: - FILE_DATA( size_t Len ); + FILE_DATA(size_t Len); ~FILE_DATA(); u8 *data; size_t len; @@ -78,93 +74,85 @@ class FILE_DATA }; typedef struct { - RAMDISK_FILE_ENTRY *file; - bool isLink; - u32 current_pos; - bool read; - bool write; + 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(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; + 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_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::RAMDISK_BASE_ENTRY( const char *Name, RAMDISK_DIR_ENTRY *Parent ) - : - name( strdup( Name ) ), - parent( Parent ), - next( NULL ) -{} +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 ); + free(name); + if (parent) parent->RemoveEntry(this); } -void RAMDISK_BASE_ENTRY::Rename( const char *Name ) +void RAMDISK_BASE_ENTRY::Rename(const char *Name) { - free( name ); - name = strdup( Name ); + free(name); + name = strdup(Name); } inline RAMDISK_LINK_ENTRY *RAMDISK_BASE_ENTRY::IsLink() { - return dynamic_cast( this ); + 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 ); + 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_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 ); + 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_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 ); + RAMDISK_BASE_ENTRY* entry = new RAMDISK_LINK_ENTRY(".", this, this); first = entry; last = entry; - if ( parent ) + if (parent) { - entry = new RAMDISK_LINK_ENTRY( "..", this, parent ); + entry = new RAMDISK_LINK_ENTRY("..", this, parent); first->next = entry; last = entry; } } RAMDISK_DIR_ENTRY::~RAMDISK_DIR_ENTRY() { - while ( first ) + while (first) { first->parent = NULL; // ~RAMDISK_BASE_ENTRY() no calls RemoveEntry() RAMDISK_BASE_ENTRY* next = first->next; @@ -173,175 +161,171 @@ RAMDISK_DIR_ENTRY::~RAMDISK_DIR_ENTRY() } } -RAMDISK_BASE_ENTRY *RAMDISK_DIR_ENTRY::FindEntry( const char* Path ) +RAMDISK_BASE_ENTRY *RAMDISK_DIR_ENTRY::FindEntry(const char* Path) { const char* dirpath = Path; const char* cptr; - while ( dirpath[0] == '/' ) dirpath++; // move past leading '/' + 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 ) + 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 (strncmp(curr->name, dirpath, cptr - dirpath) == 0) { if ( RAMDISK_DIR_ENTRY *dir = curr->IsDir() ) - return dir->FindEntry( cptr ); - else - return curr; + return dir->FindEntry(cptr); + else return curr; } } return NULL; } -RAMDISK_FILE_ENTRY *RAMDISK_DIR_ENTRY::CreateFile( const char *Filename ) +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; + RAMDISK_FILE_ENTRY* file = new RAMDISK_FILE_ENTRY(Filename, this); + if (!first) first = file; last->next = file; last = file; return file; } - catch ( ... ) { return NULL; } + catch (...) + { + return NULL; + } } -RAMDISK_DIR_ENTRY *RAMDISK_DIR_ENTRY::CreateDir( const char *Filename ) +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; + 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 ) +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 ) ) + for (RAMDISK_BASE_ENTRY **curr = &first; *curr; curr = &((*curr)->next)) { - if ( *curr == Entry ) + if (*curr == Entry) { *curr = Entry->next; - if ( Entry->next == NULL ) // entry is last - last = *p_last; + 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_PARTITION::RAMDISK_PARTITION(const char *Mountpoint, bool AutoMount) : + RAMDISK_DIR_ENTRY(Mountpoint, NULL), cwd(this), automount(AutoMount) { } -RAMDISK_BASE_ENTRY * RAMDISK_PARTITION::FindEntry( const char* path ) +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 ) + if ((cptr = strchr(path, ':'))) path = cptr + 1; //move path past any device names + if (strchr(path, ':') != NULL) { -// r->_errno = EINVAL; + // 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 ); + 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 ) +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 + 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!) + 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 + strlcpy(dirfilename, path, 1 + cptr - path); //copy string up till and including / or : + filename = cptr; //filename = now remainder of string break; } } - if ( !filename ) + if (!filename) { - filename = path; //filename = complete path - dirfilename[0] = 0; //make directory path "" + filename = path; //filename = complete path + dirfilename[0] = 0; //make directory path "" } - RAMDISK_BASE_ENTRY *entry = FindEntry( dirfilename ); - if ( entry ) + RAMDISK_BASE_ENTRY *entry = FindEntry(dirfilename); + if (entry) { - if ( basename ) *basename = filename; + if (basename) *basename = filename; return entry->IsDir(); } return NULL; } - -FILE_DATA::FILE_DATA( size_t Len ) : - next( NULL ) +FILE_DATA::FILE_DATA(size_t Len) : + next(NULL) { data = new u8[Len]; len = Len; - memset( data, 0, len ); + memset(data, 0, len); } FILE_DATA::~FILE_DATA() { - delete [] 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(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 ); + Truncate(0); } #define CLUSTER_SIZE 4*1024 -bool RAMDISK_FILE_ENTRY::Truncate( size_t newSize ) +bool RAMDISK_FILE_ENTRY::Truncate(size_t newSize) { - if ( newSize > cluster_len ) + if (newSize > cluster_len) { // Expanding the file over cluster_len - return AddCluster( newSize - cluster_len ); + return AddCluster(newSize - cluster_len); } - else if ( newSize < file_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 ) + for (FILE_DATA **p_cluster = &first_cluster; *p_cluster; p_cluster = &(*p_cluster)->next) { - if ( len >= newSize ) + if (len >= newSize) { last_cluster = prev_cluster; delete *p_cluster; - ( *p_cluster ) = NULL; + (*p_cluster) = NULL; break; } - len += ( *p_cluster )->len; + len += (*p_cluster)->len; prev_cluster = *p_cluster; } } @@ -349,40 +333,39 @@ bool RAMDISK_FILE_ENTRY::Truncate( size_t newSize ) return true; } - - -bool RAMDISK_FILE_ENTRY::AddCluster( size_t len ) +bool RAMDISK_FILE_ENTRY::AddCluster(size_t len) { - if ( len < CLUSTER_SIZE ) - len = CLUSTER_SIZE; + if (len < CLUSTER_SIZE) len = CLUSTER_SIZE; try { - *( last_cluster ? &last_cluster->next : &first_cluster ) = last_cluster = new FILE_DATA( len ); + *(last_cluster ? &last_cluster->next : &first_cluster) = last_cluster = new FILE_DATA(len); cluster_len += len; return true; } - catch ( ... ) { return false; } + catch (...) + { + return false; + } } -size_t RAMDISK_FILE_ENTRY::Read( struct _reent *r, FILE_STRUCT *fileStruct, char *ptr, size_t len ) +size_t RAMDISK_FILE_ENTRY::Read(struct _reent *r, FILE_STRUCT *fileStruct, char *ptr, size_t len) { - if ( !fileStruct->read ) + if (!fileStruct->read) { r->_errno = EBADF; return 0; } // Short circuit cases where len is 0 (or less) - if ( len <= 0 ) - return 0; + 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 ) + 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 ) + if (len + fileStruct->current_pos > file_len) { r->_errno = EOVERFLOW; len = fileStruct->current_pos - file_len; @@ -391,28 +374,25 @@ size_t RAMDISK_FILE_ENTRY::Read( struct _reent *r, FILE_STRUCT *fileStruct, char 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 ) + for (FILE_DATA *cluster = first_cluster; cluster; cluster = cluster->next) { - if ( pos > cluster->len ) + if (pos > cluster->len) { - pos -= cluster->len; + pos -= cluster->len; max_len -= cluster->len; } else { size_t read = max_len; - if ( read > cluster->len ) - read = cluster->len; + if (read > cluster->len) read = cluster->len; read -= pos; - if ( read > len ) - read = len; - memcpy( ptr, &( cluster->data[pos] ), read ); + if (read > len) read = len; + memcpy(ptr, &(cluster->data[pos]), read); readed += read; ptr += read; len -= read; - if ( len == 0 ) - break; - pos -= cluster->len; + if (len == 0) break; + pos -= cluster->len; max_len -= cluster->len; } @@ -420,48 +400,45 @@ size_t RAMDISK_FILE_ENTRY::Read( struct _reent *r, FILE_STRUCT *fileStruct, char 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 ) + if (!fileStruct->write) { r->_errno = EBADF; return 0; } // Short circuit cases where len is 0 (or less) - if ( len <= 0 ) - return 0; + if (len <= 0) return 0; off_t pos = fileStruct->current_pos; - if ( cluster_len < ( pos + len ) && !AddCluster( ( pos + len ) - cluster_len ) ) + 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 ); + 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 ) + for (FILE_DATA *cluster = first_cluster; cluster; cluster = cluster->next) { - if ( pos > cluster->len ) + if (pos > cluster->len) { - 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 ); + if (write > len) write = len; + memcpy(&(cluster->data[pos]), ptr, write); written += write; ptr += write; len -= write; - if ( len == 0 ) - break; - pos -= cluster->len; + if (len == 0) break; + pos -= cluster->len; max_len -= cluster->len; } } @@ -469,95 +446,88 @@ size_t RAMDISK_FILE_ENTRY::Write( struct _reent *r, FILE_STRUCT *fileStruct, con return written; } +static int ramdiskFS_open_r(struct _reent *r, void *fileStruct, const char *path, int flags, int mode); +static int ramdiskFS_close_r(struct _reent *r, int fd); +static int ramdiskFS_write_r(struct _reent *r, int fd, const char *ptr, size_t len); +static int ramdiskFS_read_r(struct _reent *r, int fd, char *ptr, size_t len); +static off_t ramdiskFS_seek_r(struct _reent *r, int fd, off_t pos, int dir); +static int ramdiskFS_fstat_r(struct _reent *r, int fd, struct stat *st); +static int ramdiskFS_stat_r(struct _reent *r, const char *file, struct stat *st); +static int ramdiskFS_unlink_r(struct _reent *r, const char *name); +static int ramdiskFS_chdir_r(struct _reent *r, const char *name); +static int ramdiskFS_mkdir_r(struct _reent *r, const char *path, int mode); -static int ramdiskFS_open_r( struct _reent *r, void *fileStruct, const char *path, int flags, int mode ); -static int ramdiskFS_close_r( struct _reent *r, int fd ); -static int ramdiskFS_write_r( struct _reent *r, int fd, const char *ptr, size_t len ); -static int ramdiskFS_read_r( struct _reent *r, int fd, char *ptr, size_t len ); -static off_t ramdiskFS_seek_r( struct _reent *r, int fd, off_t pos, int dir ); -static int ramdiskFS_fstat_r( struct _reent *r, int fd, struct stat *st ); -static int ramdiskFS_stat_r( struct _reent *r, const char *file, struct stat *st ); -static int ramdiskFS_unlink_r( struct _reent *r, const char *name ); -static int ramdiskFS_chdir_r( struct _reent *r, const char *name ); -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); +static int ramdiskFS_dirreset_r(struct _reent *r, DIR_ITER *dirState); +static int ramdiskFS_dirnext_r(struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *st); +static int ramdiskFS_dirclose_r(struct _reent *r, DIR_ITER *dirState); -static DIR_ITER* ramdiskFS_diropen_r( struct _reent *r, DIR_ITER *dirState, const char *path ); -static int ramdiskFS_dirreset_r( struct _reent *r, DIR_ITER *dirState ); -static int ramdiskFS_dirnext_r( struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *st ); -static int ramdiskFS_dirclose_r( struct _reent *r, DIR_ITER *dirState ); +static int ramdiskFS_ftruncate_r(struct _reent *r, int fd, off_t len); -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); - -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); - - NULL, // fsync_r, - NULL // Device data -}; + NULL, // fsync_r, + NULL // Device data + }; //--------------------------------------------------------------------------------- -static inline RAMDISK_PARTITION* ramdiskFS_getPartitionFromPath( const char* path ) +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); } //--------------------------------------------------------------------------------- // File functions //--------------------------------------------------------------------------------- -static int ramdiskFS_open_r( struct _reent *r, void *file_Struct, const char *path, int flags, int mode ) +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 ) + RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath(path); + if (partition == NULL) { r->_errno = ENODEV; return -1; } - if ( ( flags & 0x03 ) == O_RDONLY ) + if ((flags & 0x03) == O_RDONLY) { // Open the file for read-only access fileStruct->read = true; fileStruct->write = false; } - else if ( ( flags & 0x03 ) == O_WRONLY ) + else if ((flags & 0x03) == O_WRONLY) { // Open file for write only access fileStruct->read = false; fileStruct->write = true; } - else if ( ( flags & 0x03 ) == O_RDWR ) + else if ((flags & 0x03) == O_RDWR) { // Open file for read/write access fileStruct->read = true; @@ -568,16 +538,16 @@ static int ramdiskFS_open_r( struct _reent *r, void *file_Struct, const char *pa r->_errno = EACCES; return -1; } - RAMDISK_BASE_ENTRY *entry = partition->FindEntry( path ); + 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 ) ) + 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() ) + if (entry && entry->IsDir()) { r->_errno = EISDIR; return -1; @@ -585,18 +555,18 @@ static int ramdiskFS_open_r( struct _reent *r, void *file_Struct, const char *pa fileStruct->isLink = entry ? entry->IsLink() : false; fileStruct->file = entry ? entry->IsFile() : NULL; - if ( !fileStruct->file ) // entry not exists + if (!fileStruct->file) // entry not exists { - if ( flags & O_CREAT ) + if (flags & O_CREAT) { const char *filename; - RAMDISK_DIR_ENTRY *dir = partition->FindPath( path, &filename ); - if ( !dir ) + RAMDISK_DIR_ENTRY *dir = partition->FindPath(path, &filename); + if (!dir) { r->_errno = ENOTDIR; return -1; } - fileStruct->file = dir->CreateFile( filename ); + fileStruct->file = dir->CreateFile(filename); } else { @@ -605,51 +575,49 @@ static int ramdiskFS_open_r( struct _reent *r, void *file_Struct, const char *pa return -1; } } - if ( fileStruct->file ) + 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; + 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 ); + return (-1); } //--------------------------------------------------------------------------------- -static int ramdiskFS_close_r( struct _reent *r, int fd ) +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 ) +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 ) +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 ) +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; + FILE_STRUCT *fileStruct = (FILE_STRUCT*) fd; - switch ( dir ) + switch (dir) { case SEEK_SET: break; @@ -657,7 +625,7 @@ static off_t ramdiskFS_seek_r( struct _reent *r, int fd, off_t pos, int dir ) pos += fileStruct->current_pos; break; case SEEK_END: - pos += fileStruct->file->file_len; // set start to end of file + pos += fileStruct->file->file_len; // set start to end of file break; default: r->_errno = EINVAL; @@ -667,62 +635,62 @@ static off_t ramdiskFS_seek_r( struct _reent *r, int fd, off_t pos, int dir ) } //--------------------------------------------------------------------------------- -static int ramdiskFS_fstat_r( struct _reent *r, int fd, struct stat *st ) +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 ); + return (0); } //--------------------------------------------------------------------------------- -static int ramdiskFS_stat_r( struct _reent *r, const char *file, struct stat *st ) +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 + dirState.dirStruct = &dirStruct; //create a temp dirstruct int ret; - if ( ramdiskFS_open_r( r, &fileStruct, file, 0, 0 ) == 0 ) + 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 ); + 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 ) ) + else if ((ramdiskFS_diropen_r(r, &dirState, file) != NULL)) { st->st_mode = S_IFDIR; - ramdiskFS_dirclose_r( r, &dirState ); - return( 0 ); + ramdiskFS_dirclose_r(r, &dirState); + return (0); } r->_errno = ENOENT; - return( -1 ); + return (-1); } //--------------------------------------------------------------------------------- -static int ramdiskFS_unlink_r( struct _reent *r, const char *name ) +static int ramdiskFS_unlink_r(struct _reent *r, const char *name) { -//--------------------------------------------------------------------------------- - RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath( name ); - if ( partition == NULL ) + //--------------------------------------------------------------------------------- + RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath(name); + if (partition == NULL) { r->_errno = ENODEV; return -1; } - RAMDISK_BASE_ENTRY *entry = partition->FindEntry( name ); - if ( !entry ) + RAMDISK_BASE_ENTRY *entry = partition->FindEntry(name); + if (!entry) { r->_errno = ENOENT; return -1; } - if ( entry->IsLink() ) + if (entry->IsLink()) { - if ( entry->name[0] == '.' && ( entry->name[1] == '\0' || ( entry->name[1] == '.' && entry->name[2] == '\0' ) ) ) + if (entry->name[0] == '.' && (entry->name[1] == '\0' || (entry->name[1] == '.' && entry->name[2] == '\0'))) { r->_errno = EPERM; return -1; @@ -733,10 +701,10 @@ static int ramdiskFS_unlink_r( struct _reent *r, const char *name ) if ( RAMDISK_DIR_ENTRY *dir = entry->IsDir() ) { - for ( RAMDISK_BASE_ENTRY *entry = dir->first; entry; entry = entry->next ) + 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' ) ) ) ) + if (!(entry->name[0] == '.' + && (entry->name[1] == '\0' || (entry->name[1] == '.' && entry->name[2] == '\0')))) { r->_errno = EPERM; return -1; @@ -748,97 +716,94 @@ static int ramdiskFS_unlink_r( struct _reent *r, const char *name ) } //--------------------------------------------------------------------------------- -static int ramdiskFS_chdir_r( struct _reent *r, const char *name ) +static int ramdiskFS_chdir_r(struct _reent *r, const char *name) { -//--------------------------------------------------------------------------------- + //--------------------------------------------------------------------------------- DIR_STRUCT dirStruct; DIR_ITER dirState; dirState.dirStruct = &dirStruct; - if ( ( name == NULL ) ) + 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 ) + if (partition == NULL) { r->_errno = ENODEV; return -1; } partition->cwd = dirStruct.dir; - ramdiskFS_dirclose_r( r, &dirState ); + ramdiskFS_dirclose_r(r, &dirState); return 0; } //--------------------------------------------------------------------------------- -static int ramdiskFS_mkdir_r( struct _reent *r, const char *path, int mode ) +static int ramdiskFS_mkdir_r(struct _reent *r, const char *path, int mode) { -//--------------------------------------------------------------------------------- - RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath( path ); - if ( partition == NULL ) + //--------------------------------------------------------------------------------- + RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath(path); + if (partition == NULL) { r->_errno = ENODEV; return -1; } - RAMDISK_BASE_ENTRY *entry = partition->FindEntry( path ); - if ( entry ) + 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 ) + RAMDISK_DIR_ENTRY *dir = partition->FindPath(path, &filename); + if (!dir) { r->_errno = ENOTDIR; return -1; } - dir->CreateDir( filename ); + dir->CreateDir(filename); return 0; } //--------------------------------------------------------------------------------- // Directory functions //--------------------------------------------------------------------------------- -static DIR_ITER* ramdiskFS_diropen_r( struct _reent *r, DIR_ITER *dirState, const char *path ) +static DIR_ITER* ramdiskFS_diropen_r(struct _reent *r, DIR_ITER *dirState, const char *path) { -//--------------------------------------------------------------------------------- + //--------------------------------------------------------------------------------- - DIR_STRUCT *dirStruct = ( DIR_STRUCT* )dirState->dirStruct; + DIR_STRUCT *dirStruct = (DIR_STRUCT*) dirState->dirStruct; char *cptr; - RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath( path ); - if ( partition == 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 ) + 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 + 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 + else dirStruct->dir = partition->cwd; //else use current working dir - RAMDISK_BASE_ENTRY *entry = dirStruct->dir->FindEntry( path ); - if ( entry == NULL ) + RAMDISK_BASE_ENTRY *entry = dirStruct->dir->FindEntry(path); + if (entry == NULL) { r->_errno = ENOENT; return NULL; } dirStruct->dir = entry->IsDir(); - if ( dirStruct->dir == NULL ) + if (dirStruct->dir == NULL) { r->_errno = ENOTDIR; return NULL; @@ -850,176 +815,167 @@ static DIR_ITER* ramdiskFS_diropen_r( struct _reent *r, DIR_ITER *dirState, cons /*Consts containing relative system path strings*/ //reset dir to start of entry selected by dirStruct->cur_dir_id //--------------------------------------------------------------------------------- -static int ramdiskFS_dirreset_r( struct _reent *r, DIR_ITER *dirState ) +static int ramdiskFS_dirreset_r(struct _reent *r, DIR_ITER *dirState) { -//--------------------------------------------------------------------------------- - DIR_STRUCT *dirStruct = ( DIR_STRUCT* )dirState->dirStruct; + //--------------------------------------------------------------------------------- + DIR_STRUCT *dirStruct = (DIR_STRUCT*) dirState->dirStruct; dirStruct->current_entry = dirStruct->dir->first; - return( 0 ); + return (0); } //--------------------------------------------------------------------------------- -static int ramdiskFS_dirnext_r( struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *st ) +static int ramdiskFS_dirnext_r(struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *st) { -//--------------------------------------------------------------------------------- - DIR_STRUCT *dirStruct = ( DIR_STRUCT* )dirState->dirStruct; -// RAMDISK_BASE_ENTRY **dirStruct = (RAMDISK_BASE_ENTRY**)dirState->dirStruct; + //--------------------------------------------------------------------------------- + DIR_STRUCT *dirStruct = (DIR_STRUCT*) dirState->dirStruct; + // RAMDISK_BASE_ENTRY **dirStruct = (RAMDISK_BASE_ENTRY**)dirState->dirStruct; - if ( dirStruct->current_entry ) + if (dirStruct->current_entry) { - strcpy( filename, dirStruct->current_entry->name ); - if ( dirStruct->current_entry->IsDir() ) + strcpy(filename, dirStruct->current_entry->name); + if (dirStruct->current_entry->IsDir()) { - if ( st ) st->st_mode = S_IFDIR; + if (st) st->st_mode = S_IFDIR; } else { - if ( st ) st->st_mode = 0; + if (st) st->st_mode = 0; } dirStruct->current_entry = dirStruct->current_entry->next; - return( 0 ); + return (0); } r->_errno = ENOENT; - return( -1 ); + return (-1); } //--------------------------------------------------------------------------------- -static int ramdiskFS_dirclose_r( struct _reent *r, DIR_ITER *dirState ) +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 ) +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 ) + 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 ) + 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; + if (fileStruct->file->Truncate(len)) return 0; r->_errno = ENOSPC; return -1; } //--------------------------------------------------------------------------------- -void ramdiskFS_Unmount( const char* mountpoint ) +void ramdiskFS_Unmount(const char* mountpoint) { -//--------------------------------------------------------------------------------- + //--------------------------------------------------------------------------------- RAMDISK_PARTITION *partition; - devoptab_t *devops = ( devoptab_t* )GetDeviceOpTab( mountpoint ); + 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 (devops->open_r != ramdiskFS_devoptab.open_r) return; - if ( RemoveDevice ( mountpoint ) == -1 ) - 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 ) +extern "C" void ramdiskUnmount(const char *mountpoint) { - ramdiskFS_Unmount( mountpoint ); + ramdiskFS_Unmount(mountpoint); } //--------------------------------------------------------------------------------- -int ramdiskFS_Mount( const char *mountpoint, void *handle ) +int ramdiskFS_Mount(const char *mountpoint, void *handle) { -//--------------------------------------------------------------------------------- + //--------------------------------------------------------------------------------- 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 ) + 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 ); + 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 + 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 + 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 + memcpy(devops, &ramdiskFS_devoptab, sizeof(ramdiskFS_devoptab)); // Add an entry for this device to the devoptab table - strlcpy ( nameCopy, Mountpoint, len + 1 ); + strlcpy(nameCopy, Mountpoint, len + 1); devops->name = nameCopy; - if ( handle ) + if (handle) { - *partition = ( RAMDISK_PARTITION* )handle; - ( *partition )->Rename( Mountpoint ); + *partition = (RAMDISK_PARTITION*) handle; + (*partition)->Rename(Mountpoint); } - else - *partition = new RAMDISK_PARTITION( Mountpoint, true ); - devops->deviceData = partition; + else *partition = new RAMDISK_PARTITION(Mountpoint, true); + devops->deviceData = partition; - if ( AddDevice( devops ) < 0 ) + if (AddDevice(devops) < 0) { - free( devops ); + free(devops); return false; } return true; } -extern "C" int ramdiskMount( const char *mountpoint, void *handle ) +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 ) +extern "C" void ramdiskDelete(void* Handle) { -//--------------------------------------------------------------------------------- - RAMDISK_PARTITION *partition = ( RAMDISK_PARTITION* )Handle; - if ( partition->automount == false ) - ramdiskFS_Unmount( partition->name ); + //--------------------------------------------------------------------------------- + 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 2d7efdc8..bf1779fd 100644 --- a/source/ramdisk/ramdisk.h +++ b/source/ramdisk/ramdisk.h @@ -7,9 +7,9 @@ extern "C" #endif /* - ramdiskCreate initialize a dynamic RAM-disk. - return: Handle for ramdiskMount - */ + ramdiskCreate initialize a dynamic RAM-disk. + return: Handle for ramdiskMount + */ void* ramdiskCreate(); /************************************************** @@ -19,7 +19,7 @@ extern "C" * if the ramdisk is allready mounted forces ramdiskUnmount * IN: a Handle was created witch ramdiskCreate(); **************************************************/ - void ramdiskDelete( void* Handle ); + void ramdiskDelete(void* Handle); /************************************************** * ramdiskMount @@ -30,9 +30,7 @@ extern "C" * or NULL for auto-create * OUT: 0 = Error / !0 = OK **************************************************/ - int ramdiskMount( const char *mountpoint, void *handle ); - - + int ramdiskMount(const char *mountpoint, void *handle); /************************************************** * ramdiskUnmount @@ -40,44 +38,41 @@ extern "C" * unmounts a ramdisk * IN: mountpoint e.g "RAM" or "MEM:" **************************************************/ - void ramdiskUnmount( const char *mountpoint ); + 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 + 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 - /* - 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. - - 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/CSettings.cpp b/source/settings/CSettings.cpp index 2f0dbdda..cf98fbd1 100644 --- a/source/settings/CSettings.cpp +++ b/source/settings/CSettings.cpp @@ -1,4 +1,4 @@ - /**************************************************************************** +/**************************************************************************** * Copyright (C) 2010 * by Dimok * @@ -49,21 +49,21 @@ CSettings::~CSettings() void CSettings::SetDefault() { snprintf(ConfigPath, sizeof(ConfigPath), "%s/config/GXGlobal.cfg", BootDevice); - snprintf(covers_path, sizeof( covers_path ), "%s/images/", BootDevice ); - snprintf(covers2d_path, sizeof( covers2d_path ), "%s/images/2D/", BootDevice ); - snprintf(disc_path, sizeof( disc_path ), "%s/images/disc/", BootDevice ); - snprintf(titlestxt_path, sizeof( titlestxt_path ), "%s/config/", BootDevice ); - snprintf(language_path, sizeof( language_path ), "notset" ); - snprintf(languagefiles_path, sizeof( languagefiles_path ), "%s/config/language/", BootDevice ); - snprintf(update_path, sizeof( update_path ), "%s/apps/usbloader_gx/", BootDevice ); - snprintf(theme_downloadpath, sizeof( theme_downloadpath ), "%s/config/themes/", BootDevice ); - snprintf(homebrewapps_path, sizeof( homebrewapps_path ), "%s/apps/", BootDevice ); - snprintf(Cheatcodespath, sizeof( Cheatcodespath ), "%s/codes/", BootDevice ); - snprintf(TxtCheatcodespath, sizeof( TxtCheatcodespath ), "%s/txtcodes/", BootDevice ); - snprintf(BcaCodepath, sizeof( BcaCodepath ), "%s/bca/", BootDevice ); - snprintf(WipCodepath, sizeof( WipCodepath ), "%s/wip/", BootDevice ); - snprintf(theme_path, sizeof( theme_path ), "%s/theme/", BootDevice ); - snprintf(dolpath, sizeof( dolpath ), "%s/", BootDevice ); + snprintf(covers_path, sizeof(covers_path), "%s/images/", BootDevice); + snprintf(covers2d_path, sizeof(covers2d_path), "%s/images/2D/", BootDevice); + snprintf(disc_path, sizeof(disc_path), "%s/images/disc/", BootDevice); + snprintf(titlestxt_path, sizeof(titlestxt_path), "%s/config/", BootDevice); + snprintf(language_path, sizeof(language_path), "notset"); + snprintf(languagefiles_path, sizeof(languagefiles_path), "%s/config/language/", BootDevice); + snprintf(update_path, sizeof(update_path), "%s/apps/usbloader_gx/", BootDevice); + snprintf(theme_downloadpath, sizeof(theme_downloadpath), "%s/config/themes/", BootDevice); + snprintf(homebrewapps_path, sizeof(homebrewapps_path), "%s/apps/", BootDevice); + snprintf(Cheatcodespath, sizeof(Cheatcodespath), "%s/codes/", BootDevice); + snprintf(TxtCheatcodespath, sizeof(TxtCheatcodespath), "%s/txtcodes/", BootDevice); + snprintf(BcaCodepath, sizeof(BcaCodepath), "%s/bca/", BootDevice); + snprintf(WipCodepath, sizeof(WipCodepath), "%s/wip/", BootDevice); + snprintf(theme_path, sizeof(theme_path), "%s/theme/", BootDevice); + snprintf(dolpath, sizeof(dolpath), "%s/", BootDevice); strcpy(ogg_path, ""); strcpy(unlockCode, ""); @@ -104,38 +104,37 @@ void CSettings::SetDefault() strcpy(unlockCode, ""); strcpy(returnTo, ""); - memset( &Parental, 0, sizeof( Parental ) ); + memset(&Parental, 0, sizeof(Parental)); char buf[0x4a]; CONF_Init(); - s32 res = CONF_Get( "IPL.PC", buf, 0x4A ); - if ( res > 0 ) + s32 res = CONF_Get("IPL.PC", buf, 0x4A); + if (res > 0) { - if ( buf[2] != 0x14 ) + if (buf[2] != 0x14) { Parental.enabled = 1; Parental.rating = buf[2]; } Parental.question = buf[7]; - memcpy( Parental.pin, buf + 3, 4 ); - memcpy( Parental.answer, buf + 8, 32 ); + memcpy(Parental.pin, buf + 3, 4); + memcpy(Parental.answer, buf + 8, 32); } widescreen = CONF_GetAspectRatio(); - godmode = ( Parental.enabled == 0 ) ? 1 : 0; + godmode = (Parental.enabled == 0) ? 1 : 0; CFG_DefaultTheme(); } bool CSettings::Save() { - if(!FindConfig()) - return false; + if (!FindConfig()) return false; char filedest[100]; snprintf(filedest, sizeof(filedest), "%s", ConfigPath); char * tmppath = strrchr(filedest, '/'); - if(tmppath) + if (tmppath) { tmppath++; tmppath[0] = '\0'; @@ -144,107 +143,102 @@ bool CSettings::Save() subfoldercreate(filedest); file = fopen(ConfigPath, "w"); - if(!file) - return false; + if (!file) return false; - fprintf(file, "# USB Loader global settings file\n" ); - fprintf(file, "# Note: This file is automatically generated\n " ); - fprintf(file, "videomode = %d\n ", videomode ); - fprintf(file, "videopatch = %d\n ", videopatch ); - fprintf(file, "language = %d\n ", language ); - fprintf(file, "ocarina = %d\n ", ocarina ); - fprintf(file, "hddinfo = %d\n ", hddinfo ); - fprintf(file, "sinfo = %d\n ", sinfo ); - fprintf(file, "rumble = %d\n ", rumble ); - fprintf(file, "volume = %d\n ", volume ); - fprintf(file, "sfxvolume = %d\n ", sfxvolume ); - fprintf(file, "gamesoundvolume = %d\n ", gamesoundvolume ); - fprintf(file, "tooltips = %d\n ", tooltips ); - fprintf(file, "password = %s\n ", unlockCode ); - fprintf(file, "sort = %d\n ", sort ); - fprintf(file, "fave = %d\n ", fave ); - fprintf(file, "cios = %d\n ", cios ); - fprintf(file, "keyset = %d\n ", keyset ); - fprintf(file, "xflip = %d\n ", xflip ); - fprintf(file, "gridRows = %d\n ", gridRows ); - fprintf(file, "qboot = %d\n ", qboot ); - fprintf(file, "wsprompt = %d\n ", wsprompt ); - fprintf(file, "parentalcontrol = %d\n ", parentalcontrol ); - fprintf(file, "cover_path = %s\n ", covers_path ); - fprintf(file, "cover2d_path = %s\n ", covers2d_path ); - fprintf(file, "theme_path = %s\n ", theme_path ); - fprintf(file, "disc_path = %s\n ", disc_path ); - fprintf(file, "language_path = %s\n ", language_path ); - fprintf(file, "languagefiles_path = %s\n ", languagefiles_path ); - fprintf(file, "TxtCheatcodespath = %s\n ", TxtCheatcodespath ); - fprintf(file, "titlestxt_path = %s\n ", titlestxt_path ); - fprintf(file, "gamesound = %d\n ", gamesound ); - fprintf(file, "dolpath = %s\n ", dolpath ); - fprintf(file, "ogg_path = %s\n ", ogg_path ); - fprintf(file, "wiilight = %d\n ", wiilight ); - fprintf(file, "gameDisplay = %d\n ", gameDisplay ); - fprintf(file, "update_path = %s\n ", update_path ); - fprintf(file, "theme_downloadpath = %s\n ", theme_downloadpath ); - fprintf(file, "homebrewapps_path = %s\n ", homebrewapps_path ); - fprintf(file, "Cheatcodespath = %s\n ", Cheatcodespath ); - fprintf(file, "BcaCodepath = %s\n ", BcaCodepath ); - fprintf(file, "WipCodepath = %s\n ", WipCodepath ); - fprintf(file, "titlesOverride = %d\n ", titlesOverride ); - fprintf(file, "patchcountrystrings = %d\n ", patchcountrystrings ); - fprintf(file, "screensaver = %d\n ", screensaver ); - fprintf(file, "musicloopmode = %d\n ", musicloopmode ); - fprintf(file, "error002 = %d\n ", error002 ); - fprintf(file, "autonetwork = %d\n ", autonetwork ); - fprintf(file, "discart = %d\n ", discart ); - fprintf(file, "partition = %d\n ", partition ); - fprintf(file, "marknewtitles = %d\n ", marknewtitles ); - fprintf(file, "fatInstallToDir = %d\n ", FatInstallToDir ); - fprintf(file, "partitions = %d\n ", partitions_to_install ); - fprintf(file, "fullcopy = %d\n ", fullcopy ); - fprintf(file, "beta_upgrades = %d\n ", beta_upgrades ); - fprintf(file, "returnTo = %s\n ", returnTo ); + fprintf(file, "# USB Loader global settings file\n"); + fprintf(file, "# Note: This file is automatically generated\n "); + fprintf(file, "videomode = %d\n ", videomode); + fprintf(file, "videopatch = %d\n ", videopatch); + fprintf(file, "language = %d\n ", language); + fprintf(file, "ocarina = %d\n ", ocarina); + fprintf(file, "hddinfo = %d\n ", hddinfo); + fprintf(file, "sinfo = %d\n ", sinfo); + fprintf(file, "rumble = %d\n ", rumble); + fprintf(file, "volume = %d\n ", volume); + fprintf(file, "sfxvolume = %d\n ", sfxvolume); + fprintf(file, "gamesoundvolume = %d\n ", gamesoundvolume); + fprintf(file, "tooltips = %d\n ", tooltips); + fprintf(file, "password = %s\n ", unlockCode); + fprintf(file, "sort = %d\n ", sort); + fprintf(file, "fave = %d\n ", fave); + fprintf(file, "cios = %d\n ", cios); + fprintf(file, "keyset = %d\n ", keyset); + fprintf(file, "xflip = %d\n ", xflip); + fprintf(file, "gridRows = %d\n ", gridRows); + fprintf(file, "qboot = %d\n ", qboot); + fprintf(file, "wsprompt = %d\n ", wsprompt); + fprintf(file, "parentalcontrol = %d\n ", parentalcontrol); + fprintf(file, "cover_path = %s\n ", covers_path); + fprintf(file, "cover2d_path = %s\n ", covers2d_path); + fprintf(file, "theme_path = %s\n ", theme_path); + fprintf(file, "disc_path = %s\n ", disc_path); + fprintf(file, "language_path = %s\n ", language_path); + fprintf(file, "languagefiles_path = %s\n ", languagefiles_path); + fprintf(file, "TxtCheatcodespath = %s\n ", TxtCheatcodespath); + fprintf(file, "titlestxt_path = %s\n ", titlestxt_path); + fprintf(file, "gamesound = %d\n ", gamesound); + fprintf(file, "dolpath = %s\n ", dolpath); + fprintf(file, "ogg_path = %s\n ", ogg_path); + fprintf(file, "wiilight = %d\n ", wiilight); + fprintf(file, "gameDisplay = %d\n ", gameDisplay); + fprintf(file, "update_path = %s\n ", update_path); + fprintf(file, "theme_downloadpath = %s\n ", theme_downloadpath); + fprintf(file, "homebrewapps_path = %s\n ", homebrewapps_path); + fprintf(file, "Cheatcodespath = %s\n ", Cheatcodespath); + fprintf(file, "BcaCodepath = %s\n ", BcaCodepath); + fprintf(file, "WipCodepath = %s\n ", WipCodepath); + fprintf(file, "titlesOverride = %d\n ", titlesOverride); + fprintf(file, "patchcountrystrings = %d\n ", patchcountrystrings); + fprintf(file, "screensaver = %d\n ", screensaver); + fprintf(file, "musicloopmode = %d\n ", musicloopmode); + fprintf(file, "error002 = %d\n ", error002); + fprintf(file, "autonetwork = %d\n ", autonetwork); + fprintf(file, "discart = %d\n ", discart); + fprintf(file, "partition = %d\n ", partition); + fprintf(file, "marknewtitles = %d\n ", marknewtitles); + fprintf(file, "fatInstallToDir = %d\n ", FatInstallToDir); + fprintf(file, "partitions = %d\n ", partitions_to_install); + fprintf(file, "fullcopy = %d\n ", fullcopy); + fprintf(file, "beta_upgrades = %d\n ", beta_upgrades); + fprintf(file, "returnTo = %s\n ", returnTo); //fprintf(file, "widescreen = %d\n ", widescreen);// no need to save this to the settings. it is determined by the CONF_ stuff and there is no way to adjust it in the gui - fclose(file); + fclose(file); - return true; + return true; } bool CSettings::FindConfig() { - bool found = false; + bool found = false; strcpy(BootDevice, "SD:"); - for(int i = 0; i < 2; ++i) + for (int i = 0; i < 2; ++i) { - if(i == 1) - strcpy(BootDevice, "USB:"); + if (i == 1) strcpy(BootDevice, "USB:"); snprintf(ConfigPath, sizeof(ConfigPath), "%s/config/GXGlobal.cfg", BootDevice); - if((found = checkfile(ConfigPath))) - break; + if ((found = checkfile(ConfigPath))) break; snprintf(ConfigPath, sizeof(ConfigPath), "%s/apps/usbloader_gx/GXGlobal.cfg", BootDevice); - if((found = checkfile(ConfigPath))) - break; + if ((found = checkfile(ConfigPath))) break; } - if(!found) + if (!found) { FILE * testFp = NULL; strcpy(BootDevice, "SD:"); //! No existing config so try to find a place where we can write it too - for(int i = 0; i < 2; ++i) + for (int i = 0; i < 2; ++i) { - if(i == 1) - strcpy(BootDevice, "USB:"); - if(!found) + if (i == 1) strcpy(BootDevice, "USB:"); + if (!found) { snprintf(ConfigPath, sizeof(ConfigPath), "%s/config/GXGlobal.cfg", BootDevice); testFp = fopen(ConfigPath, "wb"); found = (testFp != NULL); fclose(testFp); } - if(!found) + if (!found) { snprintf(ConfigPath, sizeof(ConfigPath), "%s/apps/usbloader_gx/GXGlobal.cfg", BootDevice); testFp = fopen(ConfigPath, "wb"); @@ -261,25 +255,24 @@ bool CSettings::Load() { FindConfig(); - char line[1024]; + char line[1024]; char filepath[300]; snprintf(filepath, sizeof(filepath), "%s", ConfigPath); - file = fopen(filepath, "r"); - if (!file) - return false; + file = fopen(filepath, "r"); + if (!file) return false; - while (fgets(line, sizeof(line), file)) - { - if (line[0] == '#') continue; + while (fgets(line, sizeof(line), file)) + { + if (line[0] == '#') continue; this->ParseLine(line); - } - fclose(file); + } + fclose(file); - CFG_LoadTheme(widescreen, theme_path); + CFG_LoadTheme(widescreen, theme_path); - return true; + return true; } @@ -287,279 +280,318 @@ bool CSettings::Reset() { this->SetDefault(); - if(this->Save()) - return true; + if (this->Save()) return true; - return false; + return false; } bool CSettings::SetSetting(char *name, char *value) { int i = 0; - if (strcmp(name, "videomode") == 0) { - if (sscanf(value, "%d", &i) == 1) { - videomode = i; - } - return true; - } - else if (strcmp(name, "videopatch") == 0) { - if (sscanf(value, "%d", &i) == 1) { - videopatch = i; - } - return true; - } - else if (strcmp(name, "language") == 0) { - if (sscanf(value, "%d", &i) == 1) { - language = i; - } - return true; - } - else if (strcmp(name, "ocarina") == 0) { - if (sscanf(value, "%d", &i) == 1) { - ocarina = i; - } - return true; - } - else if (strcmp(name, "hddinfo") == 0) { - if (sscanf(value, "%d", &i) == 1) { - hddinfo = i; - } - return true; - } - else if (strcmp(name, "sinfo") == 0) { - if (sscanf(value, "%d", &i) == 1) { - sinfo = i; - } - return true; - } - else if (strcmp(name, "rumble") == 0) { - if (sscanf(value, "%d", &i) == 1) { - rumble = i; - } - return true; - } - else if (strcmp(name, "volume") == 0) { - if (sscanf(value, "%d", &i) == 1) { - volume = i; - } - return true; - } - else if (strcmp(name, "sfxvolume") == 0) { - if (sscanf(value, "%d", &i) == 1) { - sfxvolume = i; - } - return true; - } - else if (strcmp(name, "gamesoundvolume") == 0) { - if (sscanf(value, "%d", &i) == 1) { - gamesoundvolume = i; - } - return true; - } - else if (strcmp(name, "tooltips") == 0) { - if (sscanf(value, "%d", &i) == 1) { - tooltips = i; - } - return true; - } - else if (strcmp(name, "unlockCode") == 0) { - strcpy(unlockCode, value); - return true; - } - else if (strcmp(name, "sort") == 0) { - if (sscanf(value, "%d", &i) == 1) - sort = i; - return true; - } - else if (strcmp(name, "fave") == 0) { - if (sscanf(value, "%d", &i) == 1) - fave = i; - return true; - } - else if (strcmp(name, "cios") == 0) { - if (sscanf(value, "%d", &i) == 1) - cios = i; - return true; - } - else if (strcmp(name, "keyset") == 0) { - if (sscanf(value, "%d", &i) == 1) - keyset = i; - return true; - } - else if (strcmp(name, "xflip") == 0) { - if (sscanf(value, "%d", &i) == 1) - xflip = i; - return true; - } - else if (strcmp(name, "gridRows") == 0) { - if (sscanf(value, "%d", &i) == 1) - gridRows = i; - return true; - } - else if (strcmp(name, "qboot") == 0) { - if (sscanf(value, "%d", &i) == 1) - qboot = i; - return true; - } - else if (strcmp(name, "partition") == 0) { - if (sscanf(value, "%d", &i) == 1) - partition = i; - return true; - } - else if (strcmp(name, "wsprompt") == 0) { - if (sscanf(value, "%d", &i) == 1) - wsprompt = i; - return true; - } - else if (strcmp(name, "gameDisplay") == 0) { - if (sscanf(value, "%d", &i) == 1) - gameDisplay = i; - return true; - } - else if (strcmp(name, "parentalcontrol") == 0) { - if (sscanf(value, "%d", &i) == 1) - parentalcontrol = i; - return true; - } - else if (strcmp(name, "screensaver") == 0) { - if (sscanf(value, "%d", &i) == 1) - screensaver = i; - return true; - } - else if (strcmp(name, "titlesOverride") == 0) { - if (sscanf(value, "%d", &i) == 1) - titlesOverride = i; - return true; - } - else if (strcmp(name, "musicloopmode") == 0) { - if (sscanf(value, "%d", &i) == 1) - musicloopmode = i; - return true; - } - else if (strcmp(name, "gamesound") == 0) { - if (sscanf(value, "%d", &i) == 1) - gamesound = i; - return true; - } - else if (strcmp(name, "wiilight") == 0) { - if (sscanf(value, "%d", &i) == 1) - wiilight = i; - return true; - } - else if (strcmp(name, "marknewtitles") == 0) { - if (sscanf(value, "%d", &i) == 1) - marknewtitles = i; - return true; - } - else if (strcmp(name, "patchcountrystrings") == 0) { - if (sscanf(value, "%d", &i) == 1) - patchcountrystrings = i; - return true; - } - else if (strcmp(name, "fullcopy") == 0) { - if (sscanf(value, "%d", &i) == 1) - fullcopy = i; - return true; - } - else if (strcmp(name, "discart") == 0) { - if (sscanf(value, "%d", &i) == 1) - discart = i; - return true; - } - else if (strcmp(name, "error002") == 0) { - if (sscanf(value, "%d", &i) == 1) - error002 = i; - return true; - } - else if (strcmp(name, "autonetwork") == 0) { - if (sscanf(value, "%d", &i) == 1) - autonetwork = i; - return true; - } - else if (strcmp(name, "FatInstallToDir") == 0) { - if (sscanf(value, "%d", &i) == 1) - FatInstallToDir = i; - return true; - } - else if (strcmp(name, "beta_upgrades") == 0) { - if (sscanf(value, "%d", &i) == 1) - beta_upgrades = i; - return true; - } - else if (strcmp(name, "partitions_to_install") == 0) { - if (sscanf(value, "%d", &i) == 1) - partitions_to_install = i; - return true; - } - else if (strcmp(name, "covers_path") == 0) { - strcpy(covers_path, value); - return true; - } - else if (strcmp(name, "covers2d_path") == 0) { - strcpy(covers2d_path, value); - return true; - } - else if (strcmp(name, "theme_path") == 0) { - strcpy(theme_path, value); - return true; - } - else if (strcmp(name, "disc_path") == 0) { - strcpy(disc_path, value); - return true; - } - else if (strcmp(name, "language_path") == 0) { - strcpy(language_path, value); - return true; - } - else if (strcmp(name, "languagefiles_path") == 0) { - strcpy(languagefiles_path, value); - return true; - } - else if (strcmp(name, "TxtCheatcodespath") == 0) { - strcpy(TxtCheatcodespath, value); - return true; - } - else if (strcmp(name, "titlestxt_path") == 0) { - strcpy(titlestxt_path, value); - return true; - } - else if (strcmp(name, "dolpath") == 0) { - strcpy(dolpath, value); - return true; - } - else if (strcmp(name, "ogg_path") == 0) { - strcpy(ogg_path, value); - return true; - } - else if (strcmp(name, "update_path") == 0) { - strcpy(update_path, value); - return true; - } - else if (strcmp(name, "theme_downloadpath") == 0) { - strcpy(theme_downloadpath, value); - return true; - } - else if (strcmp(name, "homebrewapps_path") == 0) { - strcpy(homebrewapps_path, value); - return true; - } - else if (strcmp(name, "Cheatcodespath") == 0) { - strcpy(Cheatcodespath, value); - return true; - } - else if (strcmp(name, "BcaCodepath") == 0) { - strcpy(BcaCodepath, value); - return true; - } - else if (strcmp(name, "WipCodepath") == 0) { - strcpy(WipCodepath, value); - return true; - } - else if (strcmp(name, "returnTo") == 0) { - strcpy(returnTo, value); - return true; - } + if (strcmp(name, "videomode") == 0) + { + if (sscanf(value, "%d", &i) == 1) + { + videomode = i; + } + return true; + } + else if (strcmp(name, "videopatch") == 0) + { + if (sscanf(value, "%d", &i) == 1) + { + videopatch = i; + } + return true; + } + else if (strcmp(name, "language") == 0) + { + if (sscanf(value, "%d", &i) == 1) + { + language = i; + } + return true; + } + else if (strcmp(name, "ocarina") == 0) + { + if (sscanf(value, "%d", &i) == 1) + { + ocarina = i; + } + return true; + } + else if (strcmp(name, "hddinfo") == 0) + { + if (sscanf(value, "%d", &i) == 1) + { + hddinfo = i; + } + return true; + } + else if (strcmp(name, "sinfo") == 0) + { + if (sscanf(value, "%d", &i) == 1) + { + sinfo = i; + } + return true; + } + else if (strcmp(name, "rumble") == 0) + { + if (sscanf(value, "%d", &i) == 1) + { + rumble = i; + } + return true; + } + else if (strcmp(name, "volume") == 0) + { + if (sscanf(value, "%d", &i) == 1) + { + volume = i; + } + return true; + } + else if (strcmp(name, "sfxvolume") == 0) + { + if (sscanf(value, "%d", &i) == 1) + { + sfxvolume = i; + } + return true; + } + else if (strcmp(name, "gamesoundvolume") == 0) + { + if (sscanf(value, "%d", &i) == 1) + { + gamesoundvolume = i; + } + return true; + } + else if (strcmp(name, "tooltips") == 0) + { + if (sscanf(value, "%d", &i) == 1) + { + tooltips = i; + } + return true; + } + else if (strcmp(name, "unlockCode") == 0) + { + strcpy(unlockCode, value); + return true; + } + else if (strcmp(name, "sort") == 0) + { + if (sscanf(value, "%d", &i) == 1) sort = i; + return true; + } + else if (strcmp(name, "fave") == 0) + { + if (sscanf(value, "%d", &i) == 1) fave = i; + return true; + } + else if (strcmp(name, "cios") == 0) + { + if (sscanf(value, "%d", &i) == 1) cios = i; + return true; + } + else if (strcmp(name, "keyset") == 0) + { + if (sscanf(value, "%d", &i) == 1) keyset = i; + return true; + } + else if (strcmp(name, "xflip") == 0) + { + if (sscanf(value, "%d", &i) == 1) xflip = i; + return true; + } + else if (strcmp(name, "gridRows") == 0) + { + if (sscanf(value, "%d", &i) == 1) gridRows = i; + return true; + } + else if (strcmp(name, "qboot") == 0) + { + if (sscanf(value, "%d", &i) == 1) qboot = i; + return true; + } + else if (strcmp(name, "partition") == 0) + { + if (sscanf(value, "%d", &i) == 1) partition = i; + return true; + } + else if (strcmp(name, "wsprompt") == 0) + { + if (sscanf(value, "%d", &i) == 1) wsprompt = i; + return true; + } + else if (strcmp(name, "gameDisplay") == 0) + { + if (sscanf(value, "%d", &i) == 1) gameDisplay = i; + return true; + } + else if (strcmp(name, "parentalcontrol") == 0) + { + if (sscanf(value, "%d", &i) == 1) parentalcontrol = i; + return true; + } + else if (strcmp(name, "screensaver") == 0) + { + if (sscanf(value, "%d", &i) == 1) screensaver = i; + return true; + } + else if (strcmp(name, "titlesOverride") == 0) + { + if (sscanf(value, "%d", &i) == 1) titlesOverride = i; + return true; + } + else if (strcmp(name, "musicloopmode") == 0) + { + if (sscanf(value, "%d", &i) == 1) musicloopmode = i; + return true; + } + else if (strcmp(name, "gamesound") == 0) + { + if (sscanf(value, "%d", &i) == 1) gamesound = i; + return true; + } + else if (strcmp(name, "wiilight") == 0) + { + if (sscanf(value, "%d", &i) == 1) wiilight = i; + return true; + } + else if (strcmp(name, "marknewtitles") == 0) + { + if (sscanf(value, "%d", &i) == 1) marknewtitles = i; + return true; + } + else if (strcmp(name, "patchcountrystrings") == 0) + { + if (sscanf(value, "%d", &i) == 1) patchcountrystrings = i; + return true; + } + else if (strcmp(name, "fullcopy") == 0) + { + if (sscanf(value, "%d", &i) == 1) fullcopy = i; + return true; + } + else if (strcmp(name, "discart") == 0) + { + if (sscanf(value, "%d", &i) == 1) discart = i; + return true; + } + else if (strcmp(name, "error002") == 0) + { + if (sscanf(value, "%d", &i) == 1) error002 = i; + return true; + } + else if (strcmp(name, "autonetwork") == 0) + { + if (sscanf(value, "%d", &i) == 1) autonetwork = i; + return true; + } + else if (strcmp(name, "FatInstallToDir") == 0) + { + if (sscanf(value, "%d", &i) == 1) FatInstallToDir = i; + return true; + } + else if (strcmp(name, "beta_upgrades") == 0) + { + if (sscanf(value, "%d", &i) == 1) beta_upgrades = i; + return true; + } + else if (strcmp(name, "partitions_to_install") == 0) + { + if (sscanf(value, "%d", &i) == 1) partitions_to_install = i; + return true; + } + else if (strcmp(name, "covers_path") == 0) + { + strcpy(covers_path, value); + return true; + } + else if (strcmp(name, "covers2d_path") == 0) + { + strcpy(covers2d_path, value); + return true; + } + else if (strcmp(name, "theme_path") == 0) + { + strcpy(theme_path, value); + return true; + } + else if (strcmp(name, "disc_path") == 0) + { + strcpy(disc_path, value); + return true; + } + else if (strcmp(name, "language_path") == 0) + { + strcpy(language_path, value); + return true; + } + else if (strcmp(name, "languagefiles_path") == 0) + { + strcpy(languagefiles_path, value); + return true; + } + else if (strcmp(name, "TxtCheatcodespath") == 0) + { + strcpy(TxtCheatcodespath, value); + return true; + } + else if (strcmp(name, "titlestxt_path") == 0) + { + strcpy(titlestxt_path, value); + return true; + } + else if (strcmp(name, "dolpath") == 0) + { + strcpy(dolpath, value); + return true; + } + else if (strcmp(name, "ogg_path") == 0) + { + strcpy(ogg_path, value); + return true; + } + else if (strcmp(name, "update_path") == 0) + { + strcpy(update_path, value); + return true; + } + else if (strcmp(name, "theme_downloadpath") == 0) + { + strcpy(theme_downloadpath, value); + return true; + } + else if (strcmp(name, "homebrewapps_path") == 0) + { + strcpy(homebrewapps_path, value); + return true; + } + else if (strcmp(name, "Cheatcodespath") == 0) + { + strcpy(Cheatcodespath, value); + return true; + } + else if (strcmp(name, "BcaCodepath") == 0) + { + strcpy(BcaCodepath, value); + return true; + } + else if (strcmp(name, "WipCodepath") == 0) + { + strcpy(WipCodepath, value); + return true; + } + else if (strcmp(name, "returnTo") == 0) + { + strcpy(returnTo, value); + return true; + } return false; } @@ -572,30 +604,32 @@ void CSettings::ParseLine(char *line) char * eq = strchr(temp, '='); - if(!eq) return; + if (!eq) return; *eq = 0; this->TrimLine(name, temp, sizeof(name)); - this->TrimLine(value, eq+1, sizeof(value)); + this->TrimLine(value, eq + 1, sizeof(value)); - this->SetSetting(name, value); + this->SetSetting(name, value); } void CSettings::TrimLine(char *dest, char *src, int size) { - int len; - while (*src == ' ') src++; - len = strlen(src); - while (len > 0 && strchr(" \r\n", src[len-1])) len--; - if (len >= size) len = size-1; - strncpy(dest, src, len); - dest[len] = 0; + int len; + while (*src == ' ') + src++; + len = strlen(src); + while (len > 0 && strchr(" \r\n", src[len - 1])) + len--; + if (len >= size) len = size - 1; + strncpy(dest, src, len); + dest[len] = 0; } -static inline const char * GetLangCode( int langid ) +static inline const char * GetLangCode(int langid) { - switch ( langid ) + switch (langid) { case CONF_LANG_JAPANESE: return "JA"; @@ -626,90 +660,87 @@ bool CSettings::LoadLanguage(const char *path, int language) { bool ret = false; - if(language >= 0 || !path) + if (language >= 0 || !path) { - if(language < 0) - return false; + if (language < 0) return false; char filepath[150]; char langpath[150]; snprintf(langpath, sizeof(langpath), "%s", language_path); - if(langpath[strlen(langpath)-1] != '/') + if (langpath[strlen(langpath) - 1] != '/') { char * ptr = strrchr(langpath, '/'); - if(ptr) + if (ptr) { ptr++; ptr[0] = '\0'; } } - if(language == APP_DEFAULT) + if (language == APP_DEFAULT) { strcpy(language_path, langpath); gettextCleanUp(); return true; } - else if(language == CONSOLE_DEFAULT) + else if (language == CONSOLE_DEFAULT) { - return LoadLanguage(NULL, CONF_GetLanguage()+2); + return LoadLanguage(NULL, CONF_GetLanguage() + 2); } - else if(language == JAPANESE) + else if (language == JAPANESE) { snprintf(filepath, sizeof(filepath), "%s/japanese.lang", langpath); } - else if(language == ENGLISH) + else if (language == ENGLISH) { snprintf(filepath, sizeof(filepath), "%s/english.lang", langpath); } - else if(language == GERMAN) + else if (language == GERMAN) { snprintf(filepath, sizeof(filepath), "%s/german.lang", langpath); } - else if(language == FRENCH) + else if (language == FRENCH) { snprintf(filepath, sizeof(filepath), "%s/french.lang", langpath); } - else if(language == SPANISH) + else if (language == SPANISH) { snprintf(filepath, sizeof(filepath), "%s/spanish.lang", langpath); } - else if(language == ITALIAN) + else if (language == ITALIAN) { snprintf(filepath, sizeof(filepath), "%s/italian.lang", langpath); } - else if(language == DUTCH) + else if (language == DUTCH) { snprintf(filepath, sizeof(filepath), "%s/dutch.lang", langpath); } - else if(language == S_CHINESE) + else if (language == S_CHINESE) { snprintf(filepath, sizeof(filepath), "%s/s_chinese.lang", langpath); } - else if(language == T_CHINESE) + else if (language == T_CHINESE) { snprintf(filepath, sizeof(filepath), "%s/t_chinese.lang", langpath); } - else if(language == KOREAN) + else if (language == KOREAN) { snprintf(filepath, sizeof(filepath), "%s%s/korean.lang", BootDevice, langpath); } ret = gettextLoadLanguage(filepath); - if(ret) - strncpy(language_path, filepath, sizeof(language_path)); + if (ret) strncpy(language_path, filepath, sizeof(language_path)); strcpy(db_language, GetLangCode(language)); } - else if(strlen(path) < 3) + else if (strlen(path) < 3) { - return LoadLanguage(NULL, CONF_GetLanguage()+2); + return LoadLanguage(NULL, CONF_GetLanguage() + 2); } else { ret = gettextLoadLanguage(path); - if(ret) - strncpy(language_path, path, sizeof(language_path)); + if (ret) strncpy(language_path, path, sizeof(language_path)); } return ret; diff --git a/source/settings/CSettings.h b/source/settings/CSettings.h index f6816ff6..260a62c3 100644 --- a/source/settings/CSettings.h +++ b/source/settings/CSettings.h @@ -1,4 +1,4 @@ - /**************************************************************************** +/**************************************************************************** * Copyright (C) 2010 * by Dimok * @@ -29,7 +29,8 @@ #include #include "cfg.h" -enum { +enum +{ APP_DEFAULT = 0, CONSOLE_DEFAULT, JAPANESE, @@ -48,92 +49,92 @@ enum { class CSettings { public: - //!Constructor + //!Constructor CSettings(); - //!Destructor - ~CSettings(); - //!Set Default Settings - void SetDefault(); - //!Load Settings - bool Load(); - //!Save Settings + //!Destructor + ~CSettings(); + //!Set Default Settings + void SetDefault(); + //!Load Settings + bool Load(); + //!Save Settings bool Save(); - //!Reset Settings + //!Reset Settings bool Reset(); - //!Load a languagefile - //!\param language + //!Load a languagefile + //!\param language bool LoadLanguage(const char *path, int language = -1); /** Variables **/ - char BootDevice[10]; - char ConfigPath[80]; - short videomode; - short language; - short ocarina; - short videopatch; - short sinfo; - short hddinfo; - short rumble; - short xflip; - int volume; - int sfxvolume; - int gamesoundvolume; - short tooltips; - char unlockCode[20]; - short parentalcontrol; - short cios; - short quickboot; - short wsprompt; - short keyset; - short sort; - short fave; - short wiilight; - short gameDisplay; - short patchcountrystrings; - short screensaver; - short partition; - short musicloopmode; - short widescreen; - short godmode; - char covers_path[100]; - char covers2d_path[100]; - char theme_path[100]; - char theme_downloadpath[100]; - char disc_path[100]; - char titlestxt_path[100]; - char language_path[100]; - char languagefiles_path[100]; - char ogg_path[250]; - 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; - short titlesOverride; // db_titles - char db_url[200]; - char db_language[20]; - short db_JPtoEN; - short gridRows; - short autonetwork; - short discart; - short gamesound; - short marknewtitles; - short FatInstallToDir; - short partitions_to_install; - short fullcopy; - short beta_upgrades; - char returnTo[20]; + char BootDevice[10]; + char ConfigPath[80]; + short videomode; + short language; + short ocarina; + short videopatch; + short sinfo; + short hddinfo; + short rumble; + short xflip; + int volume; + int sfxvolume; + int gamesoundvolume; + short tooltips; + char unlockCode[20]; + short parentalcontrol; + short cios; + short quickboot; + short wsprompt; + short keyset; + short sort; + short fave; + short wiilight; + short gameDisplay; + short patchcountrystrings; + short screensaver; + short partition; + short musicloopmode; + short widescreen; + short godmode; + char covers_path[100]; + char covers2d_path[100]; + char theme_path[100]; + char theme_downloadpath[100]; + char disc_path[100]; + char titlestxt_path[100]; + char language_path[100]; + char languagefiles_path[100]; + char ogg_path[250]; + 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; + short titlesOverride; // db_titles + char db_url[200]; + char db_language[20]; + short db_JPtoEN; + short gridRows; + short autonetwork; + short discart; + short gamesound; + short marknewtitles; + short FatInstallToDir; + short partitions_to_install; + short fullcopy; + short beta_upgrades; + char returnTo[20]; struct { - u8 enabled; - u8 rating; - u8 pin[4]; - u8 question; - wchar_t answer[32]; // IS WCHAR! + u8 enabled; + u8 rating; + u8 pin[4]; + u8 question; + wchar_t answer[32]; // IS WCHAR! } Parental; protected: bool SetSetting(char *name, char *value); diff --git a/source/settings/Settings.cpp b/source/settings/Settings.cpp index ade47bb0..21254eeb 100644 --- a/source/settings/Settings.cpp +++ b/source/settings/Settings.cpp @@ -44,18 +44,25 @@ extern PartList partitions; extern char game_partition[6]; extern u8 load_from_fs; -static const char *opts_no_yes[settings_off_on_max] = {trNOOP( "No" ), trNOOP( "Yes" ) }; -static const char *opts_off_on[settings_off_on_max] = {trNOOP( "OFF" ), trNOOP( "ON" ) }; -static const char *opts_videomode[settings_language_max][2] = {{"", trNOOP( "Disc Default" )}, {trNOOP( "System Default" ), ""}, {trNOOP( "AutoPatch" ), ""}, {trNOOP( "Force" ), " PAL50"}, {trNOOP( "Force" ), " PAL60"}, {trNOOP( "Force" ), " NTSC"}}; -static const char *opts_language[settings_language_max] = {trNOOP( "Console Default" ), trNOOP( "Japanese" ), trNOOP( "English" ), trNOOP( "German" ), trNOOP( "French" ), trNOOP( "Spanish" ), trNOOP( "Italian" ), trNOOP( "Dutch" ), trNOOP( "SChinese" ), trNOOP( "TChinese" ), trNOOP( "Korean" )}; -static const char *opts_parentalcontrol[5] = {trNOOP( "0 (Everyone)" ), trNOOP( "1 (Child 7+)" ), trNOOP( "2 (Teen 12+)" ), trNOOP( "3 (Mature 16+)" ), trNOOP( "4 (Adults Only 18+)" )}; -static const char *opts_error002[3] = {trNOOP( "No" ), trNOOP( "Yes" ), trNOOP( "Anti" )}; -static const char *opts_partitions[settings_partitions_max] = {trNOOP( "Game partition" ), trNOOP( "All partitions" ), trNOOP( "Remove update" )}; -static const char *opts_installdir[settings_installdir_max] = {trNOOP( "None" ), trNOOP( "GAMEID_Gamename" ), trNOOP( "Gamename [GAMEID]" )}; +static const char *opts_no_yes[settings_off_on_max] = { trNOOP( "No" ), trNOOP( "Yes" ) }; +static const char *opts_off_on[settings_off_on_max] = { trNOOP( "OFF" ), trNOOP( "ON" ) }; +static const char *opts_videomode[settings_language_max][2] = { { "", trNOOP( "Disc Default" ) }, { + trNOOP( "System Default" ), "" }, { trNOOP( "AutoPatch" ), "" }, { trNOOP( "Force" ), " PAL50" }, { + trNOOP( "Force" ), " PAL60" }, { trNOOP( "Force" ), " NTSC" } }; +static const char *opts_language[settings_language_max] = { trNOOP( "Console Default" ), trNOOP( "Japanese" ), + trNOOP( "English" ), trNOOP( "German" ), trNOOP( "French" ), trNOOP( "Spanish" ), trNOOP( "Italian" ), + trNOOP( "Dutch" ), trNOOP( "SChinese" ), trNOOP( "TChinese" ), trNOOP( "Korean" ) }; +static const char *opts_parentalcontrol[5] = { trNOOP( "0 (Everyone)" ), trNOOP( "1 (Child 7+)" ), + trNOOP( "2 (Teen 12+)" ), trNOOP( "3 (Mature 16+)" ), trNOOP( "4 (Adults Only 18+)" ) }; +static const char *opts_error002[3] = { trNOOP( "No" ), trNOOP( "Yes" ), trNOOP( "Anti" ) }; +static const char *opts_partitions[settings_partitions_max] = { trNOOP( "Game partition" ), trNOOP( "All partitions" ), + trNOOP( "Remove update" ) }; +static const char *opts_installdir[settings_installdir_max] = { trNOOP( "None" ), trNOOP( "GAMEID_Gamename" ), + trNOOP( "Gamename [GAMEID]" ) }; -bool IsValidPartition( int fs_type, int cios ) +bool IsValidPartition(int fs_type, int cios) { - if ( cios == 249 || cios == 250 ) + if (cios == 249 || cios == 250) { return fs_type == FS_TYPE_WBFS; } @@ -77,233 +84,239 @@ int MenuSettings() // backup game language setting char opt_lang[100]; - strcpy( opt_lang, Settings.language_path ); + 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 + FADE, LEFT, RIGHT }; int slidedirection = FADE; - GuiSound btnSoundOver( button_over_pcm, button_over_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 ); + 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 btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%ssettings_background.png", Settings.theme_path ); - GuiImageData settingsbg( imgPath, settings_background_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", Settings.theme_path); + GuiImageData settingsbg(imgPath, settings_background_png); - snprintf( imgPath, sizeof( imgPath ), "%ssettings_title.png", Settings.theme_path ); - GuiImageData MainButtonImgData( imgPath, settings_title_png ); + snprintf(imgPath, sizeof(imgPath), "%ssettings_title.png", Settings.theme_path); + GuiImageData MainButtonImgData(imgPath, settings_title_png); - snprintf( imgPath, sizeof( imgPath ), "%ssettings_title_over.png", Settings.theme_path ); - GuiImageData MainButtonImgOverData( imgPath, settings_title_over_png ); + snprintf(imgPath, sizeof(imgPath), "%ssettings_title_over.png", Settings.theme_path); + GuiImageData MainButtonImgOverData(imgPath, settings_title_over_png); - snprintf( imgPath, sizeof( imgPath ), "%spageindicator.png", Settings.theme_path ); - GuiImageData PageindicatorImgData( imgPath, pageindicator_png ); + snprintf(imgPath, sizeof(imgPath), "%spageindicator.png", Settings.theme_path); + GuiImageData PageindicatorImgData(imgPath, pageindicator_png); - snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_left.png", Settings.theme_path ); - GuiImageData arrow_left( imgPath, startgame_arrow_left_png ); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", Settings.theme_path); + GuiImageData arrow_left(imgPath, startgame_arrow_left_png); - snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_right.png", Settings.theme_path ); - GuiImageData arrow_right( imgPath, startgame_arrow_right_png ); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", Settings.theme_path); + GuiImageData arrow_right(imgPath, startgame_arrow_right_png); - snprintf( imgPath, sizeof( imgPath ), "%scredits_button.png", Settings.theme_path ); - GuiImageData creditsImgData( imgPath, credits_button_png ); + snprintf(imgPath, sizeof(imgPath), "%scredits_button.png", Settings.theme_path); + GuiImageData creditsImgData(imgPath, credits_button_png); - snprintf( imgPath, sizeof( imgPath ), "%scredits_button_over.png", Settings.theme_path ); - GuiImageData creditsOver( imgPath, credits_button_over_png ); + snprintf(imgPath, sizeof(imgPath), "%scredits_button_over.png", Settings.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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + trigMinus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0); GuiTrigger trigPlus; - trigPlus.SetButtonOnlyTrigger( -1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0 ); + 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 ) + GuiText backBtnTxt(tr( "Back" ), 22, THEME.prompttext); + backBtnTxt.SetMaxWidth(btnOutline.GetWidth() - 30); + GuiImage backBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - backBtnTxt.SetWidescreen( Settings.widescreen ); - backBtnImg.SetWidescreen( Settings.widescreen ); + backBtnTxt.SetWidescreen(Settings.widescreen); + backBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton backBtn( &backBtnImg, &backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2, 1 ); - backBtn.SetLabel( &backBtnTxt ); - backBtn.SetTrigger( &trigB ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + GoRightBtn.SetTrigger(&trigA); + GoRightBtn.SetTrigger(&trigR); + GoRightBtn.SetTrigger(&trigPlus); char MainButtonText[50]; - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", " " ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + MainButton4.SetTrigger(&trigA); - customOptionList options2( MAXOPTIONS ); - GuiCustomOptionBrowser optionBrowser2( 396, 280, &options2, Settings.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, Settings.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 ) + while (pageToDisplay > 0) { - usleep( 100 ); + usleep(100); menu = MENU_NONE; - if ( pageToDisplay == 1 ) + if (pageToDisplay == 1) { /** Standard procedure made in all pages **/ MainButton1.StopEffect(); @@ -311,64 +324,66 @@ int MenuSettings() MainButton3.StopEffect(); MainButton4.StopEffect(); - if ( slidedirection == RIGHT ) + 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 ); + 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 ) + 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 ); + 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(); - 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 ); + 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 ); + 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 ); + MainButton4.SetImage(&MainButton4Img); + MainButton4.SetImageOver(&MainButton4ImgOver); /** Disable ability to click through MainButtons */ - optionBrowser2.SetClickable( false ); + optionBrowser2.SetClickable(false); /** Default no scrollbar and reset position **/ -// optionBrowser2.SetScrollbar(0); - optionBrowser2.SetOffset( 0 ); + // optionBrowser2.SetScrollbar(0); + optionBrowser2.SetOffset(0); MainButton1.StopEffect(); MainButton2.StopEffect(); @@ -380,36 +395,37 @@ int MenuSettings() MainButton3.SetEffectGrow(); MainButton4.SetEffectGrow(); - if ( slidedirection == FADE ) + if (slidedirection == FADE) { - 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); } - else if ( slidedirection == LEFT ) + 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 ); + 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 ) + 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 ); + 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(); - while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + while (MainButton1.GetEffect() > 0) + usleep(50); } - else if ( pageToDisplay == 2 ) + else if (pageToDisplay == 2) { /** Standard procedure made in all pages **/ MainButton1.StopEffect(); @@ -417,64 +433,66 @@ int MenuSettings() MainButton3.StopEffect(); MainButton4.StopEffect(); - if ( slidedirection == RIGHT ) + 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 ); + 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 ) + 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 ); + 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(); - 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 ); + 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 ); + 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 ); + MainButton4.SetImage(&creditsImg); + MainButton4.SetImageOver(&creditsImgOver); /** Disable ability to click through MainButtons */ - optionBrowser2.SetClickable( false ); + optionBrowser2.SetClickable(false); /** Default no scrollbar and reset position **/ -// optionBrowser2.SetScrollbar(0); - optionBrowser2.SetOffset( 0 ); + // optionBrowser2.SetScrollbar(0); + optionBrowser2.SetOffset(0); MainButton1.StopEffect(); MainButton2.StopEffect(); @@ -486,36 +504,37 @@ int MenuSettings() MainButton3.SetEffectGrow(); MainButton4.SetEffectGrow(); - if ( slidedirection == FADE ) + if (slidedirection == FADE) { - 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); } - else if ( slidedirection == LEFT ) + 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 ); + 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 ) + 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 ); + 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(); - while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + while (MainButton1.GetEffect() > 0) + usleep(50); } - else if ( pageToDisplay == 3 ) + else if (pageToDisplay == 3) { /** Standard procedure made in all pages **/ MainButton1.StopEffect(); @@ -523,57 +542,59 @@ int MenuSettings() MainButton3.StopEffect(); MainButton4.StopEffect(); - if ( slidedirection == RIGHT ) + 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 ); + 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 ) + 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 ); + 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(); - 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 ); + 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(&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 ); + optionBrowser2.SetClickable(false); /** Default no scrollbar and reset position **/ -// optionBrowser2.SetScrollbar(0); - optionBrowser2.SetOffset( 0 ); + // optionBrowser2.SetScrollbar(0); + optionBrowser2.SetOffset(0); MainButton1.StopEffect(); MainButton2.StopEffect(); @@ -585,937 +606,941 @@ int MenuSettings() MainButton3.SetEffectGrow(); MainButton4.SetEffectGrow(); - if ( slidedirection == FADE ) + if (slidedirection == FADE) { - 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); } - else if ( slidedirection == LEFT ) + 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 ); + 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 ) + 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 ); + 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(); - while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + while (MainButton1.GetEffect() > 0) + usleep(50); } - while ( menu == MENU_NONE ) + while (menu == MENU_NONE) { - usleep( 100 ); + usleep(100); - if ( shutdown == 1 ) - Sys_Shutdown(); - if ( reset == 1 ) - Sys_Reboot(); + if (shutdown == 1) Sys_Shutdown(); + if (reset == 1) Sys_Reboot(); - if ( pageToDisplay == 1 ) + if (pageToDisplay == 1) { - if ( MainButton1.GetState() == STATE_CLICKED ) + 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 ); + 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" ) ); + 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 ); + options2.SetLength(0); + // optionBrowser2.SetScrollbar(1); + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); ResumeGui(); - optionBrowser2.SetEffect( EFFECT_FADE, 20 ); - while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + optionBrowser2.SetEffect(EFFECT_FADE, 20); + while (optionBrowser2.GetEffect() > 0) + usleep(50); int returnhere = 1; char * languagefile; - languagefile = strrchr( Settings.language_path, '/' ) + 1; + languagefile = strrchr(Settings.language_path, '/') + 1; bool firstRun = true; - while ( !exit ) + while (!exit) { - usleep( 100 ); + usleep(100); returnhere = 1; - if ( shutdown == 1 ) - Sys_Shutdown(); - if ( reset == 1 ) + if (shutdown == 1) Sys_Shutdown(); + if (reset == 1) Sys_Reboot(); - else if ( backBtn.GetState() == STATE_CLICKED ) + else if (backBtn.GetState() == STATE_CLICKED) { backBtn.ResetState(); exit = true; break; } - else if ( menu == MENU_DISCLIST ) + else if (menu == MENU_DISCLIST) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + w.Remove(&optionBrowser2); + w.Remove(&backBtn); WindowCredits(); - w.Append( &optionBrowser2 ); - w.Append( &backBtn ); + w.Append(&optionBrowser2); + w.Append(&backBtn); } - else if ( homo.GetState() == STATE_CLICKED ) + else if (homo.GetState() == STATE_CLICKED) { Settings.Save(); - optionBrowser2.SetState( STATE_DISABLED ); + optionBrowser2.SetState(STATE_DISABLED); bgMusic->Pause(); choice = WindowExitPrompt(); bgMusic->Resume(); - if ( choice == 3 ) + if (choice == 3) Sys_LoadMenu(); // Back to System Menu - else if ( choice == 2 ) + else if (choice == 2) Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState( STATE_DEFAULT ); + else homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); } ret = optionBrowser2.GetClickedOption(); - if ( firstRun || ret >= 0 ) + if (firstRun || ret >= 0) { int Idx = -1; - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "App Language" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "App Language" )); + if (ret == Idx) { - if ( isInserted( bootDevice ) ) + if (isInserted(bootDevice)) { - if ( Settings.godmode == 1 ) + if (Settings.godmode == 1) { - w.SetEffect( EFFECT_FADE, -20 ); - while ( w.GetEffect() > 0 ) usleep( 50 ); - mainWindow->Remove( &w ); - while ( returnhere == 1 ) + w.SetEffect(EFFECT_FADE, -20); + while (w.GetEffect() > 0) + usleep(50); + mainWindow->Remove(&w); + while (returnhere == 1) returnhere = MenuLanguageSelect(); - if ( returnhere == 2 ) + if (returnhere == 2) { menu = MENU_SETTINGS; pageToDisplay = 0; exit = true; - mainWindow->Append( &w ); + mainWindow->Append(&w); break; } else { HaltGui(); - mainWindow->Append( &w ); - w.SetEffect( EFFECT_FADE, 20 ); + mainWindow->Append(&w); + w.SetEffect(EFFECT_FADE, 20); ResumeGui(); - while ( w.GetEffect() > 0 ) usleep( 50 ); + while (w.GetEffect() > 0) + usleep(50); } } else { - WindowPrompt( tr( "Language change:" ), tr( "Console should be unlocked to modify it." ), tr( "OK" ) ); + 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" ) ); + 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 (!strcmp("notset", Settings.language_path)) + options2.SetValue(Idx, "%s", tr( "Default" )); + else options2.SetValue(Idx, "%s", languagefile); } - if ( ret == ++Idx || firstRun ) + 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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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 (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] ) ); + 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" ) ); + optionBrowser2.SetEffect(EFFECT_FADE, -20); + while (optionBrowser2.GetEffect() > 0) + usleep(50); + titleTxt.SetText(tr( "Settings" )); slidedirection = FADE; - if ( returnhere != 2 ) - pageToDisplay = 1; + if (returnhere != 2) pageToDisplay = 1; MainButton1.ResetState(); break; } - else if ( MainButton2.GetState() == STATE_CLICKED ) + 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 ); + 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" ) ); + 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 ); + options2.SetLength(0); + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); ResumeGui(); - optionBrowser2.SetEffect( EFFECT_FADE, 20 ); - while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + optionBrowser2.SetEffect(EFFECT_FADE, 20); + while (optionBrowser2.GetEffect() > 0) + usleep(50); bool firstRun = true; - while ( !exit ) + while (!exit) { - usleep( 100 ); + usleep(100); - if ( shutdown == 1 ) - Sys_Shutdown(); - if ( reset == 1 ) + if (shutdown == 1) Sys_Shutdown(); + if (reset == 1) Sys_Reboot(); - else if ( backBtn.GetState() == STATE_CLICKED ) + else if (backBtn.GetState() == STATE_CLICKED) { backBtn.ResetState(); exit = true; break; } - else if ( homo.GetState() == STATE_CLICKED ) + else if (homo.GetState() == STATE_CLICKED) { Settings.Save(); - optionBrowser2.SetState( STATE_DISABLED ); + optionBrowser2.SetState(STATE_DISABLED); bgMusic->Pause(); choice = WindowExitPrompt(); bgMusic->Resume(); - if ( choice == 3 ) - Sys_LoadMenu(); // Back to System Menu - if ( choice == 2 ) + if (choice == 3) Sys_LoadMenu(); // Back to System Menu + if (choice == 2) Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState( STATE_DEFAULT ); + else homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); } ret = optionBrowser2.GetClickedOption(); - if ( firstRun || ret >= 0 ) + if (firstRun || ret >= 0) { int Idx = -1; - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Video Mode" ) ); - if ( ret == Idx && ++Settings.videomode >= settings_video_max ) - Settings.videomode = 0; - options2.SetValue( Idx, "%s%s", opts_videomode[Settings.videomode][0], tr( opts_videomode[Settings.videomode][1] ) ); + if (firstRun) options2.SetName(Idx, "%s", tr( "Video Mode" )); + if (ret == Idx && ++Settings.videomode >= settings_video_max) Settings.videomode = 0; + options2.SetValue(Idx, "%s%s", opts_videomode[Settings.videomode][0], + tr( opts_videomode[Settings.videomode][1] )); } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "VIDTV Patch" ) ); - if ( ret == Idx && ++Settings.videopatch >= settings_off_on_max ) - Settings.videopatch = 0; - options2.SetValue( Idx, "%s", tr( opts_off_on[Settings.videopatch] ) ); + if (firstRun) options2.SetName(Idx, "%s", tr( "VIDTV Patch" )); + if (ret == Idx && ++Settings.videopatch >= settings_off_on_max) Settings.videopatch = 0; + options2.SetValue(Idx, "%s", tr( opts_off_on[Settings.videopatch] )); } - if ( ret == ++Idx || firstRun ) + 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 (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 (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 (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 (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 (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 (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Boot/Standard" ) ); - if ( ret == Idx && Settings.godmode == 1 ) + if (firstRun) options2.SetName(Idx, "%s", tr( "Boot/Standard" )); + if (ret == Idx && Settings.godmode == 1) { - switch(Settings.cios) + switch (Settings.cios) { - case 222: - Settings.cios = 223; - break; - case 223: - Settings.cios = 224; - break; - case 224: - Settings.cios = 249; - break; - case 249: - Settings.cios = 250; - break; - case 250: - Settings.cios = 222; - break; - default: - Settings.cios = 222; - break; + case 222: + Settings.cios = 223; + break; + case 223: + Settings.cios = 224; + break; + case 224: + Settings.cios = 249; + break; + case 249: + Settings.cios = 250; + break; + case 250: + Settings.cios = 222; + break; + default: + Settings.cios = 222; + break; } - if ( ( Settings.cios == 222 && titles.VersionOf( 0x1000000deULL ) != 4 ) || ( Settings.cios == 2 && titles.VersionOf( 0x1000000dfULL ) != 4 ) ) + if ((Settings.cios == 222 && titles.VersionOf(0x1000000deULL) != 4) + || (Settings.cios == 2 && titles.VersionOf(0x1000000dfULL) != 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" ) ); + 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, "IOS %i", Settings.cios ); - else - options2.SetValue( Idx, "********" ); + if (Settings.godmode == 1) + options2.SetValue(Idx, "IOS %i", Settings.cios); + else options2.SetValue(Idx, "********"); } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Partition" ) ); - if ( ret == Idx ) + 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 ) ); + 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 ); + 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 ); + 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 (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 (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 (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Quick Boot" ) ); - if ( ret == Idx && ++Settings.quickboot >= settings_off_on_max ) - Settings.quickboot = 0; - options2.SetValue( Idx, "%s", tr( opts_no_yes[Settings.quickboot] ) ); + if (firstRun) options2.SetName(Idx, "%s", tr( "Quick Boot" )); + if (ret == Idx && ++Settings.quickboot >= settings_off_on_max) Settings.quickboot = 0; + options2.SetValue(Idx, "%s", tr( opts_no_yes[Settings.quickboot] )); } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Error 002 fix" ) ); - if ( ret == Idx && ++Settings.error002 >= 3 ) - Settings.error002 = 0; - options2.SetValue( Idx, "%s", tr( opts_error002[Settings.error002] ) ); + if (firstRun) options2.SetName(Idx, "%s", tr( "Error 002 fix" )); + if (ret == Idx && ++Settings.error002 >= 3) Settings.error002 = 0; + options2.SetValue(Idx, "%s", tr( opts_error002[Settings.error002] )); } - if ( ret == ++Idx || firstRun ) + 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 (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] ) ); - } + 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] )); + } - if ( ret == ++Idx || firstRun ) - { - char* name = NULL; - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Return To" ) ); - if ( ret == Idx ) - { - char tidChar[ 10 ]; - bool getChannel = TitleSelector( tidChar ); - if( getChannel ) - { - snprintf( Settings.returnTo, sizeof( Settings.returnTo ), "%s", tidChar ); - } - } - int haveTitle = titles.FindU32( Settings.returnTo ); - if( haveTitle >= 0 ) - { - name = (char*)titles.NameFromIndex( haveTitle ); - if( !strlen( name ) ) - name = NULL; - } - options2.SetValue( Idx, "%s", name ? name : tr( opts_off_on[ 0 ] ) ); - } + if (ret == ++Idx || firstRun) + { + char* name = NULL; + if (firstRun) options2.SetName(Idx, "%s", tr( "Return To" )); + if (ret == Idx) + { + char tidChar[10]; + bool getChannel = TitleSelector(tidChar); + if (getChannel) + { + snprintf(Settings.returnTo, sizeof(Settings.returnTo), "%s", tidChar); + } + } + int haveTitle = titles.FindU32(Settings.returnTo); + if (haveTitle >= 0) + { + name = (char*) titles.NameFromIndex(haveTitle); + if (!strlen(name)) name = NULL; + } + options2.SetValue(Idx, "%s", name ? name : tr( opts_off_on[ 0 ] )); + } firstRun = false; } } - optionBrowser2.SetEffect( EFFECT_FADE, -20 ); - while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); - titleTxt.SetText( tr( "Settings" ) ); + 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 ) + 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 ); + 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" ) ); + 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 ); + options2.SetLength(0); + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); ResumeGui(); - optionBrowser2.SetEffect( EFFECT_FADE, 20 ); - while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + optionBrowser2.SetEffect(EFFECT_FADE, 20); + while (optionBrowser2.GetEffect() > 0) + usleep(50); bool firstRun = true; - while ( !exit ) + while (!exit) { - usleep( 100 ); + usleep(100); - if ( shutdown == 1 ) - Sys_Shutdown(); - if ( reset == 1 ) + if (shutdown == 1) Sys_Shutdown(); + if (reset == 1) Sys_Reboot(); - else if ( backBtn.GetState() == STATE_CLICKED ) + else if (backBtn.GetState() == STATE_CLICKED) { backBtn.ResetState(); exit = true; break; } - else if ( homo.GetState() == STATE_CLICKED ) + else if (homo.GetState() == STATE_CLICKED) { Settings.Save(); - optionBrowser2.SetState( STATE_DISABLED ); + optionBrowser2.SetState(STATE_DISABLED); bgMusic->Pause(); choice = WindowExitPrompt(); bgMusic->Resume(); - if ( choice == 3 ) + if (choice == 3) Sys_LoadMenu(); // Back to System Menu - else if ( choice == 2 ) + else if (choice == 2) Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState( STATE_DEFAULT ); + else homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); } ret = optionBrowser2.GetClickedOption(); - if ( firstRun || ret >= 0 ) + if (firstRun || ret >= 0) { int Idx = -1; - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Console" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "Console" )); + if (ret == Idx) { - if ( !strcmp( "", Settings.unlockCode ) && Settings.Parental.enabled == 0 ) + if (!strcmp("", Settings.unlockCode) && Settings.Parental.enabled == 0) { Settings.godmode = !Settings.godmode; } - else if ( Settings.godmode == 0 ) + else if (Settings.godmode == 0) { char entered[20]; - memset( entered, 0, 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 ) + 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 (!strcmp(entered, Settings.unlockCode) || !memcmp(entered, + Settings.Parental.pin, 4)) //if password correct { - if ( Settings.godmode == 0 ) + if (Settings.godmode == 0) { - WindowPrompt( tr( "Correct Password" ), tr( "All the features of USB Loader GX are unlocked." ), tr( "OK" ) ); + 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 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 ) + 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" ) ); + 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] ) ); + static const char *opts[] = { trNOOP( "Locked" ), trNOOP( "Unlocked" ) }; + options2.SetValue(Idx, "%s", tr( opts[Settings.godmode] )); } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Password" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "Password" )); + if (ret == Idx) { - if ( Settings.godmode == 1 ) + if (Settings.godmode == 1) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + 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(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" ) ); + 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" ) ); + 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 (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 (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, "********" ); + 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" ) ); + 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 ) + 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 ); + 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" ) ); + 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 ); + options2.SetLength(0); + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); ResumeGui(); - optionBrowser2.SetEffect( EFFECT_FADE, 20 ); - while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); - + optionBrowser2.SetEffect(EFFECT_FADE, 20); + while (optionBrowser2.GetEffect() > 0) + usleep(50); bool firstRun = true; - while ( !exit ) + while (!exit) { - usleep( 100 ); + usleep(100); bool returnhere = true; - if ( shutdown == 1 ) - Sys_Shutdown(); - if ( reset == 1 ) + if (shutdown == 1) Sys_Shutdown(); + if (reset == 1) Sys_Reboot(); - else if ( backBtn.GetState() == STATE_CLICKED ) + else if (backBtn.GetState() == STATE_CLICKED) { backBtn.ResetState(); exit = true; break; } - else if ( homo.GetState() == STATE_CLICKED ) + else if (homo.GetState() == STATE_CLICKED) { Settings.Save(); - optionBrowser2.SetState( STATE_DISABLED ); + optionBrowser2.SetState(STATE_DISABLED); bgMusic->Pause(); choice = WindowExitPrompt(); bgMusic->Resume(); - if ( choice == 3 ) + if (choice == 3) Sys_LoadMenu(); // Back to System Menu - else if ( choice == 2 ) + else if (choice == 2) Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState( STATE_DEFAULT ); + else homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); } ret = optionBrowser2.GetClickedOption(); - if ( firstRun || ret >= 0 ) + if (firstRun || ret >= 0) { int Idx = -1; - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Backgroundmusic" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "Backgroundmusic" )); + if (ret == Idx) { - if ( isInserted( bootDevice ) ) + if (isInserted(bootDevice)) { - w.SetEffect( EFFECT_FADE, -20 ); - while ( w.GetEffect() > 0 ) usleep( 50 ); - mainWindow->Remove( &w ); + w.SetEffect(EFFECT_FADE, -20); + while (w.GetEffect() > 0) + usleep(50); + mainWindow->Remove(&w); returnhere = MenuBackgroundMusic(); HaltGui(); - mainWindow->Append( &w ); - w.SetEffect( EFFECT_FADE, 20 ); + mainWindow->Append(&w); + w.SetEffect(EFFECT_FADE, 20); ResumeGui(); - while ( w.GetEffect() > 0 ) usleep( 50 ); + while (w.GetEffect() > 0) + usleep(50); } - else - WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to use this option." ), tr( "OK" ) ); + else WindowPrompt(tr( "No SD-Card inserted!" ), + tr( "Insert an SD-Card to use this option." ), tr( "OK" )); } - char * filename = strrchr( Settings.ogg_path, '/' ); - if ( filename ) + char * filename = strrchr(Settings.ogg_path, '/'); + if (filename) { filename += 1; - options2.SetValue( Idx, "%s", filename ); + options2.SetValue(Idx, "%s", filename); } - else - options2.SetValue( Idx, "%s", tr( "Standard" ) ); + else options2.SetValue(Idx, "%s", tr( "Standard" )); } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Music Volume" ) ); - if ( ret == Idx ) + 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 > 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 (Settings.volume > 0) + options2.SetValue(Idx, "%i", Settings.volume); + else options2.SetValue(Idx, "%s", tr( "OFF" )); } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "SFX Volume" ) ); - if ( ret == Idx ) + 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 > 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 (Settings.sfxvolume > 0) + options2.SetValue(Idx, "%i", Settings.sfxvolume); + else options2.SetValue(Idx, "%s", tr( "OFF" )); } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Game Sound Mode" ) ); - if ( ret == Idx ) + 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 > 2) Settings.gamesound = 0; } - if ( Settings.gamesound == 1 ) - options2.SetValue( Idx, "%s", tr( "Sound+BGM" ) ); - else if ( Settings.gamesound == 2 ) - options2.SetValue( Idx, "%s", tr( "Loop Sound" ) ); - else - options2.SetValue( Idx, "%s", tr( "Sound+Quiet" ) ); + if (Settings.gamesound == 1) + options2.SetValue(Idx, "%s", tr( "Sound+BGM" )); + 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 (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Game Sound Volume" ) ); - if ( ret == Idx ) + 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 > 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" )); } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Music Loop Mode" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "Music Loop Mode" )); + if (ret == Idx) { Settings.musicloopmode++; - if ( Settings.musicloopmode > 3 ) - Settings.musicloopmode = 0; - bgMusic->SetLoop( Settings.musicloopmode ); + if (Settings.musicloopmode > 3) Settings.musicloopmode = 0; + bgMusic->SetLoop(Settings.musicloopmode); } - if ( Settings.musicloopmode == ONCE ) - options2.SetValue( Idx, tr( "Play Once" ) ); - else if ( Settings.musicloopmode == LOOP ) - options2.SetValue( Idx, tr( "Loop Music" ) ); - else if ( Settings.musicloopmode == DIR_LOOP ) - options2.SetValue( Idx, tr( "Loop Directory" ) ); - else if ( Settings.musicloopmode == RANDOM_BGM ) - options2.SetValue( Idx, tr( "Random Directory Music" ) ); + if (Settings.musicloopmode == ONCE) + options2.SetValue(Idx, tr( "Play Once" )); + else if (Settings.musicloopmode == LOOP) + options2.SetValue(Idx, tr( "Loop Music" )); + else if (Settings.musicloopmode == DIR_LOOP) + options2.SetValue(Idx, tr( "Loop Directory" )); + else if (Settings.musicloopmode == RANDOM_BGM) options2.SetValue(Idx, + tr( "Random Directory Music" )); } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Reset BG Music" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "Reset BG Music" )); + if (ret == Idx) { - int result = WindowPrompt( tr( "Reset to standard BGM?" ), 0, tr( "Yes" ), tr( "No" ) ); - if ( result ) + int result = + WindowPrompt(tr( "Reset to standard BGM?" ), 0, tr( "Yes" ), tr( "No" )); + if (result) { bgMusic->LoadStandard(); bgMusic->Play(); - options2.SetValue( Idx, "%s", tr( "Standard" ) ); + options2.SetValue(Idx, "%s", tr( "Standard" )); } } - options2.SetValue( Idx, tr( " " ) ); + options2.SetValue(Idx, tr( " " )); } firstRun = false; } } - optionBrowser2.SetEffect( EFFECT_FADE, -20 ); - while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); - titleTxt.SetText( tr( "Settings" ) ); + optionBrowser2.SetEffect(EFFECT_FADE, -20); + while (optionBrowser2.GetEffect() > 0) + usleep(50); + titleTxt.SetText(tr( "Settings" )); slidedirection = FADE; pageToDisplay = 1; MainButton4.ResetState(); @@ -1523,483 +1548,472 @@ int MenuSettings() } } - else if ( pageToDisplay == 2 ) + else if (pageToDisplay == 2) { - if ( MainButton1.GetState() == STATE_CLICKED ) + 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 ); + 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" ) ); + 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 ); + options2.SetLength(0); + // optionBrowser2.SetScrollbar(1); + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); ResumeGui(); - optionBrowser2.SetEffect( EFFECT_FADE, 20 ); - while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + optionBrowser2.SetEffect(EFFECT_FADE, 20); + while (optionBrowser2.GetEffect() > 0) + usleep(50); - if ( Settings.godmode ) + if (Settings.godmode) { bool firstRun = true; - while ( !exit ) + while (!exit) { - usleep( 100 ); + usleep(100); - if ( shutdown == 1 ) - Sys_Shutdown(); - if ( reset == 1 ) + if (shutdown == 1) Sys_Shutdown(); + if (reset == 1) Sys_Reboot(); - else if ( backBtn.GetState() == STATE_CLICKED ) + else if (backBtn.GetState() == STATE_CLICKED) { backBtn.ResetState(); exit = true; break; } - else if ( homo.GetState() == STATE_CLICKED ) + else if (homo.GetState() == STATE_CLICKED) { Settings.Save(); - optionBrowser2.SetState( STATE_DISABLED ); + optionBrowser2.SetState(STATE_DISABLED); bgMusic->Pause(); choice = WindowExitPrompt(); bgMusic->Resume(); - if ( choice == 3 ) + if (choice == 3) Sys_LoadMenu(); // Back to System Menu - else if ( choice == 2 ) + else if (choice == 2) Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState( STATE_DEFAULT ); + else homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); } ret = optionBrowser2.GetClickedOption(); - if ( firstRun || ret >= 0 ) + if (firstRun || ret >= 0) { int Idx = -1; - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "3D Cover Path" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "3D Cover Path" )); + if (ret == Idx) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + 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 ) + 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" ) ); + 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 ); + options2.SetValue(Idx, "%s", Settings.covers_path); } - - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "2D Cover Path" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "2D Cover Path" )); + if (ret == Idx) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + 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 ) + 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" ) ); + 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 ); + options2.SetValue(Idx, "%s", Settings.covers2d_path); } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Disc Artwork Path" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "Disc Artwork Path" )); + if (ret == Idx) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + 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 ) + 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" ) ); + 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 ); + options2.SetValue(Idx, "%s", Settings.disc_path); } - - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Theme Path" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "Theme Path" )); + if (ret == Idx) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + w.Remove(&optionBrowser2); + w.Remove(&backBtn); char entered[100] = ""; - titleTxt.SetText( tr( "Theme Path" ) ); - strlcpy( entered, Settings.theme_path, sizeof( entered ) ); - int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + titleTxt.SetText(tr( "Theme Path" )); + strlcpy(entered, Settings.theme_path, sizeof(entered)); + int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); HaltGui(); w.RemoveAll(); - if ( result == 1 ) + if (result == 1) { - int len = ( strlen( entered ) - 1 ); - if ( entered[len] != '/' ) - strncat ( entered, "/", 1 ); - strlcpy( Settings.theme_path, entered, sizeof( Settings.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 - Settings.Save(); - mainWindow->Remove( bgImg ); + int len = (strlen(entered) - 1); + if (entered[len] != '/') strncat(entered, "/", 1); + strlcpy(Settings.theme_path, entered, sizeof(Settings.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 Settings.Save(); + mainWindow->Remove(bgImg); HaltGui(); CFG_LoadTheme(Settings.widescreen, Settings.theme_path); ResumeGui(); menu = MENU_SETTINGS; - snprintf( imgPath, sizeof( imgPath ), "%splayer1_point.png", Settings.theme_path ); - pointer[0] = new GuiImageData( imgPath, player1_point_png ); - snprintf( imgPath, sizeof( imgPath ), "%splayer2_point.png", Settings.theme_path ); - pointer[1] = new GuiImageData( imgPath, player2_point_png ); - snprintf( imgPath, sizeof( imgPath ), "%splayer3_point.png", Settings.theme_path ); - pointer[2] = new GuiImageData( imgPath, player3_point_png ); - snprintf( imgPath, sizeof( imgPath ), "%splayer4_point.png", Settings.theme_path ); - pointer[3] = new GuiImageData( imgPath, player4_point_png ); - if ( Settings.widescreen ) - snprintf( imgPath, sizeof( imgPath ), "%swbackground.png", Settings.theme_path ); - else - snprintf( imgPath, sizeof( imgPath ), "%sbackground.png", Settings.theme_path ); + snprintf(imgPath, sizeof(imgPath), "%splayer1_point.png", + Settings.theme_path); + pointer[0] = new GuiImageData(imgPath, player1_point_png); + snprintf(imgPath, sizeof(imgPath), "%splayer2_point.png", + Settings.theme_path); + pointer[1] = new GuiImageData(imgPath, player2_point_png); + snprintf(imgPath, sizeof(imgPath), "%splayer3_point.png", + Settings.theme_path); + pointer[2] = new GuiImageData(imgPath, player3_point_png); + snprintf(imgPath, sizeof(imgPath), "%splayer4_point.png", + Settings.theme_path); + pointer[3] = new GuiImageData(imgPath, player4_point_png); + if (Settings.widescreen) + snprintf(imgPath, sizeof(imgPath), "%swbackground.png", + Settings.theme_path); + else snprintf(imgPath, sizeof(imgPath), "%sbackground.png", + Settings.theme_path); - background = new GuiImageData( imgPath, Settings.widescreen ? wbackground_png : background_png ); + background = new GuiImageData(imgPath, + Settings.widescreen ? wbackground_png : background_png); - bgImg = new GuiImage( background ); - mainWindow->Append( bgImg ); - mainWindow->Append( &w ); + 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 ); + w.Append(&settingsbackground); + w.Append(&titleTxt); + titleTxt.SetText(tr( "Custom Paths" )); + w.Append(&backBtn); + w.Append(&optionBrowser2); ResumeGui(); } - options2.SetValue( Idx, "%s", Settings.theme_path ); + options2.SetValue(Idx, "%s", Settings.theme_path); } - - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "WiiTDB Path" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "WiiTDB Path" )); + if (ret == Idx) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + 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 ) + 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 ) ) + 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)) { Settings.Save(); HaltGui(); Settings.Load(); ResumeGui(); } - else - WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ) ); + else WindowPrompt(tr( "No SD-Card inserted!" ), + tr( "Insert an SD-Card to save." ), tr( "OK" )); } } - options2.SetValue( Idx, "%s", Settings.titlestxt_path ); + options2.SetValue(Idx, "%s", Settings.titlestxt_path); } - - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Update Path" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "Update Path" )); + if (ret == Idx) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + 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 ) + 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" ) ); + 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 ); + options2.SetValue(Idx, "%s", Settings.update_path); } - - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "GCT Cheatcodes Path" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "GCT Cheatcodes Path" )); + if (ret == Idx) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + 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 ) + 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" ) ); + 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 ); + options2.SetValue(Idx, "%s", Settings.Cheatcodespath); } - - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "TXT Cheatcodes Path" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "TXT Cheatcodes Path" )); + if (ret == Idx) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + 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 ) + 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" ) ); + 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 ); + options2.SetValue(Idx, "%s", Settings.TxtCheatcodespath); } - - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "DOL Path" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "DOL Path" )); + if (ret == Idx) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + 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 ) + 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 ) ) + 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" ) ); + WindowPrompt(tr( "No SD-Card inserted!" ), + tr( "Insert an SD-Card to save." ), tr( "OK" )); } } } - options2.SetValue( Idx, "%s", Settings.dolpath ); + options2.SetValue(Idx, "%s", Settings.dolpath); } - - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Homebrew Apps Path" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "Homebrew Apps Path" )); + if (ret == Idx) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + 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 ) + 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 ) ) + 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" ) ); + WindowPrompt(tr( "No SD-Card inserted!" ), + tr( "Insert an SD-Card to save." ), tr( "OK" )); } } } - options2.SetValue( Idx, "%s", Settings.homebrewapps_path ); + options2.SetValue(Idx, "%s", Settings.homebrewapps_path); } - - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Theme Download Path" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "Theme Download Path" )); + if (ret == Idx) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + 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 ) + 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" ) ); + 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 ); + options2.SetValue(Idx, "%s", Settings.theme_downloadpath); } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "BCA Codes Path" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "BCA Codes Path" )); + if (ret == Idx) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + 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 ) + 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" ) ); + 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 ); + options2.SetValue(Idx, "%s", Settings.BcaCodepath); } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "WIP Patches Path" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "WIP Patches Path" )); + if (ret == Idx) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + 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 ) + 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" ) ); + 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 ); + options2.SetValue(Idx, "%s", Settings.WipCodepath); } firstRun = false; @@ -2007,73 +2021,73 @@ int MenuSettings() } /** 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" ) ); + 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 ) + 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 ) + 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 ); + 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 ); + 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" ) ); + 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 ) + 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 ) + 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 ) + int choice = WindowPrompt(tr( "Are you sure?" ), 0, tr( "Yes" ), tr( "Cancel" )); + if (choice == 1) { gettextCleanUp(); HaltGui(); @@ -2083,32 +2097,32 @@ int MenuSettings() pageToDisplay = 0; } } - else - WindowPrompt( tr( "Console Locked" ), tr( "Unlock console to use this option." ), tr( "OK" ) ); - w.Append( &backBtn ); - w.Append( &optionBrowser2 ); + 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 ) + 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 ); + 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; @@ -2117,54 +2131,49 @@ int MenuSettings() } } - else if ( pageToDisplay == 3 ) + else if (pageToDisplay == 3) { - if ( MainButton1.GetState() == STATE_CLICKED ) + if (MainButton1.GetState() == STATE_CLICKED) { - if ( isInserted( bootDevice ) ) - Settings.Save(); + if (isInserted(bootDevice)) Settings.Save(); menu = MENU_THEMEDOWNLOADER; pageToDisplay = 0; break; } } - - if ( backBtn.GetState() == STATE_CLICKED ) + if (backBtn.GetState() == STATE_CLICKED) { //Add the procedure call to save the global configuration - if ( isInserted( bootDevice ) ) - Settings.Save(); + if (isInserted(bootDevice)) Settings.Save(); menu = MENU_DISCLIST; pageToDisplay = 0; backBtn.ResetState(); break; } - else if ( GoLeftBtn.GetState() == STATE_CLICKED ) + else if (GoLeftBtn.GetState() == STATE_CLICKED) { pageToDisplay--; /** Change direction of the flying buttons **/ - if ( pageToDisplay < 1 ) - pageToDisplay = 3; + if (pageToDisplay < 1) pageToDisplay = 3; slidedirection = LEFT; GoLeftBtn.ResetState(); break; } - else if ( GoRightBtn.GetState() == STATE_CLICKED ) + else if (GoRightBtn.GetState() == STATE_CLICKED) { pageToDisplay++; /** Change direction of the flying buttons **/ - if ( pageToDisplay > 3 ) - pageToDisplay = 1; + if (pageToDisplay > 3) pageToDisplay = 1; slidedirection = RIGHT; GoRightBtn.ResetState(); break; } - else if ( PageIndicatorBtn1.GetState() == STATE_CLICKED ) + else if (PageIndicatorBtn1.GetState() == STATE_CLICKED) { - if ( pageToDisplay > 1 ) + if (pageToDisplay > 1) { slidedirection = LEFT; pageToDisplay = 1; @@ -2173,101 +2182,99 @@ int MenuSettings() } PageIndicatorBtn1.ResetState(); } - else if ( PageIndicatorBtn2.GetState() == STATE_CLICKED ) + else if (PageIndicatorBtn2.GetState() == STATE_CLICKED) { - if ( pageToDisplay < 2 ) + if (pageToDisplay < 2) { slidedirection = RIGHT; pageToDisplay = 2; PageIndicatorBtn2.ResetState(); break; } - else if ( pageToDisplay > 2 ) + else if (pageToDisplay > 2) { slidedirection = LEFT; pageToDisplay = 2; PageIndicatorBtn2.ResetState(); break; } - else - PageIndicatorBtn2.ResetState(); + else PageIndicatorBtn2.ResetState(); } - else if ( PageIndicatorBtn3.GetState() == STATE_CLICKED ) + else if (PageIndicatorBtn3.GetState() == STATE_CLICKED) { - if ( pageToDisplay < 3 ) + if (pageToDisplay < 3) { slidedirection = RIGHT; pageToDisplay = 3; PageIndicatorBtn3.ResetState(); break; } - else - PageIndicatorBtn3.ResetState(); + else PageIndicatorBtn3.ResetState(); } - else if ( homo.GetState() == STATE_CLICKED ) + else if (homo.GetState() == STATE_CLICKED) { Settings.Save(); - optionBrowser2.SetState( STATE_DISABLED ); + optionBrowser2.SetState(STATE_DISABLED); bgMusic->Pause(); choice = WindowExitPrompt(); bgMusic->Resume(); - if ( choice == 3 ) + if (choice == 3) Sys_LoadMenu(); // Back to System Menu - else if ( choice == 2 ) + else if (choice == 2) Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState( STATE_DEFAULT ); + 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 ) + if (Settings.partition != settingspartitionold) { PartInfo pinfo = partitions.pinfo[Settings.partition]; partitionEntry pentry = partitions.pentry[Settings.partition]; - WBFS_OpenPart( pinfo.part_fs, pinfo.index, pentry.sector, pentry.size, ( char * ) &game_partition ); + WBFS_OpenPart(pinfo.part_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 ); + 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 (strcmp(opt_lang, opt_langnew) || (opt_override != opt_overridenew && Settings.titlesOverride == 1) + || (Settings.partition != settingspartitionold)) { - if ( Settings.partition != settingspartitionold ) + if (Settings.partition != settingspartitionold) { reloaddatabasefile = true; CloseXMLDatabase(); CFG_Cleanup(); } - OpenXMLDatabase( Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, reloaddatabasefile, Settings.titlesOverride == 1 ? true : false, true ); // open file, reload titles, keep in memory + 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 (opt_override != opt_overridenew && Settings.titlesOverride == 0) titles_default(); HaltGui(); mainWindow->RemoveAll(); - mainWindow->Append( bgImg ); + mainWindow->Append(bgImg); ResumeGui(); return menu; } - /******************************************************************************** -*Game specific settings -*********************************************************************************/ -int GameSettings( struct discHdr * header ) + *Game specific settings + *********************************************************************************/ +int GameSettings(struct discHdr * header) { int menu = MENU_NONE; int ret; @@ -2276,158 +2283,162 @@ int GameSettings( struct discHdr * header ) int retVal = 0; - GuiSound btnSoundOver( button_over_pcm, button_over_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 ); + 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 btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%ssettings_background.png", Settings.theme_path ); - GuiImageData settingsbg( imgPath, settings_background_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", Settings.theme_path); + GuiImageData settingsbg(imgPath, settings_background_png); - snprintf( imgPath, sizeof( imgPath ), "%ssettings_title.png", Settings.theme_path ); - GuiImageData MainButtonImgData( imgPath, settings_title_png ); + snprintf(imgPath, sizeof(imgPath), "%ssettings_title.png", Settings.theme_path); + GuiImageData MainButtonImgData(imgPath, settings_title_png); - snprintf( imgPath, sizeof( imgPath ), "%ssettings_title_over.png", Settings.theme_path ); - GuiImageData MainButtonImgOverData( imgPath, settings_title_over_png ); + snprintf(imgPath, sizeof(imgPath), "%ssettings_title_over.png", Settings.theme_path); + GuiImageData MainButtonImgOverData(imgPath, settings_title_over_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + 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 ); + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); char gameName[31]; - if ( !mountMethod ) + if (!mountMethod) { - if ( strlen( get_title( header ) ) < ( 27 + 3 ) ) - sprintf( gameName, "%s", get_title( header ) ); + if (strlen(get_title(header)) < (27 + 3)) + sprintf(gameName, "%s", get_title(header)); else { - strncpy( gameName, get_title( header ), 27 ); + strncpy(gameName, get_title(header), 27); gameName[27] = '\0'; - strncat( gameName, "...", 3 ); + 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] ); + 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, SCROLL_HORIZONTAL ); + 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, SCROLL_HORIZONTAL); - 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 ) + GuiText backBtnTxt(tr( "Back" ), 22, THEME.prompttext); + backBtnTxt.SetMaxWidth(btnOutline.GetWidth() - 30); + GuiImage backBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - backBtnTxt.SetWidescreen( Settings.widescreen ); - backBtnImg.SetWidescreen( Settings.widescreen ); + backBtnTxt.SetWidescreen(Settings.widescreen); + backBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton backBtn( &backBtnImg, &backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2, 1 ); - backBtn.SetLabel( &backBtnTxt ); - backBtn.SetTrigger( &trigB ); + 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 ) + GuiText saveBtnTxt(tr( "Save" ), 22, THEME.prompttext); + saveBtnTxt.SetMaxWidth(btnOutline.GetWidth() - 30); + GuiImage saveBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - saveBtnTxt.SetWidescreen( Settings.widescreen ); - saveBtnImg.SetWidescreen( Settings.widescreen ); + saveBtnTxt.SetWidescreen(Settings.widescreen); + saveBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton saveBtn( &saveBtnImg, &saveBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2, 1 ); - saveBtn.SetLabel( &saveBtnTxt ); - - + GuiButton saveBtn(&saveBtnImg, &saveBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2, 1); + saveBtn.SetLabel(&saveBtnTxt); char MainButtonText[50]; - snprintf( MainButtonText, sizeof( MainButtonText ), "%s", " " ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + MainButton4.SetTrigger(&trigA); - customOptionList options2( MAXOPTIONS ); - GuiCustomOptionBrowser optionBrowser2( 396, 280, &options2, Settings.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, Settings.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 opt_lang = languageChoice; // backup language setting - struct Game_CFG* game_cfg = CFG_get_game_opt( header->id ); + struct Game_CFG* game_cfg = CFG_get_game_opt(header->id); int pageToDisplay = 1; - while ( pageToDisplay > 0 ) + while (pageToDisplay > 0) { - usleep( 100 ); + usleep(100); menu = MENU_NONE; @@ -2439,32 +2450,32 @@ int GameSettings( struct discHdr * header ) 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 ); + 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 ); + 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 ); + optionBrowser2.SetClickable(false); /** Default no scrollbar and reset position **/ -// optionBrowser2.SetScrollbar(0); - optionBrowser2.SetOffset( 0 ); + // optionBrowser2.SetScrollbar(0); + optionBrowser2.SetOffset(0); MainButton1.StopEffect(); MainButton2.StopEffect(); @@ -2476,17 +2487,14 @@ int GameSettings( struct discHdr * header ) 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 + if (game_cfg) //if there are saved settings for this game use them { videoChoice = game_cfg->video; languageChoice = game_cfg->language; @@ -2498,9 +2506,9 @@ int GameSettings( struct discHdr * header ) countrystrings = game_cfg->patchcountrystrings; alternatedol = game_cfg->loadalternatedol; alternatedoloffset = game_cfg->alternatedolstart; - reloadblock = game_cfg->iosreloadblock; - strlcpy( alternatedname, game_cfg->alternatedolname, sizeof( alternatedname ) ); - returnToLoaderGV = game_cfg->returnTo; + reloadblock = game_cfg->iosreloadblock; + strlcpy(alternatedname, game_cfg->alternatedolname, sizeof(alternatedname)); + returnToLoaderGV = game_cfg->returnTo; } else { @@ -2515,443 +2523,437 @@ int GameSettings( struct discHdr * header ) alternatedol = off; alternatedoloffset = 0; reloadblock = off; - strcpy( alternatedname, "" ); - returnToLoaderGV = 1; + strcpy(alternatedname, ""); + returnToLoaderGV = 1; } ResumeGui(); - while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + while (MainButton1.GetEffect() > 0) + usleep(50); - - - while ( menu == MENU_NONE ) + while (menu == MENU_NONE) { - usleep( 100 ); + usleep(100); - 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 ) + 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 ); + 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 ); + w.Remove(&MainButton1); + w.Remove(&MainButton2); + w.Remove(&MainButton3); + w.Remove(&MainButton4); exit = false; - options2.SetLength( 0 ); - w.Append( &optionBrowser2 ); - optionBrowser2.SetClickable( true ); + options2.SetLength(0); + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); ResumeGui(); - optionBrowser2.SetEffect( EFFECT_FADE, 20 ); - while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + optionBrowser2.SetEffect(EFFECT_FADE, 20); + while (optionBrowser2.GetEffect() > 0) + usleep(50); int returnhere = 1; char * languagefile; - languagefile = strrchr( Settings.language_path, '/' ) + 1; + languagefile = strrchr(Settings.language_path, '/') + 1; bool firstRun = true; - while ( !exit ) + while (!exit) { - usleep( 100 ); + usleep(100); returnhere = 1; - if ( shutdown == 1 ) - Sys_Shutdown(); - if ( reset == 1 ) - Sys_Reboot(); - if ( backBtn.GetState() == STATE_CLICKED ) + 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 ) + else if (menu == MENU_DISCLIST) { - w.Remove( &optionBrowser2 ); - w.Remove( &backBtn ); + w.Remove(&optionBrowser2); + w.Remove(&backBtn); WindowCredits(); - w.Append( &optionBrowser2 ); - w.Append( &backBtn ); + w.Append(&optionBrowser2); + w.Append(&backBtn); } - else if ( homo.GetState() == STATE_CLICKED ) + else if (homo.GetState() == STATE_CLICKED) { Settings.Save(); - optionBrowser2.SetState( STATE_DISABLED ); + optionBrowser2.SetState(STATE_DISABLED); bgMusic->Pause(); choice = WindowExitPrompt(); bgMusic->Resume(); - if ( choice == 3 ) + if (choice == 3) Sys_LoadMenu(); // Back to System Menu - else if ( choice == 2 ) + else if (choice == 2) Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState( STATE_DEFAULT ); + else homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); } - else if ( saveBtn.GetState() == STATE_CLICKED ) + else if (saveBtn.GetState() == STATE_CLICKED) { - if ( isInserted( bootDevice ) ) + if (isInserted(bootDevice)) { - if ( CFG_save_game_opt( header->id ) ) + 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" ) ); + // 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( "Save Failed" ), 0, tr( "OK" )); } - else - WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ) ); + else WindowPrompt(tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" )); saveBtn.ResetState(); - optionBrowser2.SetFocus( 1 ); + optionBrowser2.SetFocus(1); } ret = optionBrowser2.GetClickedOption(); - if ( ret >= 0 || firstRun == true ) + if (ret >= 0 || firstRun == true) { int Idx = -1; - if ( ret == ++Idx || firstRun ) + 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 (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 (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 (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 (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 (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 (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 (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 (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "IOS" ); - if ( ret == Idx ) - { - switch(iosChoice) - { - case 222: - iosChoice = 223; - break; - case 223: - iosChoice = 224; - break; - case 224: - iosChoice = 249; - break; - case 249: - iosChoice = 250; - break; - case 250: - iosChoice = 222; - break; - default: - iosChoice = 222; - break; - } - } - options2.SetValue( Idx, "IOS %i", 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( "Error 002 fix" ) ); - if ( ret == Idx && ++fix002 >= 3 ) - fix002 = 0; - options2.SetValue( Idx, "%s", tr( opts_error002[fix002] ) ); - } - - if ( ret == ++Idx || firstRun ) - { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Return To" ) ); - if ( ret == Idx && ++returnToLoaderGV >= settings_off_on_max ) - returnToLoaderGV = 0; - - char text[ IMET_MAX_NAME_LEN ]; - int channel = titles.FindU32( Settings.returnTo );//is the channel set in the global settings actually installed? - - if( !returnToLoaderGV || channel < 0 )//channel is not installed or the uer wants to not use it - sprintf( text, "%s", tr( opts_off_on[ 0 ] ) ); - - else snprintf( text, sizeof( text ), "%s", titles.NameFromIndex( channel ) ); - - options2.SetValue( Idx, "%s", text ); - } - - 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 ) + if (firstRun) options2.SetName(Idx, "IOS"); + if (ret == Idx) { - firstRun = true; // force re-init follow Entries - options2.SetLength( Idx + 1 ); + switch (iosChoice) + { + case 222: + iosChoice = 223; + break; + case 223: + iosChoice = 224; + break; + case 224: + iosChoice = 249; + break; + case 249: + iosChoice = 250; + break; + case 250: + iosChoice = 222; + break; + default: + iosChoice = 222; + break; + } + } + options2.SetValue(Idx, "IOS %i", 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( "Error 002 fix" )); + if (ret == Idx && ++fix002 >= 3) fix002 = 0; + options2.SetValue(Idx, "%s", tr( opts_error002[fix002] )); + } + + if (ret == ++Idx || firstRun) + { + if (firstRun) options2.SetName(Idx, "%s", tr( "Return To" )); + if (ret == Idx && ++returnToLoaderGV >= settings_off_on_max) returnToLoaderGV = 0; + + char text[IMET_MAX_NAME_LEN]; + int channel = titles.FindU32(Settings.returnTo);//is the channel set in the global settings actually installed? + + if (!returnToLoaderGV || channel < 0)//channel is not installed or the uer wants to not use it + sprintf(text, "%s", tr( opts_off_on[ 0 ] )); + + else snprintf(text, sizeof(text), "%s", titles.NameFromIndex(channel)); + + options2.SetValue(Idx, "%s", text); + } + + 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 ( alternatedol == 2 && ( ret == ++Idx || firstRun ) ) + if (alternatedol == 2 && (ret == ++Idx || firstRun)) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Selected DOL" ) ); - if ( ret == Idx ) + if (firstRun) options2.SetName(Idx, "%s", tr( "Selected DOL" )); + if (ret == Idx) { - if ( alternatedol == 2 ) + 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] ); + 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 ); + int autodol = autoSelectDolMenu(filename, false); - if ( autodol > 0 ) + if (autodol > 0) { alternatedoloffset = autodol; - snprintf( alternatedname, sizeof( alternatedname ), "%s <%i>", tr( "AUTO" ), autodol ); + snprintf(alternatedname, sizeof(alternatedname), "%s <%i>", tr( "AUTO" ), + autodol); } - else if ( autodol == 0 ) - alternatedol = 0; // default was chosen + 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 ); + int autodol = autoSelectDol(filename, false); //if we do know that offset ask if they want to use it - if ( autodol > 0 ) + 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 ) + 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 ) + else if (dolchoice == 1) { alternatedoloffset = autodol; - snprintf( alternatedname, sizeof( alternatedname ), "%s <%i>", tr( "AUTO" ), autodol ); + snprintf(alternatedname, sizeof(alternatedname), "%s <%i>", + tr( "AUTO" ), autodol); } - else if ( dolchoice == 2 ) //they want to search for the correct dol themselves + 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; + 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 ) ) + 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" ) ); + 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 ) + 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 + 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 ); + else options2.SetValue(Idx, alternatedname); } - if ( ret == ++Idx || firstRun ) + 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 (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; } } - optionBrowser2.SetEffect( EFFECT_FADE, -20 ); - while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + optionBrowser2.SetEffect(EFFECT_FADE, -20); + while (optionBrowser2.GetEffect() > 0) + usleep(50); MainButton1.ResetState(); break; - w.Remove( &saveBtn ); + w.Remove(&saveBtn); } - else if ( MainButton2.GetState() == STATE_CLICKED ) + 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 ); + 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 ) + 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 ); + 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 ); + w.Remove(&MainButton1); + w.Remove(&MainButton2); + w.Remove(&MainButton3); + w.Remove(&MainButton4); exit = false; - options2.SetLength( 0 ); - w.Append( &optionBrowser2 ); - optionBrowser2.SetClickable( true ); + options2.SetLength(0); + w.Append(&optionBrowser2); + optionBrowser2.SetClickable(true); ResumeGui(); 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 ) + while (!exit) { - usleep( 100 ); + usleep(100); - if ( shutdown == 1 ) - Sys_Shutdown(); - if ( reset == 1 ) - Sys_Reboot(); - if ( backBtn.GetState() == STATE_CLICKED ) + 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 ) + else if (homo.GetState() == STATE_CLICKED) { Settings.Save(); - optionBrowser2.SetState( STATE_DISABLED ); + optionBrowser2.SetState(STATE_DISABLED); bgMusic->Pause(); choice = WindowExitPrompt(); bgMusic->Resume(); - if ( choice == 3 ) + if (choice == 3) Sys_LoadMenu(); // Back to System Menu - else if ( choice == 2 ) + else if (choice == 2) Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState( STATE_DEFAULT ); + else homo.ResetState(); + optionBrowser2.SetState(STATE_DEFAULT); } ret = optionBrowser2.GetClickedOption(); - if ( firstRun || ret >= 0 ) + if (firstRun || ret >= 0) { int Idx = -1; - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Uninstall Game" ) ); - if ( ret == Idx ) + 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 ) + 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 ) + 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" ) ); + WindowPrompt(tr( "Can't delete:" ), gameName, tr( "OK" )); } else { - WindowPrompt( tr( "Successfully deleted:" ), gameName, tr( "OK" ) ); + WindowPrompt(tr( "Successfully deleted:" ), gameName, tr( "OK" )); retVal = 1; } } - else if ( choice1 == 0 ) - optionBrowser2.SetFocus( 1 ); + else if (choice1 == 0) optionBrowser2.SetFocus(1); } } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Reset Playcounter" ) ); - if ( ret == Idx ) + 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 ) + int result = WindowPrompt(tr( "Are you sure?" ), 0, tr( "Yes" ), tr( "Cancel" )); + if (result == 1) { - if ( isInserted( bootDevice ) ) + if (isInserted(bootDevice)) { - struct Game_NUM* game_num = CFG_get_game_num( header->id ); - if ( game_num ) + struct Game_NUM* game_num = CFG_get_game_num(header->id); + if (game_num) { favoritevar = game_num->favorite; playcount = game_num->count; @@ -2962,76 +2964,78 @@ int GameSettings( struct discHdr * header ) playcount = 0; } playcount = 0; - CFG_save_game_num( header->id ); + CFG_save_game_num(header->id); } } } } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Delete Cover Artwork" ) ); - if ( ret == Idx ) + 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] ); + 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 ) + int choice1 = WindowPrompt(tr( "Delete" ), tmp, tr( "Yes" ), tr( "No" )); + if (choice1 == 1) { - if ( checkfile( tmp ) ) - remove( tmp ); + if (checkfile(tmp)) remove(tmp); } } } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Delete Disc Artwork" ) ); - if ( ret == Idx ) + 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] ); + 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 ) + int choice1 = WindowPrompt(tr( "Delete" ), tmp, tr( "Yes" ), tr( "No" )); + if (choice1 == 1) { - if ( checkfile( tmp ) ) - remove( tmp ); + if (checkfile(tmp)) remove(tmp); } } } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Delete Cheat TXT" ) ); - if ( ret == Idx ) + 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] ); + 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 ) + int choice1 = WindowPrompt(tr( "Delete" ), tmp, tr( "Yes" ), tr( "No" )); + if (choice1 == 1) { - if ( checkfile( tmp ) ) - remove( tmp ); + if (checkfile(tmp)) remove(tmp); } } } - if ( ret == ++Idx || firstRun ) + if (ret == ++Idx || firstRun) { - if ( firstRun ) options2.SetName( Idx, "%s", tr( "Delete Cheat GCT" ) ); - if ( ret == Idx ) + 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] ); + 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 ) + int choice1 = WindowPrompt(tr( "Delete" ), tmp, tr( "Yes" ), tr( "No" )); + if (choice1 == 1) { - if ( checkfile( tmp ) ) - remove( tmp ); + if (checkfile(tmp)) remove(tmp); } } } @@ -3039,17 +3043,18 @@ int GameSettings( struct discHdr * header ) firstRun = false; } } - optionBrowser2.SetEffect( EFFECT_FADE, -20 ); - while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + optionBrowser2.SetEffect(EFFECT_FADE, -20); + while (optionBrowser2.GetEffect() > 0) + usleep(50); pageToDisplay = 1; MainButton3.ResetState(); break; } - else if ( MainButton4.GetState() == STATE_CLICKED ) + else if (MainButton4.GetState() == STATE_CLICKED) { - int choice1 = WindowPrompt( tr( "Are you sure?" ), 0, tr( "Yes" ), tr( "Cancel" ) ); - if ( choice1 == 1 ) + int choice1 = WindowPrompt(tr( "Are you sure?" ), 0, tr( "Yes" ), tr( "Cancel" )); + if (choice1 == 1) { videoChoice = Settings.videomode; viChoice = Settings.videopatch; @@ -3061,10 +3066,10 @@ int GameSettings( struct discHdr * header ) alternatedoloffset = 0; reloadblock = off; iosChoice = Settings.cios; - parentalcontrolChoice = 0; - strcpy( alternatedname, "" ); - returnToLoaderGV = 1; - CFG_forget_game_opt( header->id ); + parentalcontrolChoice = 0; + strcpy(alternatedname, ""); + returnToLoaderGV = 1; + CFG_forget_game_opt(header->id); } pageToDisplay = 1; @@ -3072,8 +3077,7 @@ int GameSettings( struct discHdr * header ) break; } - - else if ( backBtn.GetState() == STATE_CLICKED ) + else if (backBtn.GetState() == STATE_CLICKED) { menu = MENU_DISCLIST; pageToDisplay = 0; @@ -3081,33 +3085,31 @@ int GameSettings( struct discHdr * header ) break; } - else if ( homo.GetState() == STATE_CLICKED ) + else if (homo.GetState() == STATE_CLICKED) { Settings.Save(); - optionBrowser2.SetState( STATE_DISABLED ); + optionBrowser2.SetState(STATE_DISABLED); bgMusic->Pause(); choice = WindowExitPrompt(); bgMusic->Resume(); - if ( choice == 3 ) + if (choice == 3) Sys_LoadMenu(); // Back to System Menu - else if ( choice == 2 ) + else if (choice == 2) Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState( STATE_DEFAULT ); + 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); HaltGui(); mainWindow->RemoveAll(); - mainWindow->Append( bgImg ); + mainWindow->Append(bgImg); ResumeGui(); return retVal; diff --git a/source/settings/Settings.h b/source/settings/Settings.h index 7dc36eaf..3cec126e 100644 --- a/source/settings/Settings.h +++ b/source/settings/Settings.h @@ -9,5 +9,5 @@ #define _SETTINGS_H_ int MenuSettings(); -int GameSettings( struct discHdr * header ); +int GameSettings(struct discHdr * header); #endif diff --git a/source/settings/cfg.c b/source/settings/cfg.c index 6685a639..ddf3f471 100644 --- a/source/settings/cfg.c +++ b/source/settings/cfg.c @@ -64,7 +64,6 @@ int num_saved_game_num = 0; struct Game_CFG cfg_game[MAX_SAVED_GAMES]; struct Game_NUM cfg_game_num[MAX_SAVED_GAME_NUM]; - /* For Mapping */ static char *cfg_name, *cfg_val; @@ -75,70 +74,44 @@ struct TextMap int id; }; -struct TextMap map_video[] = -{ - { "system", CFG_VIDEO_SYS }, - { "game", CFG_VIDEO_GAME }, - { "patch", CFG_VIDEO_PATCH }, - { "pal50", CFG_VIDEO_PAL50 }, - { "pal60", CFG_VIDEO_PAL60 }, - { "ntsc", CFG_VIDEO_NTSC }, - { NULL, -1 } -}; +struct TextMap map_video[] = { { "system", CFG_VIDEO_SYS }, { "game", CFG_VIDEO_GAME }, { "patch", CFG_VIDEO_PATCH }, { + "pal50", CFG_VIDEO_PAL50 }, { "pal60", CFG_VIDEO_PAL60 }, { "ntsc", CFG_VIDEO_NTSC }, { NULL, -1 } }; -struct TextMap map_language[] = -{ - { "console", CFG_LANG_CONSOLE }, - { "japanese", CFG_LANG_JAPANESE }, - { "english", CFG_LANG_ENGLISH }, - { "german", CFG_LANG_GERMAN }, - { "french", CFG_LANG_FRENCH }, - { "spanish", CFG_LANG_SPANISH }, - { "italian", CFG_LANG_ITALIAN }, - { "dutch", CFG_LANG_DUTCH }, - { "schinese", CFG_LANG_S_CHINESE }, // without a dot between s and chinese to match the language filename "schinese.lang" - { "tchinese", CFG_LANG_T_CHINESE }, - { "korean", CFG_LANG_KOREAN }, - { NULL, -1 } -}; +struct TextMap map_language[] = { { "console", CFG_LANG_CONSOLE }, { "japanese", CFG_LANG_JAPANESE }, { "english", + CFG_LANG_ENGLISH }, { "german", CFG_LANG_GERMAN }, { "french", CFG_LANG_FRENCH }, + { "spanish", CFG_LANG_SPANISH }, { "italian", CFG_LANG_ITALIAN }, { "dutch", CFG_LANG_DUTCH }, { "schinese", + CFG_LANG_S_CHINESE }, // without a dot between s and chinese to match the language filename "schinese.lang" + { "tchinese", CFG_LANG_T_CHINESE }, { "korean", CFG_LANG_KOREAN }, { NULL, -1 } }; +struct TextMap map_alignment[] = { { "left", CFG_ALIGN_LEFT }, { "right", CFG_ALIGN_RIGHT }, { "center", + CFG_ALIGN_CENTRE }, { "top", CFG_ALIGN_TOP }, { "bottom", CFG_ALIGN_BOTTOM }, { "middle", CFG_ALIGN_MIDDLE }, { + NULL, -1 } }; -struct TextMap map_alignment[] = -{ - { "left", CFG_ALIGN_LEFT }, - { "right", CFG_ALIGN_RIGHT }, - { "center", CFG_ALIGN_CENTRE }, - { "top", CFG_ALIGN_TOP }, - { "bottom", CFG_ALIGN_BOTTOM }, - { "middle", CFG_ALIGN_MIDDLE }, - { NULL, -1 } -}; - -int map_get_id( struct TextMap *map, char *name ) +int map_get_id(struct TextMap *map, char *name) { int i; - for ( i = 0; map[i].name != NULL; i++ ) + for (i = 0; map[i].name != NULL; i++) { - if ( strcmp( name, map[i].name ) == 0 ) return map[i].id; + if (strcmp(name, map[i].name) == 0) return map[i].id; } return -1; } -char* map_get_name( struct TextMap *map, short id ) +char* map_get_name(struct TextMap *map, short id) { int i; - for ( i = 0; map[i].name != NULL; i++ ) + for (i = 0; map[i].name != NULL; i++) { - if ( id == map[i].id ) return map[i].name; + if (id == map[i].id) return map[i].name; } return NULL; } -bool map_auto( char *name, char *name2, char *val, struct TextMap *map, short *var ) +bool map_auto(char *name, char *name2, char *val, struct TextMap *map, short *var) { - if ( strcmp( name, name2 ) != 0 ) return false; - int id = map_get_id( map, val ); - if ( id == -1 ) + if (strcmp(name, name2) != 0) return false; + int id = map_get_id(map, val); + if (id == -1) { //printf("MAP FAIL: %s=%s : %d\n", name, val, id); sleep(1); return false; @@ -148,14 +121,14 @@ bool map_auto( char *name, char *name2, char *val, struct TextMap *map, short *v return true; } -bool cfg_map_auto( char *name, struct TextMap *map, short *var ) +bool cfg_map_auto(char *name, struct TextMap *map, short *var) { - return map_auto( name, cfg_name, cfg_val, map, var ); + return map_auto(name, cfg_name, cfg_val, map, var); } -bool cfg_map( char *name, char *val, short *var, short id ) +bool cfg_map(char *name, char *val, short *var, short id) { - if ( strcmp( name, cfg_name ) == 0 && strcmpi( val, cfg_val ) == 0 ) + if (strcmp(name, cfg_name) == 0 && strcmpi(val, cfg_val) == 0) { *var = id; return true; @@ -163,23 +136,23 @@ bool cfg_map( char *name, char *val, short *var, short id ) return false; } -bool cfg_bool( char *name, short *var ) +bool cfg_bool(char *name, short *var) { - return ( cfg_map( name, "0", var, 0 ) || cfg_map( name, "1", var, 1 ) ); + return (cfg_map(name, "0", var, 0) || cfg_map(name, "1", var, 1)); } -void cfg_int( char *name, short *var, int count ) +void cfg_int(char *name, short *var, int count) { char tmp[6]; short i; - if ( count > 10 ) //avoid overflow - return; + if (count > 10) //avoid overflow + return; - for ( i = 0; i < count; i++ ) + for (i = 0; i < count; i++) { - sprintf( tmp, "%d", i ); - cfg_map( name, tmp, var, i ); + sprintf(tmp, "%d", i); + cfg_map(name, tmp, var, i); } } @@ -227,98 +200,101 @@ void CFG_DefaultTheme() // -1 = non forced Mode 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 = WideScreen ? 256 : 220; - THEME.gamelist_favorite_y = 13; - THEME.gamelist_search_x = WideScreen ? 288 : 260; - THEME.gamelist_search_y = 13; - THEME.gamelist_abc_x = WideScreen ? 320 : 300; - THEME.gamelist_abc_y = 13; - THEME.gamelist_count_x = WideScreen ? 352 : 340; - THEME.gamelist_count_y = 13; - THEME.gamelist_list_x = WideScreen ? 384 : 380; - THEME.gamelist_list_y = 13; - THEME.gamelist_grid_x = WideScreen ? 416 : 420; - THEME.gamelist_grid_y = 13; - THEME.gamelist_carousel_x = WideScreen ? 448 : 460; - THEME.gamelist_carousel_y = 13; - THEME.gamelist_lock_x = WideScreen ? 480 : 500; - THEME.gamelist_lock_y = 13; - THEME.gamelist_dvd_x = WideScreen ? 512 : 540; - THEME.gamelist_dvd_y = 13; + THEME.gamelist_favorite_x = WideScreen ? 256 : 220; + THEME.gamelist_favorite_y = 13; + THEME.gamelist_search_x = WideScreen ? 288 : 260; + THEME.gamelist_search_y = 13; + THEME.gamelist_abc_x = WideScreen ? 320 : 300; + THEME.gamelist_abc_y = 13; + THEME.gamelist_count_x = WideScreen ? 352 : 340; + THEME.gamelist_count_y = 13; + THEME.gamelist_list_x = WideScreen ? 384 : 380; + THEME.gamelist_list_y = 13; + THEME.gamelist_grid_x = WideScreen ? 416 : 420; + THEME.gamelist_grid_y = 13; + THEME.gamelist_carousel_x = WideScreen ? 448 : 460; + THEME.gamelist_carousel_y = 13; + THEME.gamelist_lock_x = WideScreen ? 480 : 500; + THEME.gamelist_lock_y = 13; + THEME.gamelist_dvd_x = WideScreen ? 512 : 540; + THEME.gamelist_dvd_y = 13; - THEME.gamegrid_favorite_x = WideScreen ? 192 : 160; - THEME.gamegrid_favorite_y = 13; - THEME.gamegrid_search_x = WideScreen ? 224 : 200; - THEME.gamegrid_search_y = 13; - THEME.gamegrid_abc_x = WideScreen ? 256 : 240; - THEME.gamegrid_abc_y = 13; - THEME.gamegrid_count_x = WideScreen ? 288 : 280; - THEME.gamegrid_count_y = 13; - THEME.gamegrid_list_x = WideScreen ? 320 : 320; - THEME.gamegrid_list_y = 13; - THEME.gamegrid_grid_x = WideScreen ? 352 : 360; - THEME.gamegrid_grid_y = 13; - THEME.gamegrid_carousel_x = WideScreen ? 384 : 400; - THEME.gamegrid_carousel_y = 13; - THEME.gamegrid_lock_x = WideScreen ? 416 : 440; - THEME.gamegrid_lock_y = 13; - THEME.gamegrid_dvd_x = WideScreen ? 448 : 480; - THEME.gamegrid_dvd_y = 13; + THEME.gamegrid_favorite_x = WideScreen ? 192 : 160; + THEME.gamegrid_favorite_y = 13; + THEME.gamegrid_search_x = WideScreen ? 224 : 200; + THEME.gamegrid_search_y = 13; + THEME.gamegrid_abc_x = WideScreen ? 256 : 240; + THEME.gamegrid_abc_y = 13; + THEME.gamegrid_count_x = WideScreen ? 288 : 280; + THEME.gamegrid_count_y = 13; + THEME.gamegrid_list_x = WideScreen ? 320 : 320; + THEME.gamegrid_list_y = 13; + THEME.gamegrid_grid_x = WideScreen ? 352 : 360; + THEME.gamegrid_grid_y = 13; + THEME.gamegrid_carousel_x = WideScreen ? 384 : 400; + THEME.gamegrid_carousel_y = 13; + THEME.gamegrid_lock_x = WideScreen ? 416 : 440; + THEME.gamegrid_lock_y = 13; + THEME.gamegrid_dvd_x = WideScreen ? 448 : 480; + THEME.gamegrid_dvd_y = 13; - THEME.gamecarousel_favorite_x = WideScreen ? 192 : 160; - THEME.gamecarousel_favorite_y = 13; - THEME.gamecarousel_search_x = WideScreen ? 224 : 200; - THEME.gamecarousel_search_y = 13; - THEME.gamecarousel_abc_x = WideScreen ? 256 : 240; - THEME.gamecarousel_abc_y = 13; - THEME.gamecarousel_count_x = WideScreen ? 288 : 280; - THEME.gamecarousel_count_y = 13; - THEME.gamecarousel_list_x = WideScreen ? 320 : 320; - THEME.gamecarousel_list_y = 13; - THEME.gamecarousel_grid_x = WideScreen ? 352 : 360; - THEME.gamecarousel_grid_y = 13; - THEME.gamecarousel_carousel_x = WideScreen ? 384 : 400; - THEME.gamecarousel_carousel_y = 13; - THEME.gamecarousel_lock_x = WideScreen ? 416 : 440; - THEME.gamecarousel_lock_y = 13; - THEME.gamecarousel_dvd_x = WideScreen ? 448 : 480; - THEME.gamecarousel_dvd_y = 13; -} + THEME.gamecarousel_favorite_x = WideScreen ? 192 : 160; + THEME.gamecarousel_favorite_y = 13; + THEME.gamecarousel_search_x = WideScreen ? 224 : 200; + THEME.gamecarousel_search_y = 13; + THEME.gamecarousel_abc_x = WideScreen ? 256 : 240; + THEME.gamecarousel_abc_y = 13; + THEME.gamecarousel_count_x = WideScreen ? 288 : 280; + THEME.gamecarousel_count_y = 13; + THEME.gamecarousel_list_x = WideScreen ? 320 : 320; + THEME.gamecarousel_list_y = 13; + THEME.gamecarousel_grid_x = WideScreen ? 352 : 360; + THEME.gamecarousel_grid_y = 13; + THEME.gamecarousel_carousel_x = WideScreen ? 384 : 400; + THEME.gamecarousel_carousel_y = 13; + THEME.gamecarousel_lock_x = WideScreen ? 416 : 440; + THEME.gamecarousel_lock_y = 13; + THEME.gamecarousel_dvd_x = WideScreen ? 448 : 480; + THEME.gamecarousel_dvd_y = 13; + } - -char *cfg_get_title( u8 *id ) +char *cfg_get_title(u8 *id) { - if ( !id ) - return NULL; + if (!id) return NULL; int i; - for ( i = 0; i < num_title; i++ ) + for (i = 0; i < num_title; i++) { - if ( strncmp( ( char* ) id, cfg_title[i].id, 6 ) == 0 ) + if (strncmp((char*) id, cfg_title[i].id, 6) == 0) { return cfg_title[i].title; } @@ -326,35 +302,32 @@ char *cfg_get_title( u8 *id ) return NULL; } -char *get_title( struct discHdr *header ) +char *get_title(struct discHdr *header) { - if ( !header ) - return NULL; + if (!header) return NULL; - char *title = cfg_get_title( header->id ); - if ( title ) return title; + char *title = cfg_get_title(header->id); + if (title) return title; return header->title; } -void title_set( char *id, char *title ) +void title_set(char *id, char *title) { - if ( !id || !title ) - return; + 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 ) + char *idt = cfg_get_title((u8*) id); + if (idt) { // replace - free( idt ); - idt = strdup( title ); + free(idt); + idt = strdup(title); } else { - struct ID_Title * tmpStruct = ( struct ID_Title * ) realloc( cfg_title, ( num_title + 1 ) * sizeof( struct ID_Title ) ); - if ( !tmpStruct ) + struct ID_Title * tmpStruct = (struct ID_Title *) realloc(cfg_title, (num_title + 1) * sizeof(struct ID_Title)); + if (!tmpStruct) { // error CFG_Cleanup(); @@ -365,8 +338,8 @@ void title_set( char *id, char *title ) cfg_title = tmpStruct; // add - strncpy( cfg_title[num_title].id, id, 6 ); - cfg_title[num_title].title = strdup( title ); + strncpy(cfg_title[num_title].id, id, 6); + cfg_title[num_title].title = strdup(title); num_title++; } } @@ -374,20 +347,20 @@ void title_set( char *id, char *title ) void titles_default() { int i; - for ( i = 0; i < num_title; i++ ) + for (i = 0; i < num_title; i++) { - memset( cfg_title[i].id, 0, 6 ); - free( cfg_title[i].title ); + memset(cfg_title[i].id, 0, 6); + free(cfg_title[i].title); cfg_title[i].title = NULL; } } -u8 cfg_get_block( u8 *id ) +u8 cfg_get_block(u8 *id) { int i; - for ( i = 0; i < num_control; i++ ) + for (i = 0; i < num_control; i++) { - if ( memcmp( id, cfg_control[i].id, 6 ) == 0 ) + if (memcmp(id, cfg_control[i].id, 6) == 0) { return cfg_control[i].block; } @@ -395,62 +368,69 @@ u8 cfg_get_block( u8 *id ) return 0; } -u8 get_block( struct discHdr *header ) +u8 get_block(struct discHdr *header) { - return cfg_get_block( header->id ); + return cfg_get_block(header->id); } -s8 get_pegi_block( struct discHdr *header ) +s8 get_pegi_block(struct discHdr *header) { - switch ( get_block( header ) ) + switch (get_block(header)) { - case 1: return 7; - case 2: return 12; - case 3: return 16; - case 4: return 18; - default: return -1; + case 1: + return 7; + case 2: + return 12; + case 3: + return 16; + case 4: + return 18; + default: + return -1; } } // trim leading and trailing whitespace // copy at max n or at max size-1 -char* trim_n_copy( char *dest, char *src, int n, int size ) +char* trim_n_copy(char *dest, char *src, int n, int size) { int len; // trim leading white space - while ( isspace2( *src ) ) + while (isspace2( *src )) { src++; n--; } - len = strlen( src ); - if ( len > n ) len = n; + len = strlen(src); + if (len > n) len = n; // trim trailing white space - while ( len > 0 && isspace2( src[len-1] ) ) len--; - if ( len >= size ) len = size - 1; - strlcpy( dest, src, len + 1 ); + while (len > 0 && isspace2( src[len-1] )) + len--; + if (len >= size) len = size - 1; + strlcpy(dest, src, len + 1); //printf("trim_copy: '%s' %d\n", dest, len); //sleep(1); return dest; } -char* trimcopy( char *dest, char *src, int size ) +char* trimcopy(char *dest, char *src, int size) { int len; - while ( *src == ' ' ) src++; - len = strlen( src ); + while (*src == ' ') + src++; + len = strlen(src); // trim trailing " \r\n" - while ( len > 0 && strchr( " \r\n", src[len-1] ) ) len--; - if ( len >= size ) len = size - 1; - strlcpy( dest, src, len + 1 ); + while (len > 0 && strchr(" \r\n", src[len - 1])) + len--; + if (len >= size) len = size - 1; + strlcpy(dest, src, len + 1); return dest; } -static u32 wCOORDS_FLAGS[2] = {0, 0}; // space for 64 coords - this is enough, also for the future +static u32 wCOORDS_FLAGS[2] = { 0, 0 }; // space for 64 coords - this is enough, also for the future #define GET_wCOORD_FLAG(i) (wCOORDS_FLAGS[i/32] & (1UL << (i%32))) #define SET_wCOORD_FLAG(i) (wCOORDS_FLAGS[i/32] |= (1UL << (i%32))) #define CLEAR_wCOORD_FLAGS (wCOORDS_FLAGS[0] = wCOORDS_FLAGS[1] = 0) - #define CFG_COORDS2(name) \ if ((wcoords_idx++, 1) && !GET_wCOORD_FLAG(wcoords_idx) && \ strcmp(cfg_name, #name "_coords") == 0) { \ @@ -511,8 +491,6 @@ static u32 wCOORDS_FLAGS[2] = {0, 0}; // space for 64 coords - this is enough, a } \ } - - #define CFG_BOOL(name) if(cfg_bool(#name, &THEME.name)); #define CFG_ALIGN(name) if(cfg_map_auto(#name "_align", map_alignment, &THEME.name##_align)); @@ -526,14 +504,14 @@ static u32 wCOORDS_FLAGS[2] = {0, 0}; // space for 64 coords - this is enough, a static short WorkAroundIconSet = 0; static short WorkAroundBarOffset = 100; -void theme_set(char *name, char *val ) +void theme_set(char *name, char *val) { cfg_name = name; cfg_val = val; int wcoords_idx = -1; CFG_COORDS4( gamelist ) - else CFG_COORDS4( gamegrid ) +else CFG_COORDS4( gamegrid ) else CFG_COORDS4( gamecarousel ) else CFG_COORDS2( covers ) @@ -577,345 +555,344 @@ void theme_set(char *name, char *val ) else CFG_COORDS2( gamegrid_favorite ) else CFG_COORDS2( gamecarousel_favorite ) - else CFG_COORDS2( gamelist_search ) - else CFG_COORDS2( gamegrid_search ) - else CFG_COORDS2( gamecarousel_search ) + else CFG_COORDS2( gamelist_search ) + else CFG_COORDS2( gamegrid_search ) + else CFG_COORDS2( gamecarousel_search ) - else CFG_COORDS2( gamelist_abc ) - else CFG_COORDS2( gamegrid_abc ) - else CFG_COORDS2( gamecarousel_abc ) + else CFG_COORDS2( gamelist_abc ) + else CFG_COORDS2( gamegrid_abc ) + else CFG_COORDS2( gamecarousel_abc ) - else CFG_COORDS2( gamelist_count ) - else CFG_COORDS2( gamegrid_count ) - else CFG_COORDS2( gamecarousel_count ) + else CFG_COORDS2( gamelist_count ) + else CFG_COORDS2( gamegrid_count ) + else CFG_COORDS2( gamecarousel_count ) - else CFG_COORDS2( gamelist_list ) - else CFG_COORDS2( gamegrid_list ) - else CFG_COORDS2( gamecarousel_list ) + else CFG_COORDS2( gamelist_list ) + else CFG_COORDS2( gamegrid_list ) + else CFG_COORDS2( gamecarousel_list ) - else CFG_COORDS2( gamelist_grid ) - else CFG_COORDS2( gamegrid_grid ) - else CFG_COORDS2( gamecarousel_grid ) + else CFG_COORDS2( gamelist_grid ) + else CFG_COORDS2( gamegrid_grid ) + else CFG_COORDS2( gamecarousel_grid ) - else CFG_COORDS2( gamelist_carousel ) - else CFG_COORDS2( gamegrid_carousel ) - else CFG_COORDS2( gamecarousel_carousel ) + else CFG_COORDS2( gamelist_carousel ) + else CFG_COORDS2( gamegrid_carousel ) + else CFG_COORDS2( gamecarousel_carousel ) - else CFG_COORDS2( gamelist_lock ) - else CFG_COORDS2( gamegrid_lock ) - else CFG_COORDS2( gamecarousel_lock ) + else CFG_COORDS2( gamelist_lock ) + else CFG_COORDS2( gamegrid_lock ) + else CFG_COORDS2( gamecarousel_lock ) - else CFG_COORDS2( gamelist_dvd ) - else CFG_COORDS2( gamegrid_dvd ) - else CFG_COORDS2( gamecarousel_dvd ) + else CFG_COORDS2( gamelist_dvd ) + else CFG_COORDS2( gamegrid_dvd ) + else CFG_COORDS2( gamecarousel_dvd ) - //********************************** - // Workaround for old Themes - //********************************** - else if ( strcmp( cfg_name, "favorite_coords" ) == 0 ) - { - short x, y; - if ( sscanf( val, "%hd,%hd", &x, &y ) == 2 ) - { - // the old Icons are aligned at center and the new at the left top corner. - // we must add 320 and sub the half image width to get the correct position. - x += 300; - // the old stuff is optimized for WideScreen. - // if no WideScreen, we must reposition the pos - if ( !WideScreen ) x -= 20; - // old themes have no search_coords - // set the searchIcon to the Position of the favIcon - THEME.gamelist_search_x = x; - THEME.gamegrid_search_x = THEME.gamecarousel_search_x = x - WorkAroundBarOffset; - THEME.gamelist_search_y = THEME.gamegrid_search_y = THEME.gamecarousel_search_y = y; - // place the favIcon to the left side of the searchIcon - if ( !WideScreen ) x -= WideScreen ? 32 : 40; - THEME.gamelist_favorite_x = x; - THEME.gamegrid_favorite_x = THEME.gamecarousel_favorite_x = x - WorkAroundBarOffset; - THEME.gamelist_favorite_y = THEME.gamegrid_favorite_y = THEME.gamecarousel_favorite_y = y; - WorkAroundIconSet |= OLD_FAV_ICON; - } - } - else if ( strcmp( cfg_name, "abc_coords" ) == 0 ) - { - short x, y; - if ( sscanf( val, "%hd,%hd", &x, &y ) == 2 ) - { - // the old Icons are aligned at center and the new at the left top corner. - // we must add 320 and sub the half image width to get the correct position. - x += 300; - // the old stuff is optimized for WideScreen. - // if no WideScreen, we must reposition the pos - if ( !WideScreen ) x -= 12; - THEME.gamelist_abc_x = x; - THEME.gamegrid_abc_x = THEME.gamecarousel_abc_x = x - WorkAroundBarOffset; - THEME.gamelist_abc_y = THEME.gamegrid_abc_y = THEME.gamecarousel_abc_y = y; - WorkAroundIconSet |= OLD_ABC_ICON; - } - } - else if ( strcmp( cfg_name, "count_coords" ) == 0 ) - { - short x, y; - if ( sscanf( val, "%hd,%hd", &x, &y ) == 2 ) - { - // the old Icons are aligned at center and the new at the left top corner. - // we must add 320 and sub the half image width to get the correct position. - x += 300; - // the old stuff is optimized for WideScreen. - // if no WideScreen, we must reposition the pos - if ( !WideScreen ) x -= 4; - THEME.gamelist_count_x = x; - THEME.gamegrid_count_x = THEME.gamecarousel_count_x = x - WorkAroundBarOffset; - THEME.gamelist_count_y = THEME.gamegrid_count_y = THEME.gamecarousel_count_y = y; - WorkAroundIconSet |= OLD_COUNT_ICON; - } - } - else if ( strcmp( cfg_name, "list_coords" ) == 0 ) - { - short x, y; - if ( sscanf( val, "%hd,%hd", &x, &y ) == 2 ) - { - // the old Icons are aligned at center and the new at the left top corner. - // we must add 320 and sub the half image width to get the correct position. - x += 300; - // the old stuff is optimized for WideScreen. - // if no WideScreen, we must reposition the pos - if ( !WideScreen ) x += 4; - THEME.gamelist_list_x = x; - THEME.gamegrid_list_x = THEME.gamecarousel_list_x = x - WorkAroundBarOffset; - THEME.gamelist_list_y = THEME.gamegrid_list_y = THEME.gamecarousel_list_y = y; - WorkAroundIconSet |= OLD_LIST_ICON; - } - } - else if ( strcmp( cfg_name, "grid_coords" ) == 0 ) - { - short x, y; - if ( sscanf( val, "%hd,%hd", &x, &y ) == 2 ) - { - // the old Icons are aligned at center and the new at the left top corner. - // we must add 320 and sub the half image width to get the correct position. - x += 300; - // the old stuff is optimized for WideScreen. - // if no WideScreen, we must reposition the pos - if ( !WideScreen ) x += 12; - THEME.gamelist_grid_x = x; - THEME.gamegrid_grid_x = THEME.gamecarousel_grid_x = x - WorkAroundBarOffset; - THEME.gamelist_grid_y = THEME.gamegrid_grid_y = THEME.gamecarousel_grid_y = y; - WorkAroundIconSet |= OLD_GRID_ICON; - } - } - else if ( strcmp( cfg_name, "carousel_coords" ) == 0 ) - { - short x, y; - if ( sscanf( val, "%hd,%hd", &x, &y ) == 2 ) - { - // the old Icons are aligned at center and the new at the left top corner. - // we must add 320 and sub the half image width to get the correct position. - x += 300; - // the old stuff is optimized for WideScreen. - // if no WideScreen, we must reposition the pos - if ( !WideScreen ) x += 20; - THEME.gamelist_carousel_x = x; - THEME.gamegrid_carousel_x = THEME.gamecarousel_carousel_x = x - WorkAroundBarOffset; - THEME.gamelist_carousel_y = THEME.gamegrid_carousel_y = THEME.gamecarousel_carousel_y = y; - WorkAroundIconSet |= OLD_CAROUSEL_ICON; + //********************************** + // Workaround for old Themes + //********************************** - // old themes have no dvd_coords - // place the dvdIcon to the right side of the carouselIcon - if ( !WideScreen ) x += WideScreen ? 32 : 40; - THEME.gamelist_lock_x = x; - THEME.gamegrid_lock_x = THEME.gamecarousel_lock_x = x - WorkAroundBarOffset; - THEME.gamelist_lock_y = THEME.gamegrid_lock_y = THEME.gamecarousel_lock_y = y; + else if ( strcmp( cfg_name, "favorite_coords" ) == 0 ) + { + short x, y; + if ( sscanf( val, "%hd,%hd", &x, &y ) == 2 ) + { + // the old Icons are aligned at center and the new at the left top corner. + // we must add 320 and sub the half image width to get the correct position. + x += 300; + // the old stuff is optimized for WideScreen. + // if no WideScreen, we must reposition the pos + if ( !WideScreen ) x -= 20; + // old themes have no search_coords + // set the searchIcon to the Position of the favIcon + THEME.gamelist_search_x = x; + THEME.gamegrid_search_x = THEME.gamecarousel_search_x = x - WorkAroundBarOffset; + THEME.gamelist_search_y = THEME.gamegrid_search_y = THEME.gamecarousel_search_y = y; + // place the favIcon to the left side of the searchIcon + if ( !WideScreen ) x -= WideScreen ? 32 : 40; + THEME.gamelist_favorite_x = x; + THEME.gamegrid_favorite_x = THEME.gamecarousel_favorite_x = x - WorkAroundBarOffset; + THEME.gamelist_favorite_y = THEME.gamegrid_favorite_y = THEME.gamecarousel_favorite_y = y; + WorkAroundIconSet |= OLD_FAV_ICON; + } + } + else if ( strcmp( cfg_name, "abc_coords" ) == 0 ) + { + short x, y; + if ( sscanf( val, "%hd,%hd", &x, &y ) == 2 ) + { + // the old Icons are aligned at center and the new at the left top corner. + // we must add 320 and sub the half image width to get the correct position. + x += 300; + // the old stuff is optimized for WideScreen. + // if no WideScreen, we must reposition the pos + if ( !WideScreen ) x -= 12; + THEME.gamelist_abc_x = x; + THEME.gamegrid_abc_x = THEME.gamecarousel_abc_x = x - WorkAroundBarOffset; + THEME.gamelist_abc_y = THEME.gamegrid_abc_y = THEME.gamecarousel_abc_y = y; + WorkAroundIconSet |= OLD_ABC_ICON; + } + } + else if ( strcmp( cfg_name, "count_coords" ) == 0 ) + { + short x, y; + if ( sscanf( val, "%hd,%hd", &x, &y ) == 2 ) + { + // the old Icons are aligned at center and the new at the left top corner. + // we must add 320 and sub the half image width to get the correct position. + x += 300; + // the old stuff is optimized for WideScreen. + // if no WideScreen, we must reposition the pos + if ( !WideScreen ) x -= 4; + THEME.gamelist_count_x = x; + THEME.gamegrid_count_x = THEME.gamecarousel_count_x = x - WorkAroundBarOffset; + THEME.gamelist_count_y = THEME.gamegrid_count_y = THEME.gamecarousel_count_y = y; + WorkAroundIconSet |= OLD_COUNT_ICON; + } + } + else if ( strcmp( cfg_name, "list_coords" ) == 0 ) + { + short x, y; + if ( sscanf( val, "%hd,%hd", &x, &y ) == 2 ) + { + // the old Icons are aligned at center and the new at the left top corner. + // we must add 320 and sub the half image width to get the correct position. + x += 300; + // the old stuff is optimized for WideScreen. + // if no WideScreen, we must reposition the pos + if ( !WideScreen ) x += 4; + THEME.gamelist_list_x = x; + THEME.gamegrid_list_x = THEME.gamecarousel_list_x = x - WorkAroundBarOffset; + THEME.gamelist_list_y = THEME.gamegrid_list_y = THEME.gamecarousel_list_y = y; + WorkAroundIconSet |= OLD_LIST_ICON; + } + } + else if ( strcmp( cfg_name, "grid_coords" ) == 0 ) + { + short x, y; + if ( sscanf( val, "%hd,%hd", &x, &y ) == 2 ) + { + // the old Icons are aligned at center and the new at the left top corner. + // we must add 320 and sub the half image width to get the correct position. + x += 300; + // the old stuff is optimized for WideScreen. + // if no WideScreen, we must reposition the pos + if ( !WideScreen ) x += 12; + THEME.gamelist_grid_x = x; + THEME.gamegrid_grid_x = THEME.gamecarousel_grid_x = x - WorkAroundBarOffset; + THEME.gamelist_grid_y = THEME.gamegrid_grid_y = THEME.gamecarousel_grid_y = y; + WorkAroundIconSet |= OLD_GRID_ICON; + } + } + else if ( strcmp( cfg_name, "carousel_coords" ) == 0 ) + { + short x, y; + if ( sscanf( val, "%hd,%hd", &x, &y ) == 2 ) + { + // the old Icons are aligned at center and the new at the left top corner. + // we must add 320 and sub the half image width to get the correct position. + x += 300; + // the old stuff is optimized for WideScreen. + // if no WideScreen, we must reposition the pos + if ( !WideScreen ) x += 20; + THEME.gamelist_carousel_x = x; + THEME.gamegrid_carousel_x = THEME.gamecarousel_carousel_x = x - WorkAroundBarOffset; + THEME.gamelist_carousel_y = THEME.gamegrid_carousel_y = THEME.gamecarousel_carousel_y = y; + WorkAroundIconSet |= OLD_CAROUSEL_ICON; - x += WideScreen ? 32 : 40; - THEME.gamelist_dvd_x = x; - THEME.gamegrid_dvd_x = THEME.gamecarousel_dvd_x = x - WorkAroundBarOffset; - THEME.gamelist_dvd_y = THEME.gamegrid_dvd_y = THEME.gamecarousel_dvd_y = y; - } - } + // old themes have no dvd_coords + // place the dvdIcon to the right side of the carouselIcon + if ( !WideScreen ) x += WideScreen ? 32 : 40; + THEME.gamelist_lock_x = x; + THEME.gamegrid_lock_x = THEME.gamecarousel_lock_x = x - WorkAroundBarOffset; + THEME.gamelist_lock_y = THEME.gamegrid_lock_y = THEME.gamecarousel_lock_y = y; - else if ( strcmp( cfg_name, "sortBarOffset" ) == 0 ) - { - short o; - if ( sscanf( val, "%hd", &o ) == 1 ) - { - if ( WorkAroundIconSet & OLD_FAV_ICON ) - { - THEME.gamegrid_favorite_x += WorkAroundBarOffset - o; - THEME.gamecarousel_favorite_x += WorkAroundBarOffset - o; - THEME.gamegrid_search_x += WorkAroundBarOffset - o; - THEME.gamecarousel_search_x += WorkAroundBarOffset - o; - } - if ( WorkAroundIconSet & OLD_ABC_ICON ) - { - THEME.gamegrid_abc_x += WorkAroundBarOffset - o; - THEME.gamecarousel_abc_x += WorkAroundBarOffset - o; - } - if ( WorkAroundIconSet & OLD_COUNT_ICON ) - { - THEME.gamegrid_count_x += WorkAroundBarOffset - o; - THEME.gamecarousel_count_x += WorkAroundBarOffset - o; - } - if ( WorkAroundIconSet & OLD_LIST_ICON ) - { - THEME.gamegrid_list_x += WorkAroundBarOffset - o; - THEME.gamecarousel_list_x += WorkAroundBarOffset - o; - } - if ( WorkAroundIconSet & OLD_GRID_ICON ) - { - THEME.gamegrid_grid_x += WorkAroundBarOffset - o; - THEME.gamecarousel_grid_x += WorkAroundBarOffset - o; - } - if ( WorkAroundIconSet & OLD_CAROUSEL_ICON ) - { - THEME.gamegrid_carousel_x += WorkAroundBarOffset - o; - THEME.gamecarousel_carousel_x += WorkAroundBarOffset - o; - THEME.gamegrid_lock_x += WorkAroundBarOffset - o; - THEME.gamecarousel_lock_x += WorkAroundBarOffset - o; - THEME.gamegrid_dvd_x += WorkAroundBarOffset - o; - THEME.gamecarousel_dvd_x += WorkAroundBarOffset - o; - } - WorkAroundBarOffset = o; - } - } + x += WideScreen ? 32 : 40; + THEME.gamelist_dvd_x = x; + THEME.gamegrid_dvd_x = THEME.gamecarousel_dvd_x = x - WorkAroundBarOffset; + THEME.gamelist_dvd_y = THEME.gamegrid_dvd_y = THEME.gamecarousel_dvd_y = y; + } + } + else if ( strcmp( cfg_name, "sortBarOffset" ) == 0 ) + { + short o; + if ( sscanf( val, "%hd", &o ) == 1 ) + { + if ( WorkAroundIconSet & OLD_FAV_ICON ) + { + THEME.gamegrid_favorite_x += WorkAroundBarOffset - o; + THEME.gamecarousel_favorite_x += WorkAroundBarOffset - o; + THEME.gamegrid_search_x += WorkAroundBarOffset - o; + THEME.gamecarousel_search_x += WorkAroundBarOffset - o; + } + if ( WorkAroundIconSet & OLD_ABC_ICON ) + { + THEME.gamegrid_abc_x += WorkAroundBarOffset - o; + THEME.gamecarousel_abc_x += WorkAroundBarOffset - o; + } + if ( WorkAroundIconSet & OLD_COUNT_ICON ) + { + THEME.gamegrid_count_x += WorkAroundBarOffset - o; + THEME.gamecarousel_count_x += WorkAroundBarOffset - o; + } + if ( WorkAroundIconSet & OLD_LIST_ICON ) + { + THEME.gamegrid_list_x += WorkAroundBarOffset - o; + THEME.gamecarousel_list_x += WorkAroundBarOffset - o; + } + if ( WorkAroundIconSet & OLD_GRID_ICON ) + { + THEME.gamegrid_grid_x += WorkAroundBarOffset - o; + THEME.gamecarousel_grid_x += WorkAroundBarOffset - o; + } + if ( WorkAroundIconSet & OLD_CAROUSEL_ICON ) + { + THEME.gamegrid_carousel_x += WorkAroundBarOffset - o; + THEME.gamecarousel_carousel_x += WorkAroundBarOffset - o; + THEME.gamegrid_lock_x += WorkAroundBarOffset - o; + THEME.gamecarousel_lock_x += WorkAroundBarOffset - o; + THEME.gamegrid_dvd_x += WorkAroundBarOffset - o; + THEME.gamecarousel_dvd_x += WorkAroundBarOffset - o; + } + WorkAroundBarOffset = o; + } + } } - // split line to part1 delimiter part2 -bool trimsplit( char *line, char *part1, char *part2, char delim, int size ) +bool trimsplit(char *line, char *part1, char *part2, char delim, int size) { - char *eq = strchr( line, delim ); - if ( !eq ) return false; - trim_n_copy( part1, line, eq - line, size ); - trimcopy( part2, eq + 1, size ); + char *eq = strchr(line, delim); + if (!eq) return false; + trim_n_copy(part1, line, eq - line, size); + trimcopy(part2, eq + 1, size); return true; } -void cfg_parseline( char *line, void ( *set_func )( char*, char* ) ) +void cfg_parseline(char *line, void(*set_func)(char*, char*)) { // split name = value char tmp[300], name[200], val[200]; - strlcpy( tmp, line, sizeof( tmp ) ); - char *eq = strchr( tmp, '=' ); - if ( !eq ) return; + strlcpy(tmp, line, sizeof(tmp)); + char *eq = strchr(tmp, '='); + if (!eq) return; *eq = 0; - trimcopy( name, tmp, sizeof( name ) ); - trimcopy( val, eq + 1, sizeof( val ) ); + trimcopy(name, tmp, sizeof(name)); + trimcopy(val, eq + 1, sizeof(val)); //printf("CFG: %s = %s\n", name, val); - set_func( name, val ); + set_func(name, val); } -void cfg_parsetitleline( char *line, void ( *set_func )( char*, char*, u8 ) ) +void cfg_parsetitleline(char *line, void(*set_func)(char*, char*, u8)) { // split name = value char tmp[200], name[200], val[200]; int block = 0; - strlcpy( tmp, line, sizeof( tmp ) ); - char *eq = strchr( tmp, '=' ); - if ( !eq ) return; + strlcpy(tmp, line, sizeof(tmp)); + char *eq = strchr(tmp, '='); + if (!eq) return; *eq = 0; - trimcopy( name, tmp, sizeof( name ) ); + trimcopy(name, tmp, sizeof(name)); - char *blockpos = strrchr( eq + 1, '=' ); + char *blockpos = strrchr(eq + 1, '='); - if ( !blockpos ) - trimcopy( val, eq + 1, sizeof( val ) ); + if (!blockpos) + trimcopy(val, eq + 1, sizeof(val)); else { *blockpos = 0; - trimcopy( val, eq + 1, sizeof( val ) ); - if ( sscanf( blockpos + 1, "%d", &block ) != 1 ) + trimcopy(val, eq + 1, sizeof(val)); + if (sscanf(blockpos + 1, "%d", &block) != 1) { block = 0; } } - set_func( name, val, block ); + set_func(name, val, block); } -bool cfg_parsefile( char *fname, void ( *set_func )( char*, char* ) ) +bool cfg_parsefile(char *fname, void(*set_func)(char*, char*)) { FILE *f; char line[300]; //printf("opening(%s)\n", fname); - f = fopen( fname, "r" ); - if ( !f ) + f = fopen(fname, "r"); + if (!f) { //printf("error opening(%s)\n", fname); return false; } - while ( fgets( line, sizeof( line ), f ) ) + while (fgets(line, sizeof(line), f)) { // lines starting with # are comments - if ( line[0] == '#' ) continue; - cfg_parseline( line, set_func ); + if (line[0] == '#') continue; + cfg_parseline(line, set_func); } - fclose( f ); + fclose(f); return true; } -bool cfg_parsetitlefile( char *fname, void ( *set_func )( char*, char*, u8 ) ) +bool cfg_parsetitlefile(char *fname, void(*set_func)(char*, char*, u8)) { FILE *f; char line[200]; //printf("opening(%s)\n", fname); - f = fopen( fname, "r" ); - if ( !f ) + f = fopen(fname, "r"); + if (!f) { //printf("error opening(%s)\n", fname); return false; } - while ( fgets( line, sizeof( line ), f ) ) + while (fgets(line, sizeof(line), f)) { // lines starting with # are comments - if ( line[0] == '#' ) continue; - cfg_parsetitleline( line, set_func ); + if (line[0] == '#') continue; + cfg_parsetitleline(line, set_func); } - fclose( f ); + fclose(f); return true; } /* -void cfg_parsearg(int argc, char **argv) -{ - int i; - char *eq; - char pathname[200]; - for (i=1; i= MAX_SAVED_GAMES ) return NULL; + struct Game_CFG *game = CFG_get_game_opt(id); + if (game) return game; + if (num_saved_games >= MAX_SAVED_GAMES) return NULL; game = &cfg_game[num_saved_games]; num_saved_games++; return game; } // current options to game -void cfg_set_game_opt( struct Game_CFG *game, u8 *id ) +void cfg_set_game_opt(struct Game_CFG *game, u8 *id) { - strncpy( ( char* )game->id, ( char* )id, 6 ); + strncpy((char*) game->id, (char*) id, 6); game->id[6] = 0; game->video = videoChoice; game->language = languageChoice; @@ -927,36 +904,36 @@ void cfg_set_game_opt( struct Game_CFG *game, u8 *id ) game->iosreloadblock = reloadblock; game->patchcountrystrings = countrystrings; game->loadalternatedol = alternatedol; - if ( game->loadalternatedol == 0 ) + if (game->loadalternatedol == 0) { alternatedoloffset = 0; - strcpy( alternatedname, "" ); + strcpy(alternatedname, ""); } game->alternatedolstart = alternatedoloffset; - strlcpy( game->alternatedolname, alternatedname, sizeof( game->alternatedolname ) ); + strlcpy(game->alternatedolname, alternatedname, sizeof(game->alternatedolname)); game->returnTo = returnToLoaderGV; } -struct Game_NUM* cfg_get_game_num( u8 *id ) +struct Game_NUM* cfg_get_game_num(u8 *id) { - struct Game_NUM *game = CFG_get_game_num( id ); - if ( game ) return game; - if ( num_saved_game_num >= MAX_SAVED_GAME_NUM ) return NULL; + struct Game_NUM *game = CFG_get_game_num(id); + if (game) return game; + if (num_saved_game_num >= MAX_SAVED_GAME_NUM) return NULL; game = &cfg_game_num[num_saved_game_num]; num_saved_game_num++; return game; } // current options to game -void cfg_set_game_num( struct Game_NUM *game, u8 *id ) +void cfg_set_game_num(struct Game_NUM *game, u8 *id) { - strncpy( ( char* )game->id, ( char* )id, 6 ); + strncpy((char*) game->id, (char*) id, 6); game->id[6] = 0; game->favorite = favoritevar; game->count = playcount; } -void game_set( char *name, char *val ) +void game_set(char *name, char *val) { // sample line: // game:RTNP41 = video:game; language:english; ocarina:0; @@ -964,11 +941,11 @@ void game_set( char *name, char *val ) //printf("GAME: '%s=%s'\n", name, val); u8 id[8]; struct Game_CFG *game; - if ( strncmp( name, "game:", 5 ) != 0 ) return; - trimcopy( ( char* )id, name + 5, sizeof( id ) ); - game = cfg_get_game( id ); + if (strncmp(name, "game:", 5) != 0) return; + trimcopy((char*) id, name + 5, sizeof(id)); + game = cfg_get_game(id); // set id and current options as default - cfg_set_game_opt( game, id ); + cfg_set_game_opt(game, id); //printf("GAME(%s) '%s'\n", id, val); sleep(1); // parse val @@ -976,110 +953,112 @@ void game_set( char *name, char *val ) char opt[300], *p, *np; p = val; - while ( p ) + while (p) { - np = strchr( p, ';' ); - if ( np ) trim_n_copy( opt, p, np - p, sizeof( opt ) ); - else trimcopy( opt, p, sizeof( opt ) ); + np = strchr(p, ';'); + if (np) + trim_n_copy(opt, p, np - p, sizeof(opt)); + else trimcopy(opt, p, sizeof(opt)); //printf("GAME(%s) (%s)\n", id, opt); sleep(1); // parse opt 'language:english' char opt_name[200], opt_val[200]; - if ( trimsplit( opt, opt_name, opt_val, ':', sizeof( opt_name ) ) ) + if (trimsplit(opt, opt_name, opt_val, ':', sizeof(opt_name))) { //printf("GAME(%s) (%s=%s)\n", id, opt_name, opt_val); sleep(1); short opt_v, opt_l, opt_c; - if ( map_auto( "video", opt_name, opt_val, map_video, &opt_v ) ) + if (map_auto("video", opt_name, opt_val, map_video, &opt_v)) { // valid option, assign game->video = opt_v; } - if ( map_auto( "language", opt_name, opt_val, map_language, &opt_l ) ) + if (map_auto("language", opt_name, opt_val, map_language, &opt_l)) { // valid option, assign game->language = opt_l; } - if ( strcmp( "ocarina", opt_name ) == 0 ) + if (strcmp("ocarina", opt_name) == 0) { - if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + if (sscanf(opt_val, "%hd", &opt_c) == 1) { game->ocarina = opt_c; } } - if ( strcmp( "vipatch", opt_name ) == 0 ) + if (strcmp("vipatch", opt_name) == 0) { - if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + if (sscanf(opt_val, "%hd", &opt_c) == 1) { game->vipatch = opt_c; } } - if ( strcmp( "ios", opt_name ) == 0 ) + if (strcmp("ios", opt_name) == 0) { - if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + if (sscanf(opt_val, "%hd", &opt_c) == 1) { game->ios = opt_c; } } - if ( strcmp( "pctrl", opt_name ) == 0 ) + if (strcmp("pctrl", opt_name) == 0) { - if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + if (sscanf(opt_val, "%hd", &opt_c) == 1) { game->parentalcontrol = opt_c; } } - if ( strcmp( "errorfix002", opt_name ) == 0 ) + if (strcmp("errorfix002", opt_name) == 0) { - if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + if (sscanf(opt_val, "%hd", &opt_c) == 1) { game->errorfix002 = opt_c; } } - if ( strcmp( "iosreloadblock", opt_name ) == 0 ) + if (strcmp("iosreloadblock", opt_name) == 0) { - if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + if (sscanf(opt_val, "%hd", &opt_c) == 1) { game->iosreloadblock = opt_c; } } - if ( strcmp( "patchcountrystrings", opt_name ) == 0 ) + if (strcmp("patchcountrystrings", opt_name) == 0) { - if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + if (sscanf(opt_val, "%hd", &opt_c) == 1) { game->patchcountrystrings = opt_c; } } - if ( strcmp( "loadalternatedol", opt_name ) == 0 ) + if (strcmp("loadalternatedol", opt_name) == 0) { - if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + if (sscanf(opt_val, "%hd", &opt_c) == 1) { game->loadalternatedol = opt_c; } } - if ( strcmp( "alternatedolstart", opt_name ) == 0 ) + if (strcmp("alternatedolstart", opt_name) == 0) { - if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + if (sscanf(opt_val, "%hd", &opt_c) == 1) { game->alternatedolstart = opt_c; } } - if ( strcmp( "alternatedolname", opt_name ) == 0 ) - { - strlcpy( game->alternatedolname, opt_val, sizeof( game->alternatedolname ) ); - } - if ( strcmp( "returnTo", opt_name ) == 0 ) - { - if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) - { - game->returnTo = opt_c; - } - } + if (strcmp("alternatedolname", opt_name) == 0) + { + strlcpy(game->alternatedolname, opt_val, sizeof(game->alternatedolname)); + } + if (strcmp("returnTo", opt_name) == 0) + { + if (sscanf(opt_val, "%hd", &opt_c) == 1) + { + game->returnTo = opt_c; + } + } } // next opt - if ( np ) p = np + 1; + if (np) + p = np + 1; else p = NULL; } } -void parental_set( char *name, char *val ) +void parental_set(char *name, char *val) { // sample line: // game:RTNP41 = video:game; language:english; ocarina:0; @@ -1087,40 +1066,41 @@ void parental_set( char *name, char *val ) //printf("GAME: '%s=%s'\n", name, val); u8 id[8]; - if ( strncmp( name, "game:", 5 ) != 0 ) return; - trimcopy( ( char* )id, name + 5, sizeof( id ) ); + if (strncmp(name, "game:", 5) != 0) return; + trimcopy((char*) id, name + 5, sizeof(id)); // parse val // first split options by ; char opt[200], *p, *np; p = val; - while ( p ) + while (p) { - np = strchr( p, ';' ); - if ( np ) trim_n_copy( opt, p, np - p, sizeof( opt ) ); - else trimcopy( opt, p, sizeof( opt ) ); + np = strchr(p, ';'); + if (np) + trim_n_copy(opt, p, np - p, sizeof(opt)); + else trimcopy(opt, p, sizeof(opt)); //printf("GAME(%s) (%s)\n", id, opt); sleep(1); // parse opt 'language:english' char opt_name[200], opt_val[200]; - if ( trimsplit( opt, opt_name, opt_val, ':', sizeof( opt_name ) ) ) + if (trimsplit(opt, opt_name, opt_val, ':', sizeof(opt_name))) { //printf("GAME(%s) (%s=%s)\n", id, opt_name, opt_val); sleep(1); short opt_c; - if ( strcmp( "pctrl", opt_name ) == 0 ) + if (strcmp("pctrl", opt_name) == 0) { - if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + if (sscanf(opt_val, "%hd", &opt_c) == 1) { - cfg_control = realloc( cfg_control, ( num_control + 1 ) * sizeof( struct ID_Control ) ); - if ( !cfg_control ) + cfg_control = realloc(cfg_control, (num_control + 1) * sizeof(struct ID_Control)); + if (!cfg_control) { // error num_control = 0; return; } // add - strcpy( cfg_control[num_control].id, ( char* ) id ); + strcpy(cfg_control[num_control].id, (char*) id); cfg_control[num_control].block = opt_c; num_control++; } @@ -1128,55 +1108,57 @@ void parental_set( char *name, char *val ) } // next opt - if ( np ) p = np + 1; + if (np) + p = np + 1; else p = NULL; } } -void game_set_num( char *name, char *val ) +void game_set_num(char *name, char *val) { u8 id[8]; struct Game_NUM *game; - if ( strncmp( name, "game:", 5 ) != 0 ) return; - trimcopy( ( char* )id, name + 5, sizeof( id ) ); - game = cfg_get_game_num( id ); - - cfg_set_game_num( game, id ); + if (strncmp(name, "game:", 5) != 0) return; + trimcopy((char*) id, name + 5, sizeof(id)); + game = cfg_get_game_num(id); + cfg_set_game_num(game, id); // parse val // first split options by ; char opt[200], *p, *np; p = val; - while ( p ) + while (p) { - np = strchr( p, ';' ); - if ( np ) trim_n_copy( opt, p, np - p, sizeof( opt ) ); - else trimcopy( opt, p, sizeof( opt ) ); + np = strchr(p, ';'); + if (np) + trim_n_copy(opt, p, np - p, sizeof(opt)); + else trimcopy(opt, p, sizeof(opt)); char opt_name[200], opt_val[200]; - if ( trimsplit( opt, opt_name, opt_val, ':', sizeof( opt_name ) ) ) + if (trimsplit(opt, opt_name, opt_val, ':', sizeof(opt_name))) { short opt_c; - if ( strcmp( "favorite", opt_name ) == 0 ) + if (strcmp("favorite", opt_name) == 0) { - if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + if (sscanf(opt_val, "%hd", &opt_c) == 1) { game->favorite = opt_c; } } - if ( strcmp( "count", opt_name ) == 0 ) + if (strcmp("count", opt_name) == 0) { - if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + if (sscanf(opt_val, "%hd", &opt_c) == 1) { game->count = opt_c; } } } - if ( np ) p = np + 1; + if (np) + p = np + 1; else p = NULL; } } @@ -1184,15 +1166,15 @@ void game_set_num( char *name, char *val ) bool cfg_load_games() { char GXGameSettings_cfg[32]; - sprintf( GXGameSettings_cfg, "%s/config/GXGameSettings.cfg", bootDevice ); - return cfg_parsefile( GXGameSettings_cfg, &game_set ); + sprintf(GXGameSettings_cfg, "%s/config/GXGameSettings.cfg", bootDevice); + return cfg_parsefile(GXGameSettings_cfg, &game_set); } bool cfg_load_game_num() { char GXGameFavorites_cfg[32]; - sprintf( GXGameFavorites_cfg, "%s/config/GXGameFavorites.cfg", bootDevice ); - return cfg_parsefile( GXGameFavorites_cfg, &game_set_num ); + sprintf(GXGameFavorites_cfg, "%s/config/GXGameFavorites.cfg", bootDevice); + return cfg_parsefile(GXGameFavorites_cfg, &game_set_num); } bool cfg_save_games() @@ -1200,47 +1182,47 @@ bool cfg_save_games() FILE *f; int i; char GXGameSettings_cfg[50]; - sprintf( GXGameSettings_cfg, "%s/config", bootDevice ); - mkdir( GXGameSettings_cfg, 0777 ); + sprintf(GXGameSettings_cfg, "%s/config", bootDevice); + mkdir(GXGameSettings_cfg, 0777); - sprintf( GXGameSettings_cfg, "%s/config/GXGameSettings.cfg", bootDevice ); - f = fopen( GXGameSettings_cfg, "w" ); - if ( !f ) + sprintf(GXGameSettings_cfg, "%s/config/GXGameSettings.cfg", bootDevice); + f = fopen(GXGameSettings_cfg, "w"); + if (!f) { - printf( "Error saving %s\n", "GXGameSettings.cfg" ); - sleep( 1 ); + printf("Error saving %s\n", "GXGameSettings.cfg"); + sleep(1); return false; } - fprintf( f, "# USB Loader settings file\n" ); - fprintf( f, "# note: this file is automatically generated\n" ); - fclose( f ); + fprintf(f, "# USB Loader settings file\n"); + fprintf(f, "# note: this file is automatically generated\n"); + fclose(f); /* Closing and reopening because of a write issue we are having right now */ - f = fopen( GXGameSettings_cfg, "w" ); - fprintf( f, "# USB Loader settings file\n" ); - fprintf( f, "# note: this file is automatically generated\n" ); - fprintf( f, "# Num Games: %d\n", num_saved_games ); - for ( i = 0; i < num_saved_games; i++ ) + f = fopen(GXGameSettings_cfg, "w"); + fprintf(f, "# USB Loader settings file\n"); + fprintf(f, "# note: this file is automatically generated\n"); + fprintf(f, "# Num Games: %d\n", num_saved_games); + for (i = 0; i < num_saved_games; i++) { char *s; - fprintf( f, "game:%s = ", cfg_game[i].id ); - s = map_get_name( map_video, cfg_game[i].video ); - if ( s ) fprintf( f, "video:%s; ", s ); - s = map_get_name( map_language, cfg_game[i].language ); - if ( s ) fprintf( f, "language:%s; ", s ); - fprintf( f, "ocarina:%d; ", cfg_game[i].ocarina ); - fprintf( f, "vipatch:%d; ", cfg_game[i].vipatch ); - fprintf( f, "ios:%d; ", cfg_game[i].ios ); - fprintf( f, "pctrl:%d; ", cfg_game[i].parentalcontrol ); - fprintf( f, "errorfix002:%d; ", cfg_game[i].errorfix002 ); - fprintf( f, "iosreloadblock:%d; ", cfg_game[i].iosreloadblock ); - fprintf( f, "patchcountrystrings:%d; ", cfg_game[i].patchcountrystrings ); - fprintf( f, "loadalternatedol:%d;", cfg_game[i].loadalternatedol ); - fprintf( f, "alternatedolstart:%d;", cfg_game[i].alternatedolstart ); - fprintf( f, "alternatedolname:%s;\n", cfg_game[i].alternatedolname ); - fprintf( f, "returnTo:%d;\n", cfg_game[i].returnTo ); + fprintf(f, "game:%s = ", cfg_game[i].id); + s = map_get_name(map_video, cfg_game[i].video); + if (s) fprintf(f, "video:%s; ", s); + s = map_get_name(map_language, cfg_game[i].language); + if (s) fprintf(f, "language:%s; ", s); + fprintf(f, "ocarina:%d; ", cfg_game[i].ocarina); + fprintf(f, "vipatch:%d; ", cfg_game[i].vipatch); + fprintf(f, "ios:%d; ", cfg_game[i].ios); + fprintf(f, "pctrl:%d; ", cfg_game[i].parentalcontrol); + fprintf(f, "errorfix002:%d; ", cfg_game[i].errorfix002); + fprintf(f, "iosreloadblock:%d; ", cfg_game[i].iosreloadblock); + fprintf(f, "patchcountrystrings:%d; ", cfg_game[i].patchcountrystrings); + fprintf(f, "loadalternatedol:%d;", cfg_game[i].loadalternatedol); + fprintf(f, "alternatedolstart:%d;", cfg_game[i].alternatedolstart); + fprintf(f, "alternatedolname:%s;\n", cfg_game[i].alternatedolname); + fprintf(f, "returnTo:%d;\n", cfg_game[i].returnTo); } - fprintf( f, "# END\n" ); - fclose( f ); + fprintf(f, "# END\n"); + fclose(f); return true; } @@ -1249,33 +1231,33 @@ bool cfg_save_game_num() FILE *f; int i; char GXGameFavorites_cfg[32]; - sprintf( GXGameFavorites_cfg, "%s/config", bootDevice ); - mkdir( GXGameFavorites_cfg, 0777 ); + sprintf(GXGameFavorites_cfg, "%s/config", bootDevice); + mkdir(GXGameFavorites_cfg, 0777); - sprintf( GXGameFavorites_cfg, "%s/config/GXGameFavorites.cfg", bootDevice ); - f = fopen( GXGameFavorites_cfg, "w" ); - if ( !f ) + sprintf(GXGameFavorites_cfg, "%s/config/GXGameFavorites.cfg", bootDevice); + f = fopen(GXGameFavorites_cfg, "w"); + if (!f) { - printf( "Error saving %s\n", "GXGameFavorites.cfg" ); - sleep( 1 ); + printf("Error saving %s\n", "GXGameFavorites.cfg"); + sleep(1); return false; } - fprintf( f, "# USB Loader settings file\n" ); - fprintf( f, "# note: this file is automatically generated\n" ); - fclose( f ); + fprintf(f, "# USB Loader settings file\n"); + fprintf(f, "# note: this file is automatically generated\n"); + fclose(f); /* Closing and reopening because of a write issue we are having right now */ - f = fopen( GXGameFavorites_cfg, "w" ); - fprintf( f, "# USB Loader settings file\n" ); - fprintf( f, "# note: this file is automatically generated\n" ); - fprintf( f, "# Num Games: %d\n", num_saved_game_num ); - for ( i = 0; i < num_saved_game_num; i++ ) + f = fopen(GXGameFavorites_cfg, "w"); + fprintf(f, "# USB Loader settings file\n"); + fprintf(f, "# note: this file is automatically generated\n"); + fprintf(f, "# Num Games: %d\n", num_saved_game_num); + for (i = 0; i < num_saved_game_num; i++) { - fprintf( f, "game:%s = ", cfg_game_num[i].id ); - fprintf( f, "favorite:%d; ", cfg_game_num[i].favorite ); - fprintf( f, "count:%d;\n", cfg_game_num[i].count ); + fprintf(f, "game:%s = ", cfg_game_num[i].id); + fprintf(f, "favorite:%d; ", cfg_game_num[i].favorite); + fprintf(f, "count:%d;\n", cfg_game_num[i].count); } - fprintf( f, "# END\n" ); - fclose( f ); + fprintf(f, "# END\n"); + fclose(f); return true; } @@ -1284,43 +1266,42 @@ bool CFG_reset_all_playcounters() FILE *f; int i; char GXGameFavorites_cfg[32]; - sprintf( GXGameFavorites_cfg, "%s/config", bootDevice ); - mkdir( GXGameFavorites_cfg, 0777 ); + sprintf(GXGameFavorites_cfg, "%s/config", bootDevice); + mkdir(GXGameFavorites_cfg, 0777); - sprintf( GXGameFavorites_cfg, "%s/config/GXGameFavorites.cfg", bootDevice ); - f = fopen( GXGameFavorites_cfg, "w" ); - if ( !f ) + sprintf(GXGameFavorites_cfg, "%s/config/GXGameFavorites.cfg", bootDevice); + f = fopen(GXGameFavorites_cfg, "w"); + if (!f) { - printf( "Error saving %s\n", "GXGameFavorites.cfg" ); - sleep( 1 ); + printf("Error saving %s\n", "GXGameFavorites.cfg"); + sleep(1); return false; } - fprintf( f, "# USB Loader settings file\n" ); - fprintf( f, "# note: this file is automatically generated\n" ); - fclose( f ); + fprintf(f, "# USB Loader settings file\n"); + fprintf(f, "# note: this file is automatically generated\n"); + fclose(f); /* Closing and reopening because of a write issue we are having right now */ - f = fopen( GXGameFavorites_cfg, "w" ); - fprintf( f, "# USB Loader settings file\n" ); - fprintf( f, "# note: this file is automatically generated\n" ); - fprintf( f, "# Num Games: %d\n", num_saved_game_num ); - for ( i = 0; i < num_saved_game_num; i++ ) + f = fopen(GXGameFavorites_cfg, "w"); + fprintf(f, "# USB Loader settings file\n"); + fprintf(f, "# note: this file is automatically generated\n"); + fprintf(f, "# Num Games: %d\n", num_saved_game_num); + for (i = 0; i < num_saved_game_num; i++) { - fprintf( f, "game:%s = ", cfg_game_num[i].id ); - fprintf( f, "favorite:%d; ", cfg_game_num[i].favorite ); - fprintf( f, "count:0;\n" ); + fprintf(f, "game:%s = ", cfg_game_num[i].id); + fprintf(f, "favorite:%d; ", cfg_game_num[i].favorite); + fprintf(f, "count:0;\n"); } - fprintf( f, "# END\n" ); - fclose( f ); + fprintf(f, "# END\n"); + fclose(f); return true; } - -struct Game_CFG* CFG_get_game_opt( const u8 *id ) +struct Game_CFG* CFG_get_game_opt(const u8 *id) { int i; - for ( i = 0; i < num_saved_games; i++ ) + for (i = 0; i < num_saved_games; i++) { - if ( memcmp( id, cfg_game[i].id, 6 ) == 0 ) + if (memcmp(id, cfg_game[i].id, 6) == 0) { return &cfg_game[i]; } @@ -1328,13 +1309,12 @@ struct Game_CFG* CFG_get_game_opt( const u8 *id ) return NULL; } - -struct Game_NUM* CFG_get_game_num( const u8 *id ) +struct Game_NUM* CFG_get_game_num(const u8 *id) { int i; - for ( i = 0; i < num_saved_game_num; i++ ) + for (i = 0; i < num_saved_game_num; i++) { - if ( memcmp( id, cfg_game_num[i].id, 6 ) == 0 ) + if (memcmp(id, cfg_game_num[i].id, 6) == 0) { return &cfg_game_num[i]; } @@ -1342,85 +1322,84 @@ struct Game_NUM* CFG_get_game_num( const u8 *id ) return NULL; } -bool CFG_save_game_opt( u8 *id ) +bool CFG_save_game_opt(u8 *id) { - struct Game_CFG *game = cfg_get_game( id ); - if ( !game ) return false; - cfg_set_game_opt( game, id ); + struct Game_CFG *game = cfg_get_game(id); + if (!game) return false; + cfg_set_game_opt(game, id); return cfg_save_games(); } -bool CFG_save_game_num( u8 *id ) +bool CFG_save_game_num(u8 *id) { - struct Game_NUM *game = cfg_get_game_num( id ); - if ( !game ) return false; - cfg_set_game_num( game, id ); + struct Game_NUM *game = cfg_get_game_num(id); + if (!game) return false; + cfg_set_game_num(game, id); return cfg_save_game_num(); } -bool CFG_forget_game_opt( u8 *id ) +bool CFG_forget_game_opt(u8 *id) { - struct Game_CFG *game = CFG_get_game_opt( id ); + struct Game_CFG *game = CFG_get_game_opt(id); int i; - if ( !game ) return true; + if (!game) return true; // move entries down num_saved_games--; - for ( i = game - cfg_game; i < num_saved_games; i++ ) + for (i = game - cfg_game; i < num_saved_games; i++) { - cfg_game[i] = cfg_game[i+1]; + cfg_game[i] = cfg_game[i + 1]; } - memset( &cfg_game[num_saved_games], 0, sizeof( struct Game_CFG ) ); + memset(&cfg_game[num_saved_games], 0, sizeof(struct Game_CFG)); return cfg_save_games(); } -bool CFG_forget_game_num( u8 *id ) +bool CFG_forget_game_num(u8 *id) { - struct Game_NUM *game = CFG_get_game_num( id ); + struct Game_NUM *game = CFG_get_game_num(id); int i; - if ( !game ) return true; + if (!game) return true; // move entries down num_saved_game_num--; - for ( i = game - cfg_game_num; i < num_saved_game_num; i++ ) + for (i = game - cfg_game_num; i < num_saved_game_num; i++) { - cfg_game[i] = cfg_game[i+1]; + cfg_game[i] = cfg_game[i + 1]; } - memset( &cfg_game[num_saved_game_num], 0, sizeof( struct Game_NUM ) ); + memset(&cfg_game[num_saved_game_num], 0, sizeof(struct Game_NUM)); return cfg_save_game_num(); } - -void CFG_LoadTheme( bool wide, const char * theme_path ) +void CFG_LoadTheme(bool wide, const char * theme_path) { char pathname[200]; - WideScreen = wide; + WideScreen = wide; CFG_DefaultTheme(); // set defaults non forced - WorkAroundIconSet = 0; WorkAroundBarOffset = 100; // set Workaroundstuff to defaults + WorkAroundIconSet = 0; + WorkAroundBarOffset = 100; // set Workaroundstuff to defaults CLEAR_wCOORD_FLAGS; - snprintf( pathname, sizeof( pathname ), "%sGXtheme.cfg", theme_path); - cfg_parsefile( pathname, &theme_set ); //finally set theme information + snprintf(pathname, sizeof(pathname), "%sGXtheme.cfg", theme_path); + cfg_parsefile(pathname, &theme_set); //finally set theme information - snprintf( pathname, sizeof( pathname ), "%s/config/GXGameSettings.cfg", bootDevice ); - cfg_parsefile( pathname, &parental_set ); + snprintf(pathname, sizeof(pathname), "%s/config/GXGameSettings.cfg", bootDevice); + cfg_parsefile(pathname, &parental_set); // load per-game settings cfg_load_games(); cfg_load_game_num(); } -void CFG_Cleanup( void ) +void CFG_Cleanup(void) { int i = 0; - for ( i = 0; i < num_title; i++ ) + for (i = 0; i < num_title; i++) { - if ( cfg_title[i].title ) - free( cfg_title[i].title ); + if (cfg_title[i].title) free(cfg_title[i].title); cfg_title[i].title = NULL; } - if ( cfg_title ) + if (cfg_title) { - free( cfg_title ); + free(cfg_title); cfg_title = NULL; } num_title = 0; diff --git a/source/settings/cfg.h b/source/settings/cfg.h index d0cd0c8d..429b95e6 100644 --- a/source/settings/cfg.h +++ b/source/settings/cfg.h @@ -46,140 +46,140 @@ extern "C" 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 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 THEME THEME; @@ -207,168 +207,136 @@ extern "C" extern char alternatedname[40]; extern u8 returnToLoaderGV; - 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 }; 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]; - u8 returnTo; + 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]; + u8 returnTo; }; struct Game_NUM { - u8 id[8]; - u8 favorite; - u16 count; + u8 id[8]; + u8 favorite; + u16 count; }; - void CFG_DefaultTheme(); // -1 = non forced mode - void CFG_LoadTheme( bool widescreen, const char * theme_path ); - struct Game_CFG* CFG_get_game_opt( const u8 *id ); - struct Game_NUM* CFG_get_game_num( const u8 *id ); - bool CFG_save_game_opt( u8 *id ); - bool CFG_save_game_num( u8 *id ); + void CFG_LoadTheme(bool widescreen, const char * theme_path); + struct Game_CFG* CFG_get_game_opt(const u8 *id); + struct Game_NUM* CFG_get_game_num(const 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 ); + bool CFG_forget_game_opt(u8 *id); + bool CFG_forget_game_num(u8 *id); - 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, settings_off_on_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 { - hr12 = 0, - hr24, - Off, - settings_clock_max // always the last entry + enum + { + hr12 = 0, hr24, Off, settings_clock_max + // always the last entry }; - enum { - ALL = 0, - PLAYCOUNT, + enum + { + ALL = 0, PLAYCOUNT, }; - 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 + { + 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 + { + us = 0, qwerty, dvorak, euro, azerty, settings_keyset_max + // always the last entry }; - enum { - list, - grid, - carousel, - settings_display_max + enum + { + list, grid, carousel, settings_display_max }; - enum { - scrollDefault, - scrollMarquee, - settings_scrolleffect_max // always the last entry + 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 + { + 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 + enum + { + not_install_to_dir, install_to_gameid_name, install_to_name_gameid, settings_installdir_max + // always the last entry }; - char *get_title( struct discHdr *header ); - char *cfg_get_title( u8 *id ) ; - void title_set( char *id, char *title ); + 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 ); + 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 ea0226db..5810bbe8 100644 --- a/source/settings/newtitles.cpp +++ b/source/settings/newtitles.cpp @@ -11,7 +11,7 @@ NewTitles *NewTitles::instance = NULL; NewTitles* NewTitles::Instance() { - if ( instance == NULL ) + if (instance == NULL) { instance = new NewTitles(); } @@ -20,7 +20,7 @@ NewTitles* NewTitles::Instance() void NewTitles::DestroyInstance() { - if ( instance != NULL ) + if (instance != NULL) { delete instance; instance = NULL; @@ -34,23 +34,23 @@ NewTitles::NewTitles() // Read the text file char path[255]; - strcpy( path, Settings.titlestxt_path ); - path[strlen( Settings.titlestxt_path ) - 1] = '/'; - strcat( path, GAMETITLES ); + 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 ) + FILE *fp = fopen(path, "r"); + if (fp != NULL) { - while ( fgets( line, sizeof( line ), fp ) ) + while (fgets(line, sizeof(line), fp)) { // This is one line - if ( line[0] != '#' || line[0] != ';' ) + if (line[0] != '#' || line[0] != ';') { Title *title = new Title(); - if ( sscanf( line, "%6c:%ld", ( u8 * ) &title->titleId, &title->timestamp ) == 2 ) + if (sscanf(line, "%6c:%ld", (u8 *) &title->titleId, &title->timestamp) == 2) { - if ( firstTitle == NULL ) + if (firstTitle == NULL) { firstTitle = title; lastTitle = title; @@ -68,7 +68,7 @@ NewTitles::NewTitles() } } - fclose( fp ); + fclose(fp); } else { @@ -81,43 +81,43 @@ NewTitles::~NewTitles() Save(); Title *t = firstTitle; - while ( t != NULL ) + while (t != NULL) { - Title *temp = ( Title * ) t->next; + Title *temp = (Title *) t->next; delete t; t = temp; } firstTitle = lastTitle = NULL; } -void NewTitles::CheckGame( u8 *titleid ) +void NewTitles::CheckGame(u8 *titleid) { - if ( titleid == NULL || strlen( ( char * ) titleid ) == 0 ) + if (titleid == NULL || strlen((char *) titleid) == 0) { return; } Title *t = firstTitle; - while ( t != NULL ) + while (t != NULL) { // Loop all titles, search for the correct titleid - if ( strcmp( ( const char * ) titleid, ( const char * ) t->titleId ) == 0 ) + if (strcmp((const char *) titleid, (const char *) t->titleId) == 0) { return; // Game found, which is excellent } - t = ( Title * ) t->next; + t = (Title *) t->next; } // Not found, add it t = new Title(); - strncpy( ( char * ) t->titleId, ( char * ) titleid, 6 ); - t->timestamp = time( NULL ); - if ( isNewFile ) + 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 + t->timestamp -= (NEW_SECONDS + 1); // Mark all games as not new if this is a new file } - if ( firstTitle == NULL ) + if (firstTitle == NULL) { firstTitle = t; lastTitle = t; @@ -130,48 +130,46 @@ void NewTitles::CheckGame( u8 *titleid ) isDirty = true; } -bool NewTitles::IsNew( u8 *titleid ) +bool NewTitles::IsNew(u8 *titleid) { - if ( titleid == NULL || strlen( ( char * ) titleid ) == 0 ) - return false; + if (titleid == NULL || strlen((char *) titleid) == 0) return false; Title *t = firstTitle; - while ( t != NULL ) + while (t != NULL) { // Loop all titles, search for the correct titleid - if ( strcmp( ( const char * ) titleid, ( const char * ) t->titleId ) == 0 ) + 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 ) + 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 ); + Game_NUM *gnum = CFG_get_game_num(titleid); return gnum == NULL || gnum->count == 0; } return false; } - t = ( Title * ) t->next; + t = (Title *) t->next; } // We should never get here, since all files should be added by now! - CheckGame( titleid ); + CheckGame(titleid); return !isNewFile; // If this is a new file, return false } -void NewTitles::Remove( u8 *titleid ) +void NewTitles::Remove(u8 *titleid) { - if ( titleid == NULL || strlen( ( char * ) titleid ) == 0 ) - return; + if (titleid == NULL || strlen((char *) titleid) == 0) return; Title *t = firstTitle, *prev = NULL; - while ( t != NULL ) + while (t != NULL) { - if ( strcmp( ( const char * ) titleid, ( const char * ) t->titleId ) == 0 ) + if (strcmp((const char *) titleid, (const char *) t->titleId) == 0) { - if ( prev == NULL ) + if (prev == NULL) { - firstTitle = ( Title * ) t->next; + firstTitle = (Title *) t->next; } else { @@ -183,28 +181,28 @@ void NewTitles::Remove( u8 *titleid ) return; } prev = t; - t = ( Title * ) t->next; + t = (Title *) t->next; } } void NewTitles::Save() { - if ( !isDirty ) return; + if (!isDirty) return; char path[255]; - strcpy( path, Settings.titlestxt_path ); - path[strlen( Settings.titlestxt_path ) - 1] = '/'; - strcat( path, GAMETITLES ); + strcpy(path, Settings.titlestxt_path); + path[strlen(Settings.titlestxt_path) - 1] = '/'; + strcat(path, GAMETITLES); - FILE *fp = fopen( path, "w" ); - if ( fp != NULL ) + FILE *fp = fopen(path, "w"); + if (fp != NULL) { Title *t = firstTitle; - while ( t != NULL && strlen( ( char * ) t->titleId ) > 0 ) + while (t != NULL && strlen((char *) t->titleId) > 0) { - fprintf( fp, "%s:%ld\n", t->titleId, t->timestamp ); - t = ( Title * ) t->next; + fprintf(fp, "%s:%ld\n", t->titleId, t->timestamp); + t = (Title *) t->next; } - fclose( fp ); + fclose(fp); } } diff --git a/source/settings/newtitles.h b/source/settings/newtitles.h index 0fc67db3..3cc0915a 100644 --- a/source/settings/newtitles.h +++ b/source/settings/newtitles.h @@ -10,9 +10,9 @@ class NewTitles static void DestroyInstance(); void Save(); - void CheckGame( u8 *titleid ); - bool IsNew( u8 *titleid ); - void Remove( u8 *titleid ); + void CheckGame(u8 *titleid); + bool IsNew(u8 *titleid); + void Remove(u8 *titleid); private: NewTitles(); ~NewTitles(); diff --git a/source/sys.cpp b/source/sys.cpp index 8d1cfe6d..8a183b21 100644 --- a/source/sys.cpp +++ b/source/sys.cpp @@ -14,11 +14,11 @@ extern char game_partition[6]; extern u8 load_from_fs; //Wiilight stuff -static vu32 *_wiilight_reg = ( u32* )0xCD0000C0; -void wiilight( int enable ) // Toggle wiilight (thanks Bool for wiilight source) +static vu32 *_wiilight_reg = (u32*) 0xCD0000C0; +void wiilight(int enable) // Toggle wiilight (thanks Bool for wiilight source) { - u32 val = ( *_wiilight_reg&~0x20 ); - if ( enable && Settings.wiilight ) val |= 0x20; + u32 val = (*_wiilight_reg & ~0x20); + if (enable && Settings.wiilight) val |= 0x20; *_wiilight_reg = val; } @@ -26,26 +26,26 @@ void wiilight( int enable ) // Toggle wiilight (thanks Bool for wiil u8 shutdown = 0; u8 reset = 0; -void __Sys_ResetCallback( void ) +void __Sys_ResetCallback(void) { /* Reboot console */ reset = 1; } -void __Sys_PowerCallback( void ) +void __Sys_PowerCallback(void) { /* Poweroff console */ shutdown = 1; } -void Sys_Init( void ) +void Sys_Init(void) { /* Initialize video subsytem */ //VIDEO_Init(); /* Set RESET/POWER button callback */ - SYS_SetResetCallback( __Sys_ResetCallback ); - SYS_SetPowerCallback( __Sys_PowerCallback ); + SYS_SetResetCallback(__Sys_ResetCallback); + SYS_SetPowerCallback(__Sys_PowerCallback); } static void _ExitApp() @@ -57,11 +57,11 @@ static void _ExitApp() UnmountNTFS(); SDCard_deInit(); USBDevice_deInit(); - mload_set_ES_ioctlv_vector( NULL ); + mload_set_ES_ioctlv_vector(NULL); mload_close(); } -void Sys_Reboot( void ) +void Sys_Reboot(void) { /* Restart console */ _ExitApp(); @@ -72,22 +72,22 @@ void Sys_Reboot( void ) #define ShutdownToIdle 1 #define ShutdownToStandby 2 -static void _Sys_Shutdown( int SHUTDOWN_MODE ) +static void _Sys_Shutdown(int SHUTDOWN_MODE) { _ExitApp(); - WPAD_Flush( 0 ); - WPAD_Disconnect( 0 ); + WPAD_Flush(0); + WPAD_Disconnect(0); WPAD_Shutdown(); /* Poweroff console */ - if ( ( CONF_GetShutdownMode() == CONF_SHUTDOWN_IDLE && SHUTDOWN_MODE != ShutdownToStandby ) || SHUTDOWN_MODE == ShutdownToIdle ) + if ((CONF_GetShutdownMode() == CONF_SHUTDOWN_IDLE && SHUTDOWN_MODE != ShutdownToStandby) || SHUTDOWN_MODE + == ShutdownToIdle) { s32 ret; /* Set LED mode */ ret = CONF_GetIdleLedMode(); - if ( ret >= 0 && ret <= 2 ) - STM_SetLedMode( ret ); + if (ret >= 0 && ret <= 2) STM_SetLedMode(ret); /* Shutdown to idle */ STM_ShutdownToIdle(); @@ -99,34 +99,34 @@ static void _Sys_Shutdown( int SHUTDOWN_MODE ) } } -void Sys_Shutdown( void ) +void Sys_Shutdown(void) { - _Sys_Shutdown( ShutdownToDefault ); + _Sys_Shutdown(ShutdownToDefault); } -void Sys_ShutdownToIdel( void ) +void Sys_ShutdownToIdel(void) { - _Sys_Shutdown( ShutdownToIdle ); + _Sys_Shutdown(ShutdownToIdle); } -void Sys_ShutdownToStandby( void ) +void Sys_ShutdownToStandby(void) { - _Sys_Shutdown( ShutdownToStandby ); + _Sys_Shutdown(ShutdownToStandby); } -void Sys_LoadMenu( void ) +void Sys_LoadMenu(void) { _ExitApp(); /* Return to the Wii system menu */ - SYS_ResetSystem( SYS_RETURNTOMENU, 0, 0 ); + SYS_ResetSystem(SYS_RETURNTOMENU, 0, 0); } -void Sys_BackToLoader( void ) +void Sys_BackToLoader(void) { - if ( hbcStubAvailable() ) + if (hbcStubAvailable()) { _ExitApp(); - exit( 0 ); + exit(0); } // Channel Version Sys_LoadMenu(); @@ -141,14 +141,14 @@ void ScreenShot() { time_t rawtime; struct tm * timeinfo; - char buffer [80]; - char buffer2 [80]; + char buffer[80]; + char buffer2[80]; - time ( &rawtime ); - timeinfo = localtime ( &rawtime ); + 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 ); + 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/sys.h b/source/sys.h index 3141c3ba..3afb6a9e 100644 --- a/source/sys.h +++ b/source/sys.h @@ -1,16 +1,16 @@ #ifndef _SYS_H_ #define _SYS_H_ -void wiilight( int enable ); +void wiilight(int enable); /* Prototypes */ -void Sys_Init( void ); -void Sys_Reboot( void ); -void Sys_Shutdown( void ); -void Sys_ShutdownToIdel( void ); -void Sys_ShutdownToStandby( void ); -void Sys_LoadMenu( void ); -void Sys_BackToLoader( void ); +void Sys_Init(void); +void Sys_Reboot(void); +void Sys_Shutdown(void); +void Sys_ShutdownToIdel(void); +void Sys_ShutdownToStandby(void); +void Sys_LoadMenu(void); +void Sys_BackToLoader(void); bool Sys_IsHermes(); void ScreenShot(); diff --git a/source/themes/Theme_Downloader.cpp b/source/themes/Theme_Downloader.cpp index e26feea1..57d5bec2 100644 --- a/source/themes/Theme_Downloader.cpp +++ b/source/themes/Theme_Downloader.cpp @@ -35,36 +35,34 @@ extern GuiImage * bgImg; extern u8 shutdown; extern u8 reset; - -int DownloadTheme( const char *url, const char *title ) +int DownloadTheme(const char *url, const char *title) { - if ( !url ) - return 0; + if (!url) return 0; char filename[255]; - memset( filename, 0, sizeof( filename ) ); + memset(filename, 0, sizeof(filename)); - int filesize = download_request( url, ( char * ) & filename ); + int filesize = download_request(url, (char *) &filename); - if ( filesize <= 0 ) + if (filesize <= 0) { - WindowPrompt( tr( "Download request failed." ), 0, tr( "OK" ) ); + WindowPrompt(tr( "Download request failed." ), 0, tr( "OK" )); return 0; } char path[300]; char filepath[300]; - snprintf( path, sizeof( path ), "%s%s", Settings.theme_downloadpath, title ); + snprintf(path, sizeof(path), "%s%s", Settings.theme_downloadpath, title); - subfoldercreate( path ); + subfoldercreate(path); - snprintf( filepath, sizeof( filepath ), "%s/%s", path, filename ); + snprintf(filepath, sizeof(filepath), "%s/%s", path, filename); - FILE *file = fopen( filepath, "wb" ); - if ( !file ) + FILE *file = fopen(filepath, "wb"); + if (!file) { - WindowPrompt( tr( "Download failed." ), tr( "Can't create file" ), tr( "OK" ) ); + WindowPrompt(tr( "Download failed." ), tr( "Can't create file" ), tr( "OK" )); return 0; } @@ -74,214 +72,210 @@ int DownloadTheme( const char *url, const char *title ) u8 *buffer = new u8[blocksize]; - while ( done < ( u32 ) filesize ) + while (done < (u32) filesize) { - if ( ( u32 ) blocksize > filesize - done ) - blocksize = filesize - done; + if ((u32) blocksize > filesize - done) blocksize = filesize - done; - ShowProgress( tr( "Downloading file" ), 0, ( char* ) filename, done, filesize, true ); + ShowProgress(tr( "Downloading file" ), 0, (char*) filename, done, filesize, true); - int ret = network_read( buffer, blocksize ); - if ( ret < 0 ) + int ret = network_read(buffer, blocksize); + if (ret < 0) { - free( buffer ); - fclose( file ); - remove( path ); + free(buffer); + fclose(file); + remove(path); ProgressStop(); - WindowPrompt( tr( "Download failed." ), tr( "Transfer failed." ), tr( "OK" ) ); + WindowPrompt(tr( "Download failed." ), tr( "Transfer failed." ), tr( "OK" )); return 0; } - else if ( ret == 0 ) - break; + else if (ret == 0) break; - fwrite( buffer, 1, blocksize, file ); + fwrite(buffer, 1, blocksize, file); done += ret; } - delete [] buffer; - fclose( file ); + delete[] buffer; + fclose(file); ProgressStop(); - if ( done != ( u32 ) filesize ) + if (done != (u32) filesize) { - remove( filepath ); - WindowPrompt( tr( "Download failed." ), tr( "Connection lost..." ), tr( "OK" ) ); + remove(filepath); + WindowPrompt(tr( "Download failed." ), tr( "Connection lost..." ), tr( "OK" )); return 0; } - ZipFile zipfile( filepath ); + ZipFile zipfile(filepath); - int result = zipfile.ExtractAll( path ); - if ( result ) + int result = zipfile.ExtractAll(path); + 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 ) + remove(filepath); + int choice = WindowPrompt(tr( "Successfully extracted theme." ), tr( "Do you want to apply it now?" ), + tr( "Yes" ), tr( "No" )); + if (choice) { char real_themepath[1024]; - sprintf( real_themepath, "%s", Settings.theme_path ); - if ( SearchFile( path, "GXtheme.cfg", real_themepath ) == true ) + sprintf(real_themepath, "%s", Settings.theme_path); + if (SearchFile(path, "GXtheme.cfg", real_themepath) == true) { - char *ptr = strrchr( real_themepath, '/' ); - if ( ptr ) + char *ptr = strrchr(real_themepath, '/'); + if (ptr) { ptr++; ptr[0] = '\0'; } - snprintf( Settings.theme_path, sizeof( Settings.theme_path ), "%s", real_themepath ); + snprintf(Settings.theme_path, sizeof(Settings.theme_path), "%s", real_themepath); Settings.Save(); Settings.Load(); result = 2; } - else - WindowPrompt( tr( "ERROR: Can't set up theme." ), tr( "GXtheme.cfg not found in any subfolder." ), tr( "OK" ) ); + else WindowPrompt(tr( "ERROR: Can't set up theme." ), tr( "GXtheme.cfg not found in any subfolder." ), + tr( "OK" )); } } - else - WindowPrompt( tr( "Failed to extract." ), tr( "Unsupported format, try to extract manually." ), tr( "OK" ) ); + 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 ); + 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 ); + 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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%stheme_dialogue_box.png", Settings.theme_path ); - GuiImageData dialogBox( imgPath, theme_dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%stheme_dialogue_box.png", Settings.theme_path); + GuiImageData dialogBox(imgPath, theme_dialogue_box_png); - GuiImage dialogBoxImg( &dialogBox ); + GuiImage dialogBoxImg(&dialogBox); - GuiWindow promptWindow( dialogBox.GetWidth(), dialogBox.GetHeight() ); - promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - promptWindow.SetPosition( 0, -10 ); + GuiWindow promptWindow(dialogBox.GetWidth(), dialogBox.GetHeight()); + promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + promptWindow.SetPosition(0, -10); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - GuiText titleTxt( tr( "Theme Title:" ), 18, THEME.prompttext ); - titleTxt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - titleTxt.SetPosition( 230, 30 ); + GuiText titleTxt(tr( "Theme Title:" ), 18, THEME.prompttext); + titleTxt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + titleTxt.SetPosition(230, 30); - GuiText titleTxt2( title, 18, THEME.prompttext ); - titleTxt2.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - titleTxt2.SetPosition( 230, 50 ); - titleTxt2.SetMaxWidth( dialogBox.GetWidth() - 220, WRAP ); + GuiText titleTxt2(title, 18, THEME.prompttext); + titleTxt2.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + titleTxt2.SetPosition(230, 50); + titleTxt2.SetMaxWidth(dialogBox.GetWidth() - 220, WRAP); - GuiText authorTxt( tr( "Author:" ), 18, THEME.prompttext ); - authorTxt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - authorTxt.SetPosition( 230, 100 ); + GuiText authorTxt(tr( "Author:" ), 18, THEME.prompttext); + authorTxt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + authorTxt.SetPosition(230, 100); - GuiText authorTxt2( author, 18, THEME.prompttext ); - authorTxt2.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - authorTxt2.SetPosition( 230, 120 ); - authorTxt2.SetMaxWidth( dialogBox.GetWidth() - 220, DOTTED ); + GuiText authorTxt2(author, 18, THEME.prompttext); + authorTxt2.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + authorTxt2.SetPosition(230, 120); + authorTxt2.SetMaxWidth(dialogBox.GetWidth() - 220, DOTTED); - GuiText downloadBtnTxt( tr( "Download" ) , 22, THEME.prompttext ); - downloadBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); - GuiImage downloadBtnImg( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText downloadBtnTxt(tr( "Download" ), 22, THEME.prompttext); + downloadBtnTxt.SetMaxWidth(btnOutline.GetWidth() - 30); + GuiImage downloadBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - downloadBtnTxt.SetWidescreen( Settings.widescreen ); - downloadBtnImg.SetWidescreen( Settings.widescreen ); + downloadBtnTxt.SetWidescreen(Settings.widescreen); + downloadBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton downloadBtn( &downloadBtnImg, &downloadBtnImg, ALIGN_RIGHT, ALIGN_TOP, -5, 170, &trigA, &btnSoundOver, btnClick2, 1 ); - downloadBtn.SetLabel( &downloadBtnTxt ); - downloadBtn.SetScale( 0.9 ); + GuiButton downloadBtn(&downloadBtnImg, &downloadBtnImg, ALIGN_RIGHT, ALIGN_TOP, -5, 170, &trigA, &btnSoundOver, + btnClick2, 1); + downloadBtn.SetLabel(&downloadBtnTxt); + downloadBtn.SetScale(0.9); - GuiText backBtnTxt( tr( "Back" ) , 22, THEME.prompttext ); - backBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); - GuiImage backBtnImg( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText backBtnTxt(tr( "Back" ), 22, THEME.prompttext); + backBtnTxt.SetMaxWidth(btnOutline.GetWidth() - 30); + GuiImage backBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - backBtnTxt.SetWidescreen( Settings.widescreen ); - backBtnImg.SetWidescreen( Settings.widescreen ); + backBtnTxt.SetWidescreen(Settings.widescreen); + backBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton backBtn( &backBtnImg, &backBtnImg, ALIGN_RIGHT, ALIGN_TOP, -5, 220, &trigA, &btnSoundOver, btnClick2, 1 ); - backBtn.SetLabel( &backBtnTxt ); - backBtn.SetTrigger( &trigB ); - backBtn.SetScale( 0.9 ); + GuiButton backBtn(&backBtnImg, &backBtnImg, ALIGN_RIGHT, ALIGN_TOP, -5, 220, &trigA, &btnSoundOver, btnClick2, 1); + backBtn.SetLabel(&backBtnTxt); + backBtn.SetTrigger(&trigB); + backBtn.SetScale(0.9); - GuiImage ThemeImage( thumbimageData ); - ThemeImage.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - ThemeImage.SetPosition( 20, 10 ); - ThemeImage.SetScale( 0.8 ); + GuiImage ThemeImage(thumbimageData); + ThemeImage.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + ThemeImage.SetPosition(20, 10); + ThemeImage.SetScale(0.8); - ThemeImage.SetScale( 0.8 ); + ThemeImage.SetScale(0.8); - promptWindow.Append( &dialogBoxImg ); - promptWindow.Append( &ThemeImage ); - promptWindow.Append( &titleTxt ); - promptWindow.Append( &titleTxt2 ); - promptWindow.Append( &authorTxt ); - promptWindow.Append( &authorTxt2 ); - promptWindow.Append( &downloadBtn ); - promptWindow.Append( &backBtn ); + promptWindow.Append(&dialogBoxImg); + promptWindow.Append(&ThemeImage); + promptWindow.Append(&titleTxt); + promptWindow.Append(&titleTxt2); + promptWindow.Append(&authorTxt); + promptWindow.Append(&authorTxt2); + promptWindow.Append(&downloadBtn); + promptWindow.Append(&backBtn); HaltGui(); - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50 ); - mainWindow->SetState( STATE_DISABLED ); - mainWindow->Append( &promptWindow ); - mainWindow->ChangeFocus( &promptWindow ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); ResumeGui(); - while ( !leave ) + while (!leave) { VIDEO_WaitVSync(); - if ( shutdown == 1 ) + if (shutdown == 1) Sys_Shutdown(); - else if ( reset == 1 ) - Sys_Reboot(); + 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 ) + int choice = WindowPrompt(tr( "Do you want to download this theme?" ), title, tr( "Yes" ), tr( "Cancel" )); + if (choice) { - result = DownloadTheme( downloadlink, title ); - if ( result == 2 ) - leave = true; + result = DownloadTheme(downloadlink, title); + if (result == 2) leave = true; } - mainWindow->SetState( STATE_DISABLED ); - promptWindow.SetState( STATE_DEFAULT ); - mainWindow->ChangeFocus( &promptWindow ); + mainWindow->SetState(STATE_DISABLED); + promptWindow.SetState(STATE_DEFAULT); + mainWindow->ChangeFocus(&promptWindow); downloadBtn.ResetState(); } - else if ( backBtn.GetState() == STATE_CLICKED ) + else if (backBtn.GetState() == STATE_CLICKED) { leave = true; backBtn.ResetState(); } } - promptWindow.SetEffect( EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50 ); - while ( promptWindow.GetEffect() > 0 ) usleep( 50 ); + promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); + while (promptWindow.GetEffect() > 0) + usleep(50); HaltGui(); - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); return result; } - int Theme_Downloader() { int pagesize = 4; @@ -289,61 +283,62 @@ int Theme_Downloader() bool listchanged = false; char THEME_LINK[70]; - sprintf( THEME_LINK, "http://wii.spiffy360.com/themes.php?xml=1&category=1&adult=%d", Settings.godmode ); + sprintf(THEME_LINK, "http://wii.spiffy360.com/themes.php?xml=1&category=1&adult=%d", Settings.godmode); //gprintf("\nTHEME_LINK: %s", THEME_LINK); //const char THEME_LINK_ADULT[70] = "http://wii.spiffy360.com/themes.php?xml=1&category=1&adult=1"; /*** Sound Variables ***/ - GuiSound btnSoundOver( button_over_pcm, button_over_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 ); + 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 btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); /*** Image Variables ***/ char imgPath[150]; - snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf( imgPath, sizeof( imgPath ), "%stheme_box.png", Settings.theme_path ); - GuiImageData theme_box_Data( imgPath, theme_box_png ); + snprintf(imgPath, sizeof(imgPath), "%stheme_box.png", Settings.theme_path); + GuiImageData theme_box_Data(imgPath, theme_box_png); - snprintf( imgPath, sizeof( imgPath ), "%ssettings_background.png", Settings.theme_path ); - GuiImageData bgData( imgPath, settings_background_png ); + snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", Settings.theme_path); + GuiImageData bgData(imgPath, settings_background_png); - snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_left.png", Settings.theme_path ); - GuiImageData arrow_left( imgPath, startgame_arrow_left_png ); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", Settings.theme_path); + GuiImageData arrow_left(imgPath, startgame_arrow_left_png); - snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_right.png", Settings.theme_path ); - GuiImageData arrow_right( imgPath, startgame_arrow_right_png ); + snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", Settings.theme_path); + GuiImageData arrow_right(imgPath, startgame_arrow_right_png); - snprintf( imgPath, sizeof( imgPath ), "%sWifi_btn.png", Settings.theme_path ); - GuiImageData wifiImgData( imgPath, Wifi_btn_png ); + snprintf(imgPath, sizeof(imgPath), "%sWifi_btn.png", Settings.theme_path); + GuiImageData wifiImgData(imgPath, Wifi_btn_png); - snprintf( imgPath, sizeof( imgPath ), "%spageindicator.png", Settings.theme_path ); - GuiImageData PageindicatorImgData( imgPath, pageindicator_png ); + snprintf(imgPath, sizeof(imgPath), "%spageindicator.png", Settings.theme_path); + GuiImageData PageindicatorImgData(imgPath, pageindicator_png); - GuiImage background( &bgData ); + GuiImage background(&bgData); /*** Trigger Variables ***/ GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + 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 ); + 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 ); + 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 ); + 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 ); + 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 ); + trigMinus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0); GuiTrigger trigPlus; - trigPlus.SetButtonOnlyTrigger( -1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0 ); + trigPlus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0); - GuiText titleTxt( tr( "Theme Downloader" ), 28, ( GXColor ) {0, 0, 0, 255} ); - titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - titleTxt.SetPosition( 0, 40 ); + GuiText titleTxt(tr( "Theme Downloader" ), 28, ( GXColor ) + { 0, 0, 0, 255}); + titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + titleTxt.SetPosition(0, 40); GuiImageData *ImageData[pagesize]; GuiImage *Image[pagesize]; @@ -354,101 +349,101 @@ 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; - theme_box_img[i] = new GuiImage( &theme_box_Data ); + theme_box_img[i] = new GuiImage(&theme_box_Data); - MainButton[i] = new GuiButton( theme_box_Data.GetWidth(), theme_box_Data.GetHeight() ); - MainButton[i]->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - MainButton[i]->SetSoundOver( &btnSoundOver ); - MainButton[i]->SetSoundClick( &btnClick1 ); - MainButton[i]->SetImage( theme_box_img[i] ); + MainButton[i] = new GuiButton(theme_box_Data.GetWidth(), theme_box_Data.GetHeight()); + MainButton[i]->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + MainButton[i]->SetSoundOver(&btnSoundOver); + MainButton[i]->SetSoundClick(&btnClick1); + MainButton[i]->SetImage(theme_box_img[i]); MainButton[i]->SetEffectGrow(); - MainButton[i]->SetTrigger( &trigA ); + MainButton[i]->SetTrigger(&trigA); } /*** 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 ) + GuiText backBtnTxt(tr( "Back" ), 22, THEME.prompttext); + backBtnTxt.SetMaxWidth(btnOutline.GetWidth() - 30); + GuiImage backBtnImg(&btnOutline); + if (Settings.wsprompt == yes) { - backBtnTxt.SetWidescreen( Settings.widescreen ); - backBtnImg.SetWidescreen( Settings.widescreen ); + backBtnTxt.SetWidescreen(Settings.widescreen); + backBtnImg.SetWidescreen(Settings.widescreen); } - GuiButton backBtn( &backBtnImg, &backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2, 1 ); - backBtn.SetLabel( &backBtnTxt ); - backBtn.SetTrigger( &trigB ); + GuiButton backBtn(&backBtnImg, &backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2, 1); + backBtn.SetLabel(&backBtnTxt); + backBtn.SetTrigger(&trigB); - GuiButton HomeBtn( 1, 1 ); - HomeBtn.SetTrigger( &trigHome ); + GuiButton HomeBtn(1, 1); + HomeBtn.SetTrigger(&trigHome); - 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 ); + 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 ); + 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 ); + 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 ); + GoRightBtn.SetTrigger(&trigA); + GoRightBtn.SetTrigger(&trigR); + GoRightBtn.SetTrigger(&trigPlus); - GuiImage PageindicatorImg( &PageindicatorImgData ); - GuiText PageindicatorTxt( ( char * ) NULL, 22, ( GXColor ) { 0, 0, 0, 255} ); - GuiButton PageIndicatorBtn( PageindicatorImg.GetWidth(), PageindicatorImg.GetHeight() ); - PageIndicatorBtn.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); - PageIndicatorBtn.SetPosition( 110, 400 ); - PageIndicatorBtn.SetImage( &PageindicatorImg ); - PageIndicatorBtn.SetLabel( &PageindicatorTxt ); - PageIndicatorBtn.SetSoundOver( &btnSoundOver ); - PageIndicatorBtn.SetSoundClick( &btnClick1 ); - PageIndicatorBtn.SetTrigger( &trigA ); + GuiImage PageindicatorImg(&PageindicatorImgData); + GuiText PageindicatorTxt((char *) NULL, 22, ( GXColor ) + { 0, 0, 0, 255}); + GuiButton PageIndicatorBtn(PageindicatorImg.GetWidth(), PageindicatorImg.GetHeight()); + PageIndicatorBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + PageIndicatorBtn.SetPosition(110, 400); + PageIndicatorBtn.SetImage(&PageindicatorImg); + PageIndicatorBtn.SetLabel(&PageindicatorTxt); + PageIndicatorBtn.SetSoundOver(&btnSoundOver); + PageIndicatorBtn.SetSoundClick(&btnClick1); + PageIndicatorBtn.SetTrigger(&trigA); PageIndicatorBtn.SetEffectGrow(); - GuiImage wifiImg( &wifiImgData ); - if ( Settings.wsprompt == yes ) + GuiImage wifiImg(&wifiImgData); + if (Settings.wsprompt == yes) { - wifiImg.SetWidescreen( Settings.widescreen ); + wifiImg.SetWidescreen(Settings.widescreen); } - GuiButton wifiBtn( wifiImg.GetWidth(), wifiImg.GetHeight() ); - wifiBtn.SetImage( &wifiImg ); - wifiBtn.SetPosition( 500, 400 ); - wifiBtn.SetSoundOver( &btnSoundOver ); - wifiBtn.SetSoundClick( &btnClick1 ); + GuiButton wifiBtn(wifiImg.GetWidth(), wifiImg.GetHeight()); + wifiBtn.SetImage(&wifiImg); + wifiBtn.SetPosition(500, 400); + wifiBtn.SetSoundOver(&btnSoundOver); + wifiBtn.SetSoundClick(&btnClick1); wifiBtn.SetEffectGrow(); - wifiBtn.SetTrigger( &trigA ); + wifiBtn.SetTrigger(&trigA); - GuiWindow w( screenwidth, screenheight ); + GuiWindow w(screenwidth, screenheight); HaltGui(); - w.Append( &background ); - mainWindow->Append( &w ); + w.Append(&background); + mainWindow->Append(&w); ResumeGui(); - if ( !IsNetworkInit() ) - NetworkInitPrompt(); + if (!IsNetworkInit()) NetworkInitPrompt(); char url[300]; int currentpage = 1; @@ -456,108 +451,107 @@ int Theme_Downloader() HaltGui(); w.RemoveAll(); - w.Append( &background ); - w.Append( &titleTxt ); - w.Append( &backBtn ); - w.Append( &GoLeftBtn ); - w.Append( &GoRightBtn ); - w.Append( &PageIndicatorBtn ); - w.Append( &wifiBtn ); - w.Append( &HomeBtn ); + w.Append(&background); + w.Append(&titleTxt); + w.Append(&backBtn); + w.Append(&GoLeftBtn); + w.Append(&GoRightBtn); + w.Append(&PageIndicatorBtn); + w.Append(&wifiBtn); + w.Append(&HomeBtn); ResumeGui(); - ShowProgress( tr( "Downloading Page List:" ), "", ( char * ) tr( "Please wait..." ), 0, pagesize ); + ShowProgress(tr( "Downloading Page List:" ), "", (char *) tr( "Please wait..." ), 0, pagesize); - Theme = new Theme_List( THEME_LINK ); + Theme = new Theme_List(THEME_LINK); int ThemesOnPage = Theme->GetThemeCount(); - if ( !ThemesOnPage ) + if (!ThemesOnPage) { - WindowPrompt( tr( "No themes found on the site." ), 0, "OK" ); + 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 ); - w.Append( &titleTxt ); - w.Append( &backBtn ); - w.Append( &GoLeftBtn ); - w.Append( &GoRightBtn ); - w.Append( &PageIndicatorBtn ); - w.Append( &wifiBtn ); - w.Append( &HomeBtn ); + w.Append(&background); + w.Append(&titleTxt); + w.Append(&backBtn); + w.Append(&GoLeftBtn); + w.Append(&GoRightBtn); + w.Append(&PageIndicatorBtn); + w.Append(&wifiBtn); + w.Append(&HomeBtn); ResumeGui(); - sprintf( url, "%i", currentpage ); - PageindicatorTxt.SetText( url ); + sprintf(url, "%i", currentpage); + PageindicatorTxt.SetText(url); 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 ); + ShowProgress(tr( "Downloading image:" ), 0, (char *) Theme->GetThemeTitle(i), n, pagesize); - if ( MainButtonTxt[n] ) - delete MainButtonTxt[n]; - if ( ImageData[n] ) - delete ImageData[n]; - if ( Image[n] ) - delete Image[n]; + if (MainButtonTxt[n]) delete MainButtonTxt[n]; + if (ImageData[n]) delete ImageData[n]; + if (Image[n]) delete Image[n]; MainButtonTxt[n] = NULL; ImageData[n] = NULL; Image[n] = NULL; - if ( i < ThemesOnPage ) + 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, DOTTED ); + 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, DOTTED); - sprintf( url, "%s", Theme->GetImageLink( i ) ); + sprintf(url, "%s", Theme->GetImageLink(i)); char filepath[300]; - snprintf( filepath, sizeof( filepath ), "%s/tmp/%s.jpg", Settings.theme_downloadpath, Theme->GetThemeTitle( i ) ); + snprintf(filepath, sizeof(filepath), "%s/tmp/%s.jpg", Settings.theme_downloadpath, + Theme->GetThemeTitle(i)); - FILE * storefile = fopen( filepath, "rb" ); + FILE * storefile = fopen(filepath, "rb"); - if ( !storefile ) + if (!storefile) { - struct block file = downloadfile( url ); + struct block file = downloadfile(url); char storepath[300]; - snprintf( storepath, sizeof( storepath ), "%s/tmp/", Settings.theme_downloadpath ); - subfoldercreate( storepath ); - if ( file.data ) + snprintf(storepath, sizeof(storepath), "%s/tmp/", Settings.theme_downloadpath); + subfoldercreate(storepath); + if (file.data) { - storefile = fopen( filepath, "wb" ); - fwrite( file.data, 1, file.size, storefile ); - fclose( storefile ); + storefile = fopen(filepath, "wb"); + fwrite(file.data, 1, file.size, storefile); + fclose(storefile); } - ImageData[n] = new GuiImageData( file.data, file.size ); - free( file.data ); + ImageData[n] = new GuiImageData(file.data, file.size); + free(file.data); } else { - fseek( storefile, 0, SEEK_END ); - u32 filesize = ftell( storefile ); - u8 *buffer = ( u8* ) malloc( filesize ); - rewind( storefile ); - fread( buffer, 1, filesize, storefile ); - fclose( storefile ); - ImageData[n] = new GuiImageData( buffer, filesize ); - free( buffer ); + fseek(storefile, 0, SEEK_END); + u32 filesize = ftell(storefile); + u8 *buffer = (u8*) malloc(filesize); + rewind(storefile); + fread(buffer, 1, filesize, storefile); + fclose(storefile); + ImageData[n] = new GuiImageData(buffer, filesize); + free(buffer); buffer = NULL; } - Image[n] = new GuiImage( ImageData[n] ); - Image[n]->SetScale( 0.4 ); - Image[n]->SetPosition( 50, -45 ); - MainButton[n]->SetIcon( Image[n] ); - MainButton[n]->SetLabel( MainButtonTxt[n] ); + Image[n] = new GuiImage(ImageData[n]); + Image[n]->SetScale(0.4); + Image[n]->SetPosition(50, -45); + MainButton[n]->SetIcon(Image[n]); + MainButton[n]->SetLabel(MainButtonTxt[n]); } n++; } @@ -565,69 +559,69 @@ int Theme_Downloader() ProgressStop(); HaltGui(); - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { - if ( MainButtonTxt[i] ) - w.Append( MainButton[i] ); + if (MainButtonTxt[i]) w.Append(MainButton[i]); } ResumeGui(); listchanged = false; - while ( !listchanged ) + while (!listchanged) { - VIDEO_WaitVSync (); + VIDEO_WaitVSync(); - if ( shutdown == 1 ) + if (shutdown == 1) Sys_Shutdown(); - else if ( reset == 1 ) + 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 ); + currentpage = roundup((ThemesOnPage + 1.0f) / pagesize); currenttheme = currentpage * pagesize - pagesize; } GoLeftBtn.ResetState(); } - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { - if ( MainButton[i]->GetState() == STATE_CLICKED ) + 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 ); + 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; @@ -637,29 +631,24 @@ int Theme_Downloader() } } - w.SetEffect( EFFECT_FADE, -20 ); + w.SetEffect(EFFECT_FADE, -20); - while ( w.GetEffect() > 0 ) usleep( 100 ); + while (w.GetEffect() > 0) + usleep(100); HaltGui(); - mainWindow->Remove( &w ); + mainWindow->Remove(&w); - for ( int i = 0; i < pagesize; i++ ) + for (int i = 0; i < pagesize; i++) { - if ( MainButton[i] ) - delete MainButton[i]; - if ( theme_box_img[i] ) - delete theme_box_img[i]; - if ( ImageData[i] ) - delete ImageData[i]; - if ( Image[i] ) - delete Image[i]; - if ( MainButtonTxt[i] ) - delete MainButtonTxt[i]; + if (MainButton[i]) delete MainButton[i]; + if (theme_box_img[i]) delete theme_box_img[i]; + if (ImageData[i]) delete ImageData[i]; + if (Image[i]) delete Image[i]; + if (MainButtonTxt[i]) delete MainButtonTxt[i]; } - if ( Theme ) - delete Theme; + if (Theme) delete Theme; Theme = NULL; ResumeGui(); diff --git a/source/themes/Theme_List.cpp b/source/themes/Theme_List.cpp index 7a7bc980..d306f6e3 100644 --- a/source/themes/Theme_List.cpp +++ b/source/themes/Theme_List.cpp @@ -35,13 +35,13 @@ #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 ); + 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++; @@ -50,140 +50,138 @@ static void copyhtmlsting( const char *from, char *outtext, const char *stopat, 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 ); + 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 ); + free(file.data); return; } - ParseXML( file.data ); + ParseXML(file.data); - free( file.data ); + free(file.data); } Theme_List::~Theme_List() { - for ( int i = 0; i < themescount; i++ ) + for (int i = 0; i < themescount; i++) { - if ( Theme[i].themetitle ) - delete [] Theme[i].themetitle; - if ( Theme[i].author ) - delete [] Theme[i].author; - if ( Theme[i].imagelink ) - delete [] Theme[i].imagelink; - if ( Theme[i].downloadlink ) - delete [] Theme[i].downloadlink; + if (Theme[i].themetitle) delete[] Theme[i].themetitle; + if (Theme[i].author) delete[] Theme[i].author; + if (Theme[i].imagelink) delete[] Theme[i].imagelink; + if (Theme[i].downloadlink) delete[] Theme[i].downloadlink; Theme[i].themetitle = NULL; Theme[i].author = NULL; Theme[i].imagelink = NULL; Theme[i].downloadlink = NULL; } - if ( Theme ) - delete [] Theme; + if (Theme) delete[] Theme; Theme = NULL; } - -int Theme_List::CountThemes( const u8 * xmlfile ) +int Theme_List::CountThemes(const u8 * xmlfile) { char tmp[200]; u32 cnt = 0; - u32 stringlength = strlen( ( const char * ) xmlfile ); - memset( tmp, 0, sizeof( tmp ) ); + u32 stringlength = strlen((const char *) xmlfile); + memset(tmp, 0, sizeof(tmp)); - while ( cnt < stringlength ) + while (cnt < stringlength) { - if ( stringcompare( xmlfile, "", cnt ) == 0 ) + if (stringcompare( xmlfile, "", cnt ) == 0) { - copyhtmlsting( ( const char * ) xmlfile, tmp, ">", cnt ); + copyhtmlsting((const char *) xmlfile, tmp, ">", cnt); break; } cnt++; } - tmp[cnt+1] = 0; + tmp[cnt + 1] = 0; - return atoi( tmp ); + return atoi(tmp); } -bool Theme_List::ParseXML( const u8 * xmlfile ) +bool Theme_List::ParseXML(const u8 * xmlfile) { char element_text[1024]; - memset( element_text, 0, sizeof( element_text ) ); + 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 ) + nodedata = mxmlFindElement(nodetree, nodetree, "themes", NULL, NULL, MXML_DESCEND); + if (nodedata == NULL) { return false; } - nodeindex = mxmlIndexNew( nodedata, "name", NULL ); - nodeid = mxmlIndexReset( nodeindex ); + nodeindex = mxmlIndexNew(nodedata, "name", NULL); + nodeid = mxmlIndexReset(nodeindex); Theme = new Theme_Info[themescount]; - memset( Theme, 0, sizeof( Theme ) ); + memset(Theme, 0, sizeof(Theme)); - for ( int i = 0; i < themescount; i++ ) + for (int i = 0; i < themescount; i++) { - nodeid = mxmlIndexFind( nodeindex, "name", NULL ); - if ( nodeid != NULL ) + 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 ); + 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 ) ); - Theme[i].author = new char[strlen( element_text )+2]; - snprintf( Theme[i].author, strlen( element_text ) + 1, "%s", 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 ) ); - Theme[i].imagelink = new char[strlen( element_text )+2]; - snprintf( Theme[i].imagelink, strlen( element_text ) + 1, "%s", 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 ) ); - Theme[i].downloadlink = new char[strlen( element_text )+2]; - snprintf( Theme[i].downloadlink, strlen( element_text ) + 1, "%s", 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 ) ); - Theme[i].rating = atoi( 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 ); + mxmlIndexDelete(nodeindex); + free(nodetree); + free(nodedata); + free(nodeid); nodetree = NULL; nodedata = NULL; nodeid = NULL; @@ -192,36 +190,32 @@ bool Theme_List::ParseXML( const u8 * xmlfile ) return true; } -const char * Theme_List::GetThemeTitle( int ind ) +const char * Theme_List::GetThemeTitle(int ind) { - if ( ind > themescount || ind < 0 || !Theme || themescount <= 0 ) + if (ind > themescount || ind < 0 || !Theme || themescount <= 0) return NULL; - else - return Theme[ind].themetitle; + 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 ) + if (ind > themescount || ind < 0 || !Theme || themescount <= 0) return NULL; - else - return Theme[ind].author; + 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 ) + if (ind > themescount || ind < 0 || !Theme || themescount <= 0) return NULL; - else - return Theme[ind].imagelink; + 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 ) + if (ind > themescount || ind < 0 || !Theme || themescount <= 0) return NULL; - else - return Theme[ind].downloadlink; + else return Theme[ind].downloadlink; } int Theme_List::GetThemeCount() @@ -229,14 +223,14 @@ 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; + Theme_Info *ab = (Theme_Info*) a; + Theme_Info *bb = (Theme_Info*) b; - return stricmp( ( char * ) ab->themetitle, ( char * ) bb->themetitle ); + return stricmp((char *) ab->themetitle, (char *) bb->themetitle); } void Theme_List::SortList() { - qsort( Theme, themescount, sizeof( Theme_Info ), ListCompare ); + qsort(Theme, themescount, sizeof(Theme_Info), ListCompare); } diff --git a/source/themes/Theme_List.h b/source/themes/Theme_List.h index a72ab743..84ebe62b 100644 --- a/source/themes/Theme_List.h +++ b/source/themes/Theme_List.h @@ -11,38 +11,37 @@ typedef struct _theme_info { - char *themetitle; - char *author; - char *imagelink; - char *downloadlink; - u8 rating; + char *themetitle; + char *author; + char *imagelink; + char *downloadlink; + u8 rating; } Theme_Info; - class Theme_List { public: //!Constructor //!\param url from where to get the list of links - Theme_List( const char *url ); + Theme_List(const char *url); //!Destructor ~Theme_List(); //!Get Themes into a struct from the XML file amount - bool ParseXML( const u8 * xmlfile ); + bool ParseXML(const u8 * xmlfile); //!Get Theme amount - int CountThemes( const u8 * xmlfile ); + int CountThemes(const u8 * xmlfile); //! Get the a theme title //!\param list index - const char * GetThemeTitle( int index ); + const char * GetThemeTitle(int index); //! Get the author of the theme //!\param list index - const char * GetThemeAuthor( int index ); + const char * GetThemeAuthor(int index); //! Get the author of the theme //!\param list index - const char * GetImageLink( int index ); + const char * GetImageLink(int index); //! Get the download link of the theme //!\param list index - const char * GetDownloadLink( int index ); + const char * GetDownloadLink(int index); //! Get the number of links counted int GetThemeCount(); //! Sort list diff --git a/source/unzip/crypt.h b/source/unzip/crypt.h index bc90b714..e80f3b9b 100644 --- a/source/unzip/crypt.h +++ b/source/unzip/crypt.h @@ -1,75 +1,74 @@ /* crypt.h -- base code for crypt/uncrypt ZIPfile - Version 1.01e, February 12th, 2005 + Version 1.01e, February 12th, 2005 - Copyright (C) 1998-2005 Gilles Vollant + Copyright (C) 1998-2005 Gilles Vollant - This code is a modified version of crypting code in Infozip distribution + This code is a modified version of crypting code in Infozip distribution - The encryption/decryption parts of this source code (as opposed to the - non-echoing password parts) were originally written in Europe. The - whole source package can be freely distributed, including from the USA. - (Prior to January 2000, re-export from the US was a violation of US law.) + The encryption/decryption parts of this source code (as opposed to the + non-echoing password parts) were originally written in Europe. The + whole source package can be freely distributed, including from the USA. + (Prior to January 2000, re-export from the US was a violation of US law.) - This encryption code is a direct transcription of the algorithm from - Roger Schlafly, described by Phil Katz in the file appnote.txt. This - file (appnote.txt) is distributed with the PKZIP program (even in the - version without encryption capabilities). + This encryption code is a direct transcription of the algorithm from + Roger Schlafly, described by Phil Katz in the file appnote.txt. This + file (appnote.txt) is distributed with the PKZIP program (even in the + version without encryption capabilities). - If you don't need crypting in your application, just define symbols - NOCRYPT and NOUNCRYPT. + If you don't need crypting in your application, just define symbols + NOCRYPT and NOUNCRYPT. - This code support the "Traditional PKWARE Encryption". + This code support the "Traditional PKWARE Encryption". - The new AES encryption added on Zip format by Winzip (see the page - http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong - Encryption is not supported. -*/ + The new AES encryption added on Zip format by Winzip (see the page + http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong + Encryption is not supported. + */ #define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8)) /*********************************************************************** * Return the next byte in the pseudo-random sequence */ -static int decrypt_byte( unsigned long* pkeys, const unsigned long* pcrc_32_tab ) +static int decrypt_byte(unsigned long* pkeys, const unsigned long* pcrc_32_tab) { - unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an - * unpredictable manner on 16-bit systems; not a problem - * with any known compiler so far, though */ + unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an + * unpredictable manner on 16-bit systems; not a problem + * with any known compiler so far, though */ - temp = ( ( unsigned )( *( pkeys + 2 ) ) & 0xffff ) | 2; - return ( int )( ( ( temp * ( temp ^ 1 ) ) >> 8 ) & 0xff ); + temp = ((unsigned) (*(pkeys + 2)) & 0xffff) | 2; + return (int) (((temp * (temp ^ 1)) >> 8) & 0xff); } /*********************************************************************** * Update the encryption keys with the next byte of plain text */ -static int update_keys( unsigned long* pkeys, const unsigned long* pcrc_32_tab, int c ) +static int update_keys(unsigned long* pkeys, const unsigned long* pcrc_32_tab, int c) { - ( *( pkeys + 0 ) ) = CRC32( ( *( pkeys + 0 ) ), c ); - ( *( pkeys + 1 ) ) += ( *( pkeys + 0 ) ) & 0xff; - ( *( pkeys + 1 ) ) = ( *( pkeys + 1 ) ) * 134775813L + 1; + (*(pkeys + 0)) = CRC32( ( *( pkeys + 0 ) ), c ); + (*(pkeys + 1)) += (*(pkeys + 0)) & 0xff; + (*(pkeys + 1)) = (*(pkeys + 1)) * 134775813L + 1; { - register int keyshift = ( int )( ( *( pkeys + 1 ) ) >> 24 ); - ( *( pkeys + 2 ) ) = CRC32( ( *( pkeys + 2 ) ), keyshift ); + register int keyshift = (int) ((*(pkeys + 1)) >> 24); + (*(pkeys + 2)) = CRC32( ( *( pkeys + 2 ) ), keyshift ); } return c; } - /*********************************************************************** * Initialize the encryption keys and the random header according to * the given password. */ -static void init_keys( const char* passwd, unsigned long* pkeys, const unsigned long* pcrc_32_tab ) +static void init_keys(const char* passwd, unsigned long* pkeys, const unsigned long* pcrc_32_tab) { - *( pkeys + 0 ) = 305419896L; - *( pkeys + 1 ) = 591751049L; - *( pkeys + 2 ) = 878082192L; - while ( *passwd != '\0' ) + *(pkeys + 0) = 305419896L; + *(pkeys + 1) = 591751049L; + *(pkeys + 2) = 878082192L; + while (*passwd != '\0') { - update_keys( pkeys, pcrc_32_tab, ( int )*passwd ); + update_keys(pkeys, pcrc_32_tab, (int) *passwd); passwd++; } } @@ -89,21 +88,21 @@ static void init_keys( const char* passwd, unsigned long* pkeys, const unsigned # endif static int crypthead( passwd, buf, bufSize, pkeys, pcrc_32_tab, crcForCrypting ) -const char *passwd; /* password string */ -unsigned char *buf; /* where to write header */ +const char *passwd; /* password string */ +unsigned char *buf; /* where to write header */ int bufSize; unsigned long* pkeys; const unsigned long* pcrc_32_tab; unsigned long crcForCrypting; { - int n; /* index in random header */ - int t; /* temporary */ - int c; /* random byte */ + int n; /* index in random header */ + int t; /* temporary */ + int c; /* random byte */ unsigned char header[RAND_HEAD_LEN-2]; /* random header */ - static unsigned calls = 0; /* ensure different random header each time */ + static unsigned calls = 0; /* ensure different random header each time */ if ( bufSize < RAND_HEAD_LEN ) - return 0; + return 0; /* First generate RAND_HEAD_LEN-2 random bytes. We encrypt the * output of rand() to get less predictability, since rand() is diff --git a/source/unzip/inflate.c b/source/unzip/inflate.c index affa7eed..3b71bede 100644 --- a/source/unzip/inflate.c +++ b/source/unzip/inflate.c @@ -1,9 +1,8 @@ - #include "inflate.h" #define CHUNK 1024 -int inflateFile( FILE *source, FILE *dest ) +int inflateFile(FILE *source, FILE *dest) { int ret; unsigned have; @@ -18,20 +17,18 @@ int inflateFile( FILE *source, FILE *dest ) strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit( &strm ); - if ( ret != Z_OK ) - return ret; + if (ret != Z_OK) return ret; /* decompress until deflate stream ends or end of file */ do { - strm.avail_in = fread( in, 1, CHUNK, source ); - if ( ferror( source ) ) + strm.avail_in = fread(in, 1, CHUNK, source); + if (ferror( source )) { - ( void )inflateEnd( &strm ); + (void) inflateEnd(&strm); return Z_ERRNO; } - if ( strm.avail_in == 0 ) - break; + if (strm.avail_in == 0) break; strm.next_in = in; /* run inflate() on input until output buffer not full */ @@ -39,31 +36,29 @@ int inflateFile( FILE *source, FILE *dest ) { strm.avail_out = CHUNK; strm.next_out = out; - ret = inflate( &strm, Z_NO_FLUSH ); - switch ( ret ) + ret = inflate(&strm, Z_NO_FLUSH); + switch (ret) { case Z_NEED_DICT: - ( void )inflateEnd( &strm ); + (void) inflateEnd(&strm); return -20; case Z_DATA_ERROR: - ( void )inflateEnd( &strm ); + (void) inflateEnd(&strm); return -21; case Z_MEM_ERROR: - ( void )inflateEnd( &strm ); + (void) inflateEnd(&strm); return -22; } have = CHUNK - strm.avail_out; - if ( fwrite( out, 1, have, dest ) != have || ferror( dest ) ) + if (fwrite(out, 1, have, dest) != have || ferror( dest )) { - ( void )inflateEnd( &strm ); + (void) inflateEnd(&strm); return Z_ERRNO; } - } - while ( strm.avail_out == 0 ); + } while (strm.avail_out == 0); /* done when inflate() says it's done */ - } - while ( ret != Z_STREAM_END ); + } while (ret != Z_STREAM_END); /* clean up and return */ - ( void )inflateEnd( &strm ); + (void) inflateEnd(&strm); return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; } diff --git a/source/unzip/inflate.h b/source/unzip/inflate.h index 4efe654b..6aa2ccbe 100644 --- a/source/unzip/inflate.h +++ b/source/unzip/inflate.h @@ -1,4 +1,3 @@ - #ifndef _INFLATE_H #define _INFLATE_H @@ -10,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/ioapi.h b/source/unzip/ioapi.h index 31d31c40..255ff03f 100644 --- a/source/unzip/ioapi.h +++ b/source/unzip/ioapi.h @@ -1,15 +1,14 @@ /* ioapi.h -- IO base function header for compress/uncompress .zip - files using zlib + zip or unzip API + files using zlib + zip or unzip API - Version 1.01e, February 12th, 2005 + Version 1.01e, February 12th, 2005 - Copyright (C) 1998-2005 Gilles Vollant -*/ + Copyright (C) 1998-2005 Gilles Vollant + */ #ifndef _ZLIBIOAPI_H #define _ZLIBIOAPI_H - #define ZLIB_FILEFUNC_SEEK_CUR (1) #define ZLIB_FILEFUNC_SEEK_END (2) #define ZLIB_FILEFUNC_SEEK_SET (0) @@ -21,7 +20,6 @@ #define ZLIB_FILEFUNC_MODE_EXISTING (4) #define ZLIB_FILEFUNC_MODE_CREATE (8) - #ifndef ZCALLBACK #if (defined(WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK) @@ -37,28 +35,26 @@ extern "C" #endif typedef voidpf ( ZCALLBACK *open_file_func ) OF( ( voidpf opaque, const char* filename, int mode ) ); - typedef uLong ( ZCALLBACK *read_file_func ) OF( ( voidpf opaque, voidpf stream, void* buf, uLong size ) ); - typedef uLong ( ZCALLBACK *write_file_func ) OF( ( voidpf opaque, voidpf stream, const void* buf, uLong size ) ); - typedef long ( ZCALLBACK *tell_file_func ) OF( ( voidpf opaque, voidpf stream ) ); - typedef long ( ZCALLBACK *seek_file_func ) OF( ( voidpf opaque, voidpf stream, uLong offset, int origin ) ); - typedef int ( ZCALLBACK *close_file_func ) OF( ( voidpf opaque, voidpf stream ) ); - typedef int ( ZCALLBACK *testerror_file_func ) OF( ( voidpf opaque, voidpf stream ) ); + typedef uLong ( ZCALLBACK *read_file_func ) OF( ( voidpf opaque, voidpf stream, void* buf, uLong size ) ); + typedef uLong ( ZCALLBACK *write_file_func ) OF( ( voidpf opaque, voidpf stream, const void* buf, uLong size ) ); + typedef long ( ZCALLBACK *tell_file_func ) OF( ( voidpf opaque, voidpf stream ) ); + typedef long ( ZCALLBACK *seek_file_func ) OF( ( voidpf opaque, voidpf stream, uLong offset, int origin ) ); + typedef int ( ZCALLBACK *close_file_func ) OF( ( voidpf opaque, voidpf stream ) ); + typedef int ( ZCALLBACK *testerror_file_func ) OF( ( voidpf opaque, voidpf stream ) ); typedef struct zlib_filefunc_def_s { - open_file_func zopen_file; - read_file_func zread_file; - write_file_func zwrite_file; - tell_file_func ztell_file; - seek_file_func zseek_file; - close_file_func zclose_file; - testerror_file_func zerror_file; - voidpf opaque; + open_file_func zopen_file; + read_file_func zread_file; + write_file_func zwrite_file; + tell_file_func ztell_file; + seek_file_func zseek_file; + close_file_func zclose_file; + testerror_file_func zerror_file; + voidpf opaque; } zlib_filefunc_def; - - - void fill_fopen_filefunc OF( ( zlib_filefunc_def* pzlib_filefunc_def ) ); +void fill_fopen_filefunc OF( ( zlib_filefunc_def* pzlib_filefunc_def ) ); #define ZREAD(filefunc,filestream,buf,size) ((*((filefunc).zread_file))((filefunc).opaque,filestream,buf,size)) #define ZWRITE(filefunc,filestream,buf,size) ((*((filefunc).zwrite_file))((filefunc).opaque,filestream,buf,size)) @@ -67,7 +63,6 @@ extern "C" #define ZCLOSE(filefunc,filestream) ((*((filefunc).zclose_file))((filefunc).opaque,filestream)) #define ZERROR(filefunc,filestream) ((*((filefunc).zerror_file))((filefunc).opaque,filestream)) - #ifdef __cplusplus } #endif diff --git a/source/unzip/miniunz.c b/source/unzip/miniunz.c index 75a248ec..9acf4c64 100644 --- a/source/unzip/miniunz.c +++ b/source/unzip/miniunz.c @@ -1,10 +1,9 @@ /* - miniunz.c - Version 1.01e, February 12th, 2005 - - Copyright (C) 1998-2005 Gilles Vollant -*/ + miniunz.c + Version 1.01e, February 12th, 2005 + Copyright (C) 1998-2005 Gilles Vollant + */ #include #include @@ -21,80 +20,79 @@ #define WRITEBUFFERSIZE (8192) #define MAXFILENAME (256) -static int mymkdir( const char* dirname ) +static int mymkdir(const char* dirname) { int ret = 0; - ret = mkdir ( dirname, 0775 ); + ret = mkdir(dirname, 0775); return ret; } -int makedir ( char *newdir ) +int makedir(char *newdir) { - char *buffer ; + char *buffer; char *p; - int len = ( int )strlen( newdir ); + int len = (int) strlen(newdir); - if ( len <= 0 ) - return 0; + if (len <= 0) return 0; - buffer = ( char* )malloc( len + 1 ); - strcpy( buffer, newdir ); + buffer = (char*) malloc(len + 1); + strcpy(buffer, newdir); - if ( buffer[len-1] == '/' ) + if (buffer[len - 1] == '/') { - buffer[len-1] = '\0'; + buffer[len - 1] = '\0'; } - if ( mymkdir( buffer ) == 0 ) + if (mymkdir(buffer) == 0) { - free( buffer ); + free(buffer); return 1; } p = buffer + 1; - while ( 1 ) + while (1) { char hold; - while ( *p && *p != '\\' && *p != '/' ) + while (*p && *p != '\\' && *p != '/') p++; hold = *p; *p = 0; - if ( ( mymkdir( buffer ) == -1 ) && ( errno == ENOENT ) ) + if ((mymkdir(buffer) == -1) && (errno == ENOENT)) { -// printf("couldn't create directory %s\n",buffer); - free( buffer ); + // printf("couldn't create directory %s\n",buffer); + free(buffer); return 0; } - if ( hold == 0 ) - break; + if (hold == 0) break; *p++ = hold; } - free( buffer ); + free(buffer); return 1; } -static char *fullfilename( const char *basedir, char *filename ) +static char *fullfilename(const char *basedir, char *filename) { - char *file = ( char * ) malloc( strlen( basedir ) + strlen( filename ) + 1 ); - if ( basedir == NULL ) + char *file = (char *) malloc(strlen(basedir) + strlen(filename) + 1); + if (basedir == NULL) { - strcpy( file, filename ); + strcpy(file, filename); } else { - if ( basedir[strlen( basedir ) - 1] == '/' ) + if (basedir[strlen(basedir) - 1] == '/') { - sprintf( file, "%s%s", basedir, filename ); + sprintf(file, "%s%s", basedir, filename); } else { - sprintf( file, "%s/%s", basedir, filename ); + 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 ) +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; @@ -106,46 +104,45 @@ static int do_extract_currentfile( unzFile uf, const int* popt_extract_without_p uInt size_buf; unz_file_info file_info; - err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 ); + err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); - if ( err != UNZ_OK ) + if (err != UNZ_OK) { -// printf("error %d with zipfile in unzGetCurrentFileInfo\n",err); + // printf("error %d with zipfile in unzGetCurrentFileInfo\n",err); return err; } size_buf = WRITEBUFFERSIZE; - buf = ( void* )malloc( size_buf ); - if ( buf == NULL ) + buf = (void*) malloc(size_buf); + if (buf == NULL) { -// printf("Error allocating memory\n"); + // printf("Error allocating memory\n"); return UNZ_INTERNALERROR; } p = filename_withoutpath = filename_inzip; - filename_withpath = fullfilename( basedir, filename_inzip ); - while ( ( *p ) != '\0' ) + filename_withpath = fullfilename(basedir, filename_inzip); + while ((*p) != '\0') { - if ( ( ( *p ) == '/' ) || ( ( *p ) == '\\' ) ) - filename_withoutpath = p + 1; + if (((*p) == '/') || ((*p) == '\\')) filename_withoutpath = p + 1; p++; } - if ( ( *filename_withoutpath ) == '\0' ) + if ((*filename_withoutpath) == '\0') { - if ( ( *popt_extract_without_path ) == 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 ); + 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 ); + // printf("creating directory: %s\n",path); + mymkdir(path); - free( path ); + free(path); } } else @@ -153,165 +150,150 @@ static int do_extract_currentfile( unzFile uf, const int* popt_extract_without_p char* write_filename; int skip = 0; - if ( ( *popt_extract_without_path ) == 0 ) + if ((*popt_extract_without_path) == 0) write_filename = filename_withpath; - else - write_filename = filename_withoutpath; + else write_filename = filename_withoutpath; - err = unzOpenCurrentFilePassword( uf, password ); - if ( err != UNZ_OK ) + err = unzOpenCurrentFilePassword(uf, password); + if (err != UNZ_OK) { -// printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err); + // printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err); } - if ( ( ( *popt_overwrite ) == 0 ) && ( err == UNZ_OK ) ) + if (((*popt_overwrite) == 0) && (err == UNZ_OK)) { char rep = 0; FILE* ftestexist; - ftestexist = fopen( write_filename, "rb" ); - if ( ftestexist != NULL ) + ftestexist = fopen(write_filename, "rb"); + if (ftestexist != NULL) { - fclose( ftestexist ); + fclose(ftestexist); do { char answer[128]; int ret; -// printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename); - ret = scanf( "%1s", answer ); - if ( ret != 1 ) + // printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename); + ret = scanf("%1s", answer); + if (ret != 1) { - exit( EXIT_FAILURE ); + exit(EXIT_FAILURE); } - rep = answer[0] ; - if ( ( rep >= 'a' ) && ( rep <= 'z' ) ) - rep -= 0x20; - } - while ( ( rep != 'Y' ) && ( rep != 'N' ) && ( rep != 'A' ) ); + rep = answer[0]; + if ((rep >= 'a') && (rep <= 'z')) rep -= 0x20; + } while ((rep != 'Y') && (rep != 'N') && (rep != 'A')); } - if ( rep == 'N' ) - skip = 1; + if (rep == 'N') skip = 1; - if ( rep == 'A' ) - *popt_overwrite = 1; + if (rep == 'A') *popt_overwrite = 1; } - if ( ( skip == 0 ) && ( err == UNZ_OK ) ) + if ((skip == 0) && (err == UNZ_OK)) { - fout = fopen( write_filename, "wb" ); + fout = fopen(write_filename, "wb"); /* some zipfile don't contain directory alone before file */ - if ( ( fout == NULL ) && ( ( *popt_extract_without_path ) == 0 ) && - ( filename_withoutpath != ( char* )filename_inzip ) ) + if ((fout == NULL) && ((*popt_extract_without_path) == 0) && (filename_withoutpath + != (char*) filename_inzip)) { - char c = *( filename_withoutpath - 1 ); - *( filename_withoutpath - 1 ) = '\0'; + 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 ); + char *path = (char *) malloc(strlen(write_filename)); + strcpy(path, write_filename); + char *ptr = strstr(path, filename_withoutpath); *ptr = '\0'; - makedir( path ); - free( path ); + makedir(path); + free(path); - *( filename_withoutpath - 1 ) = c; - fout = fopen( write_filename, "wb" ); + *(filename_withoutpath - 1) = c; + fout = fopen(write_filename, "wb"); } - if ( fout == NULL ) + if (fout == NULL) { -// printf("error opening %s\n",write_filename); + // printf("error opening %s\n",write_filename); } } - if ( fout != NULL ) + if (fout != NULL) { -// printf(" extracting: %s\n",write_filename); + // printf(" extracting: %s\n",write_filename); do { - err = unzReadCurrentFile( uf, buf, size_buf ); - if ( err < 0 ) + err = unzReadCurrentFile(uf, buf, size_buf); + if (err < 0) { -// printf("error %d with zipfile in unzReadCurrentFile\n",err); + // printf("error %d with zipfile in unzReadCurrentFile\n",err); break; } - if ( err > 0 ) - if ( fwrite( buf, err, 1, fout ) != 1 ) - { -// printf("error in writing extracted file\n"); - err = UNZ_ERRNO; - break; - } - } - while ( err > 0 ); - if ( fout ) - fclose( fout ); + if (err > 0) if (fwrite(buf, err, 1, fout) != 1) + { + // printf("error in writing extracted file\n"); + err = UNZ_ERRNO; + break; + } + } while (err > 0); + if (fout) fclose(fout); } - if ( err == UNZ_OK ) + if (err == UNZ_OK) { - err = unzCloseCurrentFile ( uf ); - if ( err != UNZ_OK ) + err = unzCloseCurrentFile(uf); + if (err != UNZ_OK) { -// printf("error %d with zipfile in unzCloseCurrentFile\n",err); + // printf("error %d with zipfile in unzCloseCurrentFile\n",err); } } - else - unzCloseCurrentFile( uf ); /* don't lose the error */ + else unzCloseCurrentFile(uf); /* don't lose the error */ } - free( filename_withpath ); - free( buf ); + free(filename_withpath); + free(buf); return err; } - -int extractZip( unzFile uf, int opt_extract_without_path, int opt_overwrite, const char* password, const char *basedir ) +int extractZip(unzFile uf, int opt_extract_without_path, int opt_overwrite, const char* password, const char *basedir) { uLong i; unz_global_info gi; int err; - err = unzGetGlobalInfo ( uf, &gi ); - if ( err != UNZ_OK ) -// printf("error %d with zipfile in unzGetGlobalInfo \n",err); + err = unzGetGlobalInfo(uf, &gi); + if (err != UNZ_OK) + // printf("error %d with zipfile in unzGetGlobalInfo \n",err); - for ( i = 0; i < gi.number_entry; i++ ) + for (i = 0; i < gi.number_entry; i++) + { + if (do_extract_currentfile(uf, &opt_extract_without_path, &opt_overwrite, password, basedir) != UNZ_OK) break; + + if ((i + 1) < gi.number_entry) { - if ( do_extract_currentfile( uf, &opt_extract_without_path, - &opt_overwrite, - password, basedir ) != UNZ_OK ) - break; - - if ( ( i + 1 ) < gi.number_entry ) + err = unzGoToNextFile(uf); + if (err != UNZ_OK) { - err = unzGoToNextFile( uf ); - if ( err != UNZ_OK ) - { -// printf("error %d with zipfile in unzGoToNextFile\n",err); - break; - } + // printf("error %d with zipfile in unzGoToNextFile\n",err); + break; } } + } return 0; } -int extractZipOnefile( unzFile uf, const char* filename, int opt_extract_without_path, int opt_overwrite, const char* password ) +int extractZipOnefile(unzFile uf, const char* filename, int opt_extract_without_path, int opt_overwrite, + const char* password) { - if ( unzLocateFile( uf, filename, CASESENSITIVITY ) != UNZ_OK ) + if (unzLocateFile(uf, filename, CASESENSITIVITY) != UNZ_OK) { -// printf("file %s not found in the zipfile\n",filename); + // printf("file %s not found in the zipfile\n",filename); return 2; } - if ( do_extract_currentfile( uf, &opt_extract_without_path, - &opt_overwrite, - password, NULL ) == UNZ_OK ) + if (do_extract_currentfile(uf, &opt_extract_without_path, &opt_overwrite, password, NULL) == UNZ_OK) return 0; - else - return 1; + else return 1; } diff --git a/source/unzip/miniunz.h b/source/unzip/miniunz.h index 6ef25d94..ef32fb3c 100644 --- a/source/unzip/miniunz.h +++ b/source/unzip/miniunz.h @@ -1,4 +1,3 @@ - #ifndef _miniunz_H #define _miniunz_H @@ -7,9 +6,11 @@ extern "C" { #endif - int extractZip( unzFile uf, int opt_extract_without_path, int opt_overwrite, const char* password, const char *basedir ); - int extractZipOnefile( unzFile uf, const char* filename, int opt_extract_without_path, int opt_overwrite, const char* password ); - int makedir( char *newdir ); + int extractZip(unzFile uf, int opt_extract_without_path, int opt_overwrite, const char* password, + const char *basedir); + int extractZipOnefile(unzFile uf, const char* filename, int opt_extract_without_path, int opt_overwrite, + const char* password); + int makedir(char *newdir); #ifdef __cplusplus } diff --git a/source/unzip/mztools.c b/source/unzip/mztools.c index b0b7ec97..2a79c3c6 100644 --- a/source/unzip/mztools.c +++ b/source/unzip/mztools.c @@ -1,8 +1,8 @@ /* - Additional tools for Minizip - Code: Xavier Roche '2004 - License: Same as ZLIB (www.gzip.org) -*/ + Additional tools for Minizip + Code: Xavier Roche '2004 + License: Same as ZLIB (www.gzip.org) + */ /* Code */ #include @@ -27,18 +27,14 @@ WRITE_16((unsigned char*)(buff) + 2, (n) >> 16); \ } while(0) -extern int ZEXPORT unzRepair( file, fileOut, fileOutTmp, nRecovered, bytesRecovered ) -const char* file; -const char* fileOut; -const char* fileOutTmp; -uLong* nRecovered; -uLong* bytesRecovered; +extern int ZEXPORT unzRepair(file, fileOut, fileOutTmp, nRecovered, bytesRecovered) + const char* file;const char* fileOut;const char* fileOutTmp;uLong* nRecovered;uLong* bytesRecovered; { int err = Z_OK; - FILE* fpZip = fopen( file, "rb" ); - FILE* fpOut = fopen( fileOut, "wb" ); - FILE* fpOutCD = fopen( fileOutTmp, "wb" ); - if ( fpZip != NULL && fpOut != NULL ) + FILE* fpZip = fopen(file, "rb"); + FILE* fpOut = fopen(fileOut, "wb"); + FILE* fpOutCD = fopen(fileOutTmp, "wb"); + if (fpZip != NULL && fpOut != NULL) { int entries = 0; uLong totalBytes = 0; @@ -47,12 +43,12 @@ uLong* bytesRecovered; char extra[1024]; int offset = 0; int offsetCD = 0; - while ( fread( header, 1, 30, fpZip ) == 30 ) + while (fread(header, 1, 30, fpZip) == 30) { int currentOffset = offset; /* File entry */ - if ( READ_32( header ) == 0x04034b50 ) + if (READ_32( header ) == 0x04034b50) { unsigned int version = READ_16( header + 4 ); unsigned int gpflag = READ_16( header + 6 ); @@ -67,7 +63,7 @@ uLong* bytesRecovered; filename[0] = extra[0] = '\0'; /* Header */ - if ( fwrite( header, 1, 30, fpOut ) == 30 ) + if (fwrite(header, 1, 30, fpOut) == 30) { offset += 30; } @@ -78,11 +74,11 @@ uLong* bytesRecovered; } /* Filename */ - if ( fnsize > 0 ) + if (fnsize > 0) { - if ( fread( filename, 1, fnsize, fpZip ) == fnsize ) + if (fread(filename, 1, fnsize, fpZip) == fnsize) { - if ( fwrite( filename, 1, fnsize, fpOut ) == fnsize ) + if (fwrite(filename, 1, fnsize, fpOut) == fnsize) { offset += fnsize; } @@ -105,11 +101,11 @@ uLong* bytesRecovered; } /* Extra field */ - if ( extsize > 0 ) + if (extsize > 0) { - if ( fread( extra, 1, extsize, fpZip ) == extsize ) + if (fread(extra, 1, extsize, fpZip) == extsize) { - if ( fwrite( extra, 1, extsize, fpOut ) == extsize ) + if (fwrite(extra, 1, extsize, fpOut) == extsize) { offset += extsize; } @@ -129,18 +125,18 @@ uLong* bytesRecovered; /* Data */ { int dataSize = cpsize; - if ( dataSize == 0 ) + if (dataSize == 0) { dataSize = uncpsize; } - if ( dataSize > 0 ) + if (dataSize > 0) { - char* data = malloc( dataSize ); - if ( data != NULL ) + char* data = malloc(dataSize); + if (data != NULL) { - if ( ( int )fread( data, 1, dataSize, fpZip ) == dataSize ) + if ((int) fread(data, 1, dataSize, fpZip) == dataSize) { - if ( ( int )fwrite( data, 1, dataSize, fpOut ) == dataSize ) + if ((int) fwrite(data, 1, dataSize, fpOut) == dataSize) { offset += dataSize; totalBytes += dataSize; @@ -154,8 +150,8 @@ uLong* bytesRecovered; { err = Z_ERRNO; } - free( data ); - if ( err != Z_OK ) + free(data); + if (err != Z_OK) { break; } @@ -172,7 +168,7 @@ uLong* bytesRecovered; { char header[46]; char* comment = ""; - int comsize = ( int ) strlen( comment ); + int comsize = (int) strlen(comment); WRITE_32( header, 0x02014b50 ); WRITE_16( header + 4, version ); WRITE_16( header + 6, version ); @@ -186,19 +182,19 @@ uLong* bytesRecovered; WRITE_16( header + 28, fnsize ); WRITE_16( header + 30, extsize ); WRITE_16( header + 32, comsize ); - WRITE_16( header + 34, 0 ); /* disk # */ - WRITE_16( header + 36, 0 ); /* int attrb */ - WRITE_32( header + 38, 0 ); /* ext attrb */ + WRITE_16( header + 34, 0 ); /* disk # */ + WRITE_16( header + 36, 0 ); /* int attrb */ + WRITE_32( header + 38, 0 ); /* ext attrb */ WRITE_32( header + 42, currentOffset ); /* Header */ - if ( fwrite( header, 1, 46, fpOutCD ) == 46 ) + if (fwrite(header, 1, 46, fpOutCD) == 46) { offsetCD += 46; /* Filename */ - if ( fnsize > 0 ) + if (fnsize > 0) { - if ( fwrite( filename, 1, fnsize, fpOutCD ) == fnsize ) + if (fwrite(filename, 1, fnsize, fpOutCD) == fnsize) { offsetCD += fnsize; } @@ -215,9 +211,9 @@ uLong* bytesRecovered; } /* Extra field */ - if ( extsize > 0 ) + if (extsize > 0) { - if ( fwrite( extra, 1, extsize, fpOutCD ) == extsize ) + if (fwrite(extra, 1, extsize, fpOutCD) == extsize) { offsetCD += extsize; } @@ -229,9 +225,9 @@ uLong* bytesRecovered; } /* Comment field */ - if ( comsize > 0 ) + if (comsize > 0) { - if ( ( int )fwrite( comment, 1, comsize, fpOutCD ) == comsize ) + if ((int) fwrite(comment, 1, comsize, fpOutCD) == comsize) { offsetCD += comsize; } @@ -242,7 +238,6 @@ uLong* bytesRecovered; } } - } else { @@ -266,28 +261,28 @@ uLong* bytesRecovered; int entriesZip = entries; char header[22]; char* comment = ""; // "ZIP File recovered by zlib/minizip/mztools"; - int comsize = ( int ) strlen( comment ); - if ( entriesZip > 0xffff ) + int comsize = (int) strlen(comment); + if (entriesZip > 0xffff) { entriesZip = 0xffff; } WRITE_32( header, 0x06054b50 ); - WRITE_16( header + 4, 0 ); /* disk # */ - WRITE_16( header + 6, 0 ); /* disk # */ + WRITE_16( header + 4, 0 ); /* disk # */ + WRITE_16( header + 6, 0 ); /* disk # */ WRITE_16( header + 8, entriesZip ); /* hack */ - WRITE_16( header + 10, entriesZip ); /* hack */ - WRITE_32( header + 12, offsetCD ); /* size of CD */ - WRITE_32( header + 16, offset ); /* offset to CD */ - WRITE_16( header + 20, comsize ); /* comment */ + WRITE_16( header + 10, entriesZip ); /* hack */ + WRITE_32( header + 12, offsetCD ); /* size of CD */ + WRITE_32( header + 16, offset ); /* offset to CD */ + WRITE_16( header + 20, comsize ); /* comment */ /* Header */ - if ( fwrite( header, 1, 22, fpOutCD ) == 22 ) + if (fwrite(header, 1, 22, fpOutCD) == 22) { /* Comment field */ - if ( comsize > 0 ) + if (comsize > 0) { - if ( ( int )fwrite( comment, 1, comsize, fpOutCD ) != comsize ) + if ((int) fwrite(comment, 1, comsize, fpOutCD) != comsize) { err = Z_ERRNO; } @@ -301,41 +296,41 @@ uLong* bytesRecovered; } /* Final merge (file + central directory) */ - fclose( fpOutCD ); - if ( err == Z_OK ) + fclose(fpOutCD); + if (err == Z_OK) { - fpOutCD = fopen( fileOutTmp, "rb" ); - if ( fpOutCD != NULL ) + fpOutCD = fopen(fileOutTmp, "rb"); + if (fpOutCD != NULL) { int nRead; char buffer[8192]; - while ( ( nRead = ( int )fread( buffer, 1, sizeof( buffer ), fpOutCD ) ) > 0 ) + while ((nRead = (int) fread(buffer, 1, sizeof(buffer), fpOutCD)) > 0) { - if ( ( int )fwrite( buffer, 1, nRead, fpOut ) != nRead ) + if ((int) fwrite(buffer, 1, nRead, fpOut) != nRead) { err = Z_ERRNO; break; } } - fclose( fpOutCD ); + fclose(fpOutCD); } } /* Close */ - fclose( fpZip ); - fclose( fpOut ); + fclose(fpZip); + fclose(fpOut); /* Wipe temporary file */ - ( void )remove( fileOutTmp ); + (void) remove(fileOutTmp); /* Number of recovered entries */ - if ( err == Z_OK ) + if (err == Z_OK) { - if ( nRecovered != NULL ) + if (nRecovered != NULL) { *nRecovered = entries; } - if ( bytesRecovered != NULL ) + if (bytesRecovered != NULL) { *bytesRecovered = totalBytes; } diff --git a/source/unzip/mztools.h b/source/unzip/mztools.h index 09f419df..dc1d30c9 100644 --- a/source/unzip/mztools.h +++ b/source/unzip/mztools.h @@ -1,8 +1,8 @@ /* - Additional tools for Minizip - Code: Xavier Roche '2004 - License: Same as ZLIB (www.gzip.org) -*/ + Additional tools for Minizip + Code: Xavier Roche '2004 + License: Same as ZLIB (www.gzip.org) + */ #ifndef _zip_tools_H #define _zip_tools_H @@ -19,14 +19,11 @@ extern "C" #include "unzip.h" /* Repair a ZIP file (missing central directory) - file: file to recover - fileOut: output file after recovery - fileOutTmp: temporary file name used for recovery - */ - extern int ZEXPORT unzRepair( const char* file, - const char* fileOut, - const char* fileOutTmp, - uLong* nRecovered, - uLong* bytesRecovered ); + file: file to recover + fileOut: output file after recovery + fileOutTmp: temporary file name used for recovery + */ + extern int ZEXPORT unzRepair(const char* file, const char* fileOut, const char* fileOutTmp, uLong* nRecovered, + uLong* bytesRecovered); #endif diff --git a/source/unzip/unzip.c b/source/unzip/unzip.c index f90d2add..2b366307 100644 --- a/source/unzip/unzip.c +++ b/source/unzip/unzip.c @@ -1,40 +1,39 @@ /* unzip.c -- IO for uncompress .zip files using zlib - Version 1.01e, February 12th, 2005 + Version 1.01e, February 12th, 2005 - Copyright (C) 1998-2005 Gilles Vollant + Copyright (C) 1998-2005 Gilles Vollant - Read unzip.h for more info -*/ + Read unzip.h for more info + */ /* Decryption code comes from crypt.c by Info-ZIP but has been greatly reduced in terms of -compatibility with older software. The following is from the original crypt.c. Code -woven in by Terry Thorsen 1/2003. -*/ + compatibility with older software. The following is from the original crypt.c. Code + woven in by Terry Thorsen 1/2003. + */ /* - Copyright (c) 1990-2000 Info-ZIP. All rights reserved. + Copyright (c) 1990-2000 Info-ZIP. All rights reserved. - See the accompanying file LICENSE, version 2000-Apr-09 or later - (the contents of which are also included in zip.h) for terms of use. - If, for some reason, all these files are missing, the Info-ZIP license - also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html -*/ + See the accompanying file LICENSE, version 2000-Apr-09 or later + (the contents of which are also included in zip.h) for terms of use. + If, for some reason, all these files are missing, the Info-ZIP license + also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html + */ /* - crypt.c (full version) by Info-ZIP. Last revised: [see crypt.h] + crypt.c (full version) by Info-ZIP. Last revised: [see crypt.h] - The encryption/decryption parts of this source code (as opposed to the - non-echoing password parts) were originally written in Europe. The - whole source package can be freely distributed, including from the USA. - (Prior to January 2000, re-export from the US was a violation of US law.) + The encryption/decryption parts of this source code (as opposed to the + non-echoing password parts) were originally written in Europe. The + whole source package can be freely distributed, including from the USA. + (Prior to January 2000, re-export from the US was a violation of US law.) */ /* - This encryption code is a direct transcription of the algorithm from - Roger Schlafly, described by Phil Katz in the file appnote.txt. This - file (appnote.txt) is distributed with the PKZIP program (even in the - version without encryption capabilities). + This encryption code is a direct transcription of the algorithm from + Roger Schlafly, described by Phil Katz in the file appnote.txt. This + file (appnote.txt) is distributed with the PKZIP program (even in the + version without encryption capabilities). */ - #include #include #include @@ -52,20 +51,17 @@ extern int errno; # include #endif - #ifndef local # define local static #endif /* compile with -Dlocal if your debugger can't find static symbols */ - #ifndef CASESENSITIVITYDEFAULT_NO # if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) # define CASESENSITIVITYDEFAULT_NO # endif #endif - #ifndef UNZ_BUFSIZE #define UNZ_BUFSIZE (16384) #endif @@ -84,11 +80,7 @@ extern int errno; #define SIZECENTRALDIRITEM (0x2e) #define SIZEZIPLOCALHEADER (0x1e) - - - -const char unz_copyright[] = - " unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; +const char unz_copyright[] = " unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; /* unz_file_info_interntal contain internal info about a file in zipfile*/ typedef struct unz_file_info_internal_s @@ -96,193 +88,166 @@ typedef struct unz_file_info_internal_s uLong offset_curfile;/* relative offset of local header 4 bytes */ } unz_file_info_internal; - /* file_in_zip_read_info_s contain internal information about a file in zipfile, - when reading and decompress it */ + when reading and decompress it */ typedef struct { - char *read_buffer; /* internal buffer for compressed data */ - z_stream stream; /* zLib stream structure for inflate */ + char *read_buffer; /* internal buffer for compressed data */ + z_stream stream; /* zLib stream structure for inflate */ - uLong pos_in_zipfile; /* position in byte on the zipfile, for fseek*/ - uLong stream_initialised; /* flag set if stream structure is initialised*/ + uLong pos_in_zipfile; /* position in byte on the zipfile, for fseek*/ + uLong stream_initialised; /* flag set if stream structure is initialised*/ uLong offset_local_extrafield;/* offset of the local extra field */ - uInt size_local_extrafield;/* size of the local extra field */ - uLong pos_local_extrafield; /* position in the local extra field in read*/ + uInt size_local_extrafield;/* size of the local extra field */ + uLong pos_local_extrafield; /* position in the local extra field in read*/ - uLong crc32; /* crc32 of all data uncompressed */ - uLong crc32_wait; /* crc32 we must obtain after decompress all */ + uLong crc32; /* crc32 of all data uncompressed */ + uLong crc32_wait; /* crc32 we must obtain after decompress all */ uLong rest_read_compressed; /* number of byte to be decompressed */ uLong rest_read_uncompressed;/*number of byte to be obtained after decomp*/ zlib_filefunc_def z_filefunc; - voidpf filestream; /* io structore of the zipfile */ - uLong compression_method; /* compression method (0==store) */ + voidpf filestream; /* io structore of the zipfile */ + uLong compression_method; /* compression method (0==store) */ uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ - int raw; + int raw; } file_in_zip_read_info_s; - /* unz_s contain internal information about the zipfile -*/ + */ typedef struct { zlib_filefunc_def z_filefunc; - voidpf filestream; /* io structore of the zipfile */ - unz_global_info gi; /* public global information */ + voidpf filestream; /* io structore of the zipfile */ + unz_global_info gi; /* public global information */ uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ - uLong num_file; /* number of the current file in the zipfile*/ - uLong pos_in_central_dir; /* pos of the current file in the central dir*/ - uLong current_file_ok; /* flag about the usability of the current file*/ - uLong central_pos; /* position of the beginning of the central dir*/ + uLong num_file; /* number of the current file in the zipfile*/ + uLong pos_in_central_dir; /* pos of the current file in the central dir*/ + uLong current_file_ok; /* flag about the usability of the current file*/ + uLong central_pos; /* position of the beginning of the central dir*/ - uLong size_central_dir; /* size of the central directory */ - uLong offset_central_dir; /* offset of start of central directory with - respect to the starting disk number */ + uLong size_central_dir; /* size of the central directory */ + uLong offset_central_dir; /* offset of start of central directory with + respect to the starting disk number */ unz_file_info cur_file_info; /* public info about the current file in zip*/ unz_file_info_internal cur_file_info_internal; /* private info about it*/ file_in_zip_read_info_s* pfile_in_zip_read; /* structure about the current - file if we are decompressing it */ + file if we are decompressing it */ int encrypted; # ifndef NOUNCRYPT - unsigned long keys[3]; /* keys defining the pseudo-random sequence */ + unsigned long keys[3]; /* keys defining the pseudo-random sequence */ const unsigned long* pcrc_32_tab; # endif } unz_s; - #ifndef NOUNCRYPT #include "crypt.h" #endif /* =========================================================================== - Read a byte from a gz_stream; update next_in and avail_in. Return EOF - for end of file. - IN assertion: the stream s has been sucessfully opened for reading. -*/ - + Read a byte from a gz_stream; update next_in and avail_in. Return EOF + for end of file. + IN assertion: the stream s has been sucessfully opened for reading. + */ local int unzlocal_getByte OF( ( - const zlib_filefunc_def* pzlib_filefunc_def, - voidpf filestream, - int *pi ) ); + const zlib_filefunc_def* pzlib_filefunc_def, + voidpf filestream, + int *pi ) ); -local int unzlocal_getByte( pzlib_filefunc_def, filestream, pi ) -const zlib_filefunc_def* pzlib_filefunc_def; -voidpf filestream; -int *pi; +local int unzlocal_getByte(pzlib_filefunc_def, filestream, pi) + const zlib_filefunc_def* pzlib_filefunc_def;voidpf filestream;int *pi; { unsigned char c; - int err = ( int )ZREAD( *pzlib_filefunc_def, filestream, &c, 1 ); - if ( err == 1 ) + int err = (int) ZREAD( *pzlib_filefunc_def, filestream, &c, 1 ); + if (err == 1) { - *pi = ( int )c; + *pi = (int) c; return UNZ_OK; } else { - if ( ZERROR( *pzlib_filefunc_def, filestream ) ) + if (ZERROR( *pzlib_filefunc_def, filestream )) return UNZ_ERRNO; - else - return UNZ_EOF; + else return UNZ_EOF; } } - /* =========================================================================== - Reads a long in LSB order from the given gz_stream. Sets -*/ + Reads a long in LSB order from the given gz_stream. Sets + */ local int unzlocal_getShort OF( ( - const zlib_filefunc_def* pzlib_filefunc_def, - voidpf filestream, - uLong *pX ) ); + const zlib_filefunc_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX ) ); -local int unzlocal_getShort ( pzlib_filefunc_def, filestream, pX ) -const zlib_filefunc_def* pzlib_filefunc_def; -voidpf filestream; -uLong *pX; +local int unzlocal_getShort(pzlib_filefunc_def, filestream, pX) + const zlib_filefunc_def* pzlib_filefunc_def;voidpf filestream;uLong *pX; { - uLong x ; + uLong x; int i = 0; int err; - err = unzlocal_getByte( pzlib_filefunc_def, filestream, &i ); - x = ( uLong )i; + err = unzlocal_getByte(pzlib_filefunc_def, filestream, &i); + x = (uLong) i; - if ( err == UNZ_OK ) - err = unzlocal_getByte( pzlib_filefunc_def, filestream, &i ); - x += ( ( uLong )i ) << 8; + if (err == UNZ_OK) err = unzlocal_getByte(pzlib_filefunc_def, filestream, &i); + x += ((uLong) i) << 8; - if ( err == UNZ_OK ) + if (err == UNZ_OK) *pX = x; - else - *pX = 0; + else *pX = 0; return err; } local int unzlocal_getLong OF( ( - const zlib_filefunc_def* pzlib_filefunc_def, - voidpf filestream, - uLong *pX ) ); + const zlib_filefunc_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX ) ); -local int unzlocal_getLong ( pzlib_filefunc_def, filestream, pX ) -const zlib_filefunc_def* pzlib_filefunc_def; -voidpf filestream; -uLong *pX; +local int unzlocal_getLong(pzlib_filefunc_def, filestream, pX) + const zlib_filefunc_def* pzlib_filefunc_def;voidpf filestream;uLong *pX; { - uLong x ; + uLong x; int i = 0; int err; - err = unzlocal_getByte( pzlib_filefunc_def, filestream, &i ); - x = ( uLong )i; + err = unzlocal_getByte(pzlib_filefunc_def, filestream, &i); + x = (uLong) i; - if ( err == UNZ_OK ) - err = unzlocal_getByte( pzlib_filefunc_def, filestream, &i ); - x += ( ( uLong )i ) << 8; + if (err == UNZ_OK) err = unzlocal_getByte(pzlib_filefunc_def, filestream, &i); + x += ((uLong) i) << 8; - if ( err == UNZ_OK ) - err = unzlocal_getByte( pzlib_filefunc_def, filestream, &i ); - x += ( ( uLong )i ) << 16; + if (err == UNZ_OK) err = unzlocal_getByte(pzlib_filefunc_def, filestream, &i); + x += ((uLong) i) << 16; - if ( err == UNZ_OK ) - err = unzlocal_getByte( pzlib_filefunc_def, filestream, &i ); - x += ( ( uLong )i ) << 24; + if (err == UNZ_OK) err = unzlocal_getByte(pzlib_filefunc_def, filestream, &i); + x += ((uLong) i) << 24; - if ( err == UNZ_OK ) + if (err == UNZ_OK) *pX = x; - else - *pX = 0; + else *pX = 0; return err; } - /* My own strcmpi / strcasecmp */ -local int strcmpcasenosensitive_internal ( fileName1, fileName2 ) -const char* fileName1; -const char* fileName2; +local int strcmpcasenosensitive_internal(fileName1, fileName2) + const char* fileName1;const char* fileName2; { - for ( ;; ) + for (;;) { - char c1 = *( fileName1++ ); - char c2 = *( fileName2++ ); - if ( ( c1 >= 'a' ) && ( c1 <= 'z' ) ) - c1 -= 0x20; - if ( ( c2 >= 'a' ) && ( c2 <= 'z' ) ) - c2 -= 0x20; - if ( c1 == '\0' ) - return ( ( c2 == '\0' ) ? 0 : -1 ); - if ( c2 == '\0' ) - return 1; - if ( c1 < c2 ) - return -1; - if ( c1 > c2 ) - return 1; + char c1 = *(fileName1++); + char c2 = *(fileName2++); + if ((c1 >= 'a') && (c1 <= 'z')) c1 -= 0x20; + if ((c2 >= 'a') && (c2 <= 'z')) c2 -= 0x20; + if (c1 == '\0') return ((c2 == '\0') ? 0 : -1); + if (c2 == '\0') return 1; + if (c1 < c2) return -1; + if (c1 > c2) return 1; } } - #ifdef CASESENSITIVITYDEFAULT_NO #define CASESENSITIVITYDEFAULTVALUE 2 #else @@ -294,43 +259,36 @@ const char* fileName2; #endif /* - Compare two filename (fileName1,fileName2). - If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) - If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi - or strcasecmp) - If iCaseSenisivity = 0, case sensitivity is defaut of your operating system - (like 1 on Unix, 2 on Windows) + Compare two filename (fileName1,fileName2). + If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) + If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi + or strcasecmp) + If iCaseSenisivity = 0, case sensitivity is defaut of your operating system + (like 1 on Unix, 2 on Windows) -*/ -extern int ZEXPORT unzStringFileNameCompare ( fileName1, fileName2, iCaseSensitivity ) -const char* fileName1; -const char* fileName2; -int iCaseSensitivity; + */ +extern int ZEXPORT unzStringFileNameCompare(fileName1, fileName2, iCaseSensitivity) + const char* fileName1;const char* fileName2;int iCaseSensitivity; { - if ( iCaseSensitivity == 0 ) - iCaseSensitivity = CASESENSITIVITYDEFAULTVALUE; + if (iCaseSensitivity == 0) iCaseSensitivity = CASESENSITIVITYDEFAULTVALUE; - if ( iCaseSensitivity == 1 ) - return strcmp( fileName1, fileName2 ); + if (iCaseSensitivity == 1) return strcmp(fileName1, fileName2); - return STRCMPCASENOSENTIVEFUNCTION( fileName1, fileName2 ); + return STRCMPCASENOSENTIVEFUNCTION(fileName1, fileName2); } - #ifndef BUFREADCOMMENT #define BUFREADCOMMENT (0x400) #endif - /* - Locate the Central directory of a zipfile (at the end, just before - the global comment) -*/ + Locate the Central directory of a zipfile (at the end, just before + the global comment) + */ local uLong unzlocal_SearchCentralDir OF( ( - const zlib_filefunc_def* pzlib_filefunc_def, - voidpf filestream ) ); + const zlib_filefunc_def* pzlib_filefunc_def, + voidpf filestream ) ); -local uLong unzlocal_SearchCentralDir( pzlib_filefunc_def, filestream ) -const zlib_filefunc_def* pzlib_filefunc_def; -voidpf filestream; +local uLong unzlocal_SearchCentralDir(pzlib_filefunc_def, filestream) + const zlib_filefunc_def* pzlib_filefunc_def;voidpf filestream; { unsigned char* buf; uLong uSizeFile; @@ -338,257 +296,207 @@ voidpf filestream; uLong uMaxBack = 0xffff; /* maximum size of global comment */ uLong uPosFound = 0; - if ( ZSEEK( *pzlib_filefunc_def, filestream, 0, ZLIB_FILEFUNC_SEEK_END ) != 0 ) - return 0; - + if (ZSEEK( *pzlib_filefunc_def, filestream, 0, ZLIB_FILEFUNC_SEEK_END ) != 0) return 0; uSizeFile = ZTELL( *pzlib_filefunc_def, filestream ); - if ( uMaxBack > uSizeFile ) - uMaxBack = uSizeFile; + if (uMaxBack > uSizeFile) uMaxBack = uSizeFile; - buf = ( unsigned char* )ALLOC( BUFREADCOMMENT + 4 ); - if ( buf == NULL ) - return 0; + buf = (unsigned char*) ALLOC( BUFREADCOMMENT + 4 ); + if (buf == NULL) return 0; uBackRead = 4; - while ( uBackRead < uMaxBack ) + while (uBackRead < uMaxBack) { - uLong uReadSize, uReadPos ; + uLong uReadSize, uReadPos; int i; - if ( uBackRead + BUFREADCOMMENT > uMaxBack ) + if (uBackRead + BUFREADCOMMENT > uMaxBack) uBackRead = uMaxBack; - else - uBackRead += BUFREADCOMMENT; - uReadPos = uSizeFile - uBackRead ; + else uBackRead += BUFREADCOMMENT; + uReadPos = uSizeFile - uBackRead; - uReadSize = ( ( BUFREADCOMMENT + 4 ) < ( uSizeFile - uReadPos ) ) ? - ( BUFREADCOMMENT + 4 ) : ( uSizeFile - uReadPos ); - if ( ZSEEK( *pzlib_filefunc_def, filestream, uReadPos, ZLIB_FILEFUNC_SEEK_SET ) != 0 ) - break; + uReadSize = ((BUFREADCOMMENT + 4) < (uSizeFile - uReadPos)) ? (BUFREADCOMMENT + 4) : (uSizeFile - uReadPos); + if (ZSEEK( *pzlib_filefunc_def, filestream, uReadPos, ZLIB_FILEFUNC_SEEK_SET ) != 0) break; - if ( ZREAD( *pzlib_filefunc_def, filestream, buf, uReadSize ) != uReadSize ) - break; + if (ZREAD( *pzlib_filefunc_def, filestream, buf, uReadSize ) != uReadSize) break; - for ( i = ( int )uReadSize - 3; ( i-- ) > 0; ) - if ( ( ( *( buf + i ) ) == 0x50 ) && ( ( *( buf + i + 1 ) ) == 0x4b ) && - ( ( *( buf + i + 2 ) ) == 0x05 ) && ( ( *( buf + i + 3 ) ) == 0x06 ) ) + for (i = (int) uReadSize - 3; (i--) > 0;) + if (((*(buf + i)) == 0x50) && ((*(buf + i + 1)) == 0x4b) && ((*(buf + i + 2)) == 0x05) && ((*(buf + i + 3)) + == 0x06)) { uPosFound = uReadPos + i; break; } - if ( uPosFound != 0 ) - break; + if (uPosFound != 0) break; } TRYFREE( buf ); return uPosFound; } /* - Open a Zip file. path contain the full pathname (by example, - on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer - "zlib/zlib114.zip". - If the zipfile cannot be opened (file doesn't exist or in not valid), the - return value is NULL. - Else, the return value is a unzFile Handle, usable with other function - of this unzip package. -*/ -extern unzFile ZEXPORT unzOpen2 ( path, pzlib_filefunc_def ) -const char *path; -zlib_filefunc_def* pzlib_filefunc_def; + Open a Zip file. path contain the full pathname (by example, + on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer + "zlib/zlib114.zip". + If the zipfile cannot be opened (file doesn't exist or in not valid), the + return value is NULL. + Else, the return value is a unzFile Handle, usable with other function + of this unzip package. + */ +extern unzFile ZEXPORT unzOpen2(path, pzlib_filefunc_def) + const char *path;zlib_filefunc_def* pzlib_filefunc_def; { unz_s us; unz_s *s; uLong central_pos, uL; - uLong number_disk; /* number of the current dist, used for - spaning ZIP, unsupported, always 0*/ - uLong number_disk_with_CD; /* number the the disk with central dir, used - for spaning ZIP, unsupported, always 0*/ - uLong number_entry_CD; /* total number of entries in - the central dir - (same than number_entry on nospan) */ + uLong number_disk; /* number of the current dist, used for + spaning ZIP, unsupported, always 0*/ + uLong number_disk_with_CD; /* number the the disk with central dir, used + for spaning ZIP, unsupported, always 0*/ + uLong number_entry_CD; /* total number of entries in + the central dir + (same than number_entry on nospan) */ int err = UNZ_OK; - if ( unz_copyright[0] != ' ' ) - return NULL; + if (unz_copyright[0] != ' ') return NULL; - if ( pzlib_filefunc_def == NULL ) - fill_fopen_filefunc( &us.z_filefunc ); - else - us.z_filefunc = *pzlib_filefunc_def; + if (pzlib_filefunc_def == NULL) + fill_fopen_filefunc(&us.z_filefunc); + else us.z_filefunc = *pzlib_filefunc_def; - us.filestream = ( *( us.z_filefunc.zopen_file ) )( us.z_filefunc.opaque, - path, - ZLIB_FILEFUNC_MODE_READ | - ZLIB_FILEFUNC_MODE_EXISTING ); - if ( us.filestream == NULL ) - return NULL; + us.filestream = (*(us.z_filefunc.zopen_file))(us.z_filefunc.opaque, path, ZLIB_FILEFUNC_MODE_READ + | ZLIB_FILEFUNC_MODE_EXISTING); + if (us.filestream == NULL) return NULL; - central_pos = unzlocal_SearchCentralDir( &us.z_filefunc, us.filestream ); - if ( central_pos == 0 ) - err = UNZ_ERRNO; + central_pos = unzlocal_SearchCentralDir(&us.z_filefunc, us.filestream); + if (central_pos == 0) err = UNZ_ERRNO; - if ( ZSEEK( us.z_filefunc, us.filestream, - central_pos, ZLIB_FILEFUNC_SEEK_SET ) != 0 ) - err = UNZ_ERRNO; + if (ZSEEK( us.z_filefunc, us.filestream, + central_pos, ZLIB_FILEFUNC_SEEK_SET ) != 0) err = UNZ_ERRNO; /* the signature, already checked */ - if ( unzlocal_getLong( &us.z_filefunc, us.filestream, &uL ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getLong(&us.z_filefunc, us.filestream, &uL) != UNZ_OK) err = UNZ_ERRNO; /* number of this disk */ - if ( unzlocal_getShort( &us.z_filefunc, us.filestream, &number_disk ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&us.z_filefunc, us.filestream, &number_disk) != UNZ_OK) err = UNZ_ERRNO; /* number of the disk with the start of the central directory */ - if ( unzlocal_getShort( &us.z_filefunc, us.filestream, &number_disk_with_CD ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&us.z_filefunc, us.filestream, &number_disk_with_CD) != UNZ_OK) err = UNZ_ERRNO; /* total number of entries in the central dir on this disk */ - if ( unzlocal_getShort( &us.z_filefunc, us.filestream, &us.gi.number_entry ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&us.z_filefunc, us.filestream, &us.gi.number_entry) != UNZ_OK) err = UNZ_ERRNO; /* total number of entries in the central dir */ - if ( unzlocal_getShort( &us.z_filefunc, us.filestream, &number_entry_CD ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&us.z_filefunc, us.filestream, &number_entry_CD) != UNZ_OK) err = UNZ_ERRNO; - if ( ( number_entry_CD != us.gi.number_entry ) || - ( number_disk_with_CD != 0 ) || - ( number_disk != 0 ) ) - err = UNZ_BADZIPFILE; + if ((number_entry_CD != us.gi.number_entry) || (number_disk_with_CD != 0) || (number_disk != 0)) err + = UNZ_BADZIPFILE; /* size of the central directory */ - if ( unzlocal_getLong( &us.z_filefunc, us.filestream, &us.size_central_dir ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getLong(&us.z_filefunc, us.filestream, &us.size_central_dir) != UNZ_OK) err = UNZ_ERRNO; /* offset of start of central directory with respect to the - starting disk number */ - if ( unzlocal_getLong( &us.z_filefunc, us.filestream, &us.offset_central_dir ) != UNZ_OK ) - err = UNZ_ERRNO; + starting disk number */ + if (unzlocal_getLong(&us.z_filefunc, us.filestream, &us.offset_central_dir) != UNZ_OK) err = UNZ_ERRNO; /* zipfile comment length */ - if ( unzlocal_getShort( &us.z_filefunc, us.filestream, &us.gi.size_comment ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&us.z_filefunc, us.filestream, &us.gi.size_comment) != UNZ_OK) err = UNZ_ERRNO; - if ( ( central_pos < us.offset_central_dir + us.size_central_dir ) && - ( err == UNZ_OK ) ) - err = UNZ_BADZIPFILE; + if ((central_pos < us.offset_central_dir + us.size_central_dir) && (err == UNZ_OK)) err = UNZ_BADZIPFILE; - if ( err != UNZ_OK ) + if (err != UNZ_OK) { ZCLOSE( us.z_filefunc, us.filestream ); return NULL; } - us.byte_before_the_zipfile = central_pos - - ( us.offset_central_dir + us.size_central_dir ); + us.byte_before_the_zipfile = central_pos - (us.offset_central_dir + us.size_central_dir); us.central_pos = central_pos; us.pfile_in_zip_read = NULL; us.encrypted = 0; - - s = ( unz_s* )ALLOC( sizeof( unz_s ) ); + s = (unz_s*) ALLOC( sizeof( unz_s ) ); *s = us; - unzGoToFirstFile( ( unzFile )s ); - return ( unzFile )s; + unzGoToFirstFile((unzFile) s); + return (unzFile) s; } - -extern unzFile ZEXPORT unzOpen ( path ) -const char *path; +extern unzFile ZEXPORT unzOpen(path) + const char *path; { - return unzOpen2( path, NULL ); + return unzOpen2(path, NULL); } /* - Close a ZipFile opened with unzipOpen. - If there is files inside the .Zip opened with unzipOpenCurrentFile (see later), - these files MUST be closed with unzipCloseCurrentFile before call unzipClose. - return UNZ_OK if there is no problem. */ -extern int ZEXPORT unzClose ( file ) -unzFile file; + Close a ZipFile opened with unzipOpen. + If there is files inside the .Zip opened with unzipOpenCurrentFile (see later), + these files MUST be closed with unzipCloseCurrentFile before call unzipClose. + return UNZ_OK if there is no problem. */ +extern int ZEXPORT unzClose(file) + unzFile file; { unz_s* s; - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; - if ( s->pfile_in_zip_read != NULL ) - unzCloseCurrentFile( file ); + if (s->pfile_in_zip_read != NULL) unzCloseCurrentFile(file); ZCLOSE( s->z_filefunc, s->filestream ); TRYFREE( s ); return UNZ_OK; } - /* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. */ -extern int ZEXPORT unzGetGlobalInfo ( file, pglobal_info ) -unzFile file; -unz_global_info *pglobal_info; + Write info about the ZipFile in the *pglobal_info structure. + No preparation of the structure is needed + return UNZ_OK if there is no problem. */ +extern int ZEXPORT unzGetGlobalInfo(file, pglobal_info) + unzFile file;unz_global_info *pglobal_info; { unz_s* s; - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; *pglobal_info = s->gi; return UNZ_OK; } - /* - Translate date/time from Dos format to tm_unz (readable more easilty) -*/ -local void unzlocal_DosDateToTmuDate ( ulDosDate, ptm ) -uLong ulDosDate; -tm_unz* ptm; + Translate date/time from Dos format to tm_unz (readable more easilty) + */ +local void unzlocal_DosDateToTmuDate(ulDosDate, ptm) + uLong ulDosDate;tm_unz* ptm; { uLong uDate; - uDate = ( uLong )( ulDosDate >> 16 ); - ptm->tm_mday = ( uInt )( uDate & 0x1f ) ; - ptm->tm_mon = ( uInt )( ( ( ( uDate ) & 0x1E0 ) / 0x20 ) - 1 ) ; - ptm->tm_year = ( uInt )( ( ( uDate & 0x0FE00 ) / 0x0200 ) + 1980 ) ; + uDate = (uLong) (ulDosDate >> 16); + ptm->tm_mday = (uInt) (uDate & 0x1f); + ptm->tm_mon = (uInt) ((((uDate) & 0x1E0) / 0x20) - 1); + ptm->tm_year = (uInt) (((uDate & 0x0FE00) / 0x0200) + 1980); - ptm->tm_hour = ( uInt ) ( ( ulDosDate & 0xF800 ) / 0x800 ); - ptm->tm_min = ( uInt ) ( ( ulDosDate & 0x7E0 ) / 0x20 ) ; - ptm->tm_sec = ( uInt ) ( 2 * ( ulDosDate & 0x1f ) ) ; + ptm->tm_hour = (uInt) ((ulDosDate & 0xF800) / 0x800); + ptm->tm_min = (uInt) ((ulDosDate & 0x7E0) / 0x20); + ptm->tm_sec = (uInt) (2 * (ulDosDate & 0x1f)); } /* - Get Info about the current file in the zipfile, with internal only info -*/ + Get Info about the current file in the zipfile, with internal only info + */ local int unzlocal_GetCurrentFileInfoInternal OF( ( unzFile file, - unz_file_info *pfile_info, - unz_file_info_internal - *pfile_info_internal, - char *szFileName, - uLong fileNameBufferSize, - void *extraField, - uLong extraFieldBufferSize, - char *szComment, - uLong commentBufferSize ) ); + unz_file_info *pfile_info, + unz_file_info_internal + *pfile_info_internal, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize ) ); -local int unzlocal_GetCurrentFileInfoInternal ( file, - pfile_info, - pfile_info_internal, - szFileName, fileNameBufferSize, - extraField, extraFieldBufferSize, - szComment, commentBufferSize ) -unzFile file; -unz_file_info *pfile_info; -unz_file_info_internal *pfile_info_internal; -char *szFileName; -uLong fileNameBufferSize; -void *extraField; -uLong extraFieldBufferSize; -char *szComment; -uLong commentBufferSize; +local int unzlocal_GetCurrentFileInfoInternal(file, pfile_info, pfile_info_internal, szFileName, fileNameBufferSize, + extraField, extraFieldBufferSize, szComment, commentBufferSize) + unzFile file;unz_file_info *pfile_info;unz_file_info_internal *pfile_info_internal;char *szFileName;uLong + fileNameBufferSize;void *extraField;uLong extraFieldBufferSize;char *szComment;uLong commentBufferSize; { unz_s* s; unz_file_info file_info; @@ -597,242 +505,187 @@ uLong commentBufferSize; uLong uMagic; long lSeek = 0; - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; - if ( ZSEEK( s->z_filefunc, s->filestream, - s->pos_in_central_dir + s->byte_before_the_zipfile, - ZLIB_FILEFUNC_SEEK_SET ) != 0 ) - err = UNZ_ERRNO; - + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; + if (ZSEEK( s->z_filefunc, s->filestream, + s->pos_in_central_dir + s->byte_before_the_zipfile, + ZLIB_FILEFUNC_SEEK_SET ) != 0) err = UNZ_ERRNO; /* we check the magic */ - if ( err == UNZ_OK ) + if (err == UNZ_OK) { - if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &uMagic ) != UNZ_OK ) + if (unzlocal_getLong(&s->z_filefunc, s->filestream, &uMagic) != UNZ_OK) err = UNZ_ERRNO; - else if ( uMagic != 0x02014b50 ) - err = UNZ_BADZIPFILE; + else if (uMagic != 0x02014b50) err = UNZ_BADZIPFILE; } - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &file_info.version ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &file_info.version) != UNZ_OK) err = UNZ_ERRNO; - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &file_info.version_needed ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &file_info.version_needed) != UNZ_OK) err = UNZ_ERRNO; - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &file_info.flag ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &file_info.flag) != UNZ_OK) err = UNZ_ERRNO; - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &file_info.compression_method ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &file_info.compression_method) != UNZ_OK) err = UNZ_ERRNO; - if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &file_info.dosDate ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getLong(&s->z_filefunc, s->filestream, &file_info.dosDate) != UNZ_OK) err = UNZ_ERRNO; - unzlocal_DosDateToTmuDate( file_info.dosDate, &file_info.tmu_date ); + unzlocal_DosDateToTmuDate(file_info.dosDate, &file_info.tmu_date); - if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &file_info.crc ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getLong(&s->z_filefunc, s->filestream, &file_info.crc) != UNZ_OK) err = UNZ_ERRNO; - if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &file_info.compressed_size ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getLong(&s->z_filefunc, s->filestream, &file_info.compressed_size) != UNZ_OK) err = UNZ_ERRNO; - if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &file_info.uncompressed_size ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getLong(&s->z_filefunc, s->filestream, &file_info.uncompressed_size) != UNZ_OK) err = UNZ_ERRNO; - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &file_info.size_filename ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &file_info.size_filename) != UNZ_OK) err = UNZ_ERRNO; - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &file_info.size_file_extra ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &file_info.size_file_extra) != UNZ_OK) err = UNZ_ERRNO; - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &file_info.size_file_comment ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &file_info.size_file_comment) != UNZ_OK) err = UNZ_ERRNO; - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &file_info.disk_num_start ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &file_info.disk_num_start) != UNZ_OK) err = UNZ_ERRNO; - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &file_info.internal_fa ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &file_info.internal_fa) != UNZ_OK) err = UNZ_ERRNO; - if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &file_info.external_fa ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getLong(&s->z_filefunc, s->filestream, &file_info.external_fa) != UNZ_OK) err = UNZ_ERRNO; - if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &file_info_internal.offset_curfile ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getLong(&s->z_filefunc, s->filestream, &file_info_internal.offset_curfile) != UNZ_OK) err = UNZ_ERRNO; lSeek += file_info.size_filename; - if ( ( err == UNZ_OK ) && ( szFileName != NULL ) ) + if ((err == UNZ_OK) && (szFileName != NULL)) { - uLong uSizeRead ; - if ( file_info.size_filename < fileNameBufferSize ) + uLong uSizeRead; + if (file_info.size_filename < fileNameBufferSize) { - *( szFileName + file_info.size_filename ) = '\0'; + *(szFileName + file_info.size_filename) = '\0'; uSizeRead = file_info.size_filename; } - else - uSizeRead = fileNameBufferSize; + else uSizeRead = fileNameBufferSize; - if ( ( file_info.size_filename > 0 ) && ( fileNameBufferSize > 0 ) ) - if ( ZREAD( s->z_filefunc, s->filestream, szFileName, uSizeRead ) != uSizeRead ) - err = UNZ_ERRNO; + if ((file_info.size_filename > 0) && (fileNameBufferSize > 0)) if (ZREAD( s->z_filefunc, s->filestream, szFileName, uSizeRead ) + != uSizeRead) err = UNZ_ERRNO; lSeek -= uSizeRead; } - - if ( ( err == UNZ_OK ) && ( extraField != NULL ) ) + if ((err == UNZ_OK) && (extraField != NULL)) { - uLong uSizeRead ; - if ( file_info.size_file_extra < extraFieldBufferSize ) + uLong uSizeRead; + if (file_info.size_file_extra < extraFieldBufferSize) uSizeRead = file_info.size_file_extra; - else - uSizeRead = extraFieldBufferSize; + else uSizeRead = extraFieldBufferSize; - if ( lSeek != 0 ) + if (lSeek != 0) { - if ( ZSEEK( s->z_filefunc, s->filestream, lSeek, ZLIB_FILEFUNC_SEEK_CUR ) == 0 ) + if (ZSEEK( s->z_filefunc, s->filestream, lSeek, ZLIB_FILEFUNC_SEEK_CUR ) == 0) lSeek = 0; - else - err = UNZ_ERRNO; + else err = UNZ_ERRNO; } - if ( ( file_info.size_file_extra > 0 ) && ( extraFieldBufferSize > 0 ) ) - if ( ZREAD( s->z_filefunc, s->filestream, extraField, uSizeRead ) != uSizeRead ) - err = UNZ_ERRNO; + if ((file_info.size_file_extra > 0) && (extraFieldBufferSize > 0)) if (ZREAD( s->z_filefunc, s->filestream, extraField, uSizeRead ) + != uSizeRead) err = UNZ_ERRNO; lSeek += file_info.size_file_extra - uSizeRead; } - else - lSeek += file_info.size_file_extra; + else lSeek += file_info.size_file_extra; - - if ( ( err == UNZ_OK ) && ( szComment != NULL ) ) + if ((err == UNZ_OK) && (szComment != NULL)) { - uLong uSizeRead ; - if ( file_info.size_file_comment < commentBufferSize ) + uLong uSizeRead; + if (file_info.size_file_comment < commentBufferSize) { - *( szComment + file_info.size_file_comment ) = '\0'; + *(szComment + file_info.size_file_comment) = '\0'; uSizeRead = file_info.size_file_comment; } - else - uSizeRead = commentBufferSize; + else uSizeRead = commentBufferSize; - if ( lSeek != 0 ) + if (lSeek != 0) { - if ( ZSEEK( s->z_filefunc, s->filestream, lSeek, ZLIB_FILEFUNC_SEEK_CUR ) == 0 ) + if (ZSEEK( s->z_filefunc, s->filestream, lSeek, ZLIB_FILEFUNC_SEEK_CUR ) == 0) lSeek = 0; - else - err = UNZ_ERRNO; + else err = UNZ_ERRNO; } - if ( ( file_info.size_file_comment > 0 ) && ( commentBufferSize > 0 ) ) - if ( ZREAD( s->z_filefunc, s->filestream, szComment, uSizeRead ) != uSizeRead ) - err = UNZ_ERRNO; + if ((file_info.size_file_comment > 0) && (commentBufferSize > 0)) if (ZREAD( s->z_filefunc, s->filestream, szComment, uSizeRead ) + != uSizeRead) err = UNZ_ERRNO; lSeek += file_info.size_file_comment - uSizeRead; } - else - lSeek += file_info.size_file_comment; + else lSeek += file_info.size_file_comment; - if ( ( err == UNZ_OK ) && ( pfile_info != NULL ) ) - *pfile_info = file_info; + if ((err == UNZ_OK) && (pfile_info != NULL)) *pfile_info = file_info; - if ( ( err == UNZ_OK ) && ( pfile_info_internal != NULL ) ) - *pfile_info_internal = file_info_internal; + if ((err == UNZ_OK) && (pfile_info_internal != NULL)) *pfile_info_internal = file_info_internal; return err; } - - /* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. -*/ -extern int ZEXPORT unzGetCurrentFileInfo ( file, - pfile_info, - szFileName, fileNameBufferSize, - extraField, extraFieldBufferSize, - szComment, commentBufferSize ) -unzFile file; -unz_file_info *pfile_info; -char *szFileName; -uLong fileNameBufferSize; -void *extraField; -uLong extraFieldBufferSize; -char *szComment; -uLong commentBufferSize; + Write info about the ZipFile in the *pglobal_info structure. + No preparation of the structure is needed + return UNZ_OK if there is no problem. + */ +extern int ZEXPORT unzGetCurrentFileInfo(file, pfile_info, szFileName, fileNameBufferSize, extraField, + extraFieldBufferSize, szComment, commentBufferSize) + unzFile file;unz_file_info *pfile_info;char *szFileName;uLong fileNameBufferSize;void *extraField;uLong + extraFieldBufferSize;char *szComment;uLong commentBufferSize; { - return unzlocal_GetCurrentFileInfoInternal( file, pfile_info, NULL, - szFileName, fileNameBufferSize, - extraField, extraFieldBufferSize, - szComment, commentBufferSize ); + return unzlocal_GetCurrentFileInfoInternal(file, pfile_info, NULL, szFileName, fileNameBufferSize, extraField, + extraFieldBufferSize, szComment, commentBufferSize); } /* - Set the current file of the zipfile to the first file. - return UNZ_OK if there is no problem -*/ -extern int ZEXPORT unzGoToFirstFile ( file ) -unzFile file; + Set the current file of the zipfile to the first file. + return UNZ_OK if there is no problem + */ +extern int ZEXPORT unzGoToFirstFile(file) + unzFile file; { int err = UNZ_OK; unz_s* s; - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; s->pos_in_central_dir = s->offset_central_dir; s->num_file = 0; - err = unzlocal_GetCurrentFileInfoInternal( file, &s->cur_file_info, - &s->cur_file_info_internal, - NULL, 0, NULL, 0, NULL, 0 ); - s->current_file_ok = ( err == UNZ_OK ); + err = unzlocal_GetCurrentFileInfoInternal(file, &s->cur_file_info, &s->cur_file_info_internal, NULL, 0, NULL, 0, + NULL, 0); + s->current_file_ok = (err == UNZ_OK); return err; } /* - Set the current file of the zipfile to the next file. - return UNZ_OK if there is no problem - return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. -*/ -extern int ZEXPORT unzGoToNextFile ( file ) -unzFile file; + Set the current file of the zipfile to the next file. + return UNZ_OK if there is no problem + return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. + */ +extern int ZEXPORT unzGoToNextFile(file) + unzFile file; { unz_s* s; int err; - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; - if ( !s->current_file_ok ) - return UNZ_END_OF_LIST_OF_FILE; - if ( s->gi.number_entry != 0xffff ) /* 2^16 files overflow hack */ - if ( s->num_file + 1 == s->gi.number_entry ) - return UNZ_END_OF_LIST_OF_FILE; + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; + if (!s->current_file_ok) return UNZ_END_OF_LIST_OF_FILE; + if (s->gi.number_entry != 0xffff) /* 2^16 files overflow hack */ + if (s->num_file + 1 == s->gi.number_entry) return UNZ_END_OF_LIST_OF_FILE; - s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + - s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ; + s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + s->cur_file_info.size_file_extra + + s->cur_file_info.size_file_comment; s->num_file++; - err = unzlocal_GetCurrentFileInfoInternal( file, &s->cur_file_info, - &s->cur_file_info_internal, - NULL, 0, NULL, 0, NULL, 0 ); - s->current_file_ok = ( err == UNZ_OK ); + err = unzlocal_GetCurrentFileInfoInternal(file, &s->cur_file_info, &s->cur_file_info_internal, NULL, 0, NULL, 0, + NULL, 0); + s->current_file_ok = (err == UNZ_OK); return err; } - /* - Try locate the file szFileName in the zipfile. - For the iCaseSensitivity signification, see unzipStringFileNameCompare + Try locate the file szFileName in the zipfile. + For the iCaseSensitivity signification, see unzipStringFileNameCompare - return value : - UNZ_OK if the file is found. It becomes the current file. - UNZ_END_OF_LIST_OF_FILE if the file is not found -*/ -extern int ZEXPORT unzLocateFile ( file, szFileName, iCaseSensitivity ) -unzFile file; -const char *szFileName; -int iCaseSensitivity; + return value : + UNZ_OK if the file is found. It becomes the current file. + UNZ_END_OF_LIST_OF_FILE if the file is not found + */ +extern int ZEXPORT unzLocateFile(file, szFileName, iCaseSensitivity) + unzFile file;const char *szFileName;int iCaseSensitivity; { unz_s* s; int err; @@ -845,16 +698,12 @@ int iCaseSensitivity; uLong num_fileSaved; uLong pos_in_central_dirSaved; + if (file == NULL) return UNZ_PARAMERROR; - if ( file == NULL ) - return UNZ_PARAMERROR; + if (strlen(szFileName) >= UNZ_MAXFILENAMEINZIP) return UNZ_PARAMERROR; - if ( strlen( szFileName ) >= UNZ_MAXFILENAMEINZIP ) - return UNZ_PARAMERROR; - - s = ( unz_s* )file; - if ( !s->current_file_ok ) - return UNZ_END_OF_LIST_OF_FILE; + s = (unz_s*) file; + if (!s->current_file_ok) return UNZ_END_OF_LIST_OF_FILE; /* Save the current state */ num_fileSaved = s->num_file; @@ -862,113 +711,97 @@ int iCaseSensitivity; cur_file_infoSaved = s->cur_file_info; cur_file_info_internalSaved = s->cur_file_info_internal; - err = unzGoToFirstFile( file ); + err = unzGoToFirstFile(file); - while ( err == UNZ_OK ) + while (err == UNZ_OK) { - char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; - err = unzGetCurrentFileInfo( file, NULL, - szCurrentFileName, sizeof( szCurrentFileName ) - 1, - NULL, 0, NULL, 0 ); - if ( err == UNZ_OK ) + char szCurrentFileName[UNZ_MAXFILENAMEINZIP + 1]; + err = unzGetCurrentFileInfo(file, NULL, szCurrentFileName, sizeof(szCurrentFileName) - 1, NULL, 0, NULL, 0); + if (err == UNZ_OK) { - if ( unzStringFileNameCompare( szCurrentFileName, - szFileName, iCaseSensitivity ) == 0 ) - return UNZ_OK; - err = unzGoToNextFile( file ); + if (unzStringFileNameCompare(szCurrentFileName, szFileName, iCaseSensitivity) == 0) return UNZ_OK; + err = unzGoToNextFile(file); } } /* We failed, so restore the state of the 'current file' to where we * were. */ - s->num_file = num_fileSaved ; - s->pos_in_central_dir = pos_in_central_dirSaved ; + s->num_file = num_fileSaved; + s->pos_in_central_dir = pos_in_central_dirSaved; s->cur_file_info = cur_file_infoSaved; s->cur_file_info_internal = cur_file_info_internalSaved; return err; } +/* + /////////////////////////////////////////// + // Contributed by Ryan Haksi (mailto://cryogen@infoserve.net) + // I need random access + // + // Further optimization could be realized by adding an ability + // to cache the directory in memory. The goal being a single + // comprehensive file read to put the file I need in a memory. + */ /* -/////////////////////////////////////////// -// Contributed by Ryan Haksi (mailto://cryogen@infoserve.net) -// I need random access -// -// Further optimization could be realized by adding an ability -// to cache the directory in memory. The goal being a single -// comprehensive file read to put the file I need in a memory. -*/ + typedef struct unz_file_pos_s + { + uLong pos_in_zip_directory; // offset in file + uLong num_of_file; // # of file + } unz_file_pos; + */ -/* -typedef struct unz_file_pos_s -{ - uLong pos_in_zip_directory; // offset in file - uLong num_of_file; // # of file -} unz_file_pos; -*/ - -extern int ZEXPORT unzGetFilePos( file, file_pos ) -unzFile file; -unz_file_pos* file_pos; +extern int ZEXPORT unzGetFilePos(file, file_pos) + unzFile file;unz_file_pos* file_pos; { unz_s* s; - if ( file == NULL || file_pos == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; - if ( !s->current_file_ok ) - return UNZ_END_OF_LIST_OF_FILE; + if (file == NULL || file_pos == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; + if (!s->current_file_ok) return UNZ_END_OF_LIST_OF_FILE; - file_pos->pos_in_zip_directory = s->pos_in_central_dir; - file_pos->num_of_file = s->num_file; + file_pos->pos_in_zip_directory = s->pos_in_central_dir; + file_pos->num_of_file = s->num_file; return UNZ_OK; } -extern int ZEXPORT unzGoToFilePos( file, file_pos ) -unzFile file; -unz_file_pos* file_pos; +extern int ZEXPORT unzGoToFilePos(file, file_pos) + unzFile file;unz_file_pos* file_pos; { unz_s* s; int err; - if ( file == NULL || file_pos == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; + if (file == NULL || file_pos == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; /* jump to the right spot */ s->pos_in_central_dir = file_pos->pos_in_zip_directory; - s->num_file = file_pos->num_of_file; + s->num_file = file_pos->num_of_file; /* set the current file */ - err = unzlocal_GetCurrentFileInfoInternal( file, &s->cur_file_info, - &s->cur_file_info_internal, - NULL, 0, NULL, 0, NULL, 0 ); + err = unzlocal_GetCurrentFileInfoInternal(file, &s->cur_file_info, &s->cur_file_info_internal, NULL, 0, NULL, 0, + NULL, 0); /* return results */ - s->current_file_ok = ( err == UNZ_OK ); + s->current_file_ok = (err == UNZ_OK); return err; } /* -// Unzip Helper Functions - should be here? -/////////////////////////////////////////// -*/ + // Unzip Helper Functions - should be here? + /////////////////////////////////////////// + */ /* - Read the local header of the current zipfile - Check the coherency of the local header and info in the end of central - directory about this file - store in *piSizeVar the size of extra info in local header - (filename and size of extra field data) -*/ -local int unzlocal_CheckCurrentFileCoherencyHeader ( s, piSizeVar, - poffset_local_extrafield, - psize_local_extrafield ) -unz_s* s; -uInt* piSizeVar; -uLong *poffset_local_extrafield; -uInt *psize_local_extrafield; + Read the local header of the current zipfile + Check the coherency of the local header and info in the end of central + directory about this file + store in *piSizeVar the size of extra info in local header + (filename and size of extra field data) + */ +local int unzlocal_CheckCurrentFileCoherencyHeader(s, piSizeVar, poffset_local_extrafield, psize_local_extrafield) + unz_s* s;uInt* piSizeVar;uLong *poffset_local_extrafield;uInt *psize_local_extrafield; { uLong uMagic, uData, uFlags; uLong size_filename; @@ -979,126 +812,101 @@ uInt *psize_local_extrafield; *poffset_local_extrafield = 0; *psize_local_extrafield = 0; - if ( ZSEEK( s->z_filefunc, s->filestream, s->cur_file_info_internal.offset_curfile + - s->byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET ) != 0 ) - return UNZ_ERRNO; + if (ZSEEK( s->z_filefunc, s->filestream, s->cur_file_info_internal.offset_curfile + + s->byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET ) != 0) return UNZ_ERRNO; - - if ( err == UNZ_OK ) + if (err == UNZ_OK) { - if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &uMagic ) != UNZ_OK ) + if (unzlocal_getLong(&s->z_filefunc, s->filestream, &uMagic) != UNZ_OK) err = UNZ_ERRNO; - else if ( uMagic != 0x04034b50 ) - err = UNZ_BADZIPFILE; + else if (uMagic != 0x04034b50) err = UNZ_BADZIPFILE; } - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &uData ) != UNZ_OK ) - err = UNZ_ERRNO; + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &uData) != UNZ_OK) err = UNZ_ERRNO; /* - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) - err=UNZ_BADZIPFILE; - */ - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &uFlags ) != UNZ_OK ) + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) + err=UNZ_BADZIPFILE; + */ + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &uFlags) != UNZ_OK) err = UNZ_ERRNO; + + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &uData) != UNZ_OK) err = UNZ_ERRNO; + else if ((err == UNZ_OK) && (uData != s->cur_file_info.compression_method)) err = UNZ_BADZIPFILE; - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &uData ) != UNZ_OK ) + if ((err == UNZ_OK) && (s->cur_file_info.compression_method != 0) && (s->cur_file_info.compression_method + != Z_DEFLATED)) err = UNZ_BADZIPFILE; + + if (unzlocal_getLong(&s->z_filefunc, s->filestream, &uData) != UNZ_OK) /* date/time */ + err = UNZ_ERRNO; + + if (unzlocal_getLong(&s->z_filefunc, s->filestream, &uData) != UNZ_OK) /* crc */ err = UNZ_ERRNO; - else if ( ( err == UNZ_OK ) && ( uData != s->cur_file_info.compression_method ) ) - err = UNZ_BADZIPFILE; + else if ((err == UNZ_OK) && (uData != s->cur_file_info.crc) && ((uFlags & 8) == 0)) err = UNZ_BADZIPFILE; - if ( ( err == UNZ_OK ) && ( s->cur_file_info.compression_method != 0 ) && - ( s->cur_file_info.compression_method != Z_DEFLATED ) ) - err = UNZ_BADZIPFILE; - - if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &uData ) != UNZ_OK ) /* date/time */ + if (unzlocal_getLong(&s->z_filefunc, s->filestream, &uData) != UNZ_OK) /* size compr */ err = UNZ_ERRNO; + else if ((err == UNZ_OK) && (uData != s->cur_file_info.compressed_size) && ((uFlags & 8) == 0)) err + = UNZ_BADZIPFILE; - if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &uData ) != UNZ_OK ) /* crc */ + if (unzlocal_getLong(&s->z_filefunc, s->filestream, &uData) != UNZ_OK) /* size uncompr */ err = UNZ_ERRNO; - else if ( ( err == UNZ_OK ) && ( uData != s->cur_file_info.crc ) && - ( ( uFlags & 8 ) == 0 ) ) - err = UNZ_BADZIPFILE; + else if ((err == UNZ_OK) && (uData != s->cur_file_info.uncompressed_size) && ((uFlags & 8) == 0)) err + = UNZ_BADZIPFILE; - if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &uData ) != UNZ_OK ) /* size compr */ + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &size_filename) != UNZ_OK) err = UNZ_ERRNO; - else if ( ( err == UNZ_OK ) && ( uData != s->cur_file_info.compressed_size ) && - ( ( uFlags & 8 ) == 0 ) ) - err = UNZ_BADZIPFILE; + else if ((err == UNZ_OK) && (size_filename != s->cur_file_info.size_filename)) err = UNZ_BADZIPFILE; - if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &uData ) != UNZ_OK ) /* size uncompr */ - err = UNZ_ERRNO; - else if ( ( err == UNZ_OK ) && ( uData != s->cur_file_info.uncompressed_size ) && - ( ( uFlags & 8 ) == 0 ) ) - err = UNZ_BADZIPFILE; + *piSizeVar += (uInt) size_filename; + if (unzlocal_getShort(&s->z_filefunc, s->filestream, &size_extra_field) != UNZ_OK) err = UNZ_ERRNO; + *poffset_local_extrafield = s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + size_filename; + *psize_local_extrafield = (uInt) size_extra_field; - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &size_filename ) != UNZ_OK ) - err = UNZ_ERRNO; - else if ( ( err == UNZ_OK ) && ( size_filename != s->cur_file_info.size_filename ) ) - err = UNZ_BADZIPFILE; - - *piSizeVar += ( uInt )size_filename; - - if ( unzlocal_getShort( &s->z_filefunc, s->filestream, &size_extra_field ) != UNZ_OK ) - err = UNZ_ERRNO; - *poffset_local_extrafield = s->cur_file_info_internal.offset_curfile + - SIZEZIPLOCALHEADER + size_filename; - *psize_local_extrafield = ( uInt )size_extra_field; - - *piSizeVar += ( uInt )size_extra_field; + *piSizeVar += (uInt) size_extra_field; return err; } /* - Open for reading data the current file in the zipfile. - If there is no error and the file is opened, the return value is UNZ_OK. -*/ -extern int ZEXPORT unzOpenCurrentFile3 ( file, method, level, raw, password ) -unzFile file; -int* method; -int* level; -int raw; -const char* password; + Open for reading data the current file in the zipfile. + If there is no error and the file is opened, the return value is UNZ_OK. + */ +extern int ZEXPORT unzOpenCurrentFile3(file, method, level, raw, password) + unzFile file;int* method;int* level;int raw;const char* password; { int err = UNZ_OK; uInt iSizeVar; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; - uLong offset_local_extrafield; /* offset of the local extra field */ - uInt size_local_extrafield; /* size of the local extra field */ + uLong offset_local_extrafield; /* offset of the local extra field */ + uInt size_local_extrafield; /* size of the local extra field */ # ifndef NOUNCRYPT char source[12]; # else if ( password != NULL ) - return UNZ_PARAMERROR; + return UNZ_PARAMERROR; # endif - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; - if ( !s->current_file_ok ) - return UNZ_PARAMERROR; + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; + if (!s->current_file_ok) return UNZ_PARAMERROR; - if ( s->pfile_in_zip_read != NULL ) - unzCloseCurrentFile( file ); + if (s->pfile_in_zip_read != NULL) unzCloseCurrentFile(file); - if ( unzlocal_CheckCurrentFileCoherencyHeader( s, &iSizeVar, - &offset_local_extrafield, &size_local_extrafield ) != UNZ_OK ) - return UNZ_BADZIPFILE; + if (unzlocal_CheckCurrentFileCoherencyHeader(s, &iSizeVar, &offset_local_extrafield, &size_local_extrafield) + != UNZ_OK) return UNZ_BADZIPFILE; - pfile_in_zip_read_info = ( file_in_zip_read_info_s* ) - ALLOC( sizeof( file_in_zip_read_info_s ) ); - if ( pfile_in_zip_read_info == NULL ) - return UNZ_INTERNALERROR; + pfile_in_zip_read_info = (file_in_zip_read_info_s*) ALLOC( sizeof( file_in_zip_read_info_s ) ); + if (pfile_in_zip_read_info == NULL) return UNZ_INTERNALERROR; - pfile_in_zip_read_info->read_buffer = ( char* )ALLOC( UNZ_BUFSIZE ); + pfile_in_zip_read_info->read_buffer = (char*) ALLOC( UNZ_BUFSIZE ); pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield; pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield; pfile_in_zip_read_info->pos_local_extrafield = 0; pfile_in_zip_read_info->raw = raw; - if ( pfile_in_zip_read_info->read_buffer == NULL ) + if (pfile_in_zip_read_info->read_buffer == NULL) { TRYFREE( pfile_in_zip_read_info ); return UNZ_INTERNALERROR; @@ -1106,51 +914,47 @@ const char* password; pfile_in_zip_read_info->stream_initialised = 0; - if ( method != NULL ) - *method = ( int )s->cur_file_info.compression_method; + if (method != NULL) *method = (int) s->cur_file_info.compression_method; - if ( level != NULL ) + if (level != NULL) { *level = 6; - switch ( s->cur_file_info.flag & 0x06 ) + switch (s->cur_file_info.flag & 0x06) { - case 6 : + case 6: *level = 1; break; - case 4 : + case 4: *level = 2; break; - case 2 : + case 2: *level = 9; break; } } - if ( ( s->cur_file_info.compression_method != 0 ) && - ( s->cur_file_info.compression_method != Z_DEFLATED ) ) - err = UNZ_BADZIPFILE; + if ((s->cur_file_info.compression_method != 0) && (s->cur_file_info.compression_method != Z_DEFLATED)) err + = UNZ_BADZIPFILE; pfile_in_zip_read_info->crc32_wait = s->cur_file_info.crc; pfile_in_zip_read_info->crc32 = 0; - pfile_in_zip_read_info->compression_method = - s->cur_file_info.compression_method; + pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method; pfile_in_zip_read_info->filestream = s->filestream; pfile_in_zip_read_info->z_filefunc = s->z_filefunc; pfile_in_zip_read_info->byte_before_the_zipfile = s->byte_before_the_zipfile; pfile_in_zip_read_info->stream.total_out = 0; - if ( ( s->cur_file_info.compression_method == Z_DEFLATED ) && - ( !raw ) ) + if ((s->cur_file_info.compression_method == Z_DEFLATED) && (!raw)) { - pfile_in_zip_read_info->stream.zalloc = ( alloc_func )0; - pfile_in_zip_read_info->stream.zfree = ( free_func )0; - pfile_in_zip_read_info->stream.opaque = ( voidpf )0; - pfile_in_zip_read_info->stream.next_in = ( voidpf )0; + pfile_in_zip_read_info->stream.zalloc = (alloc_func) 0; + pfile_in_zip_read_info->stream.zfree = (free_func) 0; + pfile_in_zip_read_info->stream.opaque = (voidpf) 0; + pfile_in_zip_read_info->stream.next_in = (voidpf) 0; pfile_in_zip_read_info->stream.avail_in = 0; err = inflateInit2( &pfile_in_zip_read_info->stream, -MAX_WBITS ); - if ( err == Z_OK ) + if (err == Z_OK) pfile_in_zip_read_info->stream_initialised = 1; else { @@ -1165,35 +969,28 @@ const char* password; * size of both compressed and uncompressed data */ } - pfile_in_zip_read_info->rest_read_compressed = - s->cur_file_info.compressed_size ; - pfile_in_zip_read_info->rest_read_uncompressed = - s->cur_file_info.uncompressed_size ; + pfile_in_zip_read_info->rest_read_compressed = s->cur_file_info.compressed_size; + pfile_in_zip_read_info->rest_read_uncompressed = s->cur_file_info.uncompressed_size; + pfile_in_zip_read_info->pos_in_zipfile = s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + iSizeVar; - pfile_in_zip_read_info->pos_in_zipfile = - s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + - iSizeVar; - - pfile_in_zip_read_info->stream.avail_in = ( uInt )0; + pfile_in_zip_read_info->stream.avail_in = (uInt) 0; s->pfile_in_zip_read = pfile_in_zip_read_info; # ifndef NOUNCRYPT - if ( password != NULL ) + if (password != NULL) { int i; s->pcrc_32_tab = get_crc_table(); - init_keys( password, s->keys, s->pcrc_32_tab ); - if ( ZSEEK( s->z_filefunc, s->filestream, - s->pfile_in_zip_read->pos_in_zipfile + - s->pfile_in_zip_read->byte_before_the_zipfile, - SEEK_SET ) != 0 ) - return UNZ_INTERNALERROR; - if ( ZREAD( s->z_filefunc, s->filestream, source, 12 ) < 12 ) - return UNZ_INTERNALERROR; + init_keys(password, s->keys, s->pcrc_32_tab); + if (ZSEEK( s->z_filefunc, s->filestream, + s->pfile_in_zip_read->pos_in_zipfile + + s->pfile_in_zip_read->byte_before_the_zipfile, + SEEK_SET ) != 0) return UNZ_INTERNALERROR; + if (ZREAD( s->z_filefunc, s->filestream, source, 12 ) < 12) return UNZ_INTERNALERROR; - for ( i = 0; i < 12; i++ ) + for (i = 0; i < 12; i++) zdecode( s->keys, s->pcrc_32_tab, source[i] ); s->pfile_in_zip_read->pos_in_zipfile += 12; @@ -1201,146 +998,116 @@ const char* password; } # endif - return UNZ_OK; } -extern int ZEXPORT unzOpenCurrentFile ( file ) -unzFile file; +extern int ZEXPORT unzOpenCurrentFile(file) + unzFile file; { - return unzOpenCurrentFile3( file, NULL, NULL, 0, NULL ); + return unzOpenCurrentFile3(file, NULL, NULL, 0, NULL); } -extern int ZEXPORT unzOpenCurrentFilePassword ( file, password ) -unzFile file; -const char* password; +extern int ZEXPORT unzOpenCurrentFilePassword(file, password) + unzFile file;const char* password; { - return unzOpenCurrentFile3( file, NULL, NULL, 0, password ); + return unzOpenCurrentFile3(file, NULL, NULL, 0, password); } -extern int ZEXPORT unzOpenCurrentFile2 ( file, method, level, raw ) -unzFile file; -int* method; -int* level; -int raw; +extern int ZEXPORT unzOpenCurrentFile2(file, method, level, raw) + unzFile file;int* method;int* level;int raw; { - return unzOpenCurrentFile3( file, method, level, raw, NULL ); + return unzOpenCurrentFile3(file, method, level, raw, NULL); } /* - Read bytes from the current file. - buf contain buffer where data must be copied - len the size of buf. + Read bytes from the current file. + buf contain buffer where data must be copied + len the size of buf. - return the number of byte copied if somes bytes are copied - return 0 if the end of file was reached - return <0 with error code if there is an error - (UNZ_ERRNO for IO error, or zLib error for uncompress error) -*/ -extern int ZEXPORT unzReadCurrentFile ( file, buf, len ) -unzFile file; -voidp buf; -unsigned len; + return the number of byte copied if somes bytes are copied + return 0 if the end of file was reached + return <0 with error code if there is an error + (UNZ_ERRNO for IO error, or zLib error for uncompress error) + */ +extern int ZEXPORT unzReadCurrentFile(file, buf, len) + unzFile file;voidp buf;unsigned len; { int err = UNZ_OK; uInt iRead = 0; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; pfile_in_zip_read_info = s->pfile_in_zip_read; - if ( pfile_in_zip_read_info == NULL ) - return UNZ_PARAMERROR; + if (pfile_in_zip_read_info == NULL) return UNZ_PARAMERROR; + if ((pfile_in_zip_read_info->read_buffer == NULL)) return UNZ_END_OF_LIST_OF_FILE; + if (len == 0) return 0; - if ( ( pfile_in_zip_read_info->read_buffer == NULL ) ) - return UNZ_END_OF_LIST_OF_FILE; - if ( len == 0 ) - return 0; + pfile_in_zip_read_info->stream.next_out = (Bytef*) buf; - pfile_in_zip_read_info->stream.next_out = ( Bytef* )buf; + pfile_in_zip_read_info->stream.avail_out = (uInt) len; - pfile_in_zip_read_info->stream.avail_out = ( uInt )len; + if ((len > pfile_in_zip_read_info->rest_read_uncompressed) && (!(pfile_in_zip_read_info->raw))) pfile_in_zip_read_info->stream.avail_out + = (uInt) pfile_in_zip_read_info->rest_read_uncompressed; - if ( ( len > pfile_in_zip_read_info->rest_read_uncompressed ) && - ( !( pfile_in_zip_read_info->raw ) ) ) - pfile_in_zip_read_info->stream.avail_out = - ( uInt )pfile_in_zip_read_info->rest_read_uncompressed; + if ((len > pfile_in_zip_read_info->rest_read_compressed + pfile_in_zip_read_info->stream.avail_in) + && (pfile_in_zip_read_info->raw)) pfile_in_zip_read_info->stream.avail_out + = (uInt) pfile_in_zip_read_info->rest_read_compressed + pfile_in_zip_read_info->stream.avail_in; - if ( ( len > pfile_in_zip_read_info->rest_read_compressed + - pfile_in_zip_read_info->stream.avail_in ) && - ( pfile_in_zip_read_info->raw ) ) - pfile_in_zip_read_info->stream.avail_out = - ( uInt )pfile_in_zip_read_info->rest_read_compressed + - pfile_in_zip_read_info->stream.avail_in; - - while ( pfile_in_zip_read_info->stream.avail_out > 0 ) + while (pfile_in_zip_read_info->stream.avail_out > 0) { - if ( ( pfile_in_zip_read_info->stream.avail_in == 0 ) && - ( pfile_in_zip_read_info->rest_read_compressed > 0 ) ) + if ((pfile_in_zip_read_info->stream.avail_in == 0) && (pfile_in_zip_read_info->rest_read_compressed > 0)) { uInt uReadThis = UNZ_BUFSIZE; - if ( pfile_in_zip_read_info->rest_read_compressed < uReadThis ) - uReadThis = ( uInt )pfile_in_zip_read_info->rest_read_compressed; - if ( uReadThis == 0 ) - return UNZ_EOF; - if ( ZSEEK( pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - pfile_in_zip_read_info->pos_in_zipfile + - pfile_in_zip_read_info->byte_before_the_zipfile, - ZLIB_FILEFUNC_SEEK_SET ) != 0 ) - return UNZ_ERRNO; - if ( ZREAD( pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - pfile_in_zip_read_info->read_buffer, - uReadThis ) != uReadThis ) - return UNZ_ERRNO; - + if (pfile_in_zip_read_info->rest_read_compressed < uReadThis) uReadThis + = (uInt) pfile_in_zip_read_info->rest_read_compressed; + if (uReadThis == 0) return UNZ_EOF; + if (ZSEEK( pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->pos_in_zipfile + + pfile_in_zip_read_info->byte_before_the_zipfile, + ZLIB_FILEFUNC_SEEK_SET ) != 0) return UNZ_ERRNO; + if (ZREAD( pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->read_buffer, + uReadThis ) != uReadThis) return UNZ_ERRNO; # ifndef NOUNCRYPT - if ( s->encrypted ) + if (s->encrypted) { uInt i; - for ( i = 0; i < uReadThis; i++ ) - pfile_in_zip_read_info->read_buffer[i] = - zdecode( s->keys, s->pcrc_32_tab, - pfile_in_zip_read_info->read_buffer[i] ); + for (i = 0; i < uReadThis; i++) + pfile_in_zip_read_info->read_buffer[i] = zdecode( s->keys, s->pcrc_32_tab, + pfile_in_zip_read_info->read_buffer[i] ); } # endif - pfile_in_zip_read_info->pos_in_zipfile += uReadThis; pfile_in_zip_read_info->rest_read_compressed -= uReadThis; - pfile_in_zip_read_info->stream.next_in = - ( Bytef* )pfile_in_zip_read_info->read_buffer; - pfile_in_zip_read_info->stream.avail_in = ( uInt )uReadThis; + pfile_in_zip_read_info->stream.next_in = (Bytef*) pfile_in_zip_read_info->read_buffer; + pfile_in_zip_read_info->stream.avail_in = (uInt) uReadThis; } - if ( ( pfile_in_zip_read_info->compression_method == 0 ) || ( pfile_in_zip_read_info->raw ) ) + if ((pfile_in_zip_read_info->compression_method == 0) || (pfile_in_zip_read_info->raw)) { - uInt uDoCopy, i ; + uInt uDoCopy, i; - if ( ( pfile_in_zip_read_info->stream.avail_in == 0 ) && - ( pfile_in_zip_read_info->rest_read_compressed == 0 ) ) - return ( iRead == 0 ) ? UNZ_EOF : iRead; + if ((pfile_in_zip_read_info->stream.avail_in == 0) && (pfile_in_zip_read_info->rest_read_compressed == 0)) return (iRead + == 0) ? UNZ_EOF : iRead; - if ( pfile_in_zip_read_info->stream.avail_out < - pfile_in_zip_read_info->stream.avail_in ) - uDoCopy = pfile_in_zip_read_info->stream.avail_out ; - else - uDoCopy = pfile_in_zip_read_info->stream.avail_in ; + if (pfile_in_zip_read_info->stream.avail_out < pfile_in_zip_read_info->stream.avail_in) + uDoCopy = pfile_in_zip_read_info->stream.avail_out; + else uDoCopy = pfile_in_zip_read_info->stream.avail_in; - for ( i = 0; i < uDoCopy; i++ ) - *( pfile_in_zip_read_info->stream.next_out + i ) = - *( pfile_in_zip_read_info->stream.next_in + i ); + for (i = 0; i < uDoCopy; i++) + *(pfile_in_zip_read_info->stream.next_out + i) = *(pfile_in_zip_read_info->stream.next_in + i); - pfile_in_zip_read_info->crc32 = crc32( pfile_in_zip_read_info->crc32, - pfile_in_zip_read_info->stream.next_out, - uDoCopy ); + pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32, + pfile_in_zip_read_info->stream.next_out, uDoCopy); pfile_in_zip_read_info->rest_read_uncompressed -= uDoCopy; pfile_in_zip_read_info->stream.avail_in -= uDoCopy; pfile_in_zip_read_info->stream.avail_out -= uDoCopy; @@ -1360,176 +1127,143 @@ unsigned len; bufBefore = pfile_in_zip_read_info->stream.next_out; /* - if ((pfile_in_zip_read_info->rest_read_uncompressed == - pfile_in_zip_read_info->stream.avail_out) && - (pfile_in_zip_read_info->rest_read_compressed == 0)) - flush = Z_FINISH; - */ - err = inflate( &pfile_in_zip_read_info->stream, flush ); + if ((pfile_in_zip_read_info->rest_read_uncompressed == + pfile_in_zip_read_info->stream.avail_out) && + (pfile_in_zip_read_info->rest_read_compressed == 0)) + flush = Z_FINISH; + */ + err = inflate(&pfile_in_zip_read_info->stream, flush); - if ( ( err >= 0 ) && ( pfile_in_zip_read_info->stream.msg != NULL ) ) - err = Z_DATA_ERROR; + if ((err >= 0) && (pfile_in_zip_read_info->stream.msg != NULL)) err = Z_DATA_ERROR; uTotalOutAfter = pfile_in_zip_read_info->stream.total_out; uOutThis = uTotalOutAfter - uTotalOutBefore; - pfile_in_zip_read_info->crc32 = - crc32( pfile_in_zip_read_info->crc32, bufBefore, - ( uInt )( uOutThis ) ); + pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32, bufBefore, (uInt) (uOutThis)); - pfile_in_zip_read_info->rest_read_uncompressed -= - uOutThis; + pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis; - iRead += ( uInt )( uTotalOutAfter - uTotalOutBefore ); + iRead += (uInt) (uTotalOutAfter - uTotalOutBefore); - if ( err == Z_STREAM_END ) - return ( iRead == 0 ) ? UNZ_EOF : iRead; - if ( err != Z_OK ) - break; + if (err == Z_STREAM_END) return (iRead == 0) ? UNZ_EOF : iRead; + if (err != Z_OK) break; } } - if ( err == Z_OK ) - return iRead; + if (err == Z_OK) return iRead; return err; } - /* - Give the current position in uncompressed data -*/ -extern z_off_t ZEXPORT unztell ( file ) -unzFile file; + Give the current position in uncompressed data + */ +extern z_off_t ZEXPORT unztell(file) + unzFile file; { unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; pfile_in_zip_read_info = s->pfile_in_zip_read; - if ( pfile_in_zip_read_info == NULL ) - return UNZ_PARAMERROR; + if (pfile_in_zip_read_info == NULL) return UNZ_PARAMERROR; - return ( z_off_t )pfile_in_zip_read_info->stream.total_out; + return (z_off_t ) pfile_in_zip_read_info->stream.total_out; } - /* - return 1 if the end of file was reached, 0 elsewhere -*/ -extern int ZEXPORT unzeof ( file ) -unzFile file; + return 1 if the end of file was reached, 0 elsewhere + */ +extern int ZEXPORT unzeof(file) + unzFile file; { unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; pfile_in_zip_read_info = s->pfile_in_zip_read; - if ( pfile_in_zip_read_info == NULL ) - return UNZ_PARAMERROR; + if (pfile_in_zip_read_info == NULL) return UNZ_PARAMERROR; - if ( pfile_in_zip_read_info->rest_read_uncompressed == 0 ) + if (pfile_in_zip_read_info->rest_read_uncompressed == 0) return 1; - else - return 0; + else return 0; } - - /* - Read extra field from the current file (opened by unzOpenCurrentFile) - This is the local-header version of the extra field (sometimes, there is - more info in the local-header version than in the central-header) + Read extra field from the current file (opened by unzOpenCurrentFile) + This is the local-header version of the extra field (sometimes, there is + more info in the local-header version than in the central-header) - if buf==NULL, it return the size of the local extra field that can be read + if buf==NULL, it return the size of the local extra field that can be read - if buf!=NULL, len is the size of the buffer, the extra header is copied in - buf. - the return value is the number of bytes copied in buf, or (if <0) - the error code -*/ -extern int ZEXPORT unzGetLocalExtrafield ( file, buf, len ) -unzFile file; -voidp buf; -unsigned len; + if buf!=NULL, len is the size of the buffer, the extra header is copied in + buf. + the return value is the number of bytes copied in buf, or (if <0) + the error code + */ +extern int ZEXPORT unzGetLocalExtrafield(file, buf, len) + unzFile file;voidp buf;unsigned len; { unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; uInt read_now; uLong size_to_read; - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; pfile_in_zip_read_info = s->pfile_in_zip_read; - if ( pfile_in_zip_read_info == NULL ) - return UNZ_PARAMERROR; + if (pfile_in_zip_read_info == NULL) return UNZ_PARAMERROR; - size_to_read = ( pfile_in_zip_read_info->size_local_extrafield - - pfile_in_zip_read_info->pos_local_extrafield ); + size_to_read = (pfile_in_zip_read_info->size_local_extrafield - pfile_in_zip_read_info->pos_local_extrafield); - if ( buf == NULL ) - return ( int )size_to_read; + if (buf == NULL) return (int) size_to_read; - if ( len > size_to_read ) - read_now = ( uInt )size_to_read; - else - read_now = ( uInt )len ; + if (len > size_to_read) + read_now = (uInt) size_to_read; + else read_now = (uInt) len; - if ( read_now == 0 ) - return 0; + if (read_now == 0) return 0; - if ( ZSEEK( pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - pfile_in_zip_read_info->offset_local_extrafield + - pfile_in_zip_read_info->pos_local_extrafield, - ZLIB_FILEFUNC_SEEK_SET ) != 0 ) - return UNZ_ERRNO; + if (ZSEEK( pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->offset_local_extrafield + + pfile_in_zip_read_info->pos_local_extrafield, + ZLIB_FILEFUNC_SEEK_SET ) != 0) return UNZ_ERRNO; - if ( ZREAD( pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - buf, read_now ) != read_now ) - return UNZ_ERRNO; + if (ZREAD( pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + buf, read_now ) != read_now) return UNZ_ERRNO; - return ( int )read_now; + return (int) read_now; } /* - Close the file in zip opened with unzipOpenCurrentFile - Return UNZ_CRCERROR if all the file was read but the CRC is not good -*/ -extern int ZEXPORT unzCloseCurrentFile ( file ) -unzFile file; + Close the file in zip opened with unzipOpenCurrentFile + Return UNZ_CRCERROR if all the file was read but the CRC is not good + */ +extern int ZEXPORT unzCloseCurrentFile(file) + unzFile file; { int err = UNZ_OK; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; pfile_in_zip_read_info = s->pfile_in_zip_read; - if ( pfile_in_zip_read_info == NULL ) - return UNZ_PARAMERROR; + if (pfile_in_zip_read_info == NULL) return UNZ_PARAMERROR; - - if ( ( pfile_in_zip_read_info->rest_read_uncompressed == 0 ) && - ( !pfile_in_zip_read_info->raw ) ) + if ((pfile_in_zip_read_info->rest_read_uncompressed == 0) && (!pfile_in_zip_read_info->raw)) { - if ( pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait ) - err = UNZ_CRCERROR; + if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait) err = UNZ_CRCERROR; } - TRYFREE( pfile_in_zip_read_info->read_buffer ); pfile_in_zip_read_info->read_buffer = NULL; - if ( pfile_in_zip_read_info->stream_initialised ) - inflateEnd( &pfile_in_zip_read_info->stream ); + if (pfile_in_zip_read_info->stream_initialised) inflateEnd(&pfile_in_zip_read_info->stream); pfile_in_zip_read_info->stream_initialised = 0; TRYFREE( pfile_in_zip_read_info ); @@ -1539,75 +1273,60 @@ unzFile file; return err; } - /* - Get the global comment string of the ZipFile, in the szComment buffer. - uSizeBuf is the size of the szComment buffer. - return the number of byte copied or an error code <0 -*/ -extern int ZEXPORT unzGetGlobalComment ( file, szComment, uSizeBuf ) -unzFile file; -char *szComment; -uLong uSizeBuf; + Get the global comment string of the ZipFile, in the szComment buffer. + uSizeBuf is the size of the szComment buffer. + return the number of byte copied or an error code <0 + */ +extern int ZEXPORT unzGetGlobalComment(file, szComment, uSizeBuf) + unzFile file;char *szComment;uLong uSizeBuf; { unz_s* s; - uLong uReadThis ; - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; + uLong uReadThis; + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; uReadThis = uSizeBuf; - if ( uReadThis > s->gi.size_comment ) - uReadThis = s->gi.size_comment; + if (uReadThis > s->gi.size_comment) uReadThis = s->gi.size_comment; - if ( ZSEEK( s->z_filefunc, s->filestream, s->central_pos + 22, ZLIB_FILEFUNC_SEEK_SET ) != 0 ) - return UNZ_ERRNO; + if (ZSEEK( s->z_filefunc, s->filestream, s->central_pos + 22, ZLIB_FILEFUNC_SEEK_SET ) != 0) return UNZ_ERRNO; - if ( uReadThis > 0 ) + if (uReadThis > 0) { *szComment = '\0'; - if ( ZREAD( s->z_filefunc, s->filestream, szComment, uReadThis ) != uReadThis ) - return UNZ_ERRNO; + if (ZREAD( s->z_filefunc, s->filestream, szComment, uReadThis ) != uReadThis) return UNZ_ERRNO; } - if ( ( szComment != NULL ) && ( uSizeBuf > s->gi.size_comment ) ) - *( szComment + s->gi.size_comment ) = '\0'; - return ( int )uReadThis; + if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) *(szComment + s->gi.size_comment) = '\0'; + return (int) uReadThis; } /* Additions by RX '2004 */ -extern uLong ZEXPORT unzGetOffset ( file ) -unzFile file; +extern uLong ZEXPORT unzGetOffset(file) + unzFile file; { unz_s* s; - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; - if ( !s->current_file_ok ) - return 0; - if ( s->gi.number_entry != 0 && s->gi.number_entry != 0xffff ) - if ( s->num_file == s->gi.number_entry ) - return 0; + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; + if (!s->current_file_ok) return 0; + if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff) if (s->num_file == s->gi.number_entry) return 0; return s->pos_in_central_dir; } -extern int ZEXPORT unzSetOffset ( file, pos ) -unzFile file; -uLong pos; +extern int ZEXPORT unzSetOffset(file, pos) + unzFile file;uLong pos; { unz_s* s; int err; - if ( file == NULL ) - return UNZ_PARAMERROR; - s = ( unz_s* )file; + if (file == NULL) return UNZ_PARAMERROR; + s = (unz_s*) file; s->pos_in_central_dir = pos; - s->num_file = s->gi.number_entry; /* hack */ - err = unzlocal_GetCurrentFileInfoInternal( file, &s->cur_file_info, - &s->cur_file_info_internal, - NULL, 0, NULL, 0, NULL, 0 ); - s->current_file_ok = ( err == UNZ_OK ); + s->num_file = s->gi.number_entry; /* hack */ + err = unzlocal_GetCurrentFileInfoInternal(file, &s->cur_file_info, &s->cur_file_info_internal, NULL, 0, NULL, 0, + NULL, 0); + s->current_file_ok = (err == UNZ_OK); return err; } diff --git a/source/unzip/unzip.h b/source/unzip/unzip.h index e18a7470..feffed58 100644 --- a/source/unzip/unzip.h +++ b/source/unzip/unzip.h @@ -1,46 +1,46 @@ /* unzip.h -- IO for uncompress .zip files using zlib - Version 1.01e, February 12th, 2005 + Version 1.01e, February 12th, 2005 - Copyright (C) 1998-2005 Gilles Vollant + Copyright (C) 1998-2005 Gilles Vollant - This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g - WinZip, InfoZip tools and compatible. + This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g + WinZip, InfoZip tools and compatible. - Multi volume ZipFile (span) are not supported. - Encryption compatible with pkzip 2.04g only supported - Old compressions used by old PKZip 1.x are not supported + Multi volume ZipFile (span) are not supported. + Encryption compatible with pkzip 2.04g only supported + Old compressions used by old PKZip 1.x are not supported - I WAIT FEEDBACK at mail info@winimage.com - Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution + I WAIT FEEDBACK at mail info@winimage.com + Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution - Condition of use and distribution are the same than zlib : + Condition of use and distribution are the same than zlib : - 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. + 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: + 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. + 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. -*/ + */ /* for more info about .ZIP format, see - http://www.info-zip.org/pub/infozip/doc/appnote-981119-iz.zip - http://www.info-zip.org/pub/infozip/doc/ - PkWare has also a specification at : - ftp://ftp.pkware.com/probdesc.zip -*/ + http://www.info-zip.org/pub/infozip/doc/appnote-981119-iz.zip + http://www.info-zip.org/pub/infozip/doc/ + PkWare has also a specification at : + ftp://ftp.pkware.com/probdesc.zip + */ #ifndef _unz_H #define _unz_H @@ -60,17 +60,16 @@ extern "C" #if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP) /* like the STRICT of WIN32, we define a pointer that cannot be converted - from (void*) without cast */ + from (void*) without cast */ typedef struct TagunzFile__ { int unused; - } unzFile__; + }unzFile__; typedef unzFile__ *unzFile; #else typedef voidp unzFile; #endif - #define UNZ_OK (0) #define UNZ_END_OF_LIST_OF_FILE (-100) #define UNZ_ERRNO (Z_ERRNO) @@ -83,263 +82,257 @@ extern "C" /* tm_unz contain date/time info */ typedef struct tm_unz_s { - uInt tm_sec; /* seconds after the minute - [0,59] */ - uInt tm_min; /* minutes after the hour - [0,59] */ - uInt tm_hour; /* hours since midnight - [0,23] */ - uInt tm_mday; /* day of the month - [1,31] */ - uInt tm_mon; /* months since January - [0,11] */ - uInt tm_year; /* years - [1980..2044] */ + uInt tm_sec; /* seconds after the minute - [0,59] */ + uInt tm_min; /* minutes after the hour - [0,59] */ + uInt tm_hour; /* hours since midnight - [0,23] */ + uInt tm_mday; /* day of the month - [1,31] */ + uInt tm_mon; /* months since January - [0,11] */ + uInt tm_year; /* years - [1980..2044] */ } tm_unz; /* unz_global_info structure contain global data about the ZIPfile - These data comes from the end of central dir */ + These data comes from the end of central dir */ typedef struct unz_global_info_s { - uLong number_entry; /* total number of entries in - the central dir on this disk */ - uLong size_comment; /* size of the global comment of the zipfile */ + uLong number_entry; /* total number of entries in + the central dir on this disk */ + uLong size_comment; /* size of the global comment of the zipfile */ } unz_global_info; - /* unz_file_info contain information about a file in the zipfile */ typedef struct unz_file_info_s { - uLong version; /* version made by 2 bytes */ - uLong version_needed; /* version needed to extract 2 bytes */ - uLong flag; /* general purpose bit flag 2 bytes */ - uLong compression_method; /* compression method 2 bytes */ - uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ - uLong crc; /* crc-32 4 bytes */ - uLong compressed_size; /* compressed size 4 bytes */ - uLong uncompressed_size; /* uncompressed size 4 bytes */ - uLong size_filename; /* filename length 2 bytes */ - uLong size_file_extra; /* extra field length 2 bytes */ - uLong size_file_comment; /* file comment length 2 bytes */ + uLong version; /* version made by 2 bytes */ + uLong version_needed; /* version needed to extract 2 bytes */ + uLong flag; /* general purpose bit flag 2 bytes */ + uLong compression_method; /* compression method 2 bytes */ + uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ + uLong crc; /* crc-32 4 bytes */ + uLong compressed_size; /* compressed size 4 bytes */ + uLong uncompressed_size; /* uncompressed size 4 bytes */ + uLong size_filename; /* filename length 2 bytes */ + uLong size_file_extra; /* extra field length 2 bytes */ + uLong size_file_comment; /* file comment length 2 bytes */ - uLong disk_num_start; /* disk number start 2 bytes */ - uLong internal_fa; /* internal file attributes 2 bytes */ - uLong external_fa; /* external file attributes 4 bytes */ + uLong disk_num_start; /* disk number start 2 bytes */ + uLong internal_fa; /* internal file attributes 2 bytes */ + uLong external_fa; /* external file attributes 4 bytes */ - tm_unz tmu_date; + tm_unz tmu_date; } unz_file_info; extern int ZEXPORT unzStringFileNameCompare OF ( ( const char* fileName1, - const char* fileName2, - int iCaseSensitivity ) ); + const char* fileName2, + int iCaseSensitivity ) ); /* - Compare two filename (fileName1,fileName2). - If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) - If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi - or strcasecmp) - If iCaseSenisivity = 0, case sensitivity is defaut of your operating system - (like 1 on Unix, 2 on Windows) - */ - + Compare two filename (fileName1,fileName2). + If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) + If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi + or strcasecmp) + If iCaseSenisivity = 0, case sensitivity is defaut of your operating system + (like 1 on Unix, 2 on Windows) + */ extern unzFile ZEXPORT unzOpen OF( ( const char *path ) ); /* - Open a Zip file. path contain the full pathname (by example, - on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer - "zlib/zlib113.zip". - If the zipfile cannot be opened (file don't exist or in not valid), the - return value is NULL. - Else, the return value is a unzFile Handle, usable with other function - of this unzip package. - */ + Open a Zip file. path contain the full pathname (by example, + on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer + "zlib/zlib113.zip". + If the zipfile cannot be opened (file don't exist or in not valid), the + return value is NULL. + Else, the return value is a unzFile Handle, usable with other function + of this unzip package. + */ extern unzFile ZEXPORT unzOpen2 OF( ( const char *path, - zlib_filefunc_def* pzlib_filefunc_def ) ); + zlib_filefunc_def* pzlib_filefunc_def ) ); /* - Open a Zip file, like unzOpen, but provide a set of file low level API - for read/write the zip file (see ioapi.h) - */ + Open a Zip file, like unzOpen, but provide a set of file low level API + for read/write the zip file (see ioapi.h) + */ extern int ZEXPORT unzClose OF( ( unzFile file ) ); /* - Close a ZipFile opened with unzipOpen. - If there is files inside the .Zip opened with unzOpenCurrentFile (see later), - these files MUST be closed with unzipCloseCurrentFile before call unzipClose. - return UNZ_OK if there is no problem. */ + Close a ZipFile opened with unzipOpen. + If there is files inside the .Zip opened with unzOpenCurrentFile (see later), + these files MUST be closed with unzipCloseCurrentFile before call unzipClose. + return UNZ_OK if there is no problem. */ extern int ZEXPORT unzGetGlobalInfo OF( ( unzFile file, - unz_global_info *pglobal_info ) ); + unz_global_info *pglobal_info ) ); /* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. */ - + Write info about the ZipFile in the *pglobal_info structure. + No preparation of the structure is needed + return UNZ_OK if there is no problem. */ extern int ZEXPORT unzGetGlobalComment OF( ( unzFile file, - char *szComment, - uLong uSizeBuf ) ); + char *szComment, + uLong uSizeBuf ) ); /* - Get the global comment string of the ZipFile, in the szComment buffer. - uSizeBuf is the size of the szComment buffer. - return the number of byte copied or an error code <0 - */ - + Get the global comment string of the ZipFile, in the szComment buffer. + uSizeBuf is the size of the szComment buffer. + return the number of byte copied or an error code <0 + */ /***************************************************************************/ /* Unzip package allow you browse the directory of the zipfile */ extern int ZEXPORT unzGoToFirstFile OF( ( unzFile file ) ); /* - Set the current file of the zipfile to the first file. - return UNZ_OK if there is no problem - */ + Set the current file of the zipfile to the first file. + return UNZ_OK if there is no problem + */ extern int ZEXPORT unzGoToNextFile OF( ( unzFile file ) ); /* - Set the current file of the zipfile to the next file. - return UNZ_OK if there is no problem - return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. - */ + Set the current file of the zipfile to the next file. + return UNZ_OK if there is no problem + return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. + */ extern int ZEXPORT unzLocateFile OF( ( unzFile file, - const char *szFileName, - int iCaseSensitivity ) ); + const char *szFileName, + int iCaseSensitivity ) ); /* - Try locate the file szFileName in the zipfile. - For the iCaseSensitivity signification, see unzStringFileNameCompare - - return value : - UNZ_OK if the file is found. It becomes the current file. - UNZ_END_OF_LIST_OF_FILE if the file is not found - */ + Try locate the file szFileName in the zipfile. + For the iCaseSensitivity signification, see unzStringFileNameCompare + return value : + UNZ_OK if the file is found. It becomes the current file. + UNZ_END_OF_LIST_OF_FILE if the file is not found + */ /* ****************************************** */ /* Ryan supplied functions */ /* unz_file_info contain information about a file in the zipfile */ typedef struct unz_file_pos_s { - uLong pos_in_zip_directory; /* offset in zip file directory */ - uLong num_of_file; /* # of file */ - } unz_file_pos; + uLong pos_in_zip_directory; /* offset in zip file directory */ + uLong num_of_file; /* # of file */ + }unz_file_pos; extern int ZEXPORT unzGetFilePos( - unzFile file, - unz_file_pos* file_pos ); + unzFile file, + unz_file_pos* file_pos ); extern int ZEXPORT unzGoToFilePos( - unzFile file, - unz_file_pos* file_pos ); + unzFile file, + unz_file_pos* file_pos ); /* ****************************************** */ extern int ZEXPORT unzGetCurrentFileInfo OF( ( unzFile file, - unz_file_info *pfile_info, - char *szFileName, - uLong fileNameBufferSize, - void *extraField, - uLong extraFieldBufferSize, - char *szComment, - uLong commentBufferSize ) ); + unz_file_info *pfile_info, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize ) ); /* - Get Info about the current file - if pfile_info!=NULL, the *pfile_info structure will contain somes info about - the current file - if szFileName!=NULL, the filemane string will be copied in szFileName - (fileNameBufferSize is the size of the buffer) - if extraField!=NULL, the extra field information will be copied in extraField - (extraFieldBufferSize is the size of the buffer). - This is the Central-header version of the extra field - if szComment!=NULL, the comment string of the file will be copied in szComment - (commentBufferSize is the size of the buffer) - */ + Get Info about the current file + if pfile_info!=NULL, the *pfile_info structure will contain somes info about + the current file + if szFileName!=NULL, the filemane string will be copied in szFileName + (fileNameBufferSize is the size of the buffer) + if extraField!=NULL, the extra field information will be copied in extraField + (extraFieldBufferSize is the size of the buffer). + This is the Central-header version of the extra field + if szComment!=NULL, the comment string of the file will be copied in szComment + (commentBufferSize is the size of the buffer) + */ /***************************************************************************/ /* for reading the content of the current zipfile, you can open it, read data - from it, and close it (you can close it before reading all the file) - */ + from it, and close it (you can close it before reading all the file) + */ extern int ZEXPORT unzOpenCurrentFile OF( ( unzFile file ) ); /* - Open for reading data the current file in the zipfile. - If there is no error, the return value is UNZ_OK. - */ + Open for reading data the current file in the zipfile. + If there is no error, the return value is UNZ_OK. + */ extern int ZEXPORT unzOpenCurrentFilePassword OF( ( unzFile file, - const char* password ) ); + const char* password ) ); /* - Open for reading data the current file in the zipfile. - password is a crypting password - If there is no error, the return value is UNZ_OK. - */ + Open for reading data the current file in the zipfile. + password is a crypting password + If there is no error, the return value is UNZ_OK. + */ extern int ZEXPORT unzOpenCurrentFile2 OF( ( unzFile file, - int* method, - int* level, - int raw ) ); + int* method, + int* level, + int raw ) ); /* - Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) - if raw==1 - *method will receive method of compression, *level will receive level of - compression - note : you can set level parameter as NULL (if you did not want known level, - but you CANNOT set method parameter as NULL - */ + Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) + if raw==1 + *method will receive method of compression, *level will receive level of + compression + note : you can set level parameter as NULL (if you did not want known level, + but you CANNOT set method parameter as NULL + */ extern int ZEXPORT unzOpenCurrentFile3 OF( ( unzFile file, - int* method, - int* level, - int raw, - const char* password ) ); + int* method, + int* level, + int raw, + const char* password ) ); /* - Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) - if raw==1 - *method will receive method of compression, *level will receive level of - compression - note : you can set level parameter as NULL (if you did not want known level, - but you CANNOT set method parameter as NULL - */ - + Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) + if raw==1 + *method will receive method of compression, *level will receive level of + compression + note : you can set level parameter as NULL (if you did not want known level, + but you CANNOT set method parameter as NULL + */ extern int ZEXPORT unzCloseCurrentFile OF( ( unzFile file ) ); /* - Close the file in zip opened with unzOpenCurrentFile - Return UNZ_CRCERROR if all the file was read but the CRC is not good - */ + Close the file in zip opened with unzOpenCurrentFile + Return UNZ_CRCERROR if all the file was read but the CRC is not good + */ extern int ZEXPORT unzReadCurrentFile OF( ( unzFile file, - voidp buf, - unsigned len ) ); + voidp buf, + unsigned len ) ); /* - Read bytes from the current file (opened by unzOpenCurrentFile) - buf contain buffer where data must be copied - len the size of buf. + Read bytes from the current file (opened by unzOpenCurrentFile) + buf contain buffer where data must be copied + len the size of buf. - return the number of byte copied if somes bytes are copied - return 0 if the end of file was reached - return <0 with error code if there is an error - (UNZ_ERRNO for IO error, or zLib error for uncompress error) - */ + return the number of byte copied if somes bytes are copied + return 0 if the end of file was reached + return <0 with error code if there is an error + (UNZ_ERRNO for IO error, or zLib error for uncompress error) + */ extern z_off_t ZEXPORT unztell OF( ( unzFile file ) ); /* - Give the current position in uncompressed data - */ + Give the current position in uncompressed data + */ extern int ZEXPORT unzeof OF( ( unzFile file ) ); /* - return 1 if the end of file was reached, 0 elsewhere - */ + return 1 if the end of file was reached, 0 elsewhere + */ extern int ZEXPORT unzGetLocalExtrafield OF( ( unzFile file, - voidp buf, - unsigned len ) ); + voidp buf, + unsigned len ) ); /* - Read extra field from the current file (opened by unzOpenCurrentFile) - This is the local-header version of the extra field (sometimes, there is - more info in the local-header version than in the central-header) + Read extra field from the current file (opened by unzOpenCurrentFile) + This is the local-header version of the extra field (sometimes, there is + more info in the local-header version than in the central-header) - if buf==NULL, it return the size of the local extra field + if buf==NULL, it return the size of the local extra field - if buf!=NULL, len is the size of the buffer, the extra header is copied in - buf. - the return value is the number of bytes copied in buf, or (if <0) - the error code - */ + if buf!=NULL, len is the size of the buffer, the extra header is copied in + buf. + the return value is the number of bytes copied in buf, or (if <0) + the error code + */ /***************************************************************************/ @@ -349,10 +342,8 @@ extern "C" /* Set the current file offset */ extern int ZEXPORT unzSetOffset ( unzFile file, uLong pos ); - - #ifdef __cplusplus -} + } #endif #endif /* _unz_H */ diff --git a/source/usbloader/GameList.cpp b/source/usbloader/GameList.cpp index f86fcba6..941fbe3c 100644 --- a/source/usbloader/GameList.cpp +++ b/source/usbloader/GameList.cpp @@ -1,26 +1,26 @@ /**************************************************************************** -* Copyright (C) 2010 -* 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. -***************************************************************************/ + * Copyright (C) 2010 + * 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. + ***************************************************************************/ #include #include #include @@ -44,14 +44,13 @@ void GameList::clear() FullGameList.clear(); FilteredList.clear(); //! Clear memory of the vector completely - std::vector().swap( FilteredList ); - std::vector().swap( FullGameList ); + std::vector().swap(FilteredList); + std::vector().swap(FullGameList); } -struct discHdr * GameList::at( int i ) +struct discHdr * GameList::at(int i) { - if ( i < 0 || i >= ( int ) FilteredList.size() ) - return NULL; + if (i < 0 || i >= (int) FilteredList.size()) return NULL; return FilteredList[i]; } @@ -64,120 +63,108 @@ int GameList::ReadGameList() // Retrieve all stuff from WBFS u32 cnt; - int ret = WBFS_GetCount( &cnt ); - if ( ret < 0 ) - return -1; + int ret = WBFS_GetCount(&cnt); + if (ret < 0) return -1; /* Buffer length */ - u32 len = sizeof( struct discHdr ) * cnt; + u32 len = sizeof(struct discHdr) * cnt; /* Allocate memory */ - struct discHdr *buffer = ( struct discHdr * ) allocate_memory( len ); - if ( !buffer ) - return -1; + struct discHdr *buffer = (struct discHdr *) allocate_memory( len ); + if (!buffer) return -1; /* Clear buffer */ - memset( buffer, 0, len ); + memset(buffer, 0, len); /* Get header list */ - ret = WBFS_GetHeaders( buffer, cnt, sizeof( struct discHdr ) ); - if ( ret < 0 ) + ret = WBFS_GetHeaders(buffer, cnt, sizeof(struct discHdr)); + if (ret < 0) { - if ( buffer ) - free( buffer ); + if (buffer) free(buffer); return -1; } - FullGameList.resize( cnt ); - memcpy( &FullGameList[0], buffer, len ); + FullGameList.resize(cnt); + memcpy(&FullGameList[0], buffer, len); - free( buffer ); + free(buffer); return LoadUnfiltered(); } static bool WCharSortCallback(const wchar_t char1, const wchar_t char2) { - if(char2 == 0) - return true; - if(char1 == 0) - return false; + if (char2 == 0) return true; + if (char1 == 0) return false; return char2 > char1; } -int GameList::FilterList( const wchar_t * gameFilter ) +int GameList::FilterList(const wchar_t * gameFilter) { - if ( FullGameList.size() == 0 ) - ReadGameList(); - if ( gameFilter ) - GameFilter.assign( gameFilter ); + if (FullGameList.size() == 0) ReadGameList(); + if (gameFilter) GameFilter.assign(gameFilter); FilteredList.clear(); AvailableSearchChars.clear(); - for ( u32 i = 0; i < FullGameList.size(); ++i ) + for (u32 i = 0; i < FullGameList.size(); ++i) { struct discHdr *header = &FullGameList[i]; /* Register game */ - NewTitles::Instance()->CheckGame( header->id ); + NewTitles::Instance()->CheckGame(header->id); /* Filters */ - if ( Settings.fave ) + if (Settings.fave) { - struct Game_NUM* game_num = CFG_get_game_num( header->id ); - if ( !game_num || game_num->favorite == 0 ) - continue; + 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 ( strncasecmp( ( char* )header->id, "__CFG_", 6 ) == 0 ) - continue; + if (strncasecmp((char*) header->id, "__CFG_", 6) == 0) continue; - if ( Settings.parentalcontrol && !Settings.godmode ) - if ( get_block( header ) >= Settings.parentalcontrol ) - continue; + if (Settings.parentalcontrol && !Settings.godmode) if (get_block(header) >= Settings.parentalcontrol) continue; /* Other parental control method */ - if ( Settings.parentalcontrol == 0 && Settings.godmode == 0 && Settings.Parental.enabled == 1 ) + 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 ) ) + s32 rating = GetRatingForGame((char *) header->id); + if ((rating != -1 && rating > Settings.Parental.rating) || (rating == -1 && get_pegi_block(header) + > Settings.Parental.rating)) { continue; } } - wchar_t *gameName = charToWideChar( get_title( header ) ); + wchar_t *gameName = charToWideChar(get_title(header)); - if ( gameName && *GameFilter.c_str() ) + if (gameName && *GameFilter.c_str()) { - if ( wcsnicmp( gameName, GameFilter.c_str(), GameFilter.size() ) != 0 ) + if (wcsnicmp(gameName, GameFilter.c_str(), GameFilter.size()) != 0) { - delete [] gameName; + delete[] gameName; continue; } } - if ( gameName ) + if (gameName) { - if ( wcslen( gameName ) > GameFilter.size() && AvailableSearchChars.find( gameName[GameFilter.size()] ) == std::string::npos ) - AvailableSearchChars.push_back( gameName[GameFilter.size()] ); - delete [] gameName; + if (wcslen(gameName) > GameFilter.size() && AvailableSearchChars.find(gameName[GameFilter.size()]) + == std::string::npos) AvailableSearchChars.push_back(gameName[GameFilter.size()]); + delete[] gameName; } - FilteredList.push_back( header ); + FilteredList.push_back(header); } NewTitles::Instance()->Save(); - AvailableSearchChars.push_back( L'\0' ); + AvailableSearchChars.push_back(L'\0'); - if ( FilteredList.size() < 2 ) - AvailableSearchChars.clear(); + if (FilteredList.size() < 2) AvailableSearchChars.clear(); SortList(); @@ -186,37 +173,35 @@ int GameList::FilterList( const wchar_t * gameFilter ) int GameList::LoadUnfiltered() { - if ( FullGameList.size() == 0 ) - ReadGameList(); + if (FullGameList.size() == 0) ReadGameList(); GameFilter.clear(); AvailableSearchChars.clear(); FilteredList.clear(); - for ( u32 i = 0; i < FullGameList.size(); ++i ) + for (u32 i = 0; i < FullGameList.size(); ++i) { struct discHdr *header = &FullGameList[i]; /* Register game */ - NewTitles::Instance()->CheckGame( header->id ); + NewTitles::Instance()->CheckGame(header->id); - wchar_t *gameName = charToWideChar( get_title( header ) ); - if ( gameName ) + wchar_t *gameName = charToWideChar(get_title(header)); + if (gameName) { - if ( wcslen( gameName ) > GameFilter.size() && AvailableSearchChars.find( gameName[GameFilter.size()] ) == std::string::npos ) - AvailableSearchChars.push_back( gameName[GameFilter.size()] ); - delete [] gameName; + if (wcslen(gameName) > GameFilter.size() && AvailableSearchChars.find(gameName[GameFilter.size()]) + == std::string::npos) AvailableSearchChars.push_back(gameName[GameFilter.size()]); + delete[] gameName; } - FilteredList.push_back( header ); + FilteredList.push_back(header); } NewTitles::Instance()->Save(); - AvailableSearchChars.push_back( L'\0' ); + AvailableSearchChars.push_back(L'\0'); - if ( FilteredList.size() < 2 ) - AvailableSearchChars.clear(); + if (FilteredList.size() < 2) AvailableSearchChars.clear(); SortList(); @@ -225,24 +210,23 @@ int GameList::LoadUnfiltered() void GameList::SortList() { - if ( FilteredList.size() < 2 ) - return; + if (FilteredList.size() < 2) return; - if ( Settings.sort == PLAYCOUNT ) + if (Settings.sort == PLAYCOUNT) { - std::sort( FilteredList.begin(), FilteredList.end(), PlaycountSortCallback ); + std::sort(FilteredList.begin(), FilteredList.end(), PlaycountSortCallback); } - else if ( Settings.fave ) + else if (Settings.fave) { - std::sort( FilteredList.begin(), FilteredList.end(), FavoriteSortCallback ); + std::sort(FilteredList.begin(), FilteredList.end(), FavoriteSortCallback); } else { - std::sort( FilteredList.begin(), FilteredList.end(), NameSortCallback ); + std::sort(FilteredList.begin(), FilteredList.end(), NameSortCallback); } - if ( AvailableSearchChars.size() > 1 ) - std::sort( AvailableSearchChars.begin(), AvailableSearchChars.end(), WCharSortCallback ); + if (AvailableSearchChars.size() > 1) std::sort(AvailableSearchChars.begin(), AvailableSearchChars.end(), + WCharSortCallback); } @@ -253,34 +237,28 @@ bool GameList::NameSortCallback(const struct discHdr *a, const struct discHdr *b bool GameList::PlaycountSortCallback(const struct discHdr *a, const struct discHdr *b) { - struct Game_NUM* game_num1 = CFG_get_game_num( a->id ); - struct Game_NUM* game_num2 = CFG_get_game_num( b->id ); + struct Game_NUM* game_num1 = CFG_get_game_num(a->id); + struct Game_NUM* game_num2 = CFG_get_game_num(b->id); int count1 = 0, count2 = 0; - if (game_num1) - count1 = game_num1->count; - if (game_num2) - count2 = game_num2->count; + if (game_num1) count1 = game_num1->count; + if (game_num2) count2 = game_num2->count; - if (count1 == count2) - return NameSortCallback(a, b); + if (count1 == count2) return NameSortCallback(a, b); return (count1 > count2); } bool GameList::FavoriteSortCallback(const struct discHdr *a, const struct discHdr *b) { - struct Game_NUM* game_num1 = CFG_get_game_num( a->id ); - struct Game_NUM* game_num2 = CFG_get_game_num( b->id ); + struct Game_NUM* game_num1 = CFG_get_game_num(a->id); + struct Game_NUM* game_num2 = CFG_get_game_num(b->id); int fav1 = 0, fav2 = 0; - if (game_num1) - fav1 = game_num1->favorite; - if (game_num2) - fav2 = game_num2->favorite; + if (game_num1) fav1 = game_num1->favorite; + if (game_num2) fav2 = game_num2->favorite; - if (fav1 == fav2) - return NameSortCallback(a, b); + if (fav1 == fav2) return NameSortCallback(a, b); return (fav1 > fav2); } diff --git a/source/usbloader/GameList.h b/source/usbloader/GameList.h index 2d23a6a2..58f6b737 100644 --- a/source/usbloader/GameList.h +++ b/source/usbloader/GameList.h @@ -10,20 +10,40 @@ class GameList public: GameList(); int ReadGameList(); - int size() { return FilteredList.size(); }; - int GameCount() { return FullGameList.size(); }; - int FilterList( const wchar_t * gameFilter = NULL ); + int size() + { + return FilteredList.size(); + } + ; + int GameCount() + { + return FullGameList.size(); + } + ; + int FilterList(const wchar_t * gameFilter = NULL); int LoadUnfiltered(); - struct discHdr * at( int i ); - struct discHdr * operator[]( int i ) { return at( i ); }; - const wchar_t * GetCurrentFilter() { return GameFilter.c_str(); }; - const wchar_t * GetAvailableSearchChars() { return AvailableSearchChars.c_str(); }; + struct discHdr * at(int i); + struct discHdr * operator[](int i) + { + return at(i); + } + ; + const wchar_t * GetCurrentFilter() + { + return GameFilter.c_str(); + } + ; + const wchar_t * GetAvailableSearchChars() + { + return AvailableSearchChars.c_str(); + } + ; void SortList(); void clear(); protected: - static bool NameSortCallback( const struct discHdr *a, const struct discHdr *b ); - static bool PlaycountSortCallback( const struct discHdr *a, const struct discHdr *b ); - static bool FavoriteSortCallback( const struct discHdr *a, const struct discHdr *b ); + static bool NameSortCallback(const struct discHdr *a, const struct discHdr *b); + static bool PlaycountSortCallback(const struct discHdr *a, const struct discHdr *b); + static bool FavoriteSortCallback(const struct discHdr *a, const struct discHdr *b); wString AvailableSearchChars; wString GameFilter; diff --git a/source/usbloader/alternatedol.c b/source/usbloader/alternatedol.c index cae1de0a..32bc337c 100644 --- a/source/usbloader/alternatedol.c +++ b/source/usbloader/alternatedol.c @@ -13,7 +13,7 @@ extern u8 mountMethod; /** Alternate dolloader made by WiiPower modified by dimok **/ -bool Load_Dol( void **buffer, int* dollen, char * filepath ) +bool Load_Dol(void **buffer, int* dollen, char * filepath) { int ret; FILE* file; @@ -21,46 +21,46 @@ bool Load_Dol( void **buffer, int* dollen, char * filepath ) char fullpath[200]; char gameidbuffer6[7]; - memset( gameidbuffer6, 0, 7 ); - memcpy( gameidbuffer6, ( char* )0x80000000, 6 ); - snprintf( fullpath, 200, "%s%s.dol", filepath, gameidbuffer6 ); + memset(gameidbuffer6, 0, 7); + memcpy(gameidbuffer6, (char*) 0x80000000, 6); + snprintf(fullpath, 200, "%s%s.dol", filepath, gameidbuffer6); -// SDCard_Init(); -// USBDevice_Init(); + // SDCard_Init(); + // USBDevice_Init(); - file = fopen( fullpath, "rb" ); + file = fopen(fullpath, "rb"); - if ( file == NULL ) + if (file == NULL) { - fclose( file ); + fclose(file); // SDCard_deInit(); // USBDevice_deInit(); return false; } int filesize; - fseek( file, 0, SEEK_END ); - filesize = ftell( file ); - fseek( file, 0, SEEK_SET ); + fseek(file, 0, SEEK_END); + filesize = ftell(file); + fseek(file, 0, SEEK_SET); - dol_buffer = malloc( filesize ); - if ( dol_buffer == NULL ) + dol_buffer = malloc(filesize); + if (dol_buffer == NULL) { - fclose( file ); + fclose(file); // SDCard_deInit(); // USBDevice_deInit(); return false; } - ret = fread( dol_buffer, 1, filesize, file ); - if ( ret != filesize ) + ret = fread(dol_buffer, 1, filesize, file); + if (ret != filesize) { - free( dol_buffer ); - fclose( file ); + free(dol_buffer); + fclose(file); // SDCard_deInit(); // USBDevice_deInit(); return false; } - fclose( file ); + fclose(file); // SDCard_deInit(); // USBDevice_deInit(); @@ -69,19 +69,21 @@ bool Load_Dol( void **buffer, int* dollen, char * filepath ) return true; } -bool Remove_001_Protection( void *Address, int Size ) +bool Remove_001_Protection(void *Address, int Size) { - u8 SearchPattern[16] = { 0x40, 0x82, 0x00, 0x0C, 0x38, 0x60, 0x00, 0x01, 0x48, 0x00, 0x02, 0x44, 0x38, 0x61, 0x00, 0x18 }; - u8 PatchData[16] = { 0x40, 0x82, 0x00, 0x04, 0x38, 0x60, 0x00, 0x01, 0x48, 0x00, 0x02, 0x44, 0x38, 0x61, 0x00, 0x18 }; + u8 SearchPattern[16] = { 0x40, 0x82, 0x00, 0x0C, 0x38, 0x60, 0x00, 0x01, 0x48, 0x00, 0x02, 0x44, 0x38, 0x61, 0x00, + 0x18 }; + u8 PatchData[16] = + { 0x40, 0x82, 0x00, 0x04, 0x38, 0x60, 0x00, 0x01, 0x48, 0x00, 0x02, 0x44, 0x38, 0x61, 0x00, 0x18 }; void *Addr = Address; void *Addr_end = Address + Size; - while ( Addr <= Addr_end - sizeof( SearchPattern ) ) + while (Addr <= Addr_end - sizeof(SearchPattern)) { - if ( memcmp( Addr, SearchPattern, sizeof( SearchPattern ) ) == 0 ) + if (memcmp(Addr, SearchPattern, sizeof(SearchPattern)) == 0) { - memcpy( Addr, PatchData, sizeof( PatchData ) ); + memcpy(Addr, PatchData, sizeof(PatchData)); return true; } Addr += 4; @@ -104,38 +106,39 @@ typedef struct _dolheader static dolheader *dolfile; - -u32 load_dol_image( void *dolstart, u8 videoSelected, u8 patchcountrystring, u8 vipatch, u8 cheat ) +u32 load_dol_image(void *dolstart, u8 videoSelected, u8 patchcountrystring, u8 vipatch, u8 cheat) { u32 i; - if ( dolstart ) + if (dolstart) { - dolfile = ( dolheader * ) dolstart; - for ( i = 0; i < 7; i++ ) + dolfile = (dolheader *) dolstart; + for (i = 0; i < 7; i++) { - if ( ( !dolfile->text_size[i] ) || ( dolfile->text_start[i] < 0x100 ) ) continue; + if ((!dolfile->text_size[i]) || (dolfile->text_start[i] < 0x100)) continue; - ICInvalidateRange ( ( void * ) dolfile->text_start[i], dolfile->text_size[i] ); - memmove ( ( void * ) dolfile->text_start[i], dolstart + dolfile->text_pos[i], dolfile->text_size[i] ); - gamepatches( ( void * ) dolfile->text_start[i], dolfile->text_size[i], videoSelected, patchcountrystring, vipatch, cheat ); - Remove_001_Protection( ( void * ) dolfile->data_start[i], dolfile->data_size[i] ); + ICInvalidateRange((void *) dolfile->text_start[i], dolfile->text_size[i]); + memmove((void *) dolfile->text_start[i], dolstart + dolfile->text_pos[i], dolfile->text_size[i]); + gamepatches((void *) dolfile->text_start[i], dolfile->text_size[i], videoSelected, patchcountrystring, + vipatch, cheat); + Remove_001_Protection((void *) dolfile->data_start[i], dolfile->data_size[i]); } - for ( i = 0; i < 11; i++ ) + for (i = 0; i < 11; i++) { - if ( ( !dolfile->data_size[i] ) || ( dolfile->data_start[i] < 0x100 ) ) continue; + if ((!dolfile->data_size[i]) || (dolfile->data_start[i] < 0x100)) continue; - memmove ( ( void * ) dolfile->data_start[i], dolstart + dolfile->data_pos[i], dolfile->data_size[i] ); - gamepatches( ( void * ) dolfile->data_start[i], dolfile->data_size[i], videoSelected, patchcountrystring, vipatch, cheat ); - Remove_001_Protection( ( void * ) dolfile->data_start[i], dolfile->data_size[i] ); - DCFlushRangeNoSync ( ( void * ) dolfile->data_start[i], dolfile->data_size[i] ); + memmove((void *) dolfile->data_start[i], dolstart + dolfile->data_pos[i], dolfile->data_size[i]); + gamepatches((void *) dolfile->data_start[i], dolfile->data_size[i], videoSelected, patchcountrystring, + vipatch, cheat); + Remove_001_Protection((void *) dolfile->data_start[i], dolfile->data_size[i]); + DCFlushRangeNoSync((void *) dolfile->data_start[i], dolfile->data_size[i]); } /* - memset ((void *) dolfile->bss_start, 0, dolfile->bss_size); - DCFlushRange((void *) dolfile->bss_start, dolfile->bss_size); - */ + memset ((void *) dolfile->bss_start, 0, dolfile->bss_size); + DCFlushRange((void *) dolfile->bss_start, dolfile->bss_size); + */ return dolfile->entry_point; } return 0; @@ -144,11 +147,11 @@ u32 load_dol_image( void *dolstart, u8 videoSelected, u8 patchcountrystring, u8 static int i; static int phase; -u32 load_dol_start( void *dolstart ) +u32 load_dol_start(void *dolstart) { - if ( dolstart ) + if (dolstart) { - dolfile = ( dolheader * )dolstart; + dolfile = (dolheader *) dolstart; return dolfile->entry_point; } else @@ -156,25 +159,25 @@ u32 load_dol_start( void *dolstart ) return 0; } - memset( ( void * )dolfile->bss_start, 0, dolfile->bss_size ); - DCFlushRange( ( void * )dolfile->bss_start, dolfile->bss_size ); + memset((void *) dolfile->bss_start, 0, dolfile->bss_size); + DCFlushRange((void *) dolfile->bss_start, dolfile->bss_size); phase = 0; i = 0; } -bool load_dol_image_modified( void **offset, u32 *pos, u32 *len ) +bool load_dol_image_modified(void **offset, u32 *pos, u32 *len) { - if ( phase == 0 ) + if (phase == 0) { - if ( i == 7 ) + if (i == 7) { phase = 1; i = 0; } else { - if ( ( !dolfile->text_size[i] ) || ( dolfile->text_start[i] < 0x100 ) ) + if ((!dolfile->text_size[i]) || (dolfile->text_start[i] < 0x100)) { *offset = 0; *pos = 0; @@ -182,7 +185,7 @@ bool load_dol_image_modified( void **offset, u32 *pos, u32 *len ) } else { - *offset = ( void * )dolfile->text_start[i]; + *offset = (void *) dolfile->text_start[i]; *pos = dolfile->text_pos[i]; *len = dolfile->text_size[i]; } @@ -191,15 +194,15 @@ bool load_dol_image_modified( void **offset, u32 *pos, u32 *len ) } } - if ( phase == 1 ) + if (phase == 1) { - if ( i == 11 ) + if (i == 11) { phase = 2; return false; } - if ( ( !dolfile->data_size[i] ) || ( dolfile->data_start[i] < 0x100 ) ) + if ((!dolfile->data_size[i]) || (dolfile->data_start[i] < 0x100)) { *offset = 0; *pos = 0; @@ -207,7 +210,7 @@ bool load_dol_image_modified( void **offset, u32 *pos, u32 *len ) } else { - *offset = ( void * )dolfile->data_start[i]; + *offset = (void *) dolfile->data_start[i]; *pos = dolfile->data_pos[i]; *len = dolfile->data_size[i]; } @@ -217,36 +220,38 @@ bool load_dol_image_modified( void **offset, u32 *pos, u32 *len ) return false; } static vu32 dvddone = 0; -void __dvd_readidcb( s32 result ) +void __dvd_readidcb(s32 result) { dvddone = result; } -u32 Load_Dol_from_disc( u32 doloffset, u8 videoSelected, u8 patchcountrystring, u8 vipatch, u8 cheat ) +u32 Load_Dol_from_disc(u32 doloffset, u8 videoSelected, u8 patchcountrystring, u8 vipatch, u8 cheat) { int ret; void *dol_header; u32 entrypoint; - dol_header = memalign( 32, sizeof( dolheader ) ); - if ( dol_header == NULL ) + dol_header = memalign(32, sizeof(dolheader)); + if (dol_header == NULL) { return -1; } - if ( !mountMethod )ret = WDVD_Read( dol_header, sizeof( dolheader ), ( doloffset << 2 ) ); + if (!mountMethod) + ret = WDVD_Read(dol_header, sizeof(dolheader), (doloffset << 2)); else { dvddone = 0; - ret = bwDVD_LowRead( dol_header, sizeof( dolheader ), doloffset, __dvd_readidcb ); - while ( ret >= 0 && dvddone == 0 ); + ret = bwDVD_LowRead(dol_header, sizeof(dolheader), doloffset, __dvd_readidcb); + while (ret >= 0 && dvddone == 0) + ; } - entrypoint = load_dol_start( dol_header ); + entrypoint = load_dol_start(dol_header); - if ( entrypoint == 0 ) + if (entrypoint == 0) { - free( dol_header ); + free(dol_header); return -1; } @@ -254,21 +259,21 @@ u32 Load_Dol_from_disc( u32 doloffset, u8 videoSelected, u8 patchcountrystring, u32 pos; u32 len; - while ( load_dol_image_modified( &offset, &pos, &len ) ) + while (load_dol_image_modified(&offset, &pos, &len)) { - if ( len != 0 ) + if (len != 0) { - ret = WDVD_Read( offset, len, ( doloffset << 2 ) + pos ); + ret = WDVD_Read(offset, len, (doloffset << 2) + pos); - gamepatches( offset, len, videoSelected, patchcountrystring, vipatch, cheat ); + gamepatches(offset, len, videoSelected, patchcountrystring, vipatch, cheat); - Remove_001_Protection( offset, len ); + Remove_001_Protection(offset, len); - DCFlushRange( offset, len ); + DCFlushRange(offset, len); } } - free( dol_header ); + free(dol_header); return entrypoint; diff --git a/source/usbloader/alternatedol.h b/source/usbloader/alternatedol.h index 56f2d604..6ca15869 100644 --- a/source/usbloader/alternatedol.h +++ b/source/usbloader/alternatedol.h @@ -8,10 +8,11 @@ extern "C" /* not the full path is needed here, the path where the dol is */ - bool Load_Dol( void **buffer, int* dollen, char * path, u8 videoSelected, u8 patchcountrystring, u8 vipatch, u8 cheat ); - bool Remove_001_Protection( void *Address, int Size ); - u32 load_dol_image( void * dolstart ); - u32 Load_Dol_from_disc( u32 doloffset, u8 videoSelected, u8 patchcountrystring, u8 vipatch, u8 cheat ); + bool Load_Dol(void **buffer, int* dollen, char * path, u8 videoSelected, u8 patchcountrystring, u8 vipatch, + u8 cheat); + bool Remove_001_Protection(void *Address, int Size); + u32 load_dol_image(void * dolstart); + u32 Load_Dol_from_disc(u32 doloffset, u8 videoSelected, u8 patchcountrystring, u8 vipatch, u8 cheat); #ifdef __cplusplus } diff --git a/source/usbloader/apploader.c b/source/usbloader/apploader.c index ac4a6ea4..c38dcef6 100644 --- a/source/usbloader/apploader.c +++ b/source/usbloader/apploader.c @@ -19,14 +19,13 @@ extern bool geckoinit; /* Apploader function pointers */ -typedef int ( *app_main )( void **dst, int *size, int *offset ); -typedef void ( *app_init )( void ( *report )( const char *fmt, ... ) ); -typedef void *( *app_final )(); -typedef void ( *app_entry )( void ( **init )( void ( *report )( const char *fmt, ... ) ), int ( **main )(), void *( **final )() ); +typedef int (*app_main)(void **dst, int *size, int *offset); +typedef void (*app_init)(void(*report)(const char *fmt, ...)); +typedef void *(*app_final)(); +typedef void (*app_entry)(void(**init)(void(*report)(const char *fmt, ...)), int(**main)(), void *(**final)()); /* Apploader pointers */ -static u8 *appldr = ( u8 * )0x81200000; - +static u8 *appldr = (u8 *) 0x81200000; /* Constants */ #define APPLDR_OFFSET 0x2440 @@ -34,133 +33,126 @@ static u8 *appldr = ( u8 * )0x81200000; /* Variables */ static u32 buffer[0x20] ATTRIBUTE_ALIGN( 32 ); -void gamepatches( u8 * dst, int len, u8 videoSelected, u8 patchcountrystring, u8 vipatch, u8 cheat ) +void gamepatches(u8 * dst, int len, u8 videoSelected, u8 patchcountrystring, u8 vipatch, u8 cheat) { - VideoModePatcher( dst, len, videoSelected ); + VideoModePatcher(dst, len, videoSelected); - if ( cheat ) - dogamehooks( dst, len ); + if (cheat) dogamehooks(dst, len); - if ( vipatch ) - vidolpatcher( dst, len ); + if (vipatch) vidolpatcher(dst, len); /*LANGUAGE PATCH - FISHEARS*/ - langpatcher( dst, len ); + langpatcher(dst, len); /*Thanks to WiiPower*/ - if ( patchcountrystring == 1 ) - PatchCountryStrings( dst, len ); + if (patchcountrystring == 1) PatchCountryStrings(dst, len); - NSMBPatch( dst, len ); + NSMBPatch(dst, len); - do_wip_code( ( u8 * ) dst, len ); + do_wip_code((u8 *) dst, len); - if ( fix002 == 2 ) - Anti_002_fix( dst, len ); + if (fix002 == 2) Anti_002_fix(dst, len); } -s32 Apploader_Run( entry_point *entry, char * dolpath, u8 cheat, u8 videoSelected, u8 vipatch, u8 patchcountrystring, u8 error002fix, u8 alternatedol, u32 alternatedoloffset, u32 returnTo ) +s32 Apploader_Run(entry_point *entry, char * dolpath, u8 cheat, u8 videoSelected, u8 vipatch, u8 patchcountrystring, + u8 error002fix, u8 alternatedol, u32 alternatedoloffset, u32 returnTo) { app_entry appldr_entry; - app_init appldr_init; - app_main appldr_main; + app_init appldr_init; + app_main appldr_main; app_final appldr_final; u32 appldr_len; s32 ret; - gprintf( "\nApploader_Run() started\n" ); + gprintf("\nApploader_Run() started\n"); //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 ); - if ( ret < 0 ) - return ret; + ret = WDVD_Read(buffer, 0x20, APPLDR_OFFSET); + if (ret < 0) return ret; /* Calculate apploader length */ appldr_len = buffer[5] + buffer[6]; /* Read apploader code */ - ret = WDVD_Read( appldr, appldr_len, APPLDR_OFFSET + 0x20 ); - if ( ret < 0 ) - return ret; + ret = WDVD_Read(appldr, appldr_len, APPLDR_OFFSET + 0x20); + if (ret < 0) return ret; /* Set apploader entry function */ - appldr_entry = ( app_entry )buffer[4]; + appldr_entry = (app_entry) buffer[4]; /* Call apploader entry */ - appldr_entry( &appldr_init, &appldr_main, &appldr_final ); + appldr_entry(&appldr_init, &appldr_main, &appldr_final); /* Initialize apploader */ - appldr_init( gprintf ); + appldr_init(gprintf); - if ( error002fix != 0 ) + if (error002fix != 0) { /* ERROR 002 fix (thanks to WiiPower for sharing this)*/ - *( u32 * )0x80003188 = *( u32 * )0x80003140; + *(u32 *) 0x80003188 = *(u32 *) 0x80003140; } u32 dolStart = 0x90000000; u32 dolEnd = 0x0; - for ( ;; ) + for (;;) { void *dst = NULL; int len = 0, offset = 0; /* Run apploader main function */ - ret = appldr_main( &dst, &len, &offset ); - if ( !ret ) - break; + ret = appldr_main(&dst, &len, &offset); + if (!ret) break; /* Read data from DVD */ - WDVD_Read( dst, len, ( u64 )( offset << 2 ) ); + WDVD_Read(dst, len, (u64) (offset << 2)); - gamepatches( dst, len, videoSelected, patchcountrystring, vipatch, cheat ); - DCFlushRange( dst, len ); + gamepatches(dst, len, videoSelected, patchcountrystring, vipatch, cheat); + DCFlushRange(dst, len); - if( (u32)dst < dolStart )dolStart = (u32)dst; - if( (u32)dst + len > dolEnd ) dolEnd = (u32)dst + len; + if ((u32) dst < dolStart) dolStart = (u32) dst; + if ((u32) dst + len > dolEnd) dolEnd = (u32) dst + len; } //this patch should be run on the entire dol at 1 time - if( !alternatedol && returnTo) + if (!alternatedol && returnTo) { - if( PatchReturnTo( (u32*)dolStart, dolEnd - dolStart , returnTo) ) - { - DCFlushRange( (u32*)dolStart, dolEnd - dolStart ); - } + if (PatchReturnTo((u32*) dolStart, dolEnd - dolStart, returnTo)) + { + DCFlushRange((u32*) dolStart, dolEnd - dolStart); + } } *entry = appldr_final(); /** Load alternate dol if set **/ - if ( alternatedol == 1 ) + if (alternatedol == 1) { wip_reset_counter(); void *dolbuffer = NULL; int dollen = 0; - bool dolloaded = Load_Dol( &dolbuffer, &dollen, dolpath, videoSelected, patchcountrystring, vipatch, cheat ); - if ( dolloaded ) + bool dolloaded = Load_Dol(&dolbuffer, &dollen, dolpath, videoSelected, patchcountrystring, vipatch, cheat); + if (dolloaded) { - *entry = ( entry_point ) load_dol_image( dolbuffer ); + *entry = (entry_point) load_dol_image(dolbuffer); } - if ( dolbuffer ) - free( dolbuffer ); + if (dolbuffer) free(dolbuffer); } - else if ( alternatedol == 2 ) + else if (alternatedol == 2) { wip_reset_counter(); - FST_ENTRY *fst = ( FST_ENTRY * ) * ( u32 * )0x80000038; + FST_ENTRY *fst = (FST_ENTRY *) *(u32 *) 0x80000038; - *entry = ( entry_point ) Load_Dol_from_disc( fst[alternatedoloffset].fileoffset, videoSelected, patchcountrystring, vipatch, cheat ); + *entry = (entry_point) Load_Dol_from_disc(fst[alternatedoloffset].fileoffset, videoSelected, + patchcountrystring, vipatch, cheat); - if ( *entry == 0 ) - SYS_ResetSystem( SYS_RETURNTOMENU, 0, 0 ); + if (*entry == 0) SYS_ResetSystem(SYS_RETURNTOMENU, 0, 0); } return 0; diff --git a/source/usbloader/apploader.h b/source/usbloader/apploader.h index 8f6e4711..9a312c1e 100644 --- a/source/usbloader/apploader.h +++ b/source/usbloader/apploader.h @@ -7,11 +7,12 @@ extern "C" #endif /* Entry point */ -typedef void ( *entry_point )( void ); + typedef void (*entry_point)(void); /* Prototypes */ -s32 Apploader_Run( entry_point *entry, char * dolpath, u8 cheat, u8 videoSelected, u8 vipatch, u8 patchcountrystring, u8 error002fix, u8 alternatedol, u32 alternatedoloffset, u32 returnTo ); -void gamepatches( u8 * dst, int len, u8 videoSelected, u8 patchcountrystring, u8 vipatch, u8 cheat ); + s32 Apploader_Run(entry_point *entry, char * dolpath, u8 cheat, u8 videoSelected, u8 vipatch, + u8 patchcountrystring, u8 error002fix, u8 alternatedol, u32 alternatedoloffset, u32 returnTo); + void gamepatches(u8 * dst, int len, u8 videoSelected, u8 patchcountrystring, u8 vipatch, u8 cheat); #ifdef __cplusplus } diff --git a/source/usbloader/disc.c b/source/usbloader/disc.c index 8128c50b..8d322c38 100644 --- a/source/usbloader/disc.c +++ b/source/usbloader/disc.c @@ -26,58 +26,58 @@ u32 appentrypoint; /* Disc pointers */ -static u32 *buffer = ( u32 * )0x93000000; -static u8 *diskid = ( u8 * )Disc_ID; +static u32 *buffer = (u32 *) 0x93000000; +static u8 *diskid = (u8 *) Disc_ID; -void __Disc_SetLowMem( void ) +void __Disc_SetLowMem(void) { - *Sys_Magic = 0x0D15EA5E; // Standard Boot Code - *Version = 0x00000001; // Version - *Arena_L = 0x00000000; // Arena Low - *BI2 = 0x817E5480; // BI2 - *Bus_Speed = 0x0E7BE2C0; // Console Bus Speed - *CPU_Speed = 0x2B73A840; // Console CPU Speed + *Sys_Magic = 0x0D15EA5E; // Standard Boot Code + *Version = 0x00000001; // Version + *Arena_L = 0x00000000; // Arena Low + *BI2 = 0x817E5480; // BI2 + *Bus_Speed = 0x0E7BE2C0; // Console Bus Speed + *CPU_Speed = 0x2B73A840; // Console CPU Speed /* Setup low memory */ - *Assembler = 0x38A00040; // Assembler - *( u32 * )0x800000E4 = 0x80431A80; - *Dev_Debugger = 0x81800000; // Dev Debugger Monitor Address - *Simulated_Mem = 0x01800000; // Simulated Memory Size - *( vu32 * )0xCD00643C = 0x00000000; // 32Mhz on Bus + *Assembler = 0x38A00040; // Assembler + *(u32 *) 0x800000E4 = 0x80431A80; + *Dev_Debugger = 0x81800000; // Dev Debugger Monitor Address + *Simulated_Mem = 0x01800000; // Simulated Memory Size + *(vu32 *) 0xCD00643C = 0x00000000; // 32Mhz on Bus //If the game is sam & max: season 1 put this shit in char gameid[8]; - memset( gameid, 0, 8 ); - memcpy( gameid, ( char* )Disc_ID, 6 ); + 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 + *GameID_Address = 0x80000000; // Game ID Address } /* Copy disc ID */ - memcpy( ( void * )Online_Check, ( void * )Disc_ID, 4 ); + memcpy((void *) Online_Check, (void *) Disc_ID, 4); /* Flush cache */ - DCFlushRange( ( void * )Disc_ID, 0x3F00 ); + DCFlushRange((void *) Disc_ID, 0x3F00); } -void __Disc_SetVMode( u8 videoselected ) +void __Disc_SetVMode(u8 videoselected) { GXRModeObj *vmode = NULL; u32 progressive, tvmode, vmode_reg = 0; /* Get video mode configuration */ - progressive = ( CONF_GetProgressiveScan() > 0 ) && VIDEO_HaveComponentCable(); - tvmode = CONF_GetVideo(); + progressive = (CONF_GetProgressiveScan() > 0) && VIDEO_HaveComponentCable(); + tvmode = CONF_GetVideo(); /* Select video mode register */ - switch ( tvmode ) + switch (tvmode) { case CONF_VIDEO_PAL: - vmode_reg = ( CONF_GetEuRGB60() > 0 ) ? 5 : 1; + vmode_reg = (CONF_GetEuRGB60() > 0) ? 5 : 1; break; case CONF_VIDEO_MPAL: @@ -89,14 +89,14 @@ void __Disc_SetVMode( u8 videoselected ) break; } - switch ( videoselected ) + switch (videoselected) { case 0: /* Select video mode */ - switch ( diskid[3] ) + switch (diskid[3]) { - /* PAL */ + /* PAL */ case 'P': case 'D': case 'F': @@ -106,10 +106,10 @@ void __Disc_SetVMode( u8 videoselected ) case 'X': case 'Y': case 'Z': - if ( tvmode != CONF_VIDEO_PAL ) + if (tvmode != CONF_VIDEO_PAL) { vmode_reg = 5; - vmode = ( progressive ) ? &TVNtsc480Prog : &TVEurgb60Hz480IntDf; + vmode = (progressive) ? &TVNtsc480Prog : &TVEurgb60Hz480IntDf; } break; @@ -119,10 +119,10 @@ void __Disc_SetVMode( u8 videoselected ) case 'J': case 'K': case 'W': - if ( tvmode != CONF_VIDEO_NTSC ) + if (tvmode != CONF_VIDEO_NTSC) { vmode_reg = 0; - vmode = ( progressive ) ? &TVNtsc480Prog : &TVNtsc480IntDf; + vmode = (progressive) ? &TVNtsc480Prog : &TVNtsc480IntDf; } break; @@ -130,21 +130,21 @@ void __Disc_SetVMode( u8 videoselected ) break; case 1: - vmode = &TVPal528IntDf; - vmode_reg = ( vmode->viTVMode ) >> 2; + vmode = &TVPal528IntDf; + vmode_reg = (vmode->viTVMode) >> 2; break; case 2: - progressive = ( CONF_GetProgressiveScan() > 0 ) && VIDEO_HaveComponentCable(); - vmode = ( progressive ) ? &TVNtsc480Prog : &TVEurgb60Hz480IntDf; - vmode_reg = ( vmode->viTVMode ) >> 2; + progressive = (CONF_GetProgressiveScan() > 0) && VIDEO_HaveComponentCable(); + vmode = (progressive) ? &TVNtsc480Prog : &TVEurgb60Hz480IntDf; + vmode_reg = (vmode->viTVMode) >> 2; break; case 3: - progressive = ( CONF_GetProgressiveScan() > 0 ) && VIDEO_HaveComponentCable(); - vmode = ( progressive ) ? &TVNtsc480Prog : &TVNtsc480IntDf; - vmode_reg = ( vmode->viTVMode ) >> 2; + progressive = (CONF_GetProgressiveScan() > 0) && VIDEO_HaveComponentCable(); + vmode = (progressive) ? &TVNtsc480Prog : &TVNtsc480IntDf; + vmode_reg = (vmode->viTVMode) >> 2; break; case 4: -// vmode = VIDEO_GetPreferredMode(NULL); + // vmode = VIDEO_GetPreferredMode(NULL); break; } @@ -152,33 +152,32 @@ void __Disc_SetVMode( u8 videoselected ) *Video_Mode = vmode_reg; /* Set video mode */ - if ( vmode ) + if (vmode) { - VIDEO_Configure( vmode ); + VIDEO_Configure(vmode); /* Setup video */ - VIDEO_SetBlack( FALSE ); + VIDEO_SetBlack(FALSE); VIDEO_Flush(); VIDEO_WaitVSync(); - if ( vmode->viTVMode & VI_NON_INTERLACE ) - VIDEO_WaitVSync(); + 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 ) +void __Disc_SetTime(void) { /* Extern */ - extern void settime( u64 ); + extern void settime(u64); /* Set proper time */ - settime( secs_to_ticks( time( NULL ) - 946684800 ) ); + settime(secs_to_ticks( time( NULL ) - 946684800 )); } -s32 __Disc_FindPartition( u64 *outbuf ) +s32 __Disc_FindPartition(u64 *outbuf) { u64 offset = 0, table_offset = 0; @@ -186,32 +185,28 @@ s32 __Disc_FindPartition( u64 *outbuf ) s32 ret; /* Read partition info */ - ret = WDVD_UnencryptedRead( buffer, 0x20, PTABLE_OFFSET ); - if ( ret < 0 ) - return ret; + ret = WDVD_UnencryptedRead(buffer, 0x20, PTABLE_OFFSET); + if (ret < 0) return ret; /* Get data */ nb_partitions = buffer[0]; - table_offset = buffer[1] << 2; + table_offset = buffer[1] << 2; /* Read partition table */ - ret = WDVD_UnencryptedRead( buffer, 0x20, table_offset ); - if ( ret < 0 ) - return ret; + ret = WDVD_UnencryptedRead(buffer, 0x20, table_offset); + if (ret < 0) return ret; /* Find game partition */ - for ( cnt = 0; cnt < nb_partitions; cnt++ ) + for (cnt = 0; cnt < nb_partitions; cnt++) { u32 type = buffer[cnt * 2 + 1]; /* Game partition */ - if ( !type ) - offset = buffer[cnt * 2] << 2; + if (!type) offset = buffer[cnt * 2] << 2; } /* No game partition found */ - if ( !offset ) - return -1; + if (!offset) return -1; /* Set output buffer */ *outbuf = offset; @@ -219,47 +214,44 @@ s32 __Disc_FindPartition( u64 *outbuf ) return 0; } - -s32 Disc_Init( void ) +s32 Disc_Init(void) { /* Init DVD subsystem */ return WDVD_Init(); } -s32 Disc_Open( void ) +s32 Disc_Open(void) { s32 ret; /* Reset drive */ ret = WDVD_Reset(); - if ( ret < 0 ) - return ret; + if (ret < 0) return ret; /* Read disc ID */ - return WDVD_ReadDiskId( diskid ); + return WDVD_ReadDiskId(diskid); } -s32 Disc_Wait( void ) +s32 Disc_Wait(void) { u32 cover = 0; s32 ret; /* Wait for disc */ - while ( !( cover & 0x2 ) ) + while (!(cover & 0x2)) { /* Get cover status */ - ret = WDVD_GetCoverStatus( &cover ); - if ( ret < 0 ) - return ret; + ret = WDVD_GetCoverStatus(&cover); + if (ret < 0) return ret; } return 0; } -s32 Disc_SetUSB( const u8 *id ) +s32 Disc_SetUSB(const u8 *id) { u32 part = 0; - if ( wbfs_part_fs ) + if (wbfs_part_fs) { part = wbfs_part_lba; } @@ -269,70 +261,68 @@ s32 Disc_SetUSB( const u8 *id ) } /* Set USB mode */ - return WDVD_SetUSBMode( id, part ); + return WDVD_SetUSBMode(id, part); } -s32 Disc_ReadHeader( void *outbuf ) +s32 Disc_ReadHeader(void *outbuf) { /* Read disc header */ - return WDVD_UnencryptedRead( outbuf, sizeof( struct discHdr ), 0 ); + return WDVD_UnencryptedRead(outbuf, sizeof(struct discHdr), 0); } -s32 Disc_IsWii( void ) +s32 Disc_IsWii(void) { - struct discHdr *header = ( struct discHdr * )buffer; + struct discHdr *header = (struct discHdr *) buffer; s32 ret; /* Read disc header */ - ret = Disc_ReadHeader( header ); - if ( ret < 0 ) - return ret; + ret = Disc_ReadHeader(header); + if (ret < 0) return ret; /* Check magic word */ - if ( header->magic != WII_MAGIC ) - return -1; + if (header->magic != WII_MAGIC) return -1; return 0; } -s32 Disc_BootPartition( u64 offset, char * dolpath, u8 videoselected, u8 cheat, u8 vipatch, u8 patchcountrystring, u8 error002fix, u8 alternatedol, u32 alternatedoloffset, u32 returnTo ) +s32 Disc_BootPartition(u64 offset, char * dolpath, u8 videoselected, u8 cheat, u8 vipatch, u8 patchcountrystring, + u8 error002fix, u8 alternatedol, u32 alternatedoloffset, u32 returnTo) { - gprintf("booting partition IOS %u v%u\n", IOS_GetVersion(), IOS_GetRevision() ); + gprintf("booting partition IOS %u v%u\n", IOS_GetVersion(), IOS_GetRevision()); entry_point p_entry; s32 ret; /* Open specified partition */ - ret = WDVD_OpenPartition( offset ); - if ( ret < 0 ) - return ret; + ret = WDVD_OpenPartition(offset); + if (ret < 0) return ret; /* Setup low memory */ __Disc_SetLowMem(); char gameid[8]; - memset( gameid, 0, 8 ); - memcpy( gameid, ( char* )Disc_ID, 6 ); + memset(gameid, 0, 8); + memcpy(gameid, (char*) Disc_ID, 6); - load_wip_code( ( u8 * ) &gameid ); + load_wip_code((u8 *) &gameid); /* If a wip file is loaded for this game this does nothing - Dimok */ PoPPatch(); /* Run apploader */ - ret = Apploader_Run( &p_entry, dolpath, cheat, videoselected, vipatch, patchcountrystring, error002fix, alternatedol, alternatedoloffset, returnTo ); - if ( ret < 0 ) - return ret; + ret = Apploader_Run(&p_entry, dolpath, cheat, videoselected, vipatch, patchcountrystring, error002fix, + alternatedol, alternatedoloffset, returnTo); + if (ret < 0) return ret; free_wip(); bool cheatloaded = false; - if ( cheat ) + if (cheat) { - // OCARINA STUFF - FISHEARS - if ( ocarina_load_code( ( u8 * ) gameid ) > 0 ) + // OCARINA STUFF - FISHEARS + if (ocarina_load_code((u8 *) gameid) > 0) { ocarina_do_code(); cheatloaded = true; @@ -344,21 +334,21 @@ s32 Disc_BootPartition( u64 offset, char * dolpath, u8 videoselected, u8 cheat, SDCard_deInit(); /* Set an appropiate video mode */ - __Disc_SetVMode( videoselected ); + __Disc_SetVMode(videoselected); /* Set time */ __Disc_SetTime(); /* Disconnect Wiimote */ - WPAD_Flush( 0 ); - WPAD_Disconnect( 0 ); + WPAD_Flush(0); + WPAD_Disconnect(0); WPAD_Shutdown(); // Anti-green screen fix - VIDEO_SetBlack( TRUE ); + VIDEO_SetBlack(TRUE); VIDEO_Flush(); VIDEO_WaitVSync(); - gprintf( "USB Loader GX is done.\n" ); + gprintf("USB Loader GX is done.\n"); /* Shutdown IOS subsystems */ // fix for PeppaPig (from NeoGamma) @@ -367,60 +357,59 @@ s32 Disc_BootPartition( u64 offset, char * dolpath, u8 videoselected, u8 cheat, __IOS_ShutdownSubsystems(); __exception_closeall(); - appentrypoint = ( u32 ) p_entry; + appentrypoint = (u32) p_entry; - if ( cheat == 1 && cheatloaded ) + if (cheat == 1 && cheatloaded) { __asm__( - "lis %r3, appentrypoint@h\n" - "ori %r3, %r3, appentrypoint@l\n" - "lwz %r3, 0(%r3)\n" - "mtlr %r3\n" - "lis %r3, 0x8000\n" - "ori %r3, %r3, 0x18A8\n" - "mtctr %r3\n" - "bctr\n" + "lis %r3, appentrypoint@h\n" + "ori %r3, %r3, appentrypoint@l\n" + "lwz %r3, 0(%r3)\n" + "mtlr %r3\n" + "lis %r3, 0x8000\n" + "ori %r3, %r3, 0x18A8\n" + "mtctr %r3\n" + "bctr\n" ); } else { __asm__( - "lis %r3, appentrypoint@h\n" - "ori %r3, %r3, appentrypoint@l\n" - "lwz %r3, 0(%r3)\n" - "mtlr %r3\n" - "blr\n" + "lis %r3, appentrypoint@h\n" + "ori %r3, %r3, appentrypoint@l\n" + "lwz %r3, 0(%r3)\n" + "mtlr %r3\n" + "blr\n" ); } return 0; } -s32 Disc_WiiBoot( char * dolpath, u8 videoselected, u8 cheat, u8 vipatch, u8 patchcountrystring, u8 error002fix, u8 alternatedol, u32 alternatedoloffset, u32 returnTo ) +s32 Disc_WiiBoot(char * dolpath, u8 videoselected, u8 cheat, u8 vipatch, u8 patchcountrystring, u8 error002fix, + u8 alternatedol, u32 alternatedoloffset, u32 returnTo) { u64 offset; s32 ret; /* Find game partition offset */ - ret = __Disc_FindPartition( &offset ); - if ( ret < 0 ) - return ret; + ret = __Disc_FindPartition(&offset); + if (ret < 0) return ret; /* Boot partition */ - return Disc_BootPartition( offset, dolpath, videoselected, cheat, vipatch, patchcountrystring, error002fix, alternatedol, alternatedoloffset, returnTo ); + return Disc_BootPartition(offset, dolpath, videoselected, cheat, vipatch, patchcountrystring, error002fix, + alternatedol, alternatedoloffset, returnTo); } - - -void PatchCountryStrings( void *Address, int Size ) +void PatchCountryStrings(void *Address, int Size) { - u8 SearchPattern[4] = { 0x00, 0x00, 0x00, 0x00 }; - u8 PatchData[4] = { 0x00, 0x00, 0x00, 0x00 }; - u8 *Addr = ( u8* )Address; + u8 SearchPattern[4] = { 0x00, 0x00, 0x00, 0x00 }; + u8 PatchData[4] = { 0x00, 0x00, 0x00, 0x00 }; + u8 *Addr = (u8*) Address; int wiiregion = CONF_GetRegion(); - switch ( wiiregion ) + switch (wiiregion) { case CONF_REGION_JP: SearchPattern[0] = 0x00; @@ -449,7 +438,7 @@ void PatchCountryStrings( void *Address, int Size ) SearchPattern[2] = 0x53; // S } - switch ( diskid[3] ) + switch (diskid[3]) { case 'J': PatchData[1] = 0x4A; // J @@ -471,9 +460,10 @@ void PatchCountryStrings( void *Address, int Size ) PatchData[2] = 0x53; // S } - while ( Size >= 4 ) + while (Size >= 4) { - if ( Addr[0] == SearchPattern[0] && Addr[1] == SearchPattern[1] && Addr[2] == SearchPattern[2] && Addr[3] == SearchPattern[3] ) + if (Addr[0] == SearchPattern[0] && Addr[1] == SearchPattern[1] && Addr[2] == SearchPattern[2] && Addr[3] + == SearchPattern[3]) { //*Addr = PatchData[0]; Addr += 1; diff --git a/source/usbloader/disc.h b/source/usbloader/disc.h index 9c964f58..cd75ec65 100644 --- a/source/usbloader/disc.h +++ b/source/usbloader/disc.h @@ -11,50 +11,50 @@ extern "C" /* Disc header structure */ struct discHdr { - /* Game ID */ - u8 id[6]; + /* Game ID */ + u8 id[6]; - /* Game version */ - u16 version; + /* Game version */ + u16 version; - /* Audio streaming */ - u8 streaming; - u8 bufsize; + /* Audio streaming */ + u8 streaming; + u8 bufsize; - /* Padding */ - u8 is_ciso; - u8 unused1[13]; + /* Padding */ + u8 is_ciso; + u8 unused1[13]; - /* Magic word */ - u32 magic; + /* Magic word */ + u32 magic; - /* Padding */ - u8 unused2[4]; + /* Padding */ + u8 unused2[4]; - /* Game title */ - char title[64]; + /* Game title */ + char title[64]; - /* Encryption/Hashing */ - u8 encryption; - u8 h3_verify; + /* Encryption/Hashing */ + u8 encryption; + u8 h3_verify; - /* Padding */ - u8 unused3[30]; - } ATTRIBUTE_PACKED; + /* Padding */ + u8 unused3[30]; + }ATTRIBUTE_PACKED; /* Prototypes */ - s32 Disc_Init( void ); - s32 Disc_Open( void ); - s32 Disc_Wait( void ); - void __Disc_SetLowMem( void ); - s32 Disc_SetUSB( const u8 * ); - s32 Disc_ReadHeader( void * ); - s32 Disc_IsWii( void ); - s32 Disc_BootPartition( u64, char *, u8, u8, u8, u8, u8, u8, u32, u32 returnTo ); - s32 Disc_WiiBoot( char *, u8, u8, u8, u8, u8, u8, u32, u32 returnTo ); - s32 __Disc_FindPartition( u64 *outbuf ); - void PatchCountryStrings( void *Address, int Size ); - s32 __Disc_FindPartition( u64 *outbuf ); + s32 Disc_Init(void); + s32 Disc_Open(void); + s32 Disc_Wait(void); + void __Disc_SetLowMem(void); + s32 Disc_SetUSB(const u8 *); + s32 Disc_ReadHeader(void *); + s32 Disc_IsWii(void); + s32 Disc_BootPartition(u64, char *, u8, u8, u8, u8, u8, u8, u32, u32 returnTo); + s32 Disc_WiiBoot(char *, u8, u8, u8, u8, u8, u8, u32, u32 returnTo); + s32 __Disc_FindPartition(u64 *outbuf); + void PatchCountryStrings(void *Address, int Size); + s32 __Disc_FindPartition(u64 *outbuf); #ifdef __cplusplus } diff --git a/source/usbloader/frag.c b/source/usbloader/frag.c index be9463e3..a664873a 100644 --- a/source/usbloader/frag.c +++ b/source/usbloader/frag.c @@ -14,21 +14,20 @@ FragList *frag_list = NULL; -void frag_init( FragList *ff, int maxnum ) +void frag_init(FragList *ff, int maxnum) { - memset( ff, 0, sizeof( Fragment ) * ( maxnum + 1 ) ); + memset(ff, 0, sizeof(Fragment) * (maxnum + 1)); ff->maxnum = maxnum; } -int frag_append( FragList *ff, u32 offset, u32 sector, u32 count ) +int frag_append(FragList *ff, u32 offset, u32 sector, u32 count) { int n; - if ( count ) + 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 ) + 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; @@ -36,7 +35,7 @@ int frag_append( FragList *ff, u32 offset, u32 sector, u32 count ) else { // add - if ( ff->num >= ff->maxnum ) + if (ff->num >= ff->maxnum) { // too many fragments return -500; @@ -44,7 +43,7 @@ int frag_append( FragList *ff, u32 offset, u32 sector, u32 count ) n = ff->num; ff->frag[n].offset = offset; ff->frag[n].sector = sector; - ff->frag[n].count = count; + ff->frag[n].count = count; ff->num++; } } @@ -52,21 +51,20 @@ int frag_append( FragList *ff, u32 offset, u32 sector, u32 count ) return 0; } -int _frag_append( void *ff, u32 offset, u32 sector, u32 count ) +int _frag_append(void *ff, u32 offset, u32 sector, u32 count) { - return frag_append( ff, offset, sector, count ); + return frag_append(ff, offset, sector, count); } -int frag_concat( FragList *ff, FragList *src ) +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; i < src->num; i++ ) + for (i = 0; i < src->num; i++) { - ret = frag_append( ff, size + src->frag[i].offset, - src->frag[i].sector, src->frag[i].count ); - if ( ret ) return ret; + 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); @@ -76,38 +74,35 @@ 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 i; u32 delta; //printf("frag_get(%u %u)\n", offset, count); - for ( i = 0; i < ff->num; i++ ) + for (i = 0; i < ff->num; i++) { - if ( ff->frag[i].offset <= offset - && ff->frag[i].offset + ff->frag[i].count > offset ) + 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; + if (*pcount > count) *pcount = count; goto out; } - if ( ff->frag[i].offset > offset - && ff->frag[i].offset < offset + count ) + 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; + if (*pcount > count) *pcount = count; goto out; } } // not found - if ( offset + count > ff->size ) + if (offset + count > ff->size) { // error: out of range! return -1; @@ -117,12 +112,12 @@ int frag_get( FragList *ff, u32 offset, u32 count, *poffset = offset + count; *psector = 0; *pcount = 0; -out: + out: //printf("=>(%u %u %u)\n", *poffset, *psector, *pcount); return 0; } -int frag_remap( FragList *ff, FragList *log, FragList *phy ) +int frag_remap(FragList *ff, FragList *log, FragList *phy) { int i; int ret; @@ -130,41 +125,37 @@ int frag_remap( FragList *ff, FragList *log, FragList *phy ) u32 sector; u32 count; u32 delta; - for ( i = 0; i < log->num; i++ ) + for (i = 0; i < log->num; 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 + 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 ); + 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 ) +int get_frag_list(u8 *id) { - return WBFS_GetFragList( id ); + return WBFS_GetFragList(id); } -int set_frag_list( u8 *id ) +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_WBFS) return 0; + if (frag_list == NULL) { - if ( wbfs_part_fs == PART_FS_FAT ) + if (wbfs_part_fs == PART_FS_FAT) { // fall back to old fat method -// printf("FAT: fallback to old method\n"); + // printf("FAT: fallback to old method\n"); return 0; } // ntfs has no fallback, return error @@ -172,18 +163,18 @@ int set_frag_list( u8 *id ) } // (+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 ) + int size = sizeof(Fragment) * (frag_list->num + 1); + int ret = USBStorage_WBFS_SetFragList(frag_list, size); + if (ret) { -// printf("set_frag: %d\n", 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 ); + 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 e82d6240..fa4b678a 100644 --- a/source/usbloader/frag.h +++ b/source/usbloader/frag.h @@ -1,4 +1,3 @@ - // worst case wbfs fragmentation scenario: // 9GB (dual layer) / 2mb (wbfs sector size) = 4608 #define MAX_FRAG 20000 @@ -14,38 +13,37 @@ extern "C" typedef struct { - u32 offset; // file offset, in sectors unit - u32 sector; - u32 count; + 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]; + 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 ); + // 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_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/fstfile.c b/source/usbloader/fstfile.c index 676ef986..116f1b34 100644 --- a/source/usbloader/fstfile.c +++ b/source/usbloader/fstfile.c @@ -2,15 +2,14 @@ #include "fstfile.h" - -char *fstfiles( FST_ENTRY *fst, u32 index ) +char *fstfiles(FST_ENTRY *fst, u32 index) { u32 count = fst[0].filelen; u32 stringoffset; - if ( index < count ) + if (index < count) { - stringoffset = *( u32 * ) & ( fst[index] ) % ( 256 * 256 * 256 ); - return ( char * )( ( u32 )fst + count*12 + stringoffset ); + stringoffset = *(u32 *) &(fst[index]) % (256 * 256 * 256); + return (char *) ((u32) fst + count * 12 + stringoffset); } else { @@ -18,15 +17,15 @@ char *fstfiles( FST_ENTRY *fst, u32 index ) } } -char *fstfilename( u32 index ) +char *fstfilename(u32 index) { - FST_ENTRY *fst = ( FST_ENTRY * ) * ( u32 * )0x80000038; + FST_ENTRY *fst = (FST_ENTRY *) *(u32 *) 0x80000038; u32 count = fst[0].filelen; u32 stringoffset; - if ( index < count ) + if (index < count) { - stringoffset = *( u32 * ) & ( fst[index] ) % ( 256 * 256 * 256 ); - return ( char * )( *( u32 * )0x80000038 + count*12 + stringoffset ); + stringoffset = *(u32 *) &(fst[index]) % (256 * 256 * 256); + return (char *) (*(u32 *) 0x80000038 + count * 12 + stringoffset); } else { @@ -34,11 +33,11 @@ char *fstfilename( u32 index ) } } -u32 fstfileoffset( u32 index ) +u32 fstfileoffset(u32 index) { - FST_ENTRY *fst = ( FST_ENTRY * ) * ( u32 * )0x80000038; + FST_ENTRY *fst = (FST_ENTRY *) *(u32 *) 0x80000038; u32 count = fst[0].filelen; - if ( index < count ) + if (index < count) { return fst[index].fileoffset; } diff --git a/source/usbloader/fstfile.h b/source/usbloader/fstfile.h index a2ea42ff..dc72b14b 100644 --- a/source/usbloader/fstfile.h +++ b/source/usbloader/fstfile.h @@ -8,15 +8,15 @@ extern "C" typedef struct { - u8 filetype; - char name_offset[3]; - u32 fileoffset; - u32 filelen; - } __attribute__( ( packed ) ) FST_ENTRY; + u8 filetype; + char name_offset[3]; + u32 fileoffset; + u32 filelen; + }__attribute__( ( packed ) ) FST_ENTRY; - char *fstfiles( FST_ENTRY *fst, u32 index ); - char *fstfilename( u32 index ); - u32 fstfileoffset( u32 index ); + char *fstfiles(FST_ENTRY *fst, u32 index); + char *fstfilename(u32 index); + u32 fstfileoffset(u32 index); #ifdef __cplusplus } diff --git a/source/usbloader/partition_usbloader.c b/source/usbloader/partition_usbloader.c index 05a25dad..a063ef95 100644 --- a/source/usbloader/partition_usbloader.c +++ b/source/usbloader/partition_usbloader.c @@ -20,10 +20,9 @@ typedef struct /* Partition table entries */ partitionEntry entries[MAX_PARTITIONS]; -} ATTRIBUTE_PACKED partitionTable; +}ATTRIBUTE_PACKED partitionTable; - -s32 Partition_GetEntries( u32 device, partitionEntry *outbuf, u32 *outval ) +s32 Partition_GetEntries(u32 device, partitionEntry *outbuf, u32 *outval) { static partitionTable table ATTRIBUTE_ALIGN( 32 ); @@ -31,52 +30,48 @@ s32 Partition_GetEntries( u32 device, partitionEntry *outbuf, u32 *outval ) s32 ret; /* Read from specified device */ - switch ( device ) + switch (device) { case WBFS_DEVICE_USB: - { - /* Get sector size */ - ret = USBStorage2_GetCapacity( §or_size ); - if ( ret == 0 ) - return -1; + { + /* Get sector size */ + ret = USBStorage2_GetCapacity(§or_size); + if (ret == 0) return -1; - /* Read partition table */ - ret = USBStorage2_ReadSectors( 0, 1, &table ); - if ( ret < 0 ) - return ret; + /* Read partition table */ + ret = USBStorage2_ReadSectors(0, 1, &table); + if (ret < 0) return ret; - break; - } + break; + } case WBFS_DEVICE_SDHC: - { - /* SDHC sector size */ - sector_size = SDHC_SECTOR_SIZE; + { + /* 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; } - /* Swap endianess */ - for ( cnt = 0; cnt < 4; cnt++ ) + 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 ) ); + memcpy(outbuf, table.entries, sizeof(table.entries)); /* Set sector size */ *outval = sector_size; @@ -84,47 +79,45 @@ s32 Partition_GetEntries( u32 device, partitionEntry *outbuf, u32 *outval ) return 0; } -bool Device_ReadSectors( u32 device, u32 sector, u32 count, void *buffer ) +bool Device_ReadSectors(u32 device, u32 sector, u32 count, void *buffer) { s32 ret; /* Read from specified device */ - switch ( device ) + switch (device) { case WBFS_DEVICE_USB: - ret = USBStorage2_ReadSectors( sector, count, buffer ); - if ( ret < 0 ) - return false; + ret = USBStorage2_ReadSectors(sector, count, buffer); + if (ret < 0) return false; return true; case WBFS_DEVICE_SDHC: - return SDHC_ReadSectors( sector, count, buffer ); + return SDHC_ReadSectors(sector, count, buffer); } return false; } -bool Device_WriteSectors( u32 device, u32 sector, u32 count, void *buffer ) +bool Device_WriteSectors(u32 device, u32 sector, u32 count, void *buffer) { s32 ret; /* Read from specified device */ - switch ( device ) + switch (device) { case WBFS_DEVICE_USB: - ret = USBStorage2_WriteSectors( sector, count, buffer ); - if ( ret < 0 ) - return false; + ret = USBStorage2_WriteSectors(sector, count, buffer); + if (ret < 0) return false; return true; case WBFS_DEVICE_SDHC: - return SDHC_WriteSectors( sector, count, buffer ); + return SDHC_WriteSectors(sector, count, buffer); } return false; } -s32 Partition_GetEntriesEx( u32 device, partitionEntry *outbuf, u32 *psect_size, u8 *num ) +s32 Partition_GetEntriesEx(u32 device, partitionEntry *outbuf, u32 *psect_size, u8 *num) { static partitionTable table ATTRIBUTE_ALIGN( 32 ); partitionEntry *entry; @@ -134,11 +127,11 @@ s32 Partition_GetEntriesEx( u32 device, partitionEntry *outbuf, u32 *psect_size, int maxpart = *num; // Get sector size - switch ( device ) + switch (device) { case WBFS_DEVICE_USB: - ret = USBStorage2_GetCapacity( §or_size ); - if ( ret == 0 ) return -1; + ret = USBStorage2_GetCapacity(§or_size); + if (ret == 0) return -1; break; case WBFS_DEVICE_SDHC: sector_size = SDHC_SECTOR_SIZE; @@ -153,62 +146,62 @@ s32 Partition_GetEntriesEx( u32 device, partitionEntry *outbuf, u32 *psect_size, u32 next = 0; // Read partition table - ret = Device_ReadSectors( device, 0, 1, &table ); - if ( !ret ) return -1; + 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 ) + if (get_fs_type(&table) == FS_TYPE_WBFS) { - memset( outbuf, 0, sizeof( table.entries ) ); - wbfs_head_t *head = ( wbfs_head_t* ) & table; + 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++ ) + 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 ) ) + 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 ) ); + 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; i < maxpart - 4; i++ ) + for (i = 0; i < maxpart - 4; i++) { - ret = Device_ReadSectors( device, next, 1, &table ); - if ( !ret ) break; - if ( i == 0 ) + ret = Device_ReadSectors(device, next, 1, &table); + if (!ret) break; + if (i == 0) { // handle the invalid scenario where wbfs is on an EXTENDED // partition instead of on the Logical inside Extended. - if ( get_fs_type( &table ) == FS_TYPE_WBFS ) break; + if (get_fs_type(&table) == FS_TYPE_WBFS) break; } entry = &table.entries[0]; - entry->sector = swap32( entry->sector ); - entry->size = swap32( entry->size ); - if ( entry->type && entry->size && entry->sector ) + entry->sector = 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 )++; + memcpy(&outbuf[*num], entry, sizeof(*entry)); + (*num)++; // get next entry++; - if ( entry->type && entry->size && entry->sector ) + if (entry->type && entry->size && entry->sector) { - next = ext + swap32( entry->sector ); + next = ext + swap32(entry->sector); } else { @@ -220,125 +213,146 @@ s32 Partition_GetEntriesEx( u32 device, partitionEntry *outbuf, u32 *psect_size, return 0; } -bool part_is_extended( int type ) +bool part_is_extended(int type) { - if ( type == 0x05 ) return true; - if ( type == 0x0f ) return true; + if (type == 0x05) return true; + if (type == 0x0f) return true; return false; } -bool part_is_data( int type ) +bool part_is_data(int type) { - if ( type && !part_is_extended( type ) ) return true; + if (type && !part_is_extended(type)) return true; return false; } -bool part_valid_data( partitionEntry *entry ) +bool part_valid_data(partitionEntry *entry) { - if ( entry->size && entry->type && entry->sector ) + if (entry->size && entry->type && entry->sector) { - return part_is_data( entry->type ); + return part_is_data(entry->type); } return false; } -char* part_type_data( int type ) +char* part_type_data(int type) { - switch ( 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"; + 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 ) +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 ); + 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 ) +int get_fs_type(void *buff) { char *buf = buff; // WBFS - wbfs_head_t *head = ( wbfs_head_t * )buff; - if ( head->magic == wbfs_htonl( WBFS_MAGIC ) ) return FS_TYPE_WBFS; + wbfs_head_t *head = (wbfs_head_t *) buff; + if (head->magic == wbfs_htonl( WBFS_MAGIC )) return FS_TYPE_WBFS; // 55AA - if ( buf[0x1FE] == 0x55 && buf[0x1FF] == 0xAA ) + 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; + 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; + if (memcmp(buf + 0x03, "NTFS", 4) == 0) return FS_TYPE_NTFS; } return FS_TYPE_UNK; } -int get_part_fs( int fs_type ) +int get_part_fs(int fs_type) { - switch ( 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; + 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 ) +bool is_type_fat(int type) { - return ( type == FS_TYPE_FAT16 || type == FS_TYPE_FAT32 ); + return (type == FS_TYPE_FAT16 || type == FS_TYPE_FAT32); } - -char *get_fs_name( int i ) +char *get_fs_name(int i) { - switch ( 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"; + 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 ) +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 ) + 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 ) + if (plist->num == 1) { pinfo = &plist->pinfo[0]; entry = &plist->pentry[0]; @@ -350,54 +364,53 @@ s32 Partition_GetList( u32 device, PartList *plist ) char buf[plist->sector_size]; // scan partitions for filesystem type - for ( i = 0; i < plist->num; i++ ) + 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; + 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 ) + 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; + 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 ) ) + 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 ) + 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 ); + pinfo->part_fs = get_part_fs(pinfo->fs_type); } return 0; } - -int Partition_FixEXT( u32 device, u8 part ) +int Partition_FixEXT(u32 device, u8 part) { static partitionTable table ATTRIBUTE_ALIGN( 32 ); int ret; - if ( part > 3 ) return -1; + if (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 ) ) + 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; + 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 5fde0665..4cde26f7 100644 --- a/source/usbloader/partition_usbloader.h +++ b/source/usbloader/partition_usbloader.h @@ -26,7 +26,7 @@ extern "C" /* Partition size */ u32 size; - } ATTRIBUTE_PACKED partitionEntry; + }ATTRIBUTE_PACKED partitionEntry; /* Constants */ #define MAX_PARTITIONS 4 @@ -40,41 +40,41 @@ extern "C" typedef struct { - u8 fs_type; - u8 part_fs; - u8 wbfs_i; // seq wbfs part index - u8 fat_i; // seq fat part index - u8 ntfs_i; // seq ntfs part index - u8 index; + u8 fs_type; + u8 part_fs; + u8 wbfs_i; // seq wbfs part index + u8 fat_i; // seq fat part index + u8 ntfs_i; // seq ntfs part index + u8 index; } PartInfo; typedef struct { - u8 num; - u32 sector_size; - partitionEntry pentry[MAX_PARTITIONS_EX]; - u8 wbfs_n; - u8 fat_n; - u8 ntfs_n; - PartInfo pinfo[MAX_PARTITIONS_EX]; + u8 num; + u32 sector_size; + partitionEntry pentry[MAX_PARTITIONS_EX]; + u8 wbfs_n; + u8 fat_n; + u8 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, u8 *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, u8 part ); + s32 Partition_GetEntries(u32 device, partitionEntry *outbuf, u32 *outval); + s32 Partition_GetEntriesEx(u32 device, partitionEntry *outbuf, u32 *outval, u8 *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, u8 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 1cd20499..249fe790 100644 --- a/source/usbloader/sdhc.c +++ b/source/usbloader/sdhc.c @@ -23,214 +23,193 @@ static s32 hid = -1, fd = -1; static u32 sector_size = SDHC_SECTOR_SIZE; static void *sdhc_buf2; -extern void* SYS_AllocArena2MemLo( u32 size, u32 align ); +extern void* SYS_AllocArena2MemLo(u32 size, u32 align); -bool SDHC_Init( void ) +bool SDHC_Init(void) { s32 ret; - if ( sdhc_mode_sd ) + if (sdhc_mode_sd) { return __io_wiisd.startup(); } /* Already open */ - if ( fd >= 0 ) - return true; + if (fd >= 0) return true; /* Create heap */ - if ( hid < 0 ) + if (hid < 0) { - hid = iosCreateHeap( SDHC_HEAPSIZE ); - if ( hid < 0 ) - goto err; + hid = iosCreateHeap(SDHC_HEAPSIZE); + if (hid < 0) goto err; } // allocate buf2 - if ( sdhc_buf2 == NULL ) + if (sdhc_buf2 == NULL) { - sdhc_buf2 = SYS_AllocArena2MemLo( SDHC_MEM2_SIZE, 32 ); + sdhc_buf2 = SYS_AllocArena2MemLo(SDHC_MEM2_SIZE, 32); } /* Open SDHC device */ - fd = IOS_Open( fs, 0 ); - if ( fd < 0 ) - goto err; + fd = IOS_Open(fs, 0); + if (fd < 0) goto err; /* Initialize SDHC */ - ret = IOS_IoctlvFormat( hid, fd, IOCTL_SDHC_INIT, ":" ); - if ( ret ) - goto err; + ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_INIT, ":"); + if (ret) goto err; return true; -err: + err: /* Close SDHC device */ - if ( fd >= 0 ) + if (fd >= 0) { - IOS_Close( fd ); + IOS_Close(fd); fd = -1; } return false; } -bool SDHC_Close( void ) +bool SDHC_Close(void) { - if ( sdhc_mode_sd ) + if (sdhc_mode_sd) { return __io_wiisd.shutdown(); } /* Close SDHC device */ - if ( fd >= 0 ) + if (fd >= 0) { - IOS_Close( fd ); + IOS_Close(fd); fd = -1; } /*if (hid > 0) { - iosDestroyHeap(hid); - hid = -1; - }*/ + iosDestroyHeap(hid); + hid = -1; + }*/ return true; } -bool SDHC_IsInserted( void ) +bool SDHC_IsInserted(void) { s32 ret; - if ( sdhc_mode_sd ) + if (sdhc_mode_sd) { return __io_wiisd.isInserted(); } /* Check if SD card is inserted */ - ret = IOS_IoctlvFormat( hid, fd, IOCTL_SDHC_ISINSERTED, ":" ); + 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 ) +bool SDHC_ReadSectors(u32 sector, u32 count, void *buffer) { //printf("SD-R(%u %u)\n", sector, count); - if ( sdhc_mode_sd ) + if (sdhc_mode_sd) { - return __io_wiisd.readSectors( sector, count, buffer ); + 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; /* Device not opened */ - if ( fd < 0 ) - return false; + if (fd < 0) return false; /* Buffer not aligned */ - if ( ( u32 )buffer & 0x1F ) + if ((u32) buffer & 0x1F) { /* Allocate memory */ //buf = iosAlloc(hid, len); buf = sdhc_buf2; - if ( !buf ) - return false; + if (!buf) return false; } /* Read data */ - ret = IOS_IoctlvFormat( hid, fd, IOCTL_SDHC_READ, "ii:d", sector, count, buf, len ); + ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_READ, "ii:d", sector, count, buf, len); /* Copy data */ - if ( buf != buffer ) + if (buf != buffer) { - memcpy( buffer, buf, len ); + memcpy(buffer, buf, len); //iosFree(hid, buf); } - return ( !ret ) ? true : false; + return (!ret) ? true : false; } -bool SDHC_WriteSectors( u32 sector, u32 count, void *buffer ) +bool SDHC_WriteSectors(u32 sector, u32 count, void *buffer) { - if ( sdhc_mode_sd ) + if (sdhc_mode_sd) { - return __io_wiisd.writeSectors( sector, count, buffer ); + 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; /* Device not opened */ - if ( fd < 0 ) - return false; + if (fd < 0) return false; /* Buffer not aligned */ - if ( ( u32 )buffer & 0x1F ) + if ((u32) buffer & 0x1F) { /* Allocate memory */ //buf = iosAlloc(hid, len); buf = sdhc_buf2; - if ( !buf ) - return false; + if (!buf) return false; /* Copy data */ - memcpy( buf, buffer, len ); + memcpy(buf, buffer, len); } /* Read data */ - ret = IOS_IoctlvFormat( hid, fd, IOCTL_SDHC_WRITE, "ii:d", sector, count, buf, len ); + ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_WRITE, "ii:d", sector, count, buf, len); /* Free memory */ //if (buf != buffer) // iosFree(hid, buf); - return ( !ret ) ? true : false; + return (!ret) ? true : false; } -bool SDHC_ClearStatus( void ) +bool SDHC_ClearStatus(void) { return true; } -bool __io_SDHC_Close( void ) +bool __io_SDHC_Close(void) { // do nothing. return true; } -bool __io_SDHC_NOP( void ) +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 -}; - -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 -}; +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 }; +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 }; diff --git a/source/usbloader/sdhc.h b/source/usbloader/sdhc.h index 34e76ca8..7c405fed 100644 --- a/source/usbloader/sdhc.h +++ b/source/usbloader/sdhc.h @@ -10,10 +10,10 @@ extern "C" #endif /* Prototypes */ - bool SDHC_Init( void ); - bool SDHC_Close( void ); - bool SDHC_ReadSectors( u32, u32, void * ); - bool SDHC_WriteSectors( u32, u32, void * ); + bool SDHC_Init(void); + bool SDHC_Close(void); + bool SDHC_ReadSectors(u32, u32, void *); + bool SDHC_WriteSectors(u32, u32, void *); extern int sdhc_mode_sd; #ifdef __cplusplus diff --git a/source/usbloader/splits.c b/source/usbloader/splits.c index f0a23dba..89ba2874 100644 --- a/source/usbloader/splits.c +++ b/source/usbloader/splits.c @@ -1,4 +1,3 @@ - // by oggzee #include @@ -20,140 +19,138 @@ #define split_error(x) do { printf("\nsplit error: %s\n\n",x); } while(0) // 1 cluster less than 4gb -u64 OPT_split_size = ( u64 )4LL * 1024 * 1024 * 1024 - 32 * 1024; +u64 OPT_split_size = (u64) 4LL * 1024 * 1024 * 1024 - 32 * 1024; // 1 cluster less than 2gb //u64 OPT_split_size = (u64)2LL * 1024 * 1024 * 1024 - 32 * 1024; //split_info_t split; -void split_get_fname( split_info_t *s, int idx, char *fname ) +void split_get_fname(split_info_t *s, int idx, char *fname) { - strcpy( fname, s->fname ); - if ( idx == 0 && s->create_mode ) + strcpy(fname, s->fname); + if (idx == 0 && s->create_mode) { - strcat( fname, ".tmp" ); + strcat(fname, ".tmp"); } - else if ( idx > 0 ) + else if (idx > 0) { - char *c = fname + strlen( fname ) - 1; + char *c = fname + strlen(fname) - 1; *c = '0' + idx; } } -int split_open_file( split_info_t *s, int idx ) +int split_open_file(split_info_t *s, int idx) { int fd = s->fd[idx]; - if ( fd >= 0 ) return fd; + if (fd >= 0) return fd; char fname[1024]; - split_get_fname( s, idx, fname ); + split_get_fname(s, idx, fname); //char *mode = s->create_mode ? "wb+" : "rb+"; - int mode = s->create_mode ? ( O_CREAT | O_RDWR ) : O_RDWR ; + 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 ) + 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 ); + 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 write_zero(int fd, off_t size) { int buf[0x4000]; //64kb int chunk; int ret; - memset( buf, 0, sizeof( buf ) ); - while ( size ) + memset(buf, 0, sizeof(buf)); + while (size) { chunk = size; - if ( chunk > sizeof( buf ) ) chunk = sizeof( buf ); - ret = write( fd, buf, chunk ); + 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; + if (ret < 0) return ret; } return 0; } -int split_fill( split_info_t *s, int idx, u64 size ) +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 ) + 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 ); + 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 split_get_file(split_info_t *s, u32 lba, u32 *sec_count, int fill) { int fd; - if ( lba >= s->total_sec ) + if (lba >= s->total_sec) { - fprintf( stderr, "SPLIT: invalid sector %u / %u\n", lba, ( u32 )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 ) + if (idx >= s->max_split) { - fprintf( stderr, "SPLIT: invalid split %d / %d\n", idx, s->max_split - 1 ); + fprintf(stderr, "SPLIT: invalid split %d / %d\n", idx, s->max_split - 1); return -1; } fd = s->fd[idx]; - if ( fd < 0 ) + if (fd < 0) { // opening new, make sure all previous are full int i; - for ( i = 0; i < idx; i++ ) + for (i = 0; i < idx; i++) { - if ( split_fill( s, i, s->split_size ) ) + if (split_fill(s, i, s->split_size)) { - printf( "FILL %d\n", i ); + printf("FILL %d\n", i); } } - fd = split_open_file( s, idx ); + fd = split_open_file(s, idx); } - if ( fd < 0 ) + if (fd < 0) { - fprintf( stderr, "SPLIT %d: no file\n", idx ); + 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; + 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 (*sec_count > to_end) *sec_count = to_end; + if (s->create_mode) { - if ( fill ) + if (fill) { // extend, so that read will be succesfull - split_fill( s, idx, off + 512 * ( *sec_count ) ); + 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 ); + split_fill(s, idx, off); } } - lseek( fd, off, SEEK_SET ); + lseek(fd, off, SEEK_SET); return fd; } -int split_read_sector( void *_fp, u32 lba, u32 count, void*buf ) +int split_read_sector(void *_fp, u32 lba, u32 count, void*buf) { split_info_t *s = _fp; int fd; @@ -163,22 +160,21 @@ int split_read_sector( void *_fp, u32 lba, u32 count, void*buf ) u32 chunk; size_t ret; //fprintf(stderr,"READ %d %d\n", lba, count); - for ( i = 0; i < ( int )count; i += chunk ) + for (i = 0; i < (int) count; i += chunk) { chunk = count - i; - fd = split_get_file( s, lba + i, &chunk, 1 ); - if ( fd < 0 ) + fd = split_get_file(s, lba + i, &chunk, 1); + if (fd < 0) { - fprintf( stderr, "\n\n"FMT_lld" %d %p\n", off, count, _fp ); + fprintf(stderr, "\n\n"FMT_lld" %d %p\n", off, count, _fp); split_error( "error seeking in disc partition" ); return 1; } - void *ptr = ( ( u8 * )buf ) + ( i * 512 ); - ret = read( fd, ptr, chunk * 512 ); - if ( ret != chunk * 512 ) + void *ptr = ((u8 *) buf) + (i * 512); + ret = read(fd, ptr, chunk * 512); + if (ret != chunk * 512) { - fprintf( stderr, "error reading %u %u [%u] %u = %u\n", - lba, count, i, chunk, ret ); + fprintf(stderr, "error reading %u %u [%u] %u = %u\n", lba, count, i, chunk, ret); split_error( "error reading disc" ); return 1; } @@ -186,7 +182,7 @@ int split_read_sector( void *_fp, u32 lba, u32 count, void*buf ) return 0; } -int split_write_sector( void *_fp, u32 lba, u32 count, void*buf ) +int split_write_sector(void *_fp, u32 lba, u32 count, void*buf) { split_info_t *s = _fp; int fd; @@ -196,24 +192,24 @@ int split_write_sector( void *_fp, u32 lba, u32 count, void*buf ) u32 chunk; size_t ret; //printf("WRITE %d %d %p \n", lba, count, buf); - for ( i = 0; i < ( int )count; i += chunk ) + for (i = 0; i < (int) count; i += chunk) { chunk = count - i; - fd = split_get_file( s, lba + i, &chunk, 0 ); + 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 ) + if (fd < 0 || !chunk) { - fprintf( stderr, "\n\n"FMT_lld" %d %p\n", off, count, _fp ); + 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); - void *ptr = ( ( u8 * )buf ) + ( i * 512 ); - ret = write( fd, ptr, chunk * 512 ); + void *ptr = ((u8 *) buf) + (i * 512); + ret = write(fd, ptr, chunk * 512); //printf("write ret = %d \n", ret); - if ( ret != chunk * 512 ) + if (ret != chunk * 512) { split_error( "error writing disc" ); return 1; @@ -222,134 +218,131 @@ int split_write_sector( void *_fp, u32 lba, u32 count, void*buf ) return 0; } -void split_init( split_info_t *s, char *fname ) +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; i < MAX_SPLIT; i++ ) + memset(s, 0, sizeof(*s)); + for (i = 0; i < MAX_SPLIT; i++) { s->fd[i] = -1; } - strcpy( s->fname, fname ); + strcpy(s->fname, fname); s->max_split = 1; - p = strrchr( fname, '.' ); - if ( p && ( strcasecmp( p, ".wbfs" ) == 0 ) ) + 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 ) +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; + s->total_sec = total_size / 512; + s->split_sec = split_size / 512; } -void split_close( split_info_t *s ) +void split_close(split_info_t *s) { int i; char fname[1024]; char tmpname[1024]; - for ( i = 0; i < s->max_split; i++ ) + for (i = 0; i < s->max_split; i++) { - if ( s->fd[i] >= 0 ) + if (s->fd[i] >= 0) { - close( s->fd[i] ); + close(s->fd[i]); } } - if ( s->create_mode ) + if (s->create_mode) { - split_get_fname( s, -1, fname ); - split_get_fname( s, 0, tmpname ); - rename( tmpname, fname ); + split_get_fname(s, -1, fname); + split_get_fname(s, 0, tmpname); + rename(tmpname, fname); } - memset( s, 0, sizeof( *s ) ); + memset(s, 0, sizeof(*s)); } -int split_create( split_info_t *s, char *fname, - u64 split_size, u64 total_size, bool overwrite ) +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 ); + split_init(s, fname); s->create_mode = 1; // check if any file already exists - for ( i = -1; i < s->max_split; i++ ) + for (i = -1; i < s->max_split; i++) { - split_get_fname( s, i, sname ); - if ( overwrite ) + split_get_fname(s, i, sname); + if (overwrite) { - remove( sname ); + remove(sname); } else { - fd = open( sname, O_RDONLY ); - if ( fd >= 0 ) + fd = open(sname, O_RDONLY); + if (fd >= 0) { - fprintf( stderr, "Error: file already exists: %s\n", sname ); - close( fd ); + fprintf(stderr, "Error: file already exists: %s\n", sname); + close(fd); error = 1; } } } - if ( error ) + if (error) { - split_init( s, "" ); + split_init(s, ""); return -1; } - split_set_size( s, split_size, total_size ); + split_set_size(s, split_size, total_size); return 0; } -int split_open( split_info_t *s, char *fname ) +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; i < s->max_split; i++ ) + split_init(s, fname); + for (i = 0; i < s->max_split; i++) { - fd = split_open_file( s, i ); - if ( fd < 0 ) + fd = split_open_file(s, i); + if (fd < 0) { - if ( i == 0 ) goto err; + if (i == 0) goto err; break; } // check previous size - all splits except last must be same size - if ( i > 0 && size != split_size ) + if (i > 0 && size != split_size) { - fprintf( stderr, "split %d: invalid size "FMT_lld"", i, 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 ); + size = lseek(fd, 0, SEEK_END); // check sector alignment - if ( size % 512 ) + if (size % 512) { - fprintf( stderr, "split %d: size ("FMT_lld") not sector (512) aligned!", - i, size ); + fprintf(stderr, "split %d: size ("FMT_lld") not sector (512) aligned!", i, size); } // first sets split size - if ( i == 0 ) + if (i == 0) { split_size = size; } total_size += size; } - split_set_size( s, split_size, total_size ); + split_set_size(s, split_size, total_size); return 0; -err: - split_close( s ); + err: split_close(s); return -1; } diff --git a/source/usbloader/splits.h b/source/usbloader/splits.h index 8055a999..a5b02378 100644 --- a/source/usbloader/splits.h +++ b/source/usbloader/splits.h @@ -10,34 +10,34 @@ extern "C" 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; + 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 + // 1 sector less than 4gb extern u64 OPT_split_size; - void split_get_fname( split_info_t *s, int idx, char *fname ); -//FILE *split_open_file(split_info_t *s, int idx); -//FILE *split_get_file(split_info_t *s, u32 lba, u32 *sec_count, int fill); - int split_open_file( split_info_t *s, int idx ); - int split_get_file( split_info_t *s, u32 lba, u32 *sec_count, int fill ); - int split_fill( split_info_t *s, int idx, u64 size ); - int split_read_sector( void *_fp, u32 lba, u32 count, void*buf ); - int split_write_sector( void *_fp, u32 lba, u32 count, void*buf ); - void split_init( split_info_t *s, char *fname ); - 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 ); + void split_get_fname(split_info_t *s, int idx, char *fname); + //FILE *split_open_file(split_info_t *s, int idx); + //FILE *split_get_file(split_info_t *s, u32 lba, u32 *sec_count, int fill); + int split_open_file(split_info_t *s, int idx); + int split_get_file(split_info_t *s, u32 lba, u32 *sec_count, int fill); + int split_fill(split_info_t *s, int idx, u64 size); + int split_read_sector(void *_fp, u32 lba, u32 count, void*buf); + int split_write_sector(void *_fp, u32 lba, u32 count, void*buf); + void split_init(split_info_t *s, char *fname); + 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); #ifdef __cplusplus } diff --git a/source/usbloader/usbstorage2.c b/source/usbloader/usbstorage2.c index b070ff54..e2db8159 100644 --- a/source/usbloader/usbstorage2.c +++ b/source/usbloader/usbstorage2.c @@ -1,30 +1,30 @@ /*------------------------------------------------------------- -usbstorage_starlet.c -- USB mass storage support, inside starlet -Copyright (C) 2009 Kwiirk + usbstorage_starlet.c -- USB mass storage support, inside starlet + Copyright (C) 2009 Kwiirk -If this driver is linked before libogc, this will replace the original -usbstorage driver by svpe from libogc -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. + If this driver is linked before libogc, this will replace the original + usbstorage driver by svpe from libogc + 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: + 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. + 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. + 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. + 3. This notice may not be removed or altered from any source + distribution. --------------------------------------------------------------*/ + -------------------------------------------------------------*/ #include #include @@ -54,7 +54,6 @@ distribution. #define USB_IOCTL_WBFS_SET_FRAGLIST (WBFS_BASE+0x51) #define UMS_HEAPSIZE 0x1000 //0x10000 - /* Variables */ static char fs[] ATTRIBUTE_ALIGN( 32 ) = "/dev/usb2"; static char fs2[] ATTRIBUTE_ALIGN( 32 ) = "/dev/usb/ehc"; @@ -65,13 +64,13 @@ static s32 hid = -1, fd = -1; static u32 sector_size; static int mounted = 0; -s32 USBStorage2_Umount( void ) +s32 USBStorage2_Umount(void) { - if ( fd >= 0 && mounted ) + if (fd >= 0 && mounted) { s32 ret; - ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_UMS_UMOUNT, ":" ); + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_UMS_UMOUNT, ":"); return ret; } @@ -79,14 +78,13 @@ s32 USBStorage2_Umount( void ) return IPC_ENOENT; } - -s32 USBStorage2_Watchdog( u32 on_off ) +s32 USBStorage2_Watchdog(u32 on_off) { - if ( fd >= 0 ) + if (fd >= 0) { s32 ret; - ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_UMS_WATCHDOG, "i:", on_off ); + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_UMS_WATCHDOG, "i:", on_off); return ret; } @@ -94,13 +92,13 @@ s32 USBStorage2_Watchdog( u32 on_off ) return IPC_ENOENT; } -s32 USBStorage2_TestMode( u32 on_off ) +s32 USBStorage2_TestMode(u32 on_off) { - if ( fd >= 0 ) + if (fd >= 0) { s32 ret; - ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_UMS_TESTMODE, "i:", on_off ); + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_UMS_TESTMODE, "i:", on_off); return ret; } @@ -108,25 +106,22 @@ s32 USBStorage2_TestMode( u32 on_off ) return IPC_ENOENT; } - -inline s32 __USBStorage2_isMEM2Buffer( const void *buffer ) +inline s32 __USBStorage2_isMEM2Buffer(const void *buffer) { - u32 high_addr = ( ( u32 )buffer ) >> 24; + u32 high_addr = ((u32) buffer) >> 24; - return ( high_addr == 0x90 ) || ( high_addr == 0xD0 ); + return (high_addr == 0x90) || (high_addr == 0xD0); } - -s32 USBStorage2_GetCapacity( u32 *_sector_size ) +s32 USBStorage2_GetCapacity(u32 *_sector_size) { - if ( fd >= 0 ) + if (fd >= 0) { s32 ret; - ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_UMS_GET_CAPACITY, ":i", §or_size ); + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_UMS_GET_CAPACITY, ":i", §or_size); - if ( ret && _sector_size ) - *_sector_size = sector_size; + if (ret && _sector_size) *_sector_size = sector_size; return ret; } @@ -134,58 +129,55 @@ s32 USBStorage2_GetCapacity( u32 *_sector_size ) return IPC_ENOENT; } -s32 USBStorage2_EHC_Off( void ) +s32 USBStorage2_EHC_Off(void) { USBStorage2_Deinit(); - fd = IOS_Open( fsoff, 0 ); + fd = IOS_Open(fsoff, 0); USBStorage2_Deinit(); return 0; } -s32 USBStorage2_Init( void ) +s32 USBStorage2_Init(void) { s32 ret, ret2; static u32 sector_size = 0; /* Already open */ - if ( fd >= 0 ) - return 0; + if (fd >= 0) return 0; /* Create heap */ - if ( hid < 0 ) + if (hid < 0) { - hid = iosCreateHeap( UMS_HEAPSIZE ); - if ( hid < 0 ) - return IPC_ENOMEM; + hid = iosCreateHeap(UMS_HEAPSIZE); + if (hid < 0) return IPC_ENOMEM; } /* Open USB device */ - fd = IOS_Open( fs, 0 ); - if ( fd < 0 ) fd = IOS_Open( fs2, 0 ); + fd = IOS_Open(fs, 0); + if (fd < 0) fd = IOS_Open(fs2, 0); - if ( fd < 0 ) - return fd; + if (fd < 0) return fd; /* Initialize USB storage */ - ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_UMS_INIT, ":" ); - if ( ret < 0 ) goto err; - if ( ret > 1 ) ret = 0; + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_UMS_INIT, ":"); + if (ret < 0) goto err; + if (ret > 1) ret = 0; ret2 = ret; /* Get device capacity */ - ret = USBStorage2_GetCapacity( §or_size ); - if ( !ret ) + ret = USBStorage2_GetCapacity(§or_size); + if (!ret) { ret = -1; goto err; } - if ( ret2 == 0 && sector_size != 512 ) // check for HD sector size 512 bytes + if (ret2 == 0 && sector_size != 512) // check for HD sector size 512 bytes { ret = -20001; goto err; } - if ( ret2 == 1 && sector_size != 2048 ) // check for DVD sector size 2048 bytes + if (ret2 == 1 && sector_size != 2048) // check for DVD sector size 2048 bytes { ret = -20002; goto err; @@ -193,142 +185,132 @@ s32 USBStorage2_Init( void ) mounted = 1; return ret2; // 0->HDD, 1->DVD -err: + err: /* Close USB device */ - if ( fd >= 0 ) + if (fd >= 0) { - IOS_Close( fd ); + IOS_Close(fd); fd = -1; } - return ret; } -void USBStorage2_Deinit( void ) +void USBStorage2_Deinit(void) { mounted = 0; - /* Close USB device */ - if ( fd >= 0 ) + if (fd >= 0) { - IOS_Close( fd ); + IOS_Close(fd); fd = -1; } } -extern void* SYS_AllocArena2MemLo( u32 size, u32 align ); +extern void* SYS_AllocArena2MemLo(u32 size, u32 align); static void *mem2_ptr = NULL; -s32 USBStorage2_ReadSectors( u32 sector, u32 numSectors, void *buffer ) +s32 USBStorage2_ReadSectors(u32 sector, u32 numSectors, void *buffer) { - void *buf = ( void * )buffer; - u32 len = ( sector_size * numSectors ); + void *buf = (void *) buffer; + u32 len = (sector_size * numSectors); s32 ret; /* Device not opened */ - if ( fd < 0 ) - return fd; - if ( !mem2_ptr ) mem2_ptr = SYS_AllocArena2MemLo( 2048 * 256, 32 ); + if (fd < 0) return fd; + if (!mem2_ptr) mem2_ptr = SYS_AllocArena2MemLo(2048 * 256, 32); /* MEM1 buffer */ - if ( !__USBStorage2_isMEM2Buffer( buffer ) ) + if (!__USBStorage2_isMEM2Buffer(buffer)) { /* Allocate memory */ buf = mem2_ptr; //iosAlloc(hid, len); - if ( !buf ) - return IPC_ENOMEM; + if (!buf) return IPC_ENOMEM; } /* Read data */ - ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_UMS_READ_SECTORS, "ii:d", sector, numSectors, buf, len ); + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_UMS_READ_SECTORS, "ii:d", sector, numSectors, buf, len); /* Copy data */ - if ( buf != buffer ) + if (buf != buffer) { - memcpy( buffer, buf, len ); + memcpy(buffer, buf, len); //iosFree(hid, buf); } return ret; } -s32 USBStorage2_WriteSectors( u32 sector, u32 numSectors, const void *buffer ) +s32 USBStorage2_WriteSectors(u32 sector, u32 numSectors, const void *buffer) { - void *buf = ( void * )buffer; - u32 len = ( sector_size * numSectors ); + void *buf = (void *) buffer; + u32 len = (sector_size * numSectors); s32 ret; /* Device not opened */ - if ( fd < 0 ) - return fd; - if ( !mem2_ptr ) mem2_ptr = SYS_AllocArena2MemLo( 2048 * 256, 32 ); - + if (fd < 0) return fd; + if (!mem2_ptr) mem2_ptr = SYS_AllocArena2MemLo(2048 * 256, 32); /* MEM1 buffer */ - if ( !__USBStorage2_isMEM2Buffer( buffer ) ) + if (!__USBStorage2_isMEM2Buffer(buffer)) { /* Allocate memory */ buf = mem2_ptr; //buf = iosAlloc(hid, len); - if ( !buf ) - return IPC_ENOMEM; + if (!buf) return IPC_ENOMEM; /* Copy data */ - memcpy( buf, buffer, len ); + memcpy(buf, buffer, len); } /* Write data */ - ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_UMS_WRITE_SECTORS, "ii:d", sector, numSectors, buf, len ); + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_UMS_WRITE_SECTORS, "ii:d", sector, numSectors, buf, len); /* Free memory */ - if ( buf != buffer ) - iosFree( hid, buf ); + if (buf != buffer) iosFree(hid, buf); return ret; } -static bool __usbstorage_Startup( void ) +static bool __usbstorage_Startup(void) { return USBStorage2_Init() == 0; } -static bool __usbstorage_IsInserted( void ) +static bool __usbstorage_IsInserted(void) { - return ( USBStorage2_GetCapacity( NULL ) >= 0 ); + return (USBStorage2_GetCapacity(NULL) >= 0); } -static bool __usbstorage_ReadSectors( u32 sector, u32 numSectors, void *buffer ) +static bool __usbstorage_ReadSectors(u32 sector, u32 numSectors, void *buffer) { s32 retval; - retval = USBStorage2_ReadSectors( sector, numSectors, buffer ); + retval = USBStorage2_ReadSectors(sector, numSectors, buffer); - if ( retval < 0 ) - return false; + if (retval < 0) return false; return true; } -static bool __usbstorage_WriteSectors( u32 sector, u32 numSectors, const void *buffer ) +static bool __usbstorage_WriteSectors(u32 sector, u32 numSectors, const void *buffer) { s32 retval; - retval = USBStorage2_WriteSectors( sector, numSectors, buffer ); + retval = USBStorage2_WriteSectors(sector, numSectors, buffer); - if ( retval < 0 ) - return false; + if (retval < 0) return false; return true; } -static bool __usbstorage_ClearStatus( void ) +static bool __usbstorage_ClearStatus(void) { return true; } -static bool __usbstorage_Shutdown( void ) +static bool __usbstorage_Shutdown(void) { //if(mounted) USBStorage2_Umount(); USBStorage2_Deinit(); @@ -337,105 +319,88 @@ static bool __usbstorage_Shutdown( void ) return true; } -const DISC_INTERFACE __io_usbstorage2 = -{ - DEVICE_TYPE_WII_UMS, - FEATURE_MEDIUM_CANREAD | FEATURE_MEDIUM_CANWRITE | FEATURE_WII_USB, - ( FN_MEDIUM_STARTUP )&__usbstorage_Startup, - ( FN_MEDIUM_ISINSERTED )&__usbstorage_IsInserted, - ( FN_MEDIUM_READSECTORS )&__usbstorage_ReadSectors, - ( FN_MEDIUM_WRITESECTORS )&__usbstorage_WriteSectors, - ( FN_MEDIUM_CLEARSTATUS )&__usbstorage_ClearStatus, - ( FN_MEDIUM_SHUTDOWN )&__usbstorage_Shutdown -}; +const DISC_INTERFACE __io_usbstorage2 = { DEVICE_TYPE_WII_UMS, FEATURE_MEDIUM_CANREAD | FEATURE_MEDIUM_CANWRITE + | FEATURE_WII_USB, (FN_MEDIUM_STARTUP) &__usbstorage_Startup, (FN_MEDIUM_ISINSERTED) &__usbstorage_IsInserted, + (FN_MEDIUM_READSECTORS) &__usbstorage_ReadSectors, (FN_MEDIUM_WRITESECTORS) &__usbstorage_WriteSectors, + (FN_MEDIUM_CLEARSTATUS) &__usbstorage_ClearStatus, (FN_MEDIUM_SHUTDOWN) &__usbstorage_Shutdown }; -bool __io_usb_ReadSectors( u32 sector, u32 count, void *buffer ) +bool __io_usb_ReadSectors(u32 sector, u32 count, void *buffer) { - s32 ret = USBStorage2_ReadSectors( sector, count, buffer ); + s32 ret = USBStorage2_ReadSectors(sector, count, buffer); return ret > 0; } -bool __io_usb_WriteSectors( u32 sector, u32 count, void *buffer ) +bool __io_usb_WriteSectors(u32 sector, u32 count, void *buffer) { - s32 ret = USBStorage2_WriteSectors( sector, count, buffer ); + s32 ret = USBStorage2_WriteSectors(sector, count, buffer); return ret > 0; } -static bool __io_usb_NOP( void ) +static bool __io_usb_NOP(void) { // do nothing return true; } -const DISC_INTERFACE __io_usbstorage2_ro = -{ - DEVICE_TYPE_WII_UMS, - FEATURE_MEDIUM_CANREAD | FEATURE_MEDIUM_CANWRITE | FEATURE_WII_USB, - ( FN_MEDIUM_STARTUP )&__usbstorage_Startup, - ( FN_MEDIUM_ISINSERTED )&__usbstorage_IsInserted, - ( FN_MEDIUM_READSECTORS )&__usbstorage_ReadSectors, - ( FN_MEDIUM_WRITESECTORS )&__io_usb_NOP, - ( FN_MEDIUM_CLEARSTATUS )&__usbstorage_ClearStatus, - ( FN_MEDIUM_SHUTDOWN )&__usbstorage_Shutdown -}; +const DISC_INTERFACE __io_usbstorage2_ro = { DEVICE_TYPE_WII_UMS, FEATURE_MEDIUM_CANREAD | FEATURE_MEDIUM_CANWRITE + | FEATURE_WII_USB, (FN_MEDIUM_STARTUP) &__usbstorage_Startup, (FN_MEDIUM_ISINSERTED) &__usbstorage_IsInserted, + (FN_MEDIUM_READSECTORS) &__usbstorage_ReadSectors, (FN_MEDIUM_WRITESECTORS) &__io_usb_NOP, + (FN_MEDIUM_CLEARSTATUS) &__usbstorage_ClearStatus, (FN_MEDIUM_SHUTDOWN) &__usbstorage_Shutdown }; -s32 USBStorage_WBFS_Open( char *buffer ) +s32 USBStorage_WBFS_Open(char *buffer) { - u32 len = 8; + u32 len = 8; s32 ret; /* Device not opened */ - if ( fd < 0 ) - return fd; + if (fd < 0) return fd; 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 ); + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_OPEN_DISC, "dd:", buffer, len, &part, 4); return ret; } // woffset is in 32bit words, len is in bytes -s32 USBStorage_WBFS_Read( u32 woffset, u32 len, void *buffer ) +s32 USBStorage_WBFS_Read(u32 woffset, u32 len, void *buffer) { s32 ret; USBStorage2_Init(); /* Device not opened */ - if ( fd < 0 ) - return fd; + if (fd < 0) return fd; /* Read data */ - ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_WBFS_READ_DISC, "ii:d", woffset, len, buffer, len ); + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_READ_DISC, "ii:d", woffset, len, buffer, len); return ret; } - -s32 USBStorage_WBFS_SetDevice( int dev ) +s32 USBStorage_WBFS_SetDevice(int dev) { s32 ret; static s32 retval = 0; retval = 0; USBStorage2_Init(); // Device not opened - if ( fd < 0 ) return fd; + if (fd < 0) return fd; // ioctl - ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_WBFS_SET_DEVICE, "i:i", dev, &retval ); - if ( retval ) return retval; + 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 USBStorage_WBFS_SetFragList(void *p, int size) { s32 ret; USBStorage2_Init(); // Device not opened - if ( fd < 0 ) return fd; + if (fd < 0) return fd; // ioctl - ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_WBFS_SET_FRAGLIST, "d:", p, size ); + ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_SET_FRAGLIST, "d:", p, size); return ret; } diff --git a/source/usbloader/usbstorage2.h b/source/usbloader/usbstorage2.h index 94c998a9..a9bad2fe 100644 --- a/source/usbloader/usbstorage2.h +++ b/source/usbloader/usbstorage2.h @@ -9,23 +9,23 @@ extern "C" #endif /* Prototypes */ - s32 USBStorage2_GetCapacity( u32 * ); - s32 USBStorage2_Init( void ); - void USBStorage2_Deinit( void ); - s32 USBStorage2_Umount( void ); + s32 USBStorage2_GetCapacity(u32 *); + s32 USBStorage2_Init(void); + void USBStorage2_Deinit(void); + s32 USBStorage2_Umount(void); - s32 USBStorage2_ReadSectors( u32, u32, void * ); - s32 USBStorage2_WriteSectors( u32, u32, const void * ); + s32 USBStorage2_ReadSectors(u32, u32, void *); + s32 USBStorage2_WriteSectors(u32, u32, const void *); - s32 USBStorage2_Watchdog( u32 on_off ); + s32 USBStorage2_Watchdog(u32 on_off); - s32 USBStorage2_TestMode( u32 on_off ); + s32 USBStorage2_TestMode(u32 on_off); - s32 USBStorage2_EHC_Off( void ); + s32 USBStorage2_EHC_Off(void); - s32 USBStorage_WBFS_Read( u32 woffset, u32 len, void *buffer ); - s32 USBStorage_WBFS_SetDevice( int dev ); - s32 USBStorage_WBFS_SetFragList( void *p, int size ); + s32 USBStorage_WBFS_Read(u32 woffset, u32 len, void *buffer); + s32 USBStorage_WBFS_SetDevice(int dev); + s32 USBStorage_WBFS_SetFragList(void *p, int size); #define DEVICE_TYPE_WII_UMS (('W'<<24)|('U'<<16)|('M'<<8)|'S') diff --git a/source/usbloader/utils.c b/source/usbloader/utils.c index 4ae4dd61..d7e46448 100644 --- a/source/usbloader/utils.c +++ b/source/usbloader/utils.c @@ -1,8 +1,7 @@ #include #include - -u32 swap32( u32 x ) +u32 swap32(u32 x) { - return ( x >> 24 ) | ( ( x << 8 ) & 0x00FF0000UL ) | ( ( x >> 8 ) & 0x0000FF00UL ) | ( x << 24 ); + return (x >> 24) | ((x << 8) & 0x00FF0000UL) | ((x >> 8) & 0x0000FF00UL) | (x << 24); } diff --git a/source/usbloader/utils.h b/source/usbloader/utils.h index f617f55d..fd1e7ef1 100644 --- a/source/usbloader/utils.h +++ b/source/usbloader/utils.h @@ -17,7 +17,7 @@ extern "C" #define SAFE_FREE(P) if(P){free(P);P=NULL;} /* Prototypes */ - u32 swap32( u32 ); + u32 swap32(u32); #ifdef __cplusplus } diff --git a/source/usbloader/wbfs.cpp b/source/usbloader/wbfs.cpp index 89338690..90523df0 100644 --- a/source/usbloader/wbfs.cpp +++ b/source/usbloader/wbfs.cpp @@ -22,35 +22,35 @@ s32 wbfsDev = WBFS_MIN_DEVICE; // partition char wbfs_fs_drive[16]; -int wbfs_part_fs = PART_FS_WBFS; +int wbfs_part_fs = PART_FS_WBFS; u32 wbfs_part_idx = 0; u32 wbfs_part_lba = 0; -wbfs_disc_t* WBFS_OpenDisc( u8 *discid ) +wbfs_disc_t* WBFS_OpenDisc(u8 *discid) { - return current->OpenDisc( discid ); + return current->OpenDisc(discid); } -void WBFS_CloseDisc( wbfs_disc_t *disc ) +void WBFS_CloseDisc(wbfs_disc_t *disc) { - current->CloseDisc( disc ); + current->CloseDisc(disc); } -wbfs_t *GetHddInfo( void ) +wbfs_t *GetHddInfo(void) { return current->GetHddInfo(); } -s32 WBFS_Init( u32 device ) +s32 WBFS_Init(u32 device) { - return Wbfs::Init( device ); + return Wbfs::Init(device); } -s32 WBFS_Open( void ) +s32 WBFS_Open(void) { WBFS_Close(); - current = new Wbfs_Wbfs( WBFS_DEVICE_USB, 0, 0 ); // Fix me! + current = new Wbfs_Wbfs(WBFS_DEVICE_USB, 0, 0); // Fix me! wbfs_part_fs = wbfs_part_idx = wbfs_part_lba = 0; wbfs_part_idx = 1; @@ -58,35 +58,35 @@ s32 WBFS_Open( void ) return current->Open(); } -s32 WBFS_OpenPart( u32 part_fs, u32 part_idx, u32 part_lba, u32 part_size, char *partition ) +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 (part_fs == PART_FS_FAT) { - current = new Wbfs_Fat( wbfsDev, part_lba, part_size ); - strcpy( wbfs_fs_drive, "USB:" ); + current = new Wbfs_Fat(wbfsDev, part_lba, part_size); + strcpy(wbfs_fs_drive, "USB:"); #ifdef DEBUG_WBFS - gprintf( "\n\tCreated WBFS_Fat instance at lba: %d of size %d", part_lba, part_size ); + gprintf("\n\tCreated WBFS_Fat instance at lba: %d of size %d", part_lba, part_size); #endif } - else if ( part_fs == PART_FS_NTFS ) + else if (part_fs == PART_FS_NTFS) { - current = new Wbfs_Ntfs( wbfsDev, part_lba, part_size ); - strcpy( wbfs_fs_drive, "NTFS:" ); + current = new Wbfs_Ntfs(wbfsDev, part_lba, part_size); + strcpy(wbfs_fs_drive, "NTFS:"); #ifdef DEBUG_WBFS - gprintf( "\n\tCreated WBFS_Ntfs instance at lba: %d of size %d", part_lba, part_size ); + gprintf("\n\tCreated WBFS_Ntfs instance at lba: %d of size %d", part_lba, part_size); #endif } else { - current = new Wbfs_Wbfs( wbfsDev, part_lba, part_size ); + current = new Wbfs_Wbfs(wbfsDev, part_lba, part_size); #ifdef DEBUG_WBFS - gprintf( "\n\tCreated WBFS_Wbfs instance at lba: %d of size %d", part_lba, part_size ); + gprintf("\n\tCreated WBFS_Wbfs instance at lba: %d of size %d", part_lba, part_size); #endif } - if ( current->Open() ) + if (current->Open()) { delete current; current = NULL; @@ -99,16 +99,16 @@ s32 WBFS_OpenPart( u32 part_fs, u32 part_idx, u32 part_lba, u32 part_size, char wbfs_part_lba = part_lba; const 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 ); + 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 ) +s32 WBFS_OpenNamed(char *partition) { u32 i; - u32 part_fs = PART_FS_WBFS; + u32 part_fs = PART_FS_WBFS; u32 part_idx = 0; u32 part_lba = 0; s32 ret = 0; @@ -118,26 +118,26 @@ s32 WBFS_OpenNamed( char *partition ) WBFS_Close(); // parse partition option - if ( strncasecmp( partition, "WBFS", 4 ) == 0 ) + if (strncasecmp(partition, "WBFS", 4) == 0) { - i = atoi( partition + 4 ); - if ( i < 1 || i > 4 ) goto err; - part_fs = PART_FS_WBFS; + 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 ) + 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; + 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 ) + else if (strncasecmp(partition, "NTFS", 4) == 0) { - i = atoi( partition + 4 ); - if ( i < 1 || i > 9 ) goto err; - part_fs = PART_FS_NTFS; + i = atoi(partition + 4); + if (i < 1 || i > 9) goto err; + part_fs = PART_FS_NTFS; part_idx = i; } else @@ -146,51 +146,50 @@ s32 WBFS_OpenNamed( char *partition ) } // Get partition entries - ret = Partition_GetList( wbfsDev, &plist ); - if ( ret || plist.num == 0 ) return -1; + ret = Partition_GetList(wbfsDev, &plist); + if (ret || plist.num == 0) return -1; - if ( part_fs == PART_FS_WBFS ) + if (part_fs == PART_FS_WBFS) { - if ( part_idx > plist.wbfs_n ) goto err; - for ( i = 0; i < plist.num; i++ ) + if (part_idx > plist.wbfs_n) goto err; + for (i = 0; i < plist.num; i++) { - if ( plist.pinfo[i].wbfs_i == part_idx ) break; + if (plist.pinfo[i].wbfs_i == part_idx) break; } } - else if ( part_fs == PART_FS_FAT ) + else if (part_fs == PART_FS_FAT) { - if ( part_idx > plist.fat_n ) goto err; - for ( i = 0; i < plist.num; i++ ) + if (part_idx > plist.fat_n) goto err; + for (i = 0; i < plist.num; i++) { - if ( plist.pinfo[i].fat_i == part_idx ) break; + if (plist.pinfo[i].fat_i == part_idx) break; } } - else if ( part_fs == PART_FS_NTFS ) + else if (part_fs == PART_FS_NTFS) { - if ( part_idx > plist.ntfs_n ) goto err; - for ( i = 0; i < plist.num; i++ ) + if (part_idx > plist.ntfs_n) goto err; + for (i = 0; i < plist.num; i++) { - if ( plist.pinfo[i].ntfs_i == part_idx ) break; + if (plist.pinfo[i].ntfs_i == part_idx) break; } } - if ( i >= plist.num ) goto err; + if (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 ) ) + if (WBFS_OpenPart(part_fs, part_idx, part_lba, plist.pentry[i].size, partition)) { goto err; } // success return 0; -err: - return -1; + err: return -1; } -s32 WBFS_OpenLBA( u32 lba, u32 size ) +s32 WBFS_OpenLBA(u32 lba, u32 size) { - Wbfs *part = new Wbfs_Wbfs( wbfsDev, lba, size ); - if ( part->Open() != 0 ) + Wbfs *part = new Wbfs_Wbfs(wbfsDev, lba, size); + if (part->Open() != 0) { delete part; return -1; @@ -201,9 +200,9 @@ s32 WBFS_OpenLBA( u32 lba, u32 size ) return 0; } -bool WBFS_Close( void ) +bool WBFS_Close(void) { - if ( current != NULL ) + if (current != NULL) { current->Close(); delete current; @@ -222,86 +221,82 @@ bool WBFS_Close( void ) bool WBFS_Mounted() { - return ( current != NULL && current->Mounted() ); + return (current != NULL && current->Mounted()); } -s32 WBFS_Format( u32 lba, u32 size ) +s32 WBFS_Format(u32 lba, u32 size) { return current->Format(); } -s32 WBFS_GetCount( u32 *count ) +s32 WBFS_GetCount(u32 *count) { - return current->GetCount( count ); + return current->GetCount(count); } -s32 WBFS_GetHeaders( struct discHdr *outbuf, u32 cnt, u32 len ) +s32 WBFS_GetHeaders(struct discHdr *outbuf, u32 cnt, u32 len) { - return current->GetHeaders( outbuf, cnt, len ); + return current->GetHeaders(outbuf, cnt, len); } -s32 WBFS_CheckGame( u8 *discid ) +s32 WBFS_CheckGame(u8 *discid) { - return current->CheckGame( discid ); + return current->CheckGame(discid); } -s32 WBFS_AddGame( void ) +s32 WBFS_AddGame(void) { s32 retval = current->AddGame(); - if ( retval == 0 ) - gameList.clear(); + if (retval == 0) gameList.clear(); return retval; } -s32 WBFS_RemoveGame( u8 *discid ) +s32 WBFS_RemoveGame(u8 *discid) { - s32 retval = current->RemoveGame( discid ); - if ( retval == 0 ) - gameList.clear(); + s32 retval = current->RemoveGame(discid); + if (retval == 0) gameList.clear(); return retval; } -s32 WBFS_GameSize( u8 *discid, f32 *size ) +s32 WBFS_GameSize(u8 *discid, f32 *size) { - return current->GameSize( discid, size ); + return current->GameSize(discid, size); } -s32 WBFS_DiskSpace( f32 *used, f32 *free ) +s32 WBFS_DiskSpace(f32 *used, f32 *free) { - return current->DiskSpace( used, free ); + return current->DiskSpace(used, free); } -s32 WBFS_RenameGame( u8 *discid, const void *newname ) +s32 WBFS_RenameGame(u8 *discid, const void *newname) { - s32 retval = current->RenameGame( discid, newname ); - if ( retval == 0 ) - gameList.clear(); + s32 retval = current->RenameGame(discid, newname); + if (retval == 0) gameList.clear(); return retval; } -s32 WBFS_ReIDGame( u8 *discid, const void *newID ) +s32 WBFS_ReIDGame(u8 *discid, const void *newID) { - s32 retval = current->ReIDGame( discid, newID ); - if ( retval == 0 ) - gameList.clear(); + s32 retval = current->ReIDGame(discid, newID); + if (retval == 0) gameList.clear(); return retval; } -f32 WBFS_EstimeGameSize( void ) +f32 WBFS_EstimeGameSize(void) { return current->EstimateGameSize(); } -int WBFS_GetFragList( u8 *id ) +int WBFS_GetFragList(u8 *id) { - return current->GetFragList( id ); + return current->GetFragList(id); } -bool WBFS_ShowFreeSpace( void ) +bool WBFS_ShowFreeSpace(void) { return current->ShowFreeSpace(); } @@ -309,23 +304,22 @@ bool WBFS_ShowFreeSpace( void ) int MountWBFS() { int ret = -1; - time_t currTime = time( 0 ); + time_t currTime = time(0); - while ( time( 0 ) - currTime < 30 ) + while (time(0) - currTime < 30) { USBDevice_deInit(); USBStorage2_Deinit(); USBDevice_Init(); - ret = WBFS_Init( WBFS_DEVICE_USB ); - printf( "%i...", int( time( 0 ) - currTime ) ); - if ( ret < 0 ) - sleep( 1 ); - else - break; + ret = WBFS_Init(WBFS_DEVICE_USB); + printf("%i...", int(time(0) - currTime)); + if (ret < 0) + sleep(1); + else break; } - printf( "\n" ); + printf("\n"); return ret; } diff --git a/source/usbloader/wbfs.h b/source/usbloader/wbfs.h index b90ec426..cea4d544 100644 --- a/source/usbloader/wbfs.h +++ b/source/usbloader/wbfs.h @@ -24,40 +24,39 @@ extern "C" extern char wbfs_fs_drive[16]; /* Prototypes */ - s32 WBFS_Init( u32 ); - s32 WBFS_Open( void ); - s32 WBFS_Format( u32, u32 ); - s32 WBFS_GetCount( u32 * ); - s32 WBFS_GetHeaders( struct discHdr *, u32, u32 ); -// s32 __WBFS_ReadDVD(void *fp, u32 lba, u32 len, void *iobuf); - wbfs_t *GetHddInfo( void ); - s32 WBFS_CheckGame( u8 * ); - s32 WBFS_AddGame( void ); - s32 WBFS_RemoveGame( u8 * ); - s32 WBFS_GameSize( u8 *, f32 * ); - bool WBFS_ShowFreeSpace( void ); - s32 WBFS_DiskSpace( f32 *, f32 * ); - s32 WBFS_RenameGame( u8 *, const void * ); - s32 WBFS_ReIDGame( u8 *discid, const void *newID ); - f32 WBFS_EstimeGameSize( void ); + s32 WBFS_Init(u32); + s32 WBFS_Open(void); + s32 WBFS_Format(u32, u32); + s32 WBFS_GetCount(u32 *); + s32 WBFS_GetHeaders(struct discHdr *, u32, u32); + // s32 __WBFS_ReadDVD(void *fp, u32 lba, u32 len, void *iobuf); + wbfs_t *GetHddInfo(void); + s32 WBFS_CheckGame(u8 *); + s32 WBFS_AddGame(void); + s32 WBFS_RemoveGame(u8 *); + s32 WBFS_GameSize(u8 *, f32 *); + bool WBFS_ShowFreeSpace(void); + s32 WBFS_DiskSpace(f32 *, f32 *); + s32 WBFS_RenameGame(u8 *, const void *); + s32 WBFS_ReIDGame(u8 *discid, const void *newID); + f32 WBFS_EstimeGameSize(void); - int WBFS_GetFragList( u8 *id ); + int WBFS_GetFragList(u8 *id); /* - s32 __WBFS_ReadUSB(void *fp, u32 lba, u32 count, void *iobuf); - s32 __WBFS_WriteUSB(void *fp, u32 lba, u32 count, void *iobuf); - */ + 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 ); + 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(); int MountWBFS(); - #ifdef __cplusplus } #endif diff --git a/source/usbloader/wbfs/wbfs_base.cpp b/source/usbloader/wbfs/wbfs_base.cpp index 4eb6c413..ed510726 100644 --- a/source/usbloader/wbfs/wbfs_base.cpp +++ b/source/usbloader/wbfs/wbfs_base.cpp @@ -15,58 +15,56 @@ s32 Wbfs::done = -1; s32 Wbfs::total = -1; u32 Wbfs::nb_sectors; -Wbfs::Wbfs( u32 device, u32 lba, u32 size ) : hdd( NULL ) +Wbfs::Wbfs(u32 device, u32 lba, u32 size) : + hdd(NULL) { this->device = device; this->lba = lba; this->size = size; } -void Wbfs::GetProgressValue( s32 * d, s32 * m ) +void Wbfs::GetProgressValue(s32 * d, s32 * m) { *d = done; *m = total; } -s32 Wbfs::Init( u32 device ) +s32 Wbfs::Init(u32 device) { s32 ret; - switch ( device ) + switch (device) { case WBFS_DEVICE_USB: /* Initialize USB storage */ ret = USBStorage2_Init(); - if ( ret >= 0 ) + if (ret >= 0) { /* Setup callbacks */ readCallback = __ReadUSB; writeCallback = __WriteUSB; /* Device info */ /* Get USB capacity */ - nb_sectors = USBStorage2_GetCapacity( §or_size ); - if ( !nb_sectors ) - return -1; + nb_sectors = USBStorage2_GetCapacity(§or_size); + if (!nb_sectors) return -1; } - else - return ret; + else return ret; break; case WBFS_DEVICE_SDHC: /* Initialize SDHC */ ret = SDHC_Init(); - if ( ret ) + if (ret) { /* Setup callbacks */ - readCallback = __ReadSDHC; + readCallback = __ReadSDHC; writeCallback = __WriteSDHC; /* Device info */ - nb_sectors = 0; + nb_sectors = 0; sector_size = SDHC_SECTOR_SIZE; } - else - return -1; + else return -1; break; } @@ -75,9 +73,9 @@ s32 Wbfs::Init( u32 device ) void Wbfs::Close() { - if ( hdd ) + if (hdd) { - wbfs_close( hdd ); + wbfs_close(hdd); hdd = NULL; } @@ -90,16 +88,16 @@ s32 Wbfs::Format() return -1; } -s32 Wbfs::CheckGame( u8 *discid ) +s32 Wbfs::CheckGame(u8 *discid) { wbfs_disc_t *disc = NULL; /* Try to open game disc */ - disc = OpenDisc( discid ); - if ( disc ) + disc = OpenDisc(discid); + if (disc) { /* Close disc */ - CloseDisc( disc ); + CloseDisc(disc); return 1; } @@ -107,25 +105,24 @@ s32 Wbfs::CheckGame( u8 *discid ) return 0; } -s32 Wbfs::GameSize( u8 *discid, f32 *size ) +s32 Wbfs::GameSize(u8 *discid, f32 *size) { wbfs_disc_t *disc = NULL; u32 sectors; /* Open disc */ - disc = OpenDisc( discid ); - if ( !disc ) - return -2; + disc = 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 */ - CloseDisc( disc ); + CloseDisc(disc); return 0; } @@ -140,17 +137,17 @@ bool Wbfs::Mounted() return hdd == NULL; } -int Wbfs::GetFragList( u8 *id ) +int Wbfs::GetFragList(u8 *id) { return 0; } -int Wbfs::GetFragList( char *filename, _frag_append_t append_fragment, FragList * ) +int Wbfs::GetFragList(char *filename, _frag_append_t append_fragment, FragList *) { return 0; } -bool Wbfs::ShowFreeSpace( void ) +bool Wbfs::ShowFreeSpace(void) { return true; } diff --git a/source/usbloader/wbfs/wbfs_base.h b/source/usbloader/wbfs/wbfs_base.h index 893aab76..82f019f5 100644 --- a/source/usbloader/wbfs/wbfs_base.h +++ b/source/usbloader/wbfs/wbfs_base.h @@ -8,37 +8,37 @@ class Wbfs { public: - Wbfs( u32, u32, u32 ); + Wbfs(u32, u32, u32); - void GetProgressValue( s32 * d, s32 * m ); - static s32 Init( u32 ); + void GetProgressValue(s32 * d, s32 * m); + static s32 Init(u32); void Close(); - s32 CheckGame( u8 * ); - s32 GameSize( u8 *, f32 * ); - wbfs_t *GetHddInfo( void ); + s32 CheckGame(u8 *); + s32 GameSize(u8 *, f32 *); + wbfs_t *GetHddInfo(void); bool Mounted(); - virtual int GetFragList( u8 *id ); - virtual int GetFragList( char *filename, _frag_append_t append_fragment, FragList * ); - virtual bool ShowFreeSpace( void ); + virtual int GetFragList(u8 *id); + virtual int GetFragList(char *filename, _frag_append_t append_fragment, FragList *); + virtual bool ShowFreeSpace(void); virtual s32 Open() = 0; - virtual wbfs_disc_t* OpenDisc( u8 *discid ) = 0; - virtual void CloseDisc( wbfs_disc_t *disc ) = 0; + virtual wbfs_disc_t* OpenDisc(u8 *discid) = 0; + virtual void CloseDisc(wbfs_disc_t *disc) = 0; virtual s32 Format(); - virtual s32 GetCount( u32 * ) = 0; - virtual s32 GetHeaders( struct discHdr *, u32, u32 ) = 0; - virtual s32 AddGame( void ) = 0; - virtual s32 RemoveGame( u8 * ) = 0; - virtual s32 DiskSpace( f32 *, f32 * ) = 0; - virtual s32 RenameGame( u8 *, const void * ) = 0; - virtual s32 ReIDGame( u8 *discid, const void *newID ) = 0; - virtual f32 EstimateGameSize( void ) = 0; + virtual s32 GetCount(u32 *) = 0; + virtual s32 GetHeaders(struct discHdr *, u32, u32) = 0; + virtual s32 AddGame(void) = 0; + virtual s32 RemoveGame(u8 *) = 0; + virtual s32 DiskSpace(f32 *, f32 *) = 0; + virtual s32 RenameGame(u8 *, const void *) = 0; + virtual s32 ReIDGame(u8 *discid, const void *newID) = 0; + virtual f32 EstimateGameSize(void) = 0; /* - static s32 OpenPart(u32 part_fat, u32 part_idx, u32 part_lba, u32 part_size, char *partition); - static s32 OpenNamed(char *partition); - static s32 OpenLBA(u32 lba, u32 size); - */ + static s32 OpenPart(u32 part_fat, u32 part_idx, u32 part_lba, u32 part_size, char *partition); + static s32 OpenNamed(char *partition); + static s32 OpenLBA(u32 lba, u32 size); + */ protected: static u32 nb_sectors; diff --git a/source/usbloader/wbfs/wbfs_fat.cpp b/source/usbloader/wbfs/wbfs_fat.cpp index 2e891d07..6aa66156 100644 --- a/source/usbloader/wbfs/wbfs_fat.cpp +++ b/source/usbloader/wbfs/wbfs_fat.cpp @@ -33,93 +33,94 @@ u32 Wbfs_Fat::fat_hdr_count = 0; extern "C" { - 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); extern FragList *frag_list; } u32 Wbfs_Fat::fat_sector_size = 512; -Wbfs_Fat::Wbfs_Fat( u32 device, u32 lba, u32 size ) : Wbfs( device, lba, size ) +Wbfs_Fat::Wbfs_Fat(u32 device, u32 lba, u32 size) : + Wbfs(device, lba, size) { } s32 Wbfs_Fat::Open() { - if ( device == WBFS_DEVICE_USB && lba == fat_usb_sec ) + if (device == WBFS_DEVICE_USB && lba == fat_usb_sec) { - strcpy( wbfs_fs_drive, "USB:" ); + strcpy(wbfs_fs_drive, "USB:"); } - else if ( device == WBFS_DEVICE_SDHC && lba == fat_sd_sec ) + else if (device == WBFS_DEVICE_SDHC && lba == fat_sd_sec) { - strcpy( wbfs_fs_drive, "SD:" ); + strcpy(wbfs_fs_drive, "SD:"); } else { - if ( WBFSDevice_Init( lba ) ) return -1; - strcpy( wbfs_fs_drive, "WBFS:" ); + if (WBFSDevice_Init(lba)) return -1; + strcpy(wbfs_fs_drive, "WBFS:"); } return 0; } -wbfs_disc_t* Wbfs_Fat::OpenDisc( u8 *discid ) +wbfs_disc_t* Wbfs_Fat::OpenDisc(u8 *discid) { char fname[MAX_FAT_PATH]; // wbfs 'partition' file - if ( !FindFilename( discid, fname, sizeof( fname ) ) ) return NULL; + if (!FindFilename(discid, fname, sizeof(fname))) return NULL; - if ( strcasecmp( strrchr( fname, '.' ), ".iso" ) == 0 ) + 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 = ( wbfs_disc_t * )calloc( sizeof( wbfs_disc_t ), 1 ); - if ( iso_file == NULL ) return NULL; + fd = open(fname, O_RDONLY); + if (fd == -1) return NULL; + wbfs_disc_t *iso_file = (wbfs_disc_t *) 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 = ( wbfs_disc_info_t* )fd; + iso_file->header = (wbfs_disc_info_t*) fd; return iso_file; } - wbfs_t *part = OpenPart( fname ); - if ( !part ) return NULL; - return wbfs_open_disc( part, discid ); + wbfs_t *part = OpenPart(fname); + if (!part) return NULL; + return wbfs_open_disc(part, discid); } -void Wbfs_Fat::CloseDisc( wbfs_disc_t* disc ) +void Wbfs_Fat::CloseDisc(wbfs_disc_t* disc) { - if ( !disc ) return; + if (!disc) return; wbfs_t *part = disc->p; // is this really a .iso file? - if ( part == &wbfs_iso_file ) + if (part == &wbfs_iso_file) { - close( ( int )disc->header ); - free( disc ); + close((int) disc->header); + free(disc); return; } - wbfs_close_disc( disc ); - ClosePart( part ); + wbfs_close_disc(disc); + ClosePart(part); return; } -s32 Wbfs_Fat::GetCount( u32 *count ) +s32 Wbfs_Fat::GetCount(u32 *count) { *count = 0; GetHeadersCount(); - if ( fat_hdr_count && fat_hdr_list ) + 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 = ( struct discHdr * ) malloc( size ); - if ( buf ) + int size = fat_hdr_count * sizeof(struct discHdr); + struct discHdr *buf = (struct discHdr *) malloc(size); + if (buf) { - memcpy( buf, fat_hdr_list, size ); + memcpy(buf, fat_hdr_list, size); SAFE_FREE( fat_hdr_list ); fat_hdr_list = buf; } @@ -128,19 +129,19 @@ s32 Wbfs_Fat::GetCount( u32 *count ) return 0; } -s32 Wbfs_Fat::GetHeaders( struct discHdr *outbuf, u32 cnt, u32 len ) +s32 Wbfs_Fat::GetHeaders(struct discHdr *outbuf, u32 cnt, u32 len) { u32 i; - if ( len > sizeof( struct discHdr ) ) + if (len > sizeof(struct discHdr)) { - len = sizeof( struct discHdr ); + len = sizeof(struct discHdr); } #ifdef DEBUG_WBFS gprintf( "\n\tGetHeaders" ); #endif - for ( i = 0; i < cnt && i < fat_hdr_count; i++ ) + for (i = 0; i < cnt && i < fat_hdr_count; i++) { - memcpy( &outbuf[i], &fat_hdr_list[i], len ); + memcpy(&outbuf[i], &fat_hdr_list[i], len); } SAFE_FREE( fat_hdr_list ); fat_hdr_count = 0; @@ -150,7 +151,7 @@ s32 Wbfs_Fat::GetHeaders( struct discHdr *outbuf, u32 cnt, u32 len ) return 0; } -s32 Wbfs_Fat::AddGame( void ) +s32 Wbfs_Fat::AddGame(void) { static struct discHdr header ATTRIBUTE_ALIGN( 32 ); char path[MAX_FAT_PATH]; @@ -158,16 +159,16 @@ s32 Wbfs_Fat::AddGame( void ) s32 ret; // read ID from DVD - Disc_ReadHeader( &header ); + Disc_ReadHeader(&header); // path - GetDir( &header, path ); + GetDir(&header, path); // create wbfs 'partition' file - part = CreatePart( header.id, path ); - if ( !part ) return -1; + part = 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 ) + switch (Settings.partitions_to_install) { case install_game_only: part_sel = ONLY_GAME_PARTITION; @@ -179,33 +180,33 @@ s32 Wbfs_Fat::AddGame( void ) part_sel = REMOVE_UPDATE_PARTITION; break; } - if ( copy_1_1 ) + if (copy_1_1) { part_sel = ALL_PARTITIONS; } wbfs_t *old_hdd = hdd; hdd = part; // used by spinner - ret = wbfs_add_disc( part, __ReadDVD, NULL, ProgressCallback, part_sel, copy_1_1 ); + ret = wbfs_add_disc(part, __ReadDVD, NULL, ProgressCallback, part_sel, copy_1_1); hdd = old_hdd; - wbfs_trim( part ); - ClosePart( part ); + wbfs_trim(part); + ClosePart(part); - if ( ret < 0 ) return ret; - mk_title_txt( &header, path ); + if (ret < 0) return ret; + mk_title_txt(&header, path); return 0; } -s32 Wbfs_Fat::RemoveGame( u8 *discid ) +s32 Wbfs_Fat::RemoveGame(u8 *discid) { char fname[MAX_FAT_PATH]; int loc; // wbfs 'partition' file - loc = FindFilename( discid, fname, sizeof( fname ) ); - if ( !loc ) return -1; - split_create( &split, fname, 0, 0, true ); - split_close( &split ); - if ( loc == 1 ) return 0; + loc = FindFilename(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 @@ -213,31 +214,31 @@ s32 Wbfs_Fat::RemoveGame( u8 *discid ) 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 ) + 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 ); + 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 ); + dirclose(dir_iter); // remove game subdir - unlink( path ); + unlink(path); return 0; } -s32 Wbfs_Fat::DiskSpace( f32 *used, f32 *free ) +s32 Wbfs_Fat::DiskSpace(f32 *used, f32 *free) { f32 size; int ret; @@ -245,57 +246,55 @@ s32 Wbfs_Fat::DiskSpace( f32 *used, f32 *free ) *used = 0; *free = 0; - ret = statvfs( wbfs_fs_drive, &wbfs_fat_vfs ); - if ( ret ) return -1; + 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; + 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; } -s32 Wbfs_Fat::RenameGame( u8 *discid, const void *newname ) +s32 Wbfs_Fat::RenameGame(u8 *discid, const void *newname) { - wbfs_t *part = OpenPart( ( char * ) discid ); - if ( !part ) - return -1; + wbfs_t *part = OpenPart((char *) discid); + if (!part) return -1; - s32 ret = wbfs_ren_disc( part, discid, ( u8* )newname ); + s32 ret = wbfs_ren_disc(part, discid, (u8*) newname); - ClosePart( part ); + ClosePart(part); return ret; } -s32 Wbfs_Fat::ReIDGame( u8 *discid, const void *newID ) +s32 Wbfs_Fat::ReIDGame(u8 *discid, const void *newID) { - wbfs_t *part = OpenPart( ( char * ) discid ); - if ( !part ) - return -1; + wbfs_t *part = OpenPart((char *) discid); + if (!part) return -1; - s32 ret = wbfs_rID_disc( part, discid, ( u8* )newID ); + s32 ret = wbfs_rID_disc(part, discid, (u8*) newID); - ClosePart( part ); + ClosePart(part); - if ( ret == 0 ) + if (ret == 0) { char fname[100]; char fnamenew[100]; s32 cnt = 0x31; - Filename( discid, fname, sizeof( fname ), NULL ); - Filename( ( u8* ) newID, fnamenew, sizeof( fnamenew ), NULL ); + Filename(discid, fname, sizeof(fname), NULL); + Filename((u8*) newID, fnamenew, sizeof(fnamenew), NULL); - int stringlength = strlen( fname ); + int stringlength = strlen(fname); - while ( rename( fname, fnamenew ) == 0 ) + while (rename(fname, fnamenew) == 0) { fname[stringlength] = cnt; - fname[stringlength+1] = 0; + fname[stringlength + 1] = 0; fnamenew[stringlength] = cnt; - fnamenew[stringlength+1] = 0; + fnamenew[stringlength + 1] = 0; cnt++; } } @@ -306,20 +305,18 @@ s32 Wbfs_Fat::ReIDGame( u8 *discid, const void *newID ) f32 Wbfs_Fat::EstimateGameSize() { wbfs_t *part = NULL; - u64 size = ( u64 )143432 * 2 * 0x8000ULL; + 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_rw_sector, nop_rw_sector, - NULL, fat_sector_size, n_sector, 0, 1 ); - if ( !part ) return -1; + part = wbfs_open_partition(nop_rw_sector, nop_rw_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 ) + if (Settings.fullcopy) { part_sel = ALL_PARTITIONS; } @@ -327,29 +324,29 @@ f32 Wbfs_Fat::EstimateGameSize() { part_sel = Settings.partitions_to_install == install_game_only ? ONLY_GAME_PARTITION : ALL_PARTITIONS; } - return wbfs_estimate_disc( part, __ReadDVD, NULL, part_sel ); + return wbfs_estimate_disc(part, __ReadDVD, NULL, part_sel); } // TITLE [GAMEID] -bool Wbfs_Fat::CheckLayoutB( char *fname, int len, u8* id, char *fname_title ) +bool Wbfs_Fat::CheckLayoutB(char *fname, int len, u8* id, char *fname_title) { - if ( len <= 8 ) return false; - if ( fname[len-8] != '[' || fname[len-1] != ']' ) return false; - if ( !is_gameid( &fname[len-7] ) ) return false; - strncpy( fname_title, fname, TITLE_LEN ); + if (len <= 8) return false; + if (fname[len - 8] != '[' || fname[len - 1] != ']') return false; + if (!is_gameid(&fname[len - 7])) return false; + strncpy(fname_title, fname, TITLE_LEN); // cut at '[' - fname_title[len-8] = 0; - int n = strlen( fname_title ); - if ( n == 0 ) return false; + fname_title[len - 8] = 0; + int n = strlen(fname_title); + if (n == 0) return false; // cut trailing _ or ' ' - if ( fname_title[n - 1] == ' ' || fname_title[n - 1] == '_' ) + if (fname_title[n - 1] == ' ' || fname_title[n - 1] == '_') { fname_title[n - 1] = 0; } - if ( strlen( fname_title ) == 0 ) return false; - if ( id ) + if (strlen(fname_title) == 0) return false; + if (id) { - memcpy( id, &fname[len-7], 6 ); + memcpy(id, &fname[len - 7], 6); id[6] = 0; } return true; @@ -379,71 +376,70 @@ s32 Wbfs_Fat::GetHeadersCount() SAFE_FREE( fat_hdr_list ); fat_hdr_count = 0; - strcpy( path, wbfs_fs_drive ); - strcat( path, wbfs_fat_dir ); + strcpy(path, wbfs_fs_drive); + strcat(path, wbfs_fat_dir); - dir_iter = diropen( path ); - if ( !dir_iter ) return 0; + dir_iter = diropen(path); + if (!dir_iter) return 0; - dir_iter = diropen( path ); - if ( !dir_iter ) return 0; + dir_iter = diropen(path); + if (!dir_iter) return 0; - while ( dirnext( dir_iter, fname, &st ) == 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" + if ((char) fname[0] == '.') continue; + len = strlen(fname); + if (len < 8) continue; // "GAMEID_x" - memcpy( id, fname, 6 ); + memcpy(id, fname, 6); id[6] = 0; *fname_title = 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 ) + if (is_dir) { int lay_a = 0; int lay_b = 0; - if ( fname[6] == '_' && is_gameid( ( char* )id ) ) + if (fname[6] == '_' && is_gameid((char*) id)) { // usb:/wbfs/GAMEID_TITLE/GAMEID.wbfs lay_a = 1; } - if ( CheckLayoutB( fname, len, NULL, fname_title ) ) + if (CheckLayoutB(fname, len, NULL, fname_title)) { // usb:/wbfs/TITLE[GAMEID]/GAMEID.wbfs lay_b = 1; } - if ( !lay_a && !lay_b ) continue; - if ( lay_a ) + if (!lay_a && !lay_b) continue; + if (lay_a) { - strncpy( dir_title, &fname[7], sizeof( dir_title ) ); + strncpy(dir_title, &fname[7], sizeof(dir_title)); } else { -try_lay_b: - if ( !CheckLayoutB( fname, len, id, fname_title ) ) continue; + try_lay_b: if (!CheckLayoutB(fname, len, id, fname_title)) continue; } - snprintf( fpath, sizeof( fpath ), "%s/%s/%s.wbfs", path, fname, id ); + 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 (fat_hdr_count < 50 || (lay_a && lay_b)) { - if ( stat( fpath, &st ) == -1 ) + 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 ) + strcpy(strrchr(fpath, '.'), ".iso"); // replace .wbfs with .iso + if (stat(fpath, &st) == -1) { //printf("missing: %s\n", fpath); // try .ciso - strcpy( strrchr( fpath, '.' ), ".ciso" ); // replace .iso with .ciso - if ( stat( fpath, &st ) == -1 ) + strcpy(strrchr(fpath, '.'), ".ciso"); // replace .iso with .ciso + if (stat(fpath, &st) == -1) { - if ( lay_a && lay_b == 1 ) + 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 @@ -466,51 +462,49 @@ try_lay_b: // usb:/wbfs/GAMEID.wbfs // or usb:/wbfs/GAMEID.iso // or usb:/wbfs/GAMEID.ciso - p = strrchr( fname, '.' ); - if ( !p ) continue; - if ( ( strcasecmp( p, ".wbfs" ) != 0 ) - && ( strcasecmp( p, ".iso" ) != 0 ) - && ( strcasecmp( p, ".ciso" ) != 0 ) ) continue; + p = strrchr(fname, '.'); + if (!p) continue; + if ((strcasecmp(p, ".wbfs") != 0) && (strcasecmp(p, ".iso") != 0) && (strcasecmp(p, ".ciso") != 0)) continue; int n = p - fname; // length withouth .wbfs - if ( n != 6 ) + if (n != 6) { // TITLE [GAMEID].wbfs - if ( !CheckLayoutB( fname, n, id, fname_title ) ) continue; + if (!CheckLayoutB(fname, n, id, fname_title)) continue; } - snprintf( fpath, sizeof( fpath ), "%s/%s", path, fname ); + 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 (st.st_size < 1024 * 1024) continue; // if we have titles.txt entry use that - title = cfg_get_title( id ); + title = cfg_get_title(id); // if no titles.txt get title from dir or file name - if ( !title && *fname_title ) + if (!title && *fname_title) { title = fname_title; } - if ( title ) + if (title) { - memset( &tmpHdr, 0, sizeof( tmpHdr ) ); - memcpy( tmpHdr.id, id, 6 ); - strncpy( tmpHdr.title, title, sizeof( tmpHdr.title ) - 1 ); + 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 ) + if (strcasecmp(strrchr(fpath, '.'), ".wbfs") == 0) { // wbfs file directly - FILE *fp = fopen( fpath, "rb" ); - if ( fp != NULL ) + FILE *fp = fopen(fpath, "rb"); + if (fp != NULL) { - fseek( fp, 512, SEEK_SET ); - fread( &tmpHdr, sizeof( struct discHdr ), 1, fp ); - fclose( fp ); + fseek(fp, 512, SEEK_SET); + fread(&tmpHdr, sizeof(struct discHdr), 1, fp); + fclose(fp); tmpHdr.is_ciso = 0; - if ( ( tmpHdr.magic == 0x5D1C9EA3 ) && ( memcmp( tmpHdr.id, id, 6 ) == 0 ) ) + if ((tmpHdr.magic == 0x5D1C9EA3) && (memcmp(tmpHdr.id, id, 6) == 0)) { goto add_hdr; } @@ -518,47 +512,46 @@ try_lay_b: // no title found, read it from wbfs file // but this is a little bit slower // open 'partition' file - part = OpenPart( fpath ); - if ( !part ) + part = OpenPart(fpath); + if (!part) { continue; } // Get header - ret = wbfs_get_disc_info( part, 0, ( u8* ) & tmpHdr, - sizeof( struct discHdr ), &size ); - ClosePart( part ); - if ( ret == 0 ) + ret = wbfs_get_disc_info(part, 0, (u8*) &tmpHdr, sizeof(struct discHdr), &size); + ClosePart(part); + if (ret == 0) { goto add_hdr; } } - else if ( strcasecmp( strrchr( fpath, '.' ), ".iso" ) == 0 ) + else if (strcasecmp(strrchr(fpath, '.'), ".iso") == 0) { // iso file - FILE *fp = fopen( fpath, "rb" ); - if ( fp != NULL ) + FILE *fp = fopen(fpath, "rb"); + if (fp != NULL) { - fseek( fp, 0, SEEK_SET ); - fread( &tmpHdr, sizeof( struct discHdr ), 1, fp ); - fclose( fp ); + fseek(fp, 0, SEEK_SET); + fread(&tmpHdr, sizeof(struct discHdr), 1, fp); + fclose(fp); tmpHdr.is_ciso = 0; - if ( ( tmpHdr.magic == 0x5D1C9EA3 ) && ( memcmp( tmpHdr.id, id, 6 ) == 0 ) ) + if ((tmpHdr.magic == 0x5D1C9EA3) && (memcmp(tmpHdr.id, id, 6) == 0)) { goto add_hdr; } } } - else if ( strcasecmp( strrchr( fpath, '.' ), ".ciso" ) == 0 ) + else if (strcasecmp(strrchr(fpath, '.'), ".ciso") == 0) { // ciso file - FILE *fp = fopen( fpath, "rb" ); - if ( fp != NULL ) + FILE *fp = fopen(fpath, "rb"); + if (fp != NULL) { - fseek( fp, 0x8000, SEEK_SET ); - fread( &tmpHdr, sizeof( struct discHdr ), 1, fp ); - fclose( fp ); + fseek(fp, 0x8000, SEEK_SET); + fread(&tmpHdr, sizeof(struct discHdr), 1, fp); + fclose(fp); tmpHdr.is_ciso = 1; - if ( ( tmpHdr.magic == 0x5D1C9EA3 ) && ( memcmp( tmpHdr.id, id, 6 ) == 0 ) ) + if ((tmpHdr.magic == 0x5D1C9EA3) && (memcmp(tmpHdr.id, id, 6) == 0)) { goto add_hdr; } @@ -568,93 +561,90 @@ try_lay_b: continue; // succes: add tmpHdr to list: -add_hdr: - memset( &st, 0, sizeof( st ) ); + add_hdr: memset(&st, 0, sizeof(st)); //printf("added: %.6s %.20s\n", tmpHdr.id, tmpHdr.title); Wpad_WaitButtons(); fat_hdr_count++; - fat_hdr_list = ( struct discHdr * ) realloc( fat_hdr_list, fat_hdr_count * sizeof( struct discHdr ) ); - memcpy( &fat_hdr_list[fat_hdr_count-1], &tmpHdr, sizeof( struct discHdr ) ); + fat_hdr_list = (struct discHdr *) 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 ); + dirclose(dir_iter); //dbg_time2("\nFAT_GetCount"); Wpad_WaitButtonsCommon(); return 0; } -int Wbfs_Fat::FindFilename( u8 *id, char *fname, int len ) +int Wbfs_Fat::FindFilename(u8 *id, char *fname, int len) { struct stat st; // look for direct .wbfs file - Filename( id, fname, len, NULL ); - if ( stat( fname, &st ) == 0 ) return 1; + Filename(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; + strcpy(strrchr(fname, '.'), ".iso"); // replace .wbfs with .iso + if (stat(fname, &st) == 0) return 1; // look for direct .ciso file - strcpy( strrchr( fname, '.' ), ".ciso" ); // replace .iso with .ciso - if ( stat( fname, &st ) == 0 ) return 1; + strcpy(strrchr(fname, '.'), ".ciso"); // replace .iso with .ciso + 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 ); + 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 ) + if (!dir_iter) { return 0; } - while ( dirnext( dir_iter, name, &st ) == 0 ) + while (dirnext(dir_iter, name, &st) == 0) { //dbg_printf("name:%s\n", name); - if ( name[0] == '.' ) continue; - int n = strlen( name ); - if ( n < 8 ) continue; - if ( S_ISDIR( st.st_mode ) ) + if (name[0] == '.') continue; + int n = strlen(name); + if (n < 8) continue; + if (S_ISDIR( st.st_mode )) { - if ( name[6] == '_' ) + if (name[6] == '_') { // GAMEID_TITLE - if ( strncmp( name, ( char* )id, 6 ) != 0 ) goto try_alter; + if (strncmp(name, (char*) id, 6) != 0) goto try_alter; } else { -try_alter: + try_alter: // TITLE [GAMEID] - if ( name[n-8] != '[' || name[n-1] != ']' ) continue; - if ( strncmp( &name[n-7], ( char* )id, 6 ) != 0 ) continue; + 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; + 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; + snprintf(fname, len, "%s/%s/%.6s.iso", path, name, id); + if (stat(fname, &st) == 0) break; // look for .ciso file - snprintf( fname, len, "%s/%s/%.6s.ciso", path, name, id ); + snprintf(fname, len, "%s/%s/%.6s.ciso", path, name, id); } else { // TITLE [GAMEID].wbfs char fn_title[TITLE_LEN]; u8 fn_id[8]; - char *p = strrchr( name, '.' ); - if ( !p ) continue; - if ( ( strcasecmp( p, ".wbfs" ) != 0 ) - && ( strcasecmp( p, ".iso" ) != 0 ) - && ( strcasecmp( p, ".ciso" ) != 0 ) ) continue; + char *p = strrchr(name, '.'); + if (!p) continue; + if ((strcasecmp(p, ".wbfs") != 0) && (strcasecmp(p, ".iso") != 0) && (strcasecmp(p, ".ciso") != 0)) continue; int n = p - name; // length withouth .wbfs - if ( !CheckLayoutB( name, n, fn_id, fn_title ) ) continue; - if ( strncmp( ( char* )fn_id, ( char* )id, 6 ) != 0 ) continue; - snprintf( fname, len, "%s/%s", path, name ); + if (!CheckLayoutB(name, n, fn_id, fn_title)) continue; + if (strncmp((char*) fn_id, (char*) id, 6) != 0) continue; + snprintf(fname, len, "%s/%s", path, name); } - if ( stat( fname, &st ) == 0 ) break; + if (stat(fname, &st) == 0) break; *fname = 0; } - dirclose( dir_iter ); - if ( *fname ) + dirclose(dir_iter); + if (*fname) { // found //printf("found:%s\n", fname); @@ -664,182 +654,177 @@ try_alter: return 0; } -wbfs_t* Wbfs_Fat::OpenPart( char *fname ) +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_rw_sector, //readonly //split_write_sector, - &split, fat_sector_size, split.total_sec, 0, 0 ); - if ( !part ) + ret = split_open(&split, fname); + if (ret) return NULL; + part = wbfs_open_partition(split_read_sector, nop_rw_sector, //readonly //split_write_sector, + &split, fat_sector_size, split.total_sec, 0, 0); + if (!part) { - split_close( &split ); + split_close(&split); } return part; } -void Wbfs_Fat::ClosePart( wbfs_t* 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 ); + if (!part) return; + split_info_t *s = (split_info_t*) part->callback_data; + wbfs_close(part); + if (s) split_close(s); } -void Wbfs_Fat::Filename( u8 *id, char *fname, int len, char *path ) +void Wbfs_Fat::Filename(u8 *id, char *fname, int len, char *path) { - if ( path == NULL ) + if (path == NULL) { - snprintf( fname, len, "%s%s/%.6s.wbfs", wbfs_fs_drive, wbfs_fat_dir, id ); + snprintf(fname, len, "%s%s/%.6s.wbfs", wbfs_fs_drive, wbfs_fat_dir, id); } else { - snprintf( fname, len, "%s/%.6s.wbfs", path, id ); + snprintf(fname, len, "%s/%.6s.wbfs", path, id); } } -void Wbfs_Fat::GetDir( struct discHdr *header, char *path ) +void Wbfs_Fat::GetDir(struct discHdr *header, char *path) { - strcpy( path, wbfs_fs_drive ); - strcat( path, wbfs_fat_dir ); - if ( Settings.FatInstallToDir ) + strcpy(path, wbfs_fs_drive); + strcat(path, wbfs_fat_dir); + if (Settings.FatInstallToDir) { - strcat( path, "/" ); + strcat(path, "/"); int layout = 0; - if ( Settings.FatInstallToDir == 2 ) layout = 1; - mk_gameid_title( header, path + strlen( path ), 0, layout ); + if (Settings.FatInstallToDir == 2) layout = 1; + mk_gameid_title(header, path + strlen(path), 0, layout); } } -wbfs_t* Wbfs_Fat::CreatePart( u8 *id, char *path ) +wbfs_t* Wbfs_Fat::CreatePart(u8 *id, char *path) { char fname[MAX_FAT_PATH]; wbfs_t *part = NULL; - u64 size = ( u64 )143432 * 2 * 0x8000ULL; + 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 - Filename( 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; + snprintf(fname, sizeof(fname), "%s%s", wbfs_fs_drive, wbfs_fat_dir); + mkdir(fname, 0777); // base usb:/wbfs + mkdir(path, 0777); // game subdir + Filename(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 ) + int fd = split_get_file(&split, 0, &scnt, 0); + if (fd < 0) { - printf( "ERROR creating file\n" ); - sleep( 2 ); - split_close( &split ); + 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 ) + part = wbfs_open_partition(split_read_sector, split_write_sector, &split, fat_sector_size, n_sector, 0, 1); + if (!part) { - split_close( &split ); + split_close(&split); } return part; } -void Wbfs_Fat::mk_title_txt( struct discHdr *header, char *path ) +void Wbfs_Fat::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); } -void Wbfs_Fat::mk_gameid_title( struct discHdr *header, char *name, int re_space, int layout ) +void Wbfs_Fat::mk_gameid_title(struct discHdr *header, char *name, int re_space, int layout) { int i, len; char title[65]; char id[8]; - memcpy( name, header->id, 6 ); + memcpy(name, header->id, 6); name[6] = 0; - strncpy( title, get_title( header ), sizeof( title ) ); - title_filename( title ); + strncpy(title, get_title(header), sizeof(title)); + title_filename(title); - if ( layout == 0 ) + if (layout == 0) { - sprintf( name, "%s_%s", id, title ); + sprintf(name, "%s_%s", id, title); } else { - sprintf( name, "%s [%s]", title, id ); + sprintf(name, "%s [%s]", title, id); } // replace space with '_' - if ( re_space ) + if (re_space) { - len = strlen( name ); - for ( i = 0; i < len; i++ ) + len = strlen(name); + for (i = 0; i < len; i++) { - if ( name[i] == ' ' ) name[i] = '_'; + if (name[i] == ' ') name[i] = '_'; } } } -void Wbfs_Fat::title_filename( char *title ) +void Wbfs_Fat::title_filename(char *title) { int i, len; // trim leading space - len = strlen( title ); - while ( *title == ' ' ) + len = strlen(title); + while (*title == ' ') { - memmove( title, title + 1, len ); + memmove(title, title + 1, len); len--; } // trim trailing space - not allowed on windows directories - while ( len && title[len-1] == ' ' ) + while (len && title[len - 1] == ' ') { - title[len-1] = 0; + title[len - 1] = 0; len--; } // replace silly chars with '_' - for ( i = 0; i < len; i++ ) + for (i = 0; i < len; i++) { - if ( strchr( invalid_path, title[i] ) || iscntrl( ( int ) title[i] ) ) + if (strchr(invalid_path, title[i]) || iscntrl((int) title[i])) { title[i] = '_'; } } } -bool Wbfs_Fat::is_gameid( char *id ) +bool Wbfs_Fat::is_gameid(char *id) { int i; - for ( i = 0; i < 6; i++ ) + for (i = 0; i < 6; i++) { - if ( !isalnum( ( u32 ) id[i] ) ) return false; + if (!isalnum((u32) id[i])) return false; } return true; } -int Wbfs_Fat::GetFragList( u8 *id ) +int Wbfs_Fat::GetFragList(u8 *id) { char fname[1024]; char fname1[1024]; @@ -852,64 +837,63 @@ int Wbfs_Fat::GetFragList( u8 *id ) int is_wbfs = 0; int ret_val = -1; - ret = FindFilename( id, fname, sizeof( fname ) ); - if ( !ret ) return -1; + ret = FindFilename(id, fname, sizeof(fname)); + if (!ret) return -1; - if ( strcasecmp( strrchr( fname, '.' ), ".wbfs" ) == 0 ) + if (strcasecmp(strrchr(fname, '.'), ".wbfs") == 0) { is_wbfs = 1; } - fs = ( FragList * ) malloc( sizeof( FragList ) ); - fa = ( FragList * ) malloc( sizeof( FragList ) ); - fw = ( FragList * ) malloc( sizeof( FragList ) ); + fs = (FragList *) malloc(sizeof(FragList)); + fa = (FragList *) malloc(sizeof(FragList)); + fw = (FragList *) malloc(sizeof(FragList)); - frag_init( fa, MAX_FRAG ); + frag_init(fa, MAX_FRAG); - for ( i = 0; i < 10; i++ ) + for (i = 0; i < 10; i++) { - frag_init( fs, MAX_FRAG ); - if ( i > 0 ) + frag_init(fs, MAX_FRAG); + if (i > 0) { - fname[strlen( fname )-1] = '0' + i; - if ( stat( fname, &st ) == -1 ) break; + fname[strlen(fname) - 1] = '0' + i; + if (stat(fname, &st) == -1) break; } - strcpy( fname1, fname ); - if ( ( ret = GetFragList( ( char * ) & fname, &_frag_append, fs ) ) ) + strcpy(fname1, fname); + if ((ret = GetFragList((char *) &fname, &_frag_append, fs))) { ret_val = ret; goto out; } - frag_concat( fa, fs ); + frag_concat(fa, fs); } - frag_list = ( FragList * ) malloc( sizeof( FragList ) ); - frag_init( frag_list, MAX_FRAG ); - if ( is_wbfs ) + frag_list = (FragList *) malloc(sizeof(FragList)); + frag_init(frag_list, MAX_FRAG); + if (is_wbfs) { // if wbfs file format, remap. //printf("=====\n"); - wbfs_disc_t *d = OpenDisc( id ); - if ( !d ) goto out; - frag_init( fw, MAX_FRAG ); - ret = wbfs_get_fragments( d, &_frag_append, fw ); - if ( ret ) goto out; - CloseDisc( d ); + wbfs_disc_t *d = OpenDisc(id); + if (!d) goto out; + frag_init(fw, MAX_FRAG); + ret = wbfs_get_fragments(d, &_frag_append, fw); + if (ret) goto out; + CloseDisc(d); // DEBUG: //frag_list->num = MAX_FRAG-10; // stress test - ret = frag_remap( frag_list, fw, fa ); - if ( ret ) goto out; + 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 ) ); + memcpy(frag_list, fa, sizeof(FragList)); } ret_val = 0; -out: - if ( ret_val ) + out: if (ret_val) { // error SAFE_FREE( frag_list ); @@ -920,12 +904,12 @@ out: return ret_val; } -int Wbfs_Fat::GetFragList( char *filename, _frag_append_t append_fragment, FragList *fs ) +int Wbfs_Fat::GetFragList(char *filename, _frag_append_t append_fragment, FragList *fs) { - return _FAT_get_fragments( filename, append_fragment, fs ); + return _FAT_get_fragments(filename, append_fragment, fs); } -bool Wbfs_Fat::ShowFreeSpace( void ) +bool Wbfs_Fat::ShowFreeSpace(void) { return false; } diff --git a/source/usbloader/wbfs/wbfs_fat.h b/source/usbloader/wbfs/wbfs_fat.h index b3947d40..ebdfcb40 100644 --- a/source/usbloader/wbfs/wbfs_fat.h +++ b/source/usbloader/wbfs/wbfs_fat.h @@ -6,32 +6,32 @@ #include "usbloader/splits.h" #include "wbfs_base.h" -class Wbfs_Fat : public Wbfs +class Wbfs_Fat: public Wbfs { public: - Wbfs_Fat( u32 device, u32 lba, u32 size ); + Wbfs_Fat(u32 device, u32 lba, u32 size); ~Wbfs_Fat(); virtual s32 Open(); - wbfs_disc_t* OpenDisc( u8 * ); - void CloseDisc( wbfs_disc_t * ); + wbfs_disc_t* OpenDisc(u8 *); + void CloseDisc(wbfs_disc_t *); - s32 GetCount( u32 * ); - s32 GetHeaders( struct discHdr *, u32, u32 ); + s32 GetCount(u32 *); + s32 GetHeaders(struct discHdr *, u32, u32); s32 AddGame(); - s32 RemoveGame( u8 * ); + s32 RemoveGame(u8 *); - s32 DiskSpace( f32 *, f32 * ); + s32 DiskSpace(f32 *, f32 *); - s32 RenameGame( u8 *, const void * ); - s32 ReIDGame( u8 *, const void * ); + s32 RenameGame(u8 *, const void *); + s32 ReIDGame(u8 *, const void *); f32 EstimateGameSize(); - int GetFragList( u8 * ); - virtual int GetFragList( char *, _frag_append_t, FragList * ); - virtual bool ShowFreeSpace( void ); + int GetFragList(u8 *); + virtual int GetFragList(char *, _frag_append_t, FragList *); + virtual bool ShowFreeSpace(void); protected: static char wbfs_fs_drive[16]; @@ -44,21 +44,24 @@ class Wbfs_Fat : public Wbfs static struct discHdr *fat_hdr_list; static u32 fat_hdr_count; - wbfs_t* OpenPart( char *fname ); - void ClosePart( wbfs_t* part ); - wbfs_t* CreatePart( u8 *id, char *path ); - int FindFilename( u8 *id, char *fname, int len ); - void Filename( u8 *id, char *fname, int len, char *path ); - bool CheckLayoutB( char *fname, int len, u8* id, char *fname_title ); + wbfs_t* OpenPart(char *fname); + void ClosePart(wbfs_t* part); + wbfs_t* CreatePart(u8 *id, char *path); + int FindFilename(u8 *id, char *fname, int len); + void Filename(u8 *id, char *fname, int len, char *path); + bool CheckLayoutB(char *fname, int len, u8* id, char *fname_title); s32 GetHeadersCount(); - void GetDir( struct discHdr *header, char *path ); + void GetDir(struct discHdr *header, char *path); - void mk_title_txt( struct discHdr *header, char *path ); - void mk_gameid_title( struct discHdr *header, char *name, int re_space, int layout ); - void title_filename( char *title ); - bool is_gameid( char *id ); + void mk_title_txt(struct discHdr *header, char *path); + void mk_gameid_title(struct discHdr *header, char *name, int re_space, int layout); + void title_filename(char *title); + bool is_gameid(char *id); - static int nop_rw_sector( void *_fp, u32 lba, u32 count, void* buf ) { return 0; } + static int nop_rw_sector(void *_fp, u32 lba, u32 count, void* buf) + { + return 0; + } }; #endif //_WBFS_FAT_H diff --git a/source/usbloader/wbfs/wbfs_ntfs.cpp b/source/usbloader/wbfs/wbfs_ntfs.cpp index db227280..d70f8c8b 100644 --- a/source/usbloader/wbfs/wbfs_ntfs.cpp +++ b/source/usbloader/wbfs/wbfs_ntfs.cpp @@ -4,27 +4,27 @@ s32 Wbfs_Ntfs::Open() { - strcpy( wbfs_fs_drive, "NTFS:" ); - return MountNTFS( lba ); + strcpy(wbfs_fs_drive, "NTFS:"); + return MountNTFS(lba); } -int Wbfs_Ntfs::GetFragList( char *filename, _frag_append_t append_fragment, FragList *fs ) +int Wbfs_Ntfs::GetFragList(char *filename, _frag_append_t append_fragment, FragList *fs) { - int ret = _NTFS_get_fragments( filename, append_fragment, fs ); - if ( ret ) + int ret = _NTFS_get_fragments(filename, append_fragment, fs); + if (ret) { return ret; } // offset to start of partition - for ( unsigned int j = 0; j < fs->num; j++ ) + for (unsigned int j = 0; j < fs->num; j++) { fs->frag[j].sector += fs_ntfs_sec; } return ret; } -bool Wbfs_Ntfs::ShowFreeSpace( void ) +bool Wbfs_Ntfs::ShowFreeSpace(void) { return true; } diff --git a/source/usbloader/wbfs/wbfs_ntfs.h b/source/usbloader/wbfs/wbfs_ntfs.h index 9a386a35..fda5f607 100644 --- a/source/usbloader/wbfs/wbfs_ntfs.h +++ b/source/usbloader/wbfs/wbfs_ntfs.h @@ -3,15 +3,18 @@ #include "wbfs_fat.h" -class Wbfs_Ntfs : public Wbfs_Fat +class Wbfs_Ntfs: public Wbfs_Fat { public: - Wbfs_Ntfs( u32 device, u32 lba, u32 size ) : Wbfs_Fat( device, lba, size ) {} + Wbfs_Ntfs(u32 device, u32 lba, u32 size) : + Wbfs_Fat(device, lba, size) + { + } virtual s32 Open(); - int GetFragList( char *filename, _frag_append_t append_fragment, FragList *fs ); - bool ShowFreeSpace( void ); + int GetFragList(char *filename, _frag_append_t append_fragment, FragList *fs); + bool ShowFreeSpace(void); }; #endif //_WBFS_NTFS_H diff --git a/source/usbloader/wbfs/wbfs_rw.c b/source/usbloader/wbfs/wbfs_rw.c index 06a4de01..d2aa6f77 100644 --- a/source/usbloader/wbfs/wbfs_rw.c +++ b/source/usbloader/wbfs/wbfs_rw.c @@ -11,15 +11,15 @@ #define MAX_NB_SECTORS 32 u32 sector_size = 512; -rw_sector_callback_t readCallback = NULL; +rw_sector_callback_t readCallback = NULL; rw_sector_callback_t writeCallback = NULL; -void SetSectorSize( u32 size ) +void SetSectorSize(u32 size) { sector_size = size; } -s32 __ReadDVD( void *fp, u32 lba, u32 len, void *iobuf ) +s32 __ReadDVD(void *fp, u32 lba, u32 len, void *iobuf) { void *buffer = NULL; @@ -28,68 +28,62 @@ s32 __ReadDVD( void *fp, u32 lba, u32 len, void *iobuf ) s32 ret; /* Calculate offset */ - offset = ( ( u64 )lba ) << 2; + offset = ((u64) lba) << 2; /* Calcualte sizes */ - mod = len % 32; + mod = len % 32; size = len - mod; /* Read aligned data */ - if ( size ) + if (size) { - ret = WDVD_UnencryptedRead( iobuf, size, offset ); - if ( ret < 0 ) - goto out; + ret = WDVD_UnencryptedRead(iobuf, size, offset); + if (ret < 0) goto out; } /* Read non-aligned data */ - if ( mod ) + if (mod) { /* Allocate memory */ - buffer = memalign( 32, 0x20 ); - if ( !buffer ) - return -1; + buffer = memalign(32, 0x20); + if (!buffer) return -1; /* Read data */ - ret = WDVD_UnencryptedRead( buffer, 0x20, offset + size ); - if ( ret < 0 ) - goto out; + ret = WDVD_UnencryptedRead(buffer, 0x20, offset + size); + if (ret < 0) goto out; /* Copy data */ - void *ptr = ( ( u8 * ) iobuf ) + size; - memcpy( ptr, buffer, mod ); + void *ptr = ((u8 *) iobuf) + size; + memcpy(ptr, buffer, mod); } /* Success */ ret = 0; -out: + out: /* Free memory */ - if ( buffer ) - free( buffer ); + if (buffer) free(buffer); return ret; } -s32 __ReadUSB( void *fp, u32 lba, u32 count, void *iobuf ) +s32 __ReadUSB(void *fp, u32 lba, u32 count, void *iobuf) { u32 cnt = 0; s32 ret; /* Do reads */ - while ( cnt < count ) + while (cnt < count) { - void *ptr = ( ( u8 * )iobuf ) + ( cnt * sector_size ); - u32 sectors = ( count - cnt ); + void *ptr = ((u8 *) iobuf) + (cnt * sector_size); + u32 sectors = (count - cnt); /* Read sectors is too big */ - if ( sectors > MAX_NB_SECTORS ) - sectors = MAX_NB_SECTORS; + if (sectors > MAX_NB_SECTORS) sectors = MAX_NB_SECTORS; /* USB read */ - ret = USBStorage2_ReadSectors( lba + cnt, sectors, ptr ); - if ( ret < 0 ) - return ret; + ret = USBStorage2_ReadSectors(lba + cnt, sectors, ptr); + if (ret < 0) return ret; /* Increment counter */ cnt += sectors; @@ -98,25 +92,23 @@ s32 __ReadUSB( void *fp, u32 lba, u32 count, void *iobuf ) return 0; } -s32 __WriteUSB( void *fp, u32 lba, u32 count, void *iobuf ) +s32 __WriteUSB(void *fp, u32 lba, u32 count, void *iobuf) { u32 cnt = 0; s32 ret; /* Do writes */ - while ( cnt < count ) + while (cnt < count) { - void *ptr = ( ( u8 * )iobuf ) + ( cnt * sector_size ); - u32 sectors = ( count - cnt ); + void *ptr = ((u8 *) iobuf) + (cnt * sector_size); + u32 sectors = (count - cnt); /* Write sectors is too big */ - if ( sectors > MAX_NB_SECTORS ) - sectors = MAX_NB_SECTORS; + if (sectors > MAX_NB_SECTORS) sectors = MAX_NB_SECTORS; /* USB write */ - ret = USBStorage2_WriteSectors( lba + cnt, sectors, ptr ); - if ( ret < 0 ) - return ret; + ret = USBStorage2_WriteSectors(lba + cnt, sectors, ptr); + if (ret < 0) return ret; /* Increment counter */ cnt += sectors; @@ -125,25 +117,23 @@ s32 __WriteUSB( void *fp, u32 lba, u32 count, void *iobuf ) return 0; } -s32 __ReadSDHC( void *fp, u32 lba, u32 count, void *iobuf ) +s32 __ReadSDHC(void *fp, u32 lba, u32 count, void *iobuf) { u32 cnt = 0; s32 ret; /* Do reads */ - while ( cnt < count ) + while (cnt < count) { - void *ptr = ( ( u8 * )iobuf ) + ( cnt * sector_size ); - u32 sectors = ( count - cnt ); + void *ptr = ((u8 *) iobuf) + (cnt * sector_size); + u32 sectors = (count - cnt); /* Read sectors is too big */ - if ( sectors > MAX_NB_SECTORS ) - sectors = MAX_NB_SECTORS; + if (sectors > MAX_NB_SECTORS) sectors = MAX_NB_SECTORS; /* SDHC read */ - ret = SDHC_ReadSectors( lba + cnt, sectors, ptr ); - if ( !ret ) - return -1; + ret = SDHC_ReadSectors(lba + cnt, sectors, ptr); + if (!ret) return -1; /* Increment counter */ cnt += sectors; @@ -152,25 +142,23 @@ s32 __ReadSDHC( void *fp, u32 lba, u32 count, void *iobuf ) return 0; } -s32 __WriteSDHC( void *fp, u32 lba, u32 count, void *iobuf ) +s32 __WriteSDHC(void *fp, u32 lba, u32 count, void *iobuf) { u32 cnt = 0; s32 ret; /* Do writes */ - while ( cnt < count ) + while (cnt < count) { - void *ptr = ( ( u8 * )iobuf ) + ( cnt * sector_size ); - u32 sectors = ( count - cnt ); + void *ptr = ((u8 *) iobuf) + (cnt * sector_size); + u32 sectors = (count - cnt); /* Write sectors is too big */ - if ( sectors > MAX_NB_SECTORS ) - sectors = MAX_NB_SECTORS; + if (sectors > MAX_NB_SECTORS) sectors = MAX_NB_SECTORS; /* SDHC write */ - ret = SDHC_WriteSectors( lba + cnt, sectors, ptr ); - if ( !ret ) - return -1; + ret = SDHC_WriteSectors(lba + cnt, sectors, ptr); + if (!ret) return -1; /* Increment counter */ cnt += sectors; diff --git a/source/usbloader/wbfs/wbfs_rw.h b/source/usbloader/wbfs/wbfs_rw.h index 898f9289..4b91849a 100644 --- a/source/usbloader/wbfs/wbfs_rw.h +++ b/source/usbloader/wbfs/wbfs_rw.h @@ -12,15 +12,14 @@ extern "C" extern rw_sector_callback_t readCallback; extern rw_sector_callback_t writeCallback; - s32 __ReadDVD( void *fp, u32 lba, u32 len, void *iobuf ); - s32 __ReadUSB( void *fp, u32 lba, u32 count, void *iobuf ); - s32 __WriteUSB( void *fp, u32 lba, u32 count, void *iobuf ); - s32 __ReadSDHC( void *fp, u32 lba, u32 count, void *iobuf ); - s32 __WriteSDHC( void *fp, u32 lba, u32 count, void *iobuf ); + s32 __ReadDVD(void *fp, u32 lba, u32 len, void *iobuf); + s32 __ReadUSB(void *fp, u32 lba, u32 count, void *iobuf); + s32 __WriteUSB(void *fp, u32 lba, u32 count, void *iobuf); + s32 __ReadSDHC(void *fp, u32 lba, u32 count, void *iobuf); + s32 __WriteSDHC(void *fp, u32 lba, u32 count, void *iobuf); #ifdef __cplusplus } #endif - #endif //_WBFS_RW_H diff --git a/source/usbloader/wbfs/wbfs_wbfs.cpp b/source/usbloader/wbfs/wbfs_wbfs.cpp index b6c73734..f0069a6c 100644 --- a/source/usbloader/wbfs/wbfs_wbfs.cpp +++ b/source/usbloader/wbfs/wbfs_wbfs.cpp @@ -10,8 +10,8 @@ s32 Wbfs_Wbfs::Open() wbfs_t *part = NULL; /* Open partition */ - part = wbfs_open_partition( readCallback, writeCallback, NULL, sector_size, size, lba, 0 ); - if ( !part ) return -1; + part = wbfs_open_partition(readCallback, writeCallback, NULL, sector_size, size, lba, 0); + if (!part) return -1; /* Close current hard disk */ Close(); @@ -23,24 +23,22 @@ s32 Wbfs_Wbfs::Open() return 0; } -wbfs_disc_t* Wbfs_Wbfs::OpenDisc( u8 *discid ) +wbfs_disc_t* Wbfs_Wbfs::OpenDisc(u8 *discid) { /* No device open */ - if ( !hdd ) - return NULL; + if (!hdd) return NULL; /* Open disc */ - return wbfs_open_disc( hdd, discid ); + return wbfs_open_disc(hdd, discid); } -void Wbfs_Wbfs::CloseDisc( wbfs_disc_t *disc ) +void Wbfs_Wbfs::CloseDisc(wbfs_disc_t *disc) { /* No device open */ - if ( !hdd || !disc ) - return; + if (!hdd || !disc) return; /* Close disc */ - wbfs_close_disc( disc ); + wbfs_close_disc(disc); } s32 Wbfs_Wbfs::Format() @@ -48,45 +46,41 @@ s32 Wbfs_Wbfs::Format() wbfs_t *partition = NULL; /* Reset partition */ - partition = wbfs_open_partition( readCallback, writeCallback, NULL, sector_size, size, lba, 1 ); - if ( !partition ) - return -1; + partition = wbfs_open_partition(readCallback, writeCallback, NULL, sector_size, size, lba, 1); + if (!partition) return -1; /* Free memory */ - wbfs_close( partition ); + wbfs_close(partition); return 0; } -s32 Wbfs_Wbfs::GetCount( u32 *count ) +s32 Wbfs_Wbfs::GetCount(u32 *count) { /* No device open */ - if ( !hdd ) - return -1; + if (!hdd) return -1; /* Get list length */ - *count = wbfs_count_discs( hdd ); + *count = wbfs_count_discs(hdd); return 0; } -s32 Wbfs_Wbfs::GetHeaders( struct discHdr *outbuf, u32 cnt, u32 len ) +s32 Wbfs_Wbfs::GetHeaders(struct discHdr *outbuf, u32 cnt, u32 len) { u32 idx, size; s32 ret; /* No device open */ - if ( !hdd ) - return -1; + if (!hdd) return -1; - for ( idx = 0; idx < cnt; idx++ ) + for (idx = 0; idx < cnt; idx++) { - u8 *ptr = ( ( u8 * )outbuf ) + ( idx * len ); + u8 *ptr = ((u8 *) outbuf) + (idx * len); /* Get header */ - ret = wbfs_get_disc_info( hdd, idx, ptr, len, &size ); - if ( ret < 0 ) - return ret; + ret = wbfs_get_disc_info(hdd, idx, ptr, len, &size); + if (ret < 0) return ret; } return 0; @@ -97,14 +91,13 @@ s32 Wbfs_Wbfs::AddGame() s32 ret; /* No device open */ - if ( !hdd ) - return -1; + if (!hdd) return -1; /* Add game to device */ partition_selector_t part_sel; int copy_1_1 = 0; - if ( Settings.fullcopy ) + if (Settings.fullcopy) { part_sel = ALL_PARTITIONS; copy_1_1 = 1; @@ -114,75 +107,67 @@ s32 Wbfs_Wbfs::AddGame() part_sel = Settings.partitions_to_install == install_game_only ? ONLY_GAME_PARTITION : ALL_PARTITIONS; } - ret = wbfs_add_disc( hdd, __ReadDVD, NULL, ProgressCallback, part_sel, copy_1_1 ); - if ( ret < 0 ) - return ret; + ret = wbfs_add_disc(hdd, __ReadDVD, NULL, ProgressCallback, part_sel, copy_1_1); + if (ret < 0) return ret; return 0; } -s32 Wbfs_Wbfs::RemoveGame( u8 *discid ) +s32 Wbfs_Wbfs::RemoveGame(u8 *discid) { s32 ret; /* No device open */ - if ( !hdd ) - return -1; + if (!hdd) return -1; /* Remove game from USB device */ - ret = wbfs_rm_disc( hdd, discid ); - if ( ret < 0 ) - return ret; + ret = wbfs_rm_disc(hdd, discid); + if (ret < 0) return ret; return 0; } -s32 Wbfs_Wbfs::DiskSpace( f32 *used, f32 *free ) +s32 Wbfs_Wbfs::DiskSpace(f32 *used, f32 *free) { f32 ssize; u32 cnt; /* No device open */ - if ( !hdd ) - return -1; + if (!hdd) return -1; /* Count used blocks */ - cnt = wbfs_count_usedblocks( hdd ); + cnt = wbfs_count_usedblocks(hdd); /* Sector size in GB */ ssize = hdd->wbfs_sec_sz / GB_SIZE; /* Copy values */ *free = ssize * cnt; - *used = ssize * ( hdd->n_wbfs_sec - cnt ); + *used = ssize * (hdd->n_wbfs_sec - cnt); return 0; } -s32 Wbfs_Wbfs::RenameGame( u8 *discid, const void *newname ) +s32 Wbfs_Wbfs::RenameGame(u8 *discid, const void *newname) { s32 ret; /* No USB device open */ - if ( !hdd ) - return -1; - ret = wbfs_ren_disc( hdd, discid, ( u8* )newname ); - if ( ret < 0 ) - return ret; + if (!hdd) return -1; + ret = wbfs_ren_disc(hdd, discid, (u8*) newname); + if (ret < 0) return ret; return 0; } -s32 Wbfs_Wbfs::ReIDGame( u8 *discid, const void *newID ) +s32 Wbfs_Wbfs::ReIDGame(u8 *discid, const void *newID) { s32 ret; /* No USB device open */ - if ( !hdd ) - return -1; - ret = wbfs_rID_disc( hdd, discid, ( u8* )newID ); - if ( ret < 0 ) - return ret; + if (!hdd) return -1; + ret = wbfs_rID_disc(hdd, discid, (u8*) newID); + if (ret < 0) return ret; return 0; } @@ -190,13 +175,13 @@ s32 Wbfs_Wbfs::ReIDGame( u8 *discid, const void *newID ) f32 Wbfs_Wbfs::EstimateGameSize() { partition_selector_t part_sel = ONLY_GAME_PARTITION; - if ( Settings.fullcopy ) + if (Settings.fullcopy) { part_sel = ALL_PARTITIONS; } else { - switch ( Settings.partitions_to_install ) + switch (Settings.partitions_to_install) { case install_game_only: part_sel = ONLY_GAME_PARTITION; @@ -209,5 +194,5 @@ f32 Wbfs_Wbfs::EstimateGameSize() break; } } - return wbfs_estimate_disc( hdd, __ReadDVD, NULL, part_sel ); + return wbfs_estimate_disc(hdd, __ReadDVD, NULL, part_sel); } diff --git a/source/usbloader/wbfs/wbfs_wbfs.h b/source/usbloader/wbfs/wbfs_wbfs.h index 813d0e02..6e9933c8 100644 --- a/source/usbloader/wbfs/wbfs_wbfs.h +++ b/source/usbloader/wbfs/wbfs_wbfs.h @@ -4,26 +4,29 @@ #include "wbfs_base.h" #include "libwbfs/libwbfs.h" -class Wbfs_Wbfs : public Wbfs +class Wbfs_Wbfs: public Wbfs { public: - Wbfs_Wbfs( u32 device, u32 lba, u32 size ) : Wbfs( device, lba, size ) {} + Wbfs_Wbfs(u32 device, u32 lba, u32 size) : + Wbfs(device, lba, size) + { + } s32 Open(); - wbfs_disc_t* OpenDisc( u8 * ); - void CloseDisc( wbfs_disc_t * ); + wbfs_disc_t* OpenDisc(u8 *); + void CloseDisc(wbfs_disc_t *); s32 Format(); - s32 GetCount( u32 * ); - s32 GetHeaders( struct discHdr *, u32, u32 ); + s32 GetCount(u32 *); + s32 GetHeaders(struct discHdr *, u32, u32); s32 AddGame(); - s32 RemoveGame( u8 * ); + s32 RemoveGame(u8 *); - s32 DiskSpace( f32 *, f32 * ); + s32 DiskSpace(f32 *, f32 *); - s32 RenameGame( u8 *, const void * ); - s32 ReIDGame( u8 *, const void * ); + s32 RenameGame(u8 *, const void *); + s32 ReIDGame(u8 *, const void *); f32 EstimateGameSize(); }; diff --git a/source/usbloader/wdvd.c b/source/usbloader/wdvd.c index da22a1c9..d2788a8f 100644 --- a/source/usbloader/wdvd.c +++ b/source/usbloader/wdvd.c @@ -25,160 +25,158 @@ #define DI_SETOFFSETBASE 0xf1 /* Variables */ -static u32 inbuf[8] ATTRIBUTE_ALIGN( 32 ); +static u32 inbuf[8] ATTRIBUTE_ALIGN( 32 ); static u32 outbuf[8] ATTRIBUTE_ALIGN( 32 ); static const char di_fs[] ATTRIBUTE_ALIGN( 32 ) = "/dev/di"; static s32 di_fd = -1; -s32 WDVD_Init( void ) +s32 WDVD_Init(void) { /* Open "/dev/di" */ - if ( di_fd < 0 ) + if (di_fd < 0) { - di_fd = IOS_Open( di_fs, 0 ); - if ( di_fd < 0 ) - return di_fd; + di_fd = IOS_Open(di_fs, 0); + if (di_fd < 0) return di_fd; } return 0; } -s32 WDVD_Close( void ) +s32 WDVD_Close(void) { /* Close "/dev/di" */ - if ( di_fd >= 0 ) + if (di_fd >= 0) { - IOS_Close( di_fd ); + IOS_Close(di_fd); di_fd = -1; } return 0; } -s32 WDVD_GetHandle( void ) +s32 WDVD_GetHandle(void) { /* Return di handle */ return di_fd; } -s32 WDVD_Reset( void ) +s32 WDVD_Reset(void) { s32 ret; - memset( inbuf, 0, sizeof( inbuf ) ); + memset(inbuf, 0, sizeof(inbuf)); /* Reset drive */ inbuf[0] = IOCTL_DI_RESET << 24; inbuf[1] = 1; - ret = IOS_Ioctl( di_fd, IOCTL_DI_RESET, inbuf, sizeof( inbuf ), outbuf, sizeof( outbuf ) ); - if ( ret < 0 ) - return ret; + ret = IOS_Ioctl(di_fd, IOCTL_DI_RESET, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf)); + if (ret < 0) return ret; - return ( ret == 1 ) ? 0 : -ret; + return (ret == 1) ? 0 : -ret; } -s32 WDVD_ReadDiskId( void *id ) +s32 WDVD_ReadDiskId(void *id) { s32 ret; - memset( inbuf, 0, sizeof( inbuf ) ); + memset(inbuf, 0, sizeof(inbuf)); /* Read disc ID */ inbuf[0] = IOCTL_DI_READID << 24; - ret = IOS_Ioctl( di_fd, IOCTL_DI_READID, inbuf, sizeof( inbuf ), outbuf, sizeof( outbuf ) ); - if ( ret < 0 ) - return ret; + ret = IOS_Ioctl(di_fd, IOCTL_DI_READID, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf)); + if (ret < 0) return ret; - if ( ret == 1 ) + if (ret == 1) { - memcpy( id, outbuf, sizeof( dvddiskid ) ); + memcpy(id, outbuf, sizeof(dvddiskid)); return 0; } return -ret; } -s32 WDVD_Seek( u64 offset ) +s32 WDVD_Seek(u64 offset) { s32 ret; - memset( inbuf, 0, sizeof( inbuf ) ); + memset(inbuf, 0, sizeof(inbuf)); /* Drive seek */ inbuf[0] = IOCTL_DI_SEEK << 24; - inbuf[1] = ( u32 )( offset >> 2 ); + inbuf[1] = (u32) (offset >> 2); - ret = IOS_Ioctl( di_fd, IOCTL_DI_SEEK, inbuf, sizeof( inbuf ), outbuf, sizeof( outbuf ) ); - if ( ret != 1 ) + ret = IOS_Ioctl(di_fd, IOCTL_DI_SEEK, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf)); + if (ret != 1) { // Try old cIOS 222 /* Drive seek */ inbuf[0] = DI_SETOFFSETBASE << 24; - ret = IOS_Ioctl( di_fd, DI_SETOFFSETBASE, inbuf, sizeof( inbuf ), outbuf, sizeof( outbuf ) ); + ret = IOS_Ioctl(di_fd, DI_SETOFFSETBASE, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf)); } - if ( ret < 0 ) - return ret; + if (ret < 0) return ret; - return ( ret == 1 ) ? 0 : -ret; + return (ret == 1) ? 0 : -ret; } -s32 WDVD_Offset( 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 ) ); + memset(inbuf, 0, sizeof(inbuf)); /* Set offset */ inbuf[0] = IOCTL_DI_OFFSET << 24; - inbuf[1] = ( off.off32[0] ) ? 1 : 0; - inbuf[2] = ( off.off32[1] >> 2 ); + inbuf[1] = (off.off32[0]) ? 1 : 0; + inbuf[2] = (off.off32[1] >> 2); - ret = IOS_Ioctl( di_fd, IOCTL_DI_OFFSET, inbuf, sizeof( inbuf ), outbuf, sizeof( outbuf ) ); - if ( ret < 0 ) - return ret; + ret = IOS_Ioctl(di_fd, IOCTL_DI_OFFSET, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf)); + if (ret < 0) return ret; - return ( ret == 1 ) ? 0 : -ret; + return (ret == 1) ? 0 : -ret; } -s32 WDVD_StopLaser( void ) +s32 WDVD_StopLaser(void) { s32 ret; - memset( inbuf, 0, sizeof( inbuf ) ); + memset(inbuf, 0, sizeof(inbuf)); /* Stop laser */ inbuf[0] = IOCTL_DI_STOPLASER << 24; - ret = IOS_Ioctl( di_fd, IOCTL_DI_STOPLASER, inbuf, sizeof( inbuf ), outbuf, sizeof( outbuf ) ); - if ( ret < 0 ) - return ret; + ret = IOS_Ioctl(di_fd, IOCTL_DI_STOPLASER, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf)); + if (ret < 0) return ret; - return ( ret == 1 ) ? 0 : -ret; + return (ret == 1) ? 0 : -ret; } -s32 WDVD_StopMotor( void ) +s32 WDVD_StopMotor(void) { s32 ret; - memset( inbuf, 0, sizeof( inbuf ) ); + memset(inbuf, 0, sizeof(inbuf)); /* Stop motor */ inbuf[0] = IOCTL_DI_STOPMOTOR << 24; - ret = IOS_Ioctl( di_fd, IOCTL_DI_STOPMOTOR, inbuf, sizeof( inbuf ), outbuf, sizeof( outbuf ) ); - if ( ret < 0 ) - return ret; + ret = IOS_Ioctl(di_fd, IOCTL_DI_STOPMOTOR, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf)); + if (ret < 0) return ret; - return ( ret == 1 ) ? 0 : -ret; + return (ret == 1) ? 0 : -ret; } -s32 WDVD_OpenPartition( u64 offset ) +s32 WDVD_OpenPartition(u64 offset) { u8 *vector = NULL; @@ -186,123 +184,116 @@ s32 WDVD_OpenPartition( u64 offset ) s32 ret; /* Allocate memory */ - buffer = ( u32 * )memalign( 32, 0x5000 ); - if ( !buffer ) - return -1; + buffer = (u32 *) memalign(32, 0x5000); + if (!buffer) return -1; /* Set vector pointer */ - vector = ( u8 * )buffer; + vector = (u8 *) buffer; - memset( buffer, 0, 0x5000 ); + memset(buffer, 0, 0x5000); /* Open partition */ - buffer[0] = ( u32 )( buffer + 0x10 ); + buffer[0] = (u32) (buffer + 0x10); buffer[1] = 0x20; buffer[3] = 0x024A; - buffer[6] = ( u32 )( buffer + 0x380 ); + buffer[6] = (u32) (buffer + 0x380); buffer[7] = 0x49E4; - buffer[8] = ( u32 )( buffer + 0x360 ); + buffer[8] = (u32) (buffer + 0x360); buffer[9] = 0x20; - buffer[( 0x40 >> 2 )] = IOCTL_DI_OPENPART << 24; - buffer[( 0x40 >> 2 ) + 1] = offset >> 2; + buffer[(0x40 >> 2)] = IOCTL_DI_OPENPART << 24; + buffer[(0x40 >> 2) + 1] = offset >> 2; - ret = IOS_Ioctlv( di_fd, IOCTL_DI_OPENPART, 3, 2, ( ioctlv * )vector ); + ret = IOS_Ioctlv(di_fd, IOCTL_DI_OPENPART, 3, 2, (ioctlv *) vector); /* Free memory */ - free( buffer ); + free(buffer); - if ( ret < 0 ) - return ret; + if (ret < 0) return ret; - return ( ret == 1 ) ? 0 : -ret; + return (ret == 1) ? 0 : -ret; } -s32 WDVD_ClosePartition( void ) +s32 WDVD_ClosePartition(void) { s32 ret; - memset( inbuf, 0, sizeof( inbuf ) ); + memset(inbuf, 0, sizeof(inbuf)); /* Close partition */ inbuf[0] = IOCTL_DI_CLOSEPART << 24; - ret = IOS_Ioctl( di_fd, IOCTL_DI_CLOSEPART, inbuf, sizeof( inbuf ), NULL, 0 ); - if ( ret < 0 ) - return ret; + ret = IOS_Ioctl(di_fd, IOCTL_DI_CLOSEPART, inbuf, sizeof(inbuf), NULL, 0); + if (ret < 0) return ret; - return ( ret == 1 ) ? 0 : -ret; + return (ret == 1) ? 0 : -ret; } -s32 WDVD_UnencryptedRead( void *buf, u32 len, u64 offset ) +s32 WDVD_UnencryptedRead(void *buf, u32 len, u64 offset) { s32 ret; - memset( inbuf, 0, sizeof( inbuf ) ); + memset(inbuf, 0, sizeof(inbuf)); /* Unencrypted read */ inbuf[0] = IOCTL_DI_UNENCREAD << 24; inbuf[1] = len; - inbuf[2] = ( u32 )( offset >> 2 ); + inbuf[2] = (u32) (offset >> 2); - ret = IOS_Ioctl( di_fd, IOCTL_DI_UNENCREAD, inbuf, sizeof( inbuf ), buf, len ); - if ( ret < 0 ) - return ret; + ret = IOS_Ioctl(di_fd, IOCTL_DI_UNENCREAD, inbuf, sizeof(inbuf), buf, len); + if (ret < 0) return ret; - return ( ret == 1 ) ? 0 : -ret; + return (ret == 1) ? 0 : -ret; } -s32 WDVD_Read( void *buf, u32 len, u64 offset ) +s32 WDVD_Read(void *buf, u32 len, u64 offset) { s32 ret; - memset( inbuf, 0, sizeof( inbuf ) ); + memset(inbuf, 0, sizeof(inbuf)); /* Disc read */ inbuf[0] = IOCTL_DI_READ << 24; inbuf[1] = len; - inbuf[2] = ( u32 )( offset >> 2 ); + inbuf[2] = (u32) (offset >> 2); - ret = IOS_Ioctl( di_fd, IOCTL_DI_READ, inbuf, sizeof( inbuf ), buf, len ); - if ( ret < 0 ) - return ret; + ret = IOS_Ioctl(di_fd, IOCTL_DI_READ, inbuf, sizeof(inbuf), buf, len); + if (ret < 0) return ret; - return ( ret == 1 ) ? 0 : -ret; + return (ret == 1) ? 0 : -ret; } -s32 WDVD_WaitForDisc( void ) +s32 WDVD_WaitForDisc(void) { s32 ret; - memset( inbuf, 0, sizeof( inbuf ) ); + memset(inbuf, 0, sizeof(inbuf)); /* Wait for disc */ inbuf[0] = IOCTL_DI_WAITCVRCLOSE << 24; - ret = IOS_Ioctl( di_fd, IOCTL_DI_WAITCVRCLOSE, inbuf, sizeof( inbuf ), outbuf, sizeof( outbuf ) ); - if ( ret < 0 ) - return ret; + ret = IOS_Ioctl(di_fd, IOCTL_DI_WAITCVRCLOSE, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf)); + if (ret < 0) return ret; - return ( ret == 1 ) ? 0 : -ret; + return (ret == 1) ? 0 : -ret; } -s32 WDVD_GetCoverStatus( u32 *status ) +s32 WDVD_GetCoverStatus(u32 *status) { s32 ret; - memset( inbuf, 0, sizeof( inbuf ) ); + memset(inbuf, 0, sizeof(inbuf)); /* Get cover status */ inbuf[0] = IOCTL_DI_GETCOVER << 24; - ret = IOS_Ioctl( di_fd, IOCTL_DI_GETCOVER, inbuf, sizeof( inbuf ), outbuf, sizeof( outbuf ) ); - if ( ret < 0 ) - return ret; + ret = IOS_Ioctl(di_fd, IOCTL_DI_GETCOVER, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf)); + if (ret < 0) return ret; - if ( ret == 1 ) + if (ret == 1) { /* Copy cover status */ - memcpy( status, outbuf, sizeof( u32 ) ); + memcpy(status, outbuf, sizeof(u32)); return 0; } @@ -310,72 +301,69 @@ s32 WDVD_GetCoverStatus( u32 *status ) return -ret; } -s32 WDVD_DisableReset( u8 val ) +s32 WDVD_DisableReset(u8 val) { s32 ret; - memset( inbuf, 0, sizeof( inbuf ) ); + memset(inbuf, 0, sizeof(inbuf)); /* Disable/Enable reset */ inbuf[0] = IOCTL_DI_DISABLERESET << 24; inbuf[1] = val; - ret = IOS_Ioctl( di_fd, IOCTL_DI_DISABLERESET, inbuf, sizeof( inbuf ), outbuf, sizeof( outbuf ) ); - if ( ret < 0 ) - return ret; + ret = IOS_Ioctl(di_fd, IOCTL_DI_DISABLERESET, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf)); + if (ret < 0) return ret; - return ( ret == 1 ) ? 0 : -ret; + return (ret == 1) ? 0 : -ret; } /** Hermes **/ -s32 WDVD_SetUSBMode( const u8 *id, s32 partition ) +s32 WDVD_SetUSBMode(const u8 *id, s32 partition) { s32 ret; - memset( inbuf, 0, sizeof( inbuf ) ); + memset(inbuf, 0, sizeof(inbuf)); /* Set USB mode */ inbuf[0] = IOCTL_DI_SETUSBMODE << 24; - inbuf[1] = ( id ) ? 1 : 0; + inbuf[1] = (id) ? 1 : 0; /* Copy ID */ - if ( id ) + if (id) { - memcpy( &inbuf[2], id, 6 ); - if ( IOS_GetVersion() != 249 ) + memcpy(&inbuf[2], id, 6); + if (IOS_GetVersion() != 249) { inbuf[5] = partition; } } - ret = IOS_Ioctl( di_fd, IOCTL_DI_SETUSBMODE, inbuf, sizeof( inbuf ), outbuf, sizeof( outbuf ) ); - if ( ret != 1 ) + ret = IOS_Ioctl(di_fd, IOCTL_DI_SETUSBMODE, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf)); + if (ret != 1) { // Try old cIOS 222 /* Set USB mode */ inbuf[0] = DI_SETWBFSMODE << 24; - ret = IOS_Ioctl( di_fd, DI_SETWBFSMODE, inbuf, sizeof( inbuf ), outbuf, sizeof( outbuf ) ); + ret = IOS_Ioctl(di_fd, DI_SETWBFSMODE, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf)); } - if ( ret < 0 ) - return ret; + if (ret < 0) return ret; - return ( ret == 1 ) ? 0 : -ret; + return (ret == 1) ? 0 : -ret; } -s32 WDVD_Read_Disc_BCA( void *buf ) +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; - 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 fee4bb03..a8e353d4 100644 --- a/source/usbloader/wdvd.h +++ b/source/usbloader/wdvd.h @@ -7,28 +7,28 @@ 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_Seek( u64 ); - s32 WDVD_Offset( u64 ); - s32 WDVD_StopLaser( void ); - s32 WDVD_StopMotor( void ); - s32 WDVD_OpenPartition( u64 ); - s32 WDVD_ClosePartition( void ); - s32 WDVD_UnencryptedRead( void *, u32, u64 ); - s32 WDVD_Read( void *, u32, u64 ); - 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 ); - -#ifdef __cplusplus -} -#endif - -#endif - + 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); + s32 WDVD_StopMotor(void); + s32 WDVD_OpenPartition(u64); + s32 WDVD_ClosePartition(void); + s32 WDVD_UnencryptedRead(void *, u32, u64); + s32 WDVD_Read(void *, u32, u64); + 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); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/source/video.cpp b/source/video.cpp index 160605e6..539cfc5e 100644 --- a/source/video.cpp +++ b/source/video.cpp @@ -38,91 +38,87 @@ u8 * gameScreenTex2 = NULL; // a GX texture screen capture of the game (copy) * * Initialises GX and sets it up for use ***************************************************************************/ -static void -StartGX () +static void StartGX() { GXColor background = { 0, 0, 0, 0xff }; /*** Clear out FIFO area ***/ - memset ( &gp_fifo, 0, DEFAULT_FIFO_SIZE ); + memset(&gp_fifo, 0, DEFAULT_FIFO_SIZE); /*** Initialise GX ***/ - GX_Init ( &gp_fifo, DEFAULT_FIFO_SIZE ); - GX_SetCopyClear ( background, 0x00ffffff ); + GX_Init(&gp_fifo, DEFAULT_FIFO_SIZE); + GX_SetCopyClear(background, 0x00ffffff); - GX_SetDispCopyGamma ( GX_GM_1_0 ); - GX_SetCullMode ( GX_CULL_NONE ); + GX_SetDispCopyGamma(GX_GM_1_0); + GX_SetCullMode(GX_CULL_NONE); } /**************************************************************************** * ResetVideo_Menu * * Reset the video/rendering mode for the menu -****************************************************************************/ -void -ResetVideo_Menu() + ****************************************************************************/ +void ResetVideo_Menu() { Mtx44 p; f32 yscale; u32 xfbHeight; - VIDEO_Configure ( vmode ); + VIDEO_Configure(vmode); VIDEO_Flush(); VIDEO_WaitVSync(); - if ( vmode->viTVMode & VI_NON_INTERLACE ) + if (vmode->viTVMode & VI_NON_INTERLACE) + VIDEO_WaitVSync(); + else while (VIDEO_GetNextField()) VIDEO_WaitVSync(); - else - while ( VIDEO_GetNextField() ) - VIDEO_WaitVSync(); // clears the bg to color and clears the z buffer - GXColor background = {0, 0, 0, 255}; - GX_SetCopyClear ( background, 0x00ffffff ); + GXColor background = { 0, 0, 0, 255 }; + GX_SetCopyClear(background, 0x00ffffff); - yscale = GX_GetYScaleFactor( vmode->efbHeight, vmode->xfbHeight ); - xfbHeight = GX_SetDispCopyYScale( yscale ); - GX_SetScissor( 0, 0, vmode->fbWidth, vmode->efbHeight ); - GX_SetDispCopySrc( 0, 0, vmode->fbWidth, vmode->efbHeight ); - GX_SetDispCopyDst( vmode->fbWidth, xfbHeight ); - GX_SetCopyFilter( vmode->aa, vmode->sample_pattern, GX_TRUE, vmode->vfilter ); - GX_SetFieldMode( vmode->field_rendering, ( ( vmode->viHeight == 2*vmode->xfbHeight ) ? GX_ENABLE : GX_DISABLE ) ); + yscale = GX_GetYScaleFactor(vmode->efbHeight, vmode->xfbHeight); + xfbHeight = GX_SetDispCopyYScale(yscale); + GX_SetScissor(0, 0, vmode->fbWidth, vmode->efbHeight); + GX_SetDispCopySrc(0, 0, vmode->fbWidth, vmode->efbHeight); + GX_SetDispCopyDst(vmode->fbWidth, xfbHeight); + GX_SetCopyFilter(vmode->aa, vmode->sample_pattern, GX_TRUE, vmode->vfilter); + GX_SetFieldMode(vmode->field_rendering, ((vmode->viHeight == 2 * vmode->xfbHeight) ? GX_ENABLE : GX_DISABLE)); - if ( vmode->aa ) - GX_SetPixelFmt( GX_PF_RGB565_Z16, GX_ZC_LINEAR ); - else - GX_SetPixelFmt( GX_PF_RGB8_Z24, GX_ZC_LINEAR ); + if (vmode->aa) + GX_SetPixelFmt(GX_PF_RGB565_Z16, GX_ZC_LINEAR); + else GX_SetPixelFmt(GX_PF_RGB8_Z24, GX_ZC_LINEAR); // setup the vertex descriptor // tells the flipper to expect direct data GX_ClearVtxDesc(); - GX_InvVtxCache (); + GX_InvVtxCache(); GX_InvalidateTexAll(); - GX_SetVtxDesc( GX_VA_TEX0, GX_NONE ); - GX_SetVtxDesc( GX_VA_POS, GX_DIRECT ); - GX_SetVtxDesc ( GX_VA_CLR0, GX_DIRECT ); + GX_SetVtxDesc(GX_VA_TEX0, GX_NONE); + GX_SetVtxDesc(GX_VA_POS, GX_DIRECT); + GX_SetVtxDesc(GX_VA_CLR0, GX_DIRECT); - GX_SetVtxAttrFmt ( GX_VTXFMT0, GX_VA_POS, GX_POS_XYZ, GX_F32, 0 ); - GX_SetVtxAttrFmt ( GX_VTXFMT0, GX_VA_CLR0, GX_CLR_RGBA, GX_RGBA8, 0 ); - GX_SetVtxAttrFmt( GX_VTXFMT0, GX_VA_TEX0, GX_TEX_ST, GX_F32, 0 ); - GX_SetZMode ( GX_FALSE, GX_LEQUAL, GX_TRUE ); + GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_POS, GX_POS_XYZ, GX_F32, 0); + GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_CLR0, GX_CLR_RGBA, GX_RGBA8, 0); + GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_TEX0, GX_TEX_ST, GX_F32, 0); + GX_SetZMode(GX_FALSE, GX_LEQUAL, GX_TRUE); - GX_SetNumChans( 1 ); - GX_SetNumTexGens( 1 ); - GX_SetTevOp ( GX_TEVSTAGE0, GX_PASSCLR ); - GX_SetTevOrder( GX_TEVSTAGE0, GX_TEXCOORD0, GX_TEXMAP0, GX_COLOR0A0 ); - GX_SetTexCoordGen( GX_TEXCOORD0, GX_TG_MTX2x4, GX_TG_TEX0, GX_IDENTITY ); + GX_SetNumChans(1); + GX_SetNumTexGens(1); + GX_SetTevOp(GX_TEVSTAGE0, GX_PASSCLR); + GX_SetTevOrder(GX_TEVSTAGE0, GX_TEXCOORD0, GX_TEXMAP0, GX_COLOR0A0); + GX_SetTexCoordGen(GX_TEXCOORD0, GX_TG_MTX2x4, GX_TG_TEX0, GX_IDENTITY); - guMtxIdentity( GXmodelView2D ); - guMtxTransApply ( GXmodelView2D, GXmodelView2D, 0.0F, 0.0F, -200.0F ); - GX_LoadPosMtxImm( GXmodelView2D, GX_PNMTX0 ); + guMtxIdentity(GXmodelView2D); + guMtxTransApply(GXmodelView2D, GXmodelView2D, 0.0F, 0.0F, -200.0F); + GX_LoadPosMtxImm(GXmodelView2D, GX_PNMTX0); - guOrtho( p, 0, 479, 0, 639, 0, 300 ); - GX_LoadProjectionMtx( p, GX_ORTHOGRAPHIC ); + guOrtho(p, 0, 479, 0, 639, 0, 300); + GX_LoadProjectionMtx(p, GX_ORTHOGRAPHIC); - GX_SetViewport( 0, 0, vmode->fbWidth, vmode->efbHeight, 0, 1 ); - GX_SetBlendMode( GX_BM_BLEND, GX_BL_SRCALPHA, GX_BL_INVSRCALPHA, GX_LO_CLEAR ); - GX_SetAlphaUpdate( GX_TRUE ); + GX_SetViewport(0, 0, vmode->fbWidth, vmode->efbHeight, 0, 1); + GX_SetBlendMode(GX_BM_BLEND, GX_BL_SRCALPHA, GX_BL_INVSRCALPHA, GX_LO_CLEAR); + GX_SetAlphaUpdate(GX_TRUE); } /**************************************************************************** @@ -132,54 +128,52 @@ ResetVideo_Menu() * - also sets up menu video mode ***************************************************************************/ -void -InitVideo () +void InitVideo() { VIDEO_Init(); - vmode = VIDEO_GetPreferredMode( NULL ); // get default video mode + vmode = VIDEO_GetPreferredMode(NULL); // get default video mode - VIDEO_Configure ( vmode ); + VIDEO_Configure(vmode); screenheight = 480; screenwidth = vmode->fbWidth; // Allocate the video buffers - xfb[0] = ( u32 * ) MEM_K0_TO_K1 ( SYS_AllocateFramebuffer ( vmode ) ); - xfb[1] = ( u32 * ) MEM_K0_TO_K1 ( SYS_AllocateFramebuffer ( vmode ) ); + xfb[0] = (u32 *) MEM_K0_TO_K1 ( SYS_AllocateFramebuffer ( vmode ) ); + xfb[1] = (u32 *) MEM_K0_TO_K1 ( SYS_AllocateFramebuffer ( vmode ) ); // Clear framebuffers etc. - VIDEO_ClearFrameBuffer ( vmode, xfb[0], COLOR_BLACK ); - VIDEO_ClearFrameBuffer ( vmode, xfb[1], COLOR_BLACK ); - VIDEO_SetNextFramebuffer ( xfb[0] ); + VIDEO_ClearFrameBuffer(vmode, xfb[0], COLOR_BLACK); + VIDEO_ClearFrameBuffer(vmode, xfb[1], COLOR_BLACK); + VIDEO_SetNextFramebuffer(xfb[0]); - VIDEO_SetBlack ( FALSE ); - VIDEO_Flush (); - VIDEO_WaitVSync (); - if ( vmode->viTVMode & VI_NON_INTERLACE ) - VIDEO_WaitVSync (); + VIDEO_SetBlack(FALSE); + VIDEO_Flush(); + VIDEO_WaitVSync(); + if (vmode->viTVMode & VI_NON_INTERLACE) VIDEO_WaitVSync(); StartGX(); ResetVideo_Menu(); // Finally, the video is up and ready for use :) // A console is always useful while debugging - console_init ( xfb[0], 80, 100, 500, 350, vmode->fbWidth * 2 ); + console_init(xfb[0], 80, 100, 500, 350, vmode->fbWidth * 2); } void VIDEO_SetWidescreen(bool widescreen) { - if ( widescreen ) + if (widescreen) { // widescreen fix vmode->viWidth = VI_MAX_WIDTH_PAL - 12; - vmode->viXOrigin = ( ( VI_MAX_WIDTH_PAL - vmode->viWidth ) / 2 ) + 2; + vmode->viXOrigin = ((VI_MAX_WIDTH_PAL - vmode->viWidth) / 2) + 2; } else { - VIDEO_GetPreferredMode( NULL ); + VIDEO_GetPreferredMode(NULL); } - VIDEO_Configure ( vmode ); + VIDEO_Configure(vmode); } /**************************************************************************** * StopGX @@ -191,7 +185,7 @@ void StopGX() GX_AbortFrame(); GX_Flush(); - VIDEO_SetBlack( TRUE ); + VIDEO_SetBlack(TRUE); VIDEO_Flush(); } @@ -203,11 +197,11 @@ void StopGX() void Menu_Render() { whichfb ^= 1; // flip framebuffer - GX_SetZMode( GX_TRUE, GX_LEQUAL, GX_TRUE ); - GX_SetColorUpdate( GX_TRUE ); - GX_CopyDisp( xfb[whichfb], GX_TRUE ); - GX_DrawDone (); - VIDEO_SetNextFramebuffer( xfb[whichfb] ); + GX_SetZMode(GX_TRUE, GX_LEQUAL, GX_TRUE); + GX_SetColorUpdate(GX_TRUE); + GX_CopyDisp(xfb[whichfb], GX_TRUE); + GX_DrawDone(); + VIDEO_SetNextFramebuffer(xfb[whichfb]); VIDEO_Flush(); VIDEO_WaitVSync(); frameCount++; @@ -218,81 +212,79 @@ void Menu_Render() * * Draws the specified image on screen using GX ***************************************************************************/ -void Menu_DrawImg( f32 xpos, f32 ypos, f32 zpos, f32 width, f32 height, u8 data[], - f32 degrees, f32 scaleX, f32 scaleY, u8 alpha, int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, int XX4, int YY4 ) +void Menu_DrawImg(f32 xpos, f32 ypos, f32 zpos, f32 width, f32 height, u8 data[], f32 degrees, f32 scaleX, f32 scaleY, + u8 alpha, int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, int XX4, int YY4) { - if ( data == NULL ) - return; + if (data == NULL) return; GXTexObj texObj; - GX_InitTexObj( &texObj, data, width, height, GX_TF_RGBA8, GX_CLAMP, GX_CLAMP, GX_FALSE ); - GX_LoadTexObj( &texObj, GX_TEXMAP0 ); + GX_InitTexObj(&texObj, data, width, height, GX_TF_RGBA8, GX_CLAMP, GX_CLAMP, GX_FALSE); + GX_LoadTexObj(&texObj, GX_TEXMAP0); GX_InvalidateTexAll(); - GX_SetTevOp ( GX_TEVSTAGE0, GX_MODULATE ); - GX_SetVtxDesc ( GX_VA_TEX0, GX_DIRECT ); + GX_SetTevOp(GX_TEVSTAGE0, GX_MODULATE); + GX_SetVtxDesc(GX_VA_TEX0, GX_DIRECT); Mtx m, m1, m2, mv; width *= .5; height *= .5; - guMtxIdentity ( m1 ); - guMtxScaleApply( m1, m1, scaleX, scaleY, 1.0 ); + guMtxIdentity(m1); + guMtxScaleApply(m1, m1, scaleX, scaleY, 1.0); guVector axis = ( guVector ) { 0 , 0, 1 }; guMtxRotAxisDeg ( m2, &axis, degrees ); -// guMtxConcat(m2,m1,m); - guMtxConcat( m1, m2, m ); + // guMtxConcat(m2,m1,m); + guMtxConcat(m1, m2, m); - guMtxTransApply( m, m, xpos + width + 0.5, ypos + height + 0.5, zpos ); - guMtxConcat ( GXmodelView2D, m, mv ); - GX_LoadPosMtxImm ( mv, GX_PNMTX0 ); -// + guMtxTransApply(m, m, xpos + width + 0.5, ypos + height + 0.5, zpos); + guMtxConcat(GXmodelView2D, m, mv); + GX_LoadPosMtxImm(mv, GX_PNMTX0); + // - GX_Begin( GX_QUADS, GX_VTXFMT0, 4 ); - GX_Position3f32( -width + XX1 , -height + YY1, 0 ); - GX_Color4u8( 0xFF, 0xFF, 0xFF, alpha ); - GX_TexCoord2f32( 0, 0 ); + GX_Begin(GX_QUADS, GX_VTXFMT0, 4); + GX_Position3f32(-width + XX1, -height + YY1, 0); + GX_Color4u8(0xFF, 0xFF, 0xFF, alpha); + GX_TexCoord2f32(0, 0); - GX_Position3f32( width + XX2, -height + YY2, 0 ); - GX_Color4u8( 0xFF, 0xFF, 0xFF, alpha ); - GX_TexCoord2f32( 1, 0 ); + GX_Position3f32(width + XX2, -height + YY2, 0); + GX_Color4u8(0xFF, 0xFF, 0xFF, alpha); + GX_TexCoord2f32(1, 0); - GX_Position3f32( width + XX3, height + YY3, 0 ); - GX_Color4u8( 0xFF, 0xFF, 0xFF, alpha ); - GX_TexCoord2f32( 1, 1 ); + GX_Position3f32(width + XX3, height + YY3, 0); + GX_Color4u8(0xFF, 0xFF, 0xFF, alpha); + GX_TexCoord2f32(1, 1); - GX_Position3f32( -width + XX4, height + YY4, 0 ); - GX_Color4u8( 0xFF, 0xFF, 0xFF, alpha ); - GX_TexCoord2f32( 0, 1 ); + GX_Position3f32(-width + XX4, height + YY4, 0); + GX_Color4u8(0xFF, 0xFF, 0xFF, alpha); + GX_TexCoord2f32(0, 1); -// + // GX_End(); - GX_LoadPosMtxImm ( GXmodelView2D, GX_PNMTX0 ); + GX_LoadPosMtxImm(GXmodelView2D, GX_PNMTX0); - GX_SetTevOp ( GX_TEVSTAGE0, GX_PASSCLR ); - GX_SetVtxDesc ( GX_VA_TEX0, GX_NONE ); + GX_SetTevOp(GX_TEVSTAGE0, GX_PASSCLR); + GX_SetVtxDesc(GX_VA_TEX0, GX_NONE); } - /**************************************************************************** * Menu_DrawRectangle * * Draws a rectangle at the specified coordinates using GX ***************************************************************************/ -void Menu_DrawRectangle( f32 x, f32 y, f32 width, f32 height, GXColor color, u8 filled ) +void Menu_DrawRectangle(f32 x, f32 y, f32 width, f32 height, GXColor color, u8 filled) { u8 fmt; long n; int i; f32 x2 = x + width; f32 y2 = y + height; - guVector v[] = {{x, y, 0.0f}, {x2, y, 0.0f}, {x2, y2, 0.0f}, {x, y2, 0.0f}, {x, y, 0.0f}}; + guVector v[] = { { x, y, 0.0f }, { x2, y, 0.0f }, { x2, y2, 0.0f }, { x, y2, 0.0f }, { x, y, 0.0f } }; - if ( !filled ) + if (!filled) { fmt = GX_LINESTRIP; n = 5; @@ -303,44 +295,42 @@ void Menu_DrawRectangle( f32 x, f32 y, f32 width, f32 height, GXColor color, u8 n = 4; } - GX_Begin( fmt, GX_VTXFMT0, n ); - for ( i = 0; i < n; i++ ) + GX_Begin(fmt, GX_VTXFMT0, n); + for (i = 0; i < n; i++) { - GX_Position3f32( v[i].x, v[i].y, v[i].z ); - GX_Color4u8( color.r, color.g, color.b, color.a ); + GX_Position3f32(v[i].x, v[i].y, v[i].z); + GX_Color4u8(color.r, color.g, color.b, color.a); } GX_End(); } -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 ) +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) { - if ( data == NULL ) - return; + if (data == NULL) return; GXTexObj texObj; - GX_InitTexObj( &texObj, data, width, height, GX_TF_RGBA8, GX_CLAMP, GX_CLAMP, GX_FALSE ); - GX_LoadTexObj( &texObj, GX_TEXMAP0 ); + GX_InitTexObj(&texObj, data, width, height, GX_TF_RGBA8, GX_CLAMP, GX_CLAMP, GX_FALSE); + GX_LoadTexObj(&texObj, GX_TEXMAP0); GX_InvalidateTexAll(); - GX_SetTevOp ( GX_TEVSTAGE0, GX_MODULATE ); - GX_SetVtxDesc ( GX_VA_TEX0, GX_DIRECT ); + GX_SetTevOp(GX_TEVSTAGE0, GX_MODULATE); + GX_SetVtxDesc(GX_VA_TEX0, GX_DIRECT); - - f32 cos_beta = cos( DegToRad( deg_beta ) ); - f32 s_offset_y = ( zpos + ( cos_beta * distance ) ) * tan( DegToRad( 5 ) ); - f32 s_offset_x = ( cos_beta < 0 ? -cos_beta : cos_beta ) * s_offset_y; - f32 s_offset_z = ( s_offset_y < 0 ? 0 : s_offset_y ) * 2; + f32 cos_beta = cos(DegToRad( deg_beta )); + f32 s_offset_y = (zpos + (cos_beta * distance)) * tan(DegToRad( 5 )); + f32 s_offset_x = (cos_beta < 0 ? -cos_beta : cos_beta) * s_offset_y; + f32 s_offset_z = (s_offset_y < 0 ? 0 : s_offset_y) * 2; Mtx m, m1, m2, m3, m4, mv; width *= .5; height *= .5; - guMtxIdentity ( m4 ); - guMtxTransApply( m4, m4, 0, 0, distance ); + guMtxIdentity(m4); + guMtxTransApply(m4, m4, 0, 0, distance); - guMtxIdentity ( m1 ); - guMtxScaleApply( m1, m1, scaleX, scaleY, 1.0 ); + guMtxIdentity(m1); + guMtxScaleApply(m1, m1, scaleX, scaleY, 1.0); guVector axis2 = ( guVector ) { 0 , 1, 0 @@ -351,126 +341,124 @@ void Menu_DrawDiskCover( f32 xpos, f32 ypos, f32 zpos, u16 width, u16 height, u1 0 , 0, 1 }; guMtxRotAxisDeg ( m3, &axis, deg_alpha ); -// guMtxConcat(m2,m1,m); - guMtxConcat( m3, m4, m3 ); // move distance then rotate z-axis - guMtxConcat( m2, m3, m2 ); // rotate y-axis - guMtxConcat( m1, m2, m ); // scale + // guMtxConcat(m2,m1,m); + guMtxConcat(m3, m4, m3); // move distance then rotate z-axis + guMtxConcat(m2, m3, m2); // rotate y-axis + guMtxConcat(m1, m2, m); // scale - if ( shadow ) - guMtxTransApply( m, m, xpos + width + 0.5 + s_offset_x, ypos + height + 0.5 + s_offset_y, zpos - s_offset_z ); + if (shadow) + guMtxTransApply(m, m, xpos + width + 0.5 + s_offset_x, ypos + height + 0.5 + s_offset_y, zpos - s_offset_z); else - guMtxTransApply( m, m, xpos + width + 0.5, ypos + height + 0.5, zpos ); + guMtxTransApply(m, m, xpos + width + 0.5, ypos + height + 0.5, zpos); + guMtxConcat(GXmodelView2D, m, mv); + GX_LoadPosMtxImm(mv, GX_PNMTX0); - - guMtxConcat ( GXmodelView2D, m, mv ); - GX_LoadPosMtxImm ( mv, GX_PNMTX0 ); - - if ( shadow ) + if (shadow) { - GX_Begin( GX_QUADS, GX_VTXFMT0, 4 ); - GX_Position3f32( -width, -height, 0 ); - GX_Color4u8( 0, 0, 0, alpha ); - GX_TexCoord2f32( 0, 0 ); + GX_Begin(GX_QUADS, GX_VTXFMT0, 4); + GX_Position3f32(-width, -height, 0); + GX_Color4u8(0, 0, 0, alpha); + GX_TexCoord2f32(0, 0); - GX_Position3f32( width, -height, 0 ); - GX_Color4u8( 0, 0, 0, alpha ); - GX_TexCoord2f32( 1, 0 ); + GX_Position3f32(width, -height, 0); + GX_Color4u8(0, 0, 0, alpha); + GX_TexCoord2f32(1, 0); - GX_Position3f32( width, height, 0 ); - GX_Color4u8( 0, 0, 0, alpha ); - GX_TexCoord2f32( 1, 1 ); + GX_Position3f32(width, height, 0); + GX_Color4u8(0, 0, 0, alpha); + GX_TexCoord2f32(1, 1); - GX_Position3f32( -width, height, 0 ); - GX_Color4u8( 0, 0, 0, alpha ); - GX_TexCoord2f32( 0, 1 ); + GX_Position3f32(-width, height, 0); + GX_Color4u8(0, 0, 0, alpha); + GX_TexCoord2f32(0, 1); } else { - GX_Begin( GX_QUADS, GX_VTXFMT0, 4 ); - GX_Position3f32( -width, -height, 0 ); - GX_Color4u8( 0xFF, 0xFF, 0xFF, alpha ); - GX_TexCoord2f32( 0, 0 ); + GX_Begin(GX_QUADS, GX_VTXFMT0, 4); + GX_Position3f32(-width, -height, 0); + GX_Color4u8(0xFF, 0xFF, 0xFF, alpha); + GX_TexCoord2f32(0, 0); - GX_Position3f32( width, -height, 0 ); - GX_Color4u8( 0xFF, 0xFF, 0xFF, alpha ); - GX_TexCoord2f32( 1, 0 ); + GX_Position3f32(width, -height, 0); + GX_Color4u8(0xFF, 0xFF, 0xFF, alpha); + GX_TexCoord2f32(1, 0); - GX_Position3f32( width, height, 0 ); - GX_Color4u8( 0xFF, 0xFF, 0xFF, alpha ); - GX_TexCoord2f32( 1, 1 ); + GX_Position3f32(width, height, 0); + GX_Color4u8(0xFF, 0xFF, 0xFF, alpha); + GX_TexCoord2f32(1, 1); - GX_Position3f32( -width, height, 0 ); - GX_Color4u8( 0xFF, 0xFF, 0xFF, alpha ); - GX_TexCoord2f32( 0, 1 ); + GX_Position3f32(-width, height, 0); + GX_Color4u8(0xFF, 0xFF, 0xFF, alpha); + GX_TexCoord2f32(0, 1); } GX_End(); - GX_LoadPosMtxImm ( GXmodelView2D, GX_PNMTX0 ); + GX_LoadPosMtxImm(GXmodelView2D, GX_PNMTX0); - GX_SetTevOp ( GX_TEVSTAGE0, GX_PASSCLR ); - GX_SetVtxDesc ( GX_VA_TEX0, GX_NONE ); + GX_SetTevOp(GX_TEVSTAGE0, GX_PASSCLR); + GX_SetVtxDesc(GX_VA_TEX0, GX_NONE); } -void Menu_DrawTPLImg( f32 xpos, f32 ypos, f32 zpos, f32 width, f32 height, GXTexObj *texObj, - f32 degrees, f32 scaleX, f32 scaleY, u8 alpha, int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, int XX4, int YY4 ) +void Menu_DrawTPLImg(f32 xpos, f32 ypos, f32 zpos, f32 width, f32 height, GXTexObj *texObj, f32 degrees, f32 scaleX, + f32 scaleY, u8 alpha, int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, int XX4, int YY4) { - GX_LoadTexObj( texObj, GX_TEXMAP0 ); + GX_LoadTexObj(texObj, GX_TEXMAP0); GX_InvalidateTexAll(); - GX_SetTevOp ( GX_TEVSTAGE0, GX_REPLACE ); - GX_SetVtxDesc ( GX_VA_TEX0, GX_DIRECT ); + GX_SetTevOp(GX_TEVSTAGE0, GX_REPLACE); + GX_SetVtxDesc(GX_VA_TEX0, GX_DIRECT); Mtx m, m1, m2, mv; width *= .5; height *= .5; - guMtxIdentity ( m1 ); - guMtxScaleApply( m1, m1, scaleX, scaleY, 1.0 ); + guMtxIdentity(m1); + guMtxScaleApply(m1, m1, scaleX, scaleY, 1.0); guVector axis = ( guVector ) { 0 , 0, 1 }; guMtxRotAxisDeg ( m2, &axis, degrees ); - guMtxConcat( m1, m2, m ); + guMtxConcat(m1, m2, m); - guMtxTransApply( m, m, xpos + width + 0.5, ypos + height + 0.5, zpos ); - guMtxConcat ( GXmodelView2D, m, mv ); - GX_LoadPosMtxImm ( mv, GX_PNMTX0 ); + guMtxTransApply(m, m, xpos + width + 0.5, ypos + height + 0.5, zpos); + guMtxConcat(GXmodelView2D, m, mv); + GX_LoadPosMtxImm(mv, GX_PNMTX0); - GX_Begin( GX_QUADS, GX_VTXFMT0, 4 ); - GX_Position3f32( -width + XX1 , -height + YY1, 0 ); - GX_Color4u8( 0xFF, 0xFF, 0xFF, alpha ); - GX_TexCoord2f32( 0, 0 ); + GX_Begin(GX_QUADS, GX_VTXFMT0, 4); + GX_Position3f32(-width + XX1, -height + YY1, 0); + GX_Color4u8(0xFF, 0xFF, 0xFF, alpha); + GX_TexCoord2f32(0, 0); - GX_Position3f32( width + XX2, -height + YY2, 0 ); - GX_Color4u8( 0xFF, 0xFF, 0xFF, alpha ); - GX_TexCoord2f32( 1, 0 ); + GX_Position3f32(width + XX2, -height + YY2, 0); + GX_Color4u8(0xFF, 0xFF, 0xFF, alpha); + GX_TexCoord2f32(1, 0); - GX_Position3f32( width + XX3, height + YY3, 0 ); - GX_Color4u8( 0xFF, 0xFF, 0xFF, alpha ); - GX_TexCoord2f32( 1, 1 ); + GX_Position3f32(width + XX3, height + YY3, 0); + GX_Color4u8(0xFF, 0xFF, 0xFF, alpha); + GX_TexCoord2f32(1, 1); - GX_Position3f32( -width + XX4, height + YY4, 0 ); - GX_Color4u8( 0xFF, 0xFF, 0xFF, alpha ); - GX_TexCoord2f32( 0, 1 ); + GX_Position3f32(-width + XX4, height + YY4, 0); + GX_Color4u8(0xFF, 0xFF, 0xFF, alpha); + GX_TexCoord2f32(0, 1); GX_End(); - GX_LoadPosMtxImm ( GXmodelView2D, GX_PNMTX0 ); + GX_LoadPosMtxImm(GXmodelView2D, GX_PNMTX0); - GX_SetTevOp ( GX_TEVSTAGE0, GX_PASSCLR ); - GX_SetVtxDesc ( GX_VA_TEX0, GX_NONE ); + GX_SetTevOp(GX_TEVSTAGE0, GX_PASSCLR); + GX_SetVtxDesc(GX_VA_TEX0, GX_NONE); } /**************************************************************************** * TakeScreenshot * * 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 ); + 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; } diff --git a/source/video.h b/source/video.h index 2ebd7282..902dd4fc 100644 --- a/source/video.h +++ b/source/video.h @@ -11,17 +11,17 @@ #include -void InitVideo (); +void InitVideo(); void InitVideodebug(); void StopGX(); void ResetVideo_Menu(); void Menu_Render(); -void Menu_DrawImg( f32 xpos, f32 ypos, f32 zpos, f32 width, f32 height, u8 data[], - f32 degrees, f32 scaleX, f32 scaleY, u8 alphaF , int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, int XX4, int YY4 ); -void Menu_DrawTPLImg( f32 xpos, f32 ypos, f32 zpos, f32 width, f32 height, GXTexObj *texObj, - f32 degrees, f32 scaleX, f32 scaleY, u8 alpha, int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, int XX4, int YY4 ); -void Menu_DrawRectangle( f32 x, f32 y, f32 width, f32 height, GXColor color, u8 filled ); -s32 TakeScreenshot( const char *path ); +void Menu_DrawImg(f32 xpos, f32 ypos, f32 zpos, f32 width, f32 height, u8 data[], f32 degrees, f32 scaleX, f32 scaleY, + u8 alphaF, int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, int XX4, int YY4); +void Menu_DrawTPLImg(f32 xpos, f32 ypos, f32 zpos, f32 width, f32 height, GXTexObj *texObj, f32 degrees, f32 scaleX, + f32 scaleY, u8 alpha, int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, int XX4, int YY4); +void Menu_DrawRectangle(f32 x, f32 y, f32 width, f32 height, GXColor color, u8 filled); +s32 TakeScreenshot(const char *path); void VIDEO_SetWidescreen(bool widescreen); extern int screenheight; diff --git a/source/wad/nandtitle.cpp b/source/wad/nandtitle.cpp index 1af23f3d..b4587757 100644 --- a/source/wad/nandtitle.cpp +++ b/source/wad/nandtitle.cpp @@ -3,23 +3,28 @@ extern "C" { - extern s32 MagicPatches( s32 ); + extern s32 MagicPatches(s32); } -static u8 tmd_buf[ MAX_SIGNED_TMD_SIZE ] ATTRIBUTE_ALIGN( 32 ); +static u8 tmd_buf[MAX_SIGNED_TMD_SIZE] ATTRIBUTE_ALIGN( 32 ); //based on one from comex's nand formatter -static u64 atoi_hex( const char *s ) { - u64 ret=0; - u32 n = strlen( s ); +static u64 atoi_hex(const char *s) +{ + u64 ret = 0; + u32 n = strlen(s); - for( u32 i = 0; i < n; i++) { - if(s[i] > 0x39) { - ret += (s[i] & ~0x20) - 0x37; - } else { - ret += (s[i]-0x30); - } - if (i != (n-1)) ret *= 16; + for (u32 i = 0; i < n; i++) + { + if (s[i] > 0x39) + { + ret += (s[i] & ~0x20) - 0x37; + } + else + { + ret += (s[i] - 0x30); + } + if (i != (n - 1)) ret *= 16; } return ret; @@ -46,264 +51,251 @@ s32 NandTitle::Get() titleIds.clear(); NameList.clear(); - ret = ES_GetNumTitles( &numTitles ); - if ( ret < 0 ) - return WII_EINTERNAL; + ret = ES_GetNumTitles(&numTitles); + if (ret < 0) return WII_EINTERNAL; - list = ( u64* )memalign( 32, numTitles * sizeof( u64 ) ); - if ( !list ) + list = (u64*) memalign(32, numTitles * sizeof(u64)); + if (!list) { return -1; } - ret = ES_GetTitles( list, numTitles ); - if ( ret < 0 ) + ret = ES_GetTitles(list, numTitles); + if (ret < 0) { - free( list ); + free(list); return WII_EINTERNAL; } - for( u32 i = 0; i < numTitles; i++ ) + for (u32 i = 0; i < numTitles; i++) { - titleIds.push_back( list[ i ] ); + titleIds.push_back(list[i]); } - free( list ); + free(list); - - MagicPatches( 1 ); + MagicPatches(1); int language = CONF_GetLanguage(); ISFS_Initialize(); - wchar_t name[ IMET_MAX_NAME_LEN ]; + wchar_t name[IMET_MAX_NAME_LEN]; - for ( u32 i = 0; i < titleIds.size(); i++ ) + for (u32 i = 0; i < titleIds.size(); i++) { - bool r = GetName( titleIds.at( i ), language, name ); - if ( r ) + bool r = GetName(titleIds.at(i), language, name); + if (r) { - wString wsname( name ); - NameList[ titleIds.at( i ) ] = wsname.toUTF8(); + wString wsname(name); + NameList[titleIds.at(i)] = wsname.toUTF8(); } } ISFS_Deinitialize(); - MagicPatches( 0 ); + MagicPatches(0); return 1; } -tmd* NandTitle::GetTMD( u64 tid ) +tmd* NandTitle::GetTMD(u64 tid) { //gprintf("GetTMD( %016llx ): ", tid ); - signed_blob *s_tmd = ( signed_blob * )tmd_buf; + signed_blob *s_tmd = (signed_blob *) tmd_buf; u32 tmd_size; - if ( ES_GetStoredTMDSize( tid, &tmd_size ) < 0 ) + if (ES_GetStoredTMDSize(tid, &tmd_size) < 0) { //gprintf("!size\n"); return NULL; } - s32 ret = ES_GetStoredTMD( tid, s_tmd, tmd_size ); - if ( ret < 0 ) + s32 ret = ES_GetStoredTMD(tid, s_tmd, tmd_size); + if (ret < 0) { //gprintf("!tmd - %04x\n", ret ); return NULL; } - tmd *t = ( tmd* )SIGNATURE_PAYLOAD( s_tmd ); + tmd *t = (tmd*) SIGNATURE_PAYLOAD(s_tmd); //gprintf("ok\n"); return t; } -bool NandTitle::GetName( u64 tid, int language, wchar_t* name ) +bool NandTitle::GetName(u64 tid, int language, wchar_t* name) { - if ( TITLE_UPPER( tid ) != 0x10001 && TITLE_UPPER( tid ) != 0x10002 && TITLE_UPPER( tid ) != 0x10004 ) - return false; + if (TITLE_UPPER( tid ) != 0x10001 && TITLE_UPPER( tid ) != 0x10002 && TITLE_UPPER( tid ) != 0x10004) return false; //gprintf("GetName( %016llx ): ", tid ); - char app[ ISFS_MAXPATH ]; - IMET *imet = ( IMET* )memalign( 32, sizeof( IMET ) ); + char app[ISFS_MAXPATH]; + IMET *imet = (IMET*) memalign(32, sizeof(IMET)); - tmd* titleTmd = GetTMD( tid ); - if ( !titleTmd ) + tmd* titleTmd = GetTMD(tid); + if (!titleTmd) { //gprintf("no TMD\n"); - free( imet ); + free(imet); return false; } u16 i; bool ok = false; - for ( i = 0; i < titleTmd->num_contents; i++ ) + for (i = 0; i < titleTmd->num_contents; i++) { - if ( !titleTmd->contents[ i ].index ) + if (!titleTmd->contents[i].index) { ok = true; break; } } - if ( !ok ) + if (!ok) { - free( imet ); + free(imet); return false; } - snprintf( app, sizeof( app ), "/title/%08x/%08x/content/%08x.app", TITLE_UPPER( tid ), TITLE_LOWER( tid ), titleTmd->contents[ i ].cid ); + snprintf(app, sizeof(app), "/title/%08x/%08x/content/%08x.app", TITLE_UPPER( tid ), TITLE_LOWER( tid ), + titleTmd->contents[i].cid); //gprintf("%s\n", app ); - if ( language > CONF_LANG_KOREAN ) - language = CONF_LANG_ENGLISH; + if (language > CONF_LANG_KOREAN) language = CONF_LANG_ENGLISH; - s32 fd = ISFS_Open( app, ISFS_OPEN_READ ); - if ( fd < 0 ) + s32 fd = ISFS_Open(app, ISFS_OPEN_READ); + if (fd < 0) { //gprintf("fd: %d\n", fd ); - free( imet ); + free(imet); return false; } - if ( ISFS_Seek( fd, IMET_OFFSET, SEEK_SET ) != IMET_OFFSET ) + if (ISFS_Seek(fd, IMET_OFFSET, SEEK_SET) != IMET_OFFSET) { - ISFS_Close( fd ); - free( imet ); + ISFS_Close(fd); + free(imet); return false; } - if ( ISFS_Read( fd, imet, sizeof( IMET ) ) != sizeof( IMET ) ) + if (ISFS_Read(fd, imet, sizeof(IMET)) != sizeof(IMET)) { - ISFS_Close( fd ); - free( imet ); + ISFS_Close(fd); + free(imet); return false; } - ISFS_Close( fd ); + ISFS_Close(fd); - if ( imet->sig != IMET_SIGNATURE ) + if (imet->sig != IMET_SIGNATURE) { - free( imet ); + free(imet); return false; } - if ( imet->name_japanese[ language * IMET_MAX_NAME_LEN ] == 0 ) + if (imet->name_japanese[language * IMET_MAX_NAME_LEN] == 0) { // channel name is not available in system language - if ( imet->name_english[ 0 ] != 0 ) + if (imet->name_english[0] != 0) { language = CONF_LANG_ENGLISH; } else { // channel name is also not available on english, get ascii name - for ( int i = 0; i < 4; i++ ) + for (int i = 0; i < 4; i++) { - name[ i ] = ( TITLE_LOWER( tid ) >> ( 24 - i * 8 ) ) & 0xFF; + name[i] = (TITLE_LOWER( tid ) >> (24 - i * 8)) & 0xFF; } - name[ 4 ] = 0; - free( imet ); + name[4] = 0; + free(imet); return true; } } // retrieve channel name in system language or on english - for ( int i = 0; i < IMET_MAX_NAME_LEN; i++ ) + for (int i = 0; i < IMET_MAX_NAME_LEN; i++) { - name[ i ] = imet->name_japanese[ i + ( language * IMET_MAX_NAME_LEN ) ]; + name[i] = imet->name_japanese[i + (language * IMET_MAX_NAME_LEN)]; } - free( imet ); + free(imet); return true; } -bool NandTitle::Exists( u64 tid ) +bool NandTitle::Exists(u64 tid) { - char app[ ISFS_MAXPATH ]; - tmd* titleTmd = GetTMD( tid ); - if ( !titleTmd ) - return false; + char app[ISFS_MAXPATH]; + tmd* titleTmd = GetTMD(tid); + if (!titleTmd) return false; u16 i; bool ok = false; - for ( i = 0; i < titleTmd->num_contents; i++ ) + for (i = 0; i < titleTmd->num_contents; i++) { - if ( !titleTmd->contents[ i ].index ) + if (!titleTmd->contents[i].index) { ok = true; break; } } - if ( !ok ) - return false; + if (!ok) return false; - - snprintf( app, sizeof( app ), "/title/%08x/%08x/content/%08x.app", TITLE_UPPER( tid ), TITLE_LOWER( tid ), titleTmd->contents[ i ].cid ); - s32 fd = ISFS_Open( app, ISFS_OPEN_READ ); - if ( fd >= 0 ) - ISFS_Close( fd ); + snprintf(app, sizeof(app), "/title/%08x/%08x/content/%08x.app", TITLE_UPPER( tid ), TITLE_LOWER( tid ), + titleTmd->contents[i].cid); + s32 fd = ISFS_Open(app, ISFS_OPEN_READ); + if (fd >= 0) ISFS_Close(fd); //gprintf(" fd: %d\n", fd ); return fd >= 0 || fd == -102; //102 means it exists, but we dont have permission to open it } -bool NandTitle::ExistsFromIndex( u32 i ) +bool NandTitle::ExistsFromIndex(u32 i) { - if ( i > titleIds.size() || i < 0 ) - return false; + if (i > titleIds.size() || i < 0) return false; - return Exists( titleIds.at( i ) ); + return Exists(titleIds.at(i)); } -u64 NandTitle::At( u32 i ) +u64 NandTitle::At(u32 i) { - if ( i > titleIds.size() || i < 0 ) - return 0; + if (i > titleIds.size() || i < 0) return 0; - return titleIds.at( i ); + return titleIds.at(i); } -int NandTitle::IndexOf( u64 tid ) +int NandTitle::IndexOf(u64 tid) { - for ( u32 i = 0; i < titleIds.size(); i++ ) + for (u32 i = 0; i < titleIds.size(); i++) { - if ( titleIds.at( i ) == tid ) - return i; + if (titleIds.at(i) == tid) return i; } return WII_EINSTALL; } -const char* NandTitle::NameOf( u64 tid ) +const char* NandTitle::NameOf(u64 tid) { - map::iterator itr = NameList.find( tid ); - if( itr != NameList.end() ) - return itr->second.c_str(); + map::iterator itr = NameList.find(tid); + if (itr != NameList.end()) return itr->second.c_str(); return NULL; } -const char* NandTitle::NameFromIndex( u32 i ) +const char* NandTitle::NameFromIndex(u32 i) { - if ( i > titleIds.size() || i < 0 ) - return NULL; + if (i > titleIds.size() || i < 0) return NULL; - map::iterator itr = NameList.find( titleIds.at( i ) ); - if( itr != NameList.end() ) - return itr->second.c_str(); + map::iterator itr = NameList.find(titleIds.at(i)); + if (itr != NameList.end()) return itr->second.c_str(); return NULL; } -u16 NandTitle::VersionOf( u64 tid ) +u16 NandTitle::VersionOf(u64 tid) { - for ( u32 i = 0; i < titleIds.size(); i++ ) + for (u32 i = 0; i < titleIds.size(); i++) { - if ( titleIds.at( i ) == tid ) + if (titleIds.at(i) == tid) { - tmd* Tmd = GetTMD( tid ); - if ( !Tmd ) - break; + tmd* Tmd = GetTMD(tid); + if (!Tmd) break; return Tmd->title_version; } @@ -312,24 +304,22 @@ u16 NandTitle::VersionOf( u64 tid ) } -u16 NandTitle::VersionFromIndex( u32 i ) +u16 NandTitle::VersionFromIndex(u32 i) { - if ( i > titleIds.size() || i < 0 ) - return 0; + if (i > titleIds.size() || i < 0) return 0; - tmd* Tmd = GetTMD( titleIds.at( i ) ); - if ( !Tmd ) - return 0; + tmd* Tmd = GetTMD(titleIds.at(i)); + if (!Tmd) return 0; return Tmd->title_version; } -u32 NandTitle::CountType( u32 type ) +u32 NandTitle::CountType(u32 type) { u32 ret = 0; - for ( u32 i = 0; i < titleIds.size(); i++ ) + for (u32 i = 0; i < titleIds.size(); i++) { - if ( TITLE_UPPER( titleIds.at( i ) ) == type ) + if (TITLE_UPPER( titleIds.at( i ) ) == type) { ret++; } @@ -337,12 +327,12 @@ u32 NandTitle::CountType( u32 type ) return ret; } -u32 NandTitle::SetType( u32 upper ) +u32 NandTitle::SetType(u32 upper) { currentType = upper; currentIndex = 0; - return CountType( upper ); + return CountType(upper); } u64 NandTitle::Next() @@ -350,19 +340,19 @@ u64 NandTitle::Next() u64 ret = 0; //gprintf("Next( %08x, %u )\n", currentType, currentIndex ); u32 i; - for ( i = currentIndex; i < titleIds.size(); i++ ) + for (i = currentIndex; i < titleIds.size(); i++) { - if ( currentType ) + if (currentType) { - if ( currentType == TITLE_UPPER( titleIds.at( i ) ) ) + if (currentType == TITLE_UPPER( titleIds.at( i ) )) { - ret = titleIds.at( i ); + ret = titleIds.at(i); break; } } else { - ret = titleIds.at( i ); + ret = titleIds.at(i); break; } } @@ -376,29 +366,29 @@ void NandTitle::ResetCounter() currentIndex = 0; } -void NandTitle::AsciiTID( u64 tid, char* out ) +void NandTitle::AsciiTID(u64 tid, char* out) { //gprintf("AsciiTID( %016llx ): "); - out[ 0 ] = ascii( TITLE_3( tid ) ); - out[ 1 ] = ascii( TITLE_2( tid ) ); - out[ 2 ] = ascii( TITLE_1( tid ) ); - out[ 3 ] = ascii( ( u8 )( tid ) ); - out[ 4 ] = 0; + out[0] = ascii(TITLE_3( tid )); + out[1] = ascii(TITLE_2( tid )); + out[2] = ascii(TITLE_1( tid )); + out[3] = ascii((u8) (tid)); + out[4] = 0; //gprintf("%s\n", out ); } -void NandTitle::AsciiFromIndex( u32 i, char* out ) +void NandTitle::AsciiFromIndex(u32 i, char* out) { - if ( i > titleIds.size() || i < 0 ) + if (i > titleIds.size() || i < 0) { - out[ 0 ] = 0; + out[0] = 0; return; } - AsciiTID( titleIds.at( i ), out ); + AsciiTID(titleIds.at(i), out); } -s32 NandTitle::GetTicketViews( u64 tid, tikview **outbuf, u32 *outlen ) +s32 NandTitle::GetTicketViews(u64 tid, tikview **outbuf, u32 *outlen) { tikview *views = NULL; @@ -406,19 +396,16 @@ s32 NandTitle::GetTicketViews( u64 tid, tikview **outbuf, u32 *outlen ) s32 ret; /* Get number of ticket views */ - ret = ES_GetNumTicketViews( tid, &nb_views ); - if ( ret < 0 ) - return ret; + ret = ES_GetNumTicketViews(tid, &nb_views); + if (ret < 0) return ret; /* Allocate memory */ - views = ( tikview * )memalign( 32, sizeof( tikview ) * nb_views ); - if ( !views ) - return -1; + views = (tikview *) memalign(32, sizeof(tikview) * nb_views); + if (!views) return -1; /* Get ticket views */ - ret = ES_GetTicketViews( tid, views, nb_views ); - if ( ret < 0 ) - goto err; + ret = ES_GetTicketViews(tid, views, nb_views); + if (ret < 0) goto err; /* Set values */ *outbuf = views; @@ -426,27 +413,25 @@ s32 NandTitle::GetTicketViews( u64 tid, tikview **outbuf, u32 *outlen ) return 0; -err: + err: /* Free memory */ - if ( views ) - free( views ); + if (views) free(views); return ret; } -int NandTitle::FindU64( const char *s ) +int NandTitle::FindU64(const char *s) { - u64 tid = atoi_hex( s ); - return IndexOf( tid ); + u64 tid = atoi_hex(s); + return IndexOf(tid); } -int NandTitle::FindU32( const char *s ) +int NandTitle::FindU32(const char *s) { - u64 tid = atoi_hex( s ); - for ( u32 i = 0; i < titleIds.size(); i++ ) + u64 tid = atoi_hex(s); + for (u32 i = 0; i < titleIds.size(); i++) { - if ( TITLE_LOWER( titleIds.at( i ) ) == TITLE_LOWER( tid ) ) - return i; + if (TITLE_LOWER( titleIds.at( i ) ) == TITLE_LOWER( tid )) return i; } return WII_EINSTALL; } diff --git a/source/wad/nandtitle.h b/source/wad/nandtitle.h index 54820130..be270115 100644 --- a/source/wad/nandtitle.h +++ b/source/wad/nandtitle.h @@ -36,24 +36,24 @@ using namespace std; typedef struct { - u8 zeroes1[0x40]; - u32 sig; // "IMET" - u32 unk1; - u32 unk2; - u32 filesizes[3]; - u32 unk3; - u16 name_japanese[IMET_MAX_NAME_LEN]; - u16 name_english[IMET_MAX_NAME_LEN]; - u16 name_german[IMET_MAX_NAME_LEN]; - u16 name_french[IMET_MAX_NAME_LEN]; - u16 name_spanish[IMET_MAX_NAME_LEN]; - u16 name_italian[IMET_MAX_NAME_LEN]; - u16 name_dutch[IMET_MAX_NAME_LEN]; - u16 name_simp_chinese[IMET_MAX_NAME_LEN]; - u16 name_trad_chinese[IMET_MAX_NAME_LEN]; - u16 name_korean[IMET_MAX_NAME_LEN]; - u8 zeroes2[0x24c]; - u8 md5[0x10]; + u8 zeroes1[0x40]; + u32 sig; // "IMET" + u32 unk1; + u32 unk2; + u32 filesizes[3]; + u32 unk3; + u16 name_japanese[IMET_MAX_NAME_LEN]; + u16 name_english[IMET_MAX_NAME_LEN]; + u16 name_german[IMET_MAX_NAME_LEN]; + u16 name_french[IMET_MAX_NAME_LEN]; + u16 name_spanish[IMET_MAX_NAME_LEN]; + u16 name_italian[IMET_MAX_NAME_LEN]; + u16 name_dutch[IMET_MAX_NAME_LEN]; + u16 name_simp_chinese[IMET_MAX_NAME_LEN]; + u16 name_trad_chinese[IMET_MAX_NAME_LEN]; + u16 name_korean[IMET_MAX_NAME_LEN]; + u8 zeroes2[0x24c]; + u8 md5[0x10]; } IMET; class NandTitle @@ -63,42 +63,46 @@ class NandTitle ~NandTitle(); s32 Get(); - u64 At( u32 i ); - int IndexOf( u64 tid ); - u32 Count() { return titleIds.size(); } + u64 At(u32 i); + int IndexOf(u64 tid); + u32 Count() + { + return titleIds.size(); + } - const char* NameOf( u64 tid ); - const char* NameFromIndex( u32 i ); + const char* NameOf(u64 tid); + const char* NameFromIndex(u32 i); - u16 VersionOf( u64 tid ); - u16 VersionFromIndex( u32 i ); + u16 VersionOf(u64 tid); + u16 VersionFromIndex(u32 i); - u32 CountType( u32 type ); + u32 CountType(u32 type); - - u32 SetType( u32 upper ); + u32 SetType(u32 upper); u64 Next(); void ResetCounter(); - void AsciiTID( u64 tid, char* out ); - void AsciiFromIndex( u32 i, char* out ); + void AsciiTID(u64 tid, char* out); + void AsciiFromIndex(u32 i, char* out); - bool Exists( u64 tid ); - bool ExistsFromIndex( u32 i ); + bool Exists(u64 tid); + bool ExistsFromIndex(u32 i); - int FindU64( const char *s ); - int FindU32( const char *s ); + int FindU64(const char *s); + int FindU32(const char *s); - s32 GetTicketViews( u64 tid, tikview **outbuf, u32 *outlen ); + s32 GetTicketViews(u64 tid, tikview **outbuf, u32 *outlen); - u64 operator[]( u32 i ) { return At( i ); } + u64 operator[](u32 i) + { + return At(i); + } private: - std::vector titleIds; - std::map NameList; - bool GetName( u64 tid, int language, wchar_t* name ); - tmd* GetTMD( u64 tid ); - + std::vector titleIds; + std::map NameList; + bool GetName(u64 tid, int language, wchar_t* name); + tmd* GetTMD(u64 tid); u32 currentIndex; u32 currentType; @@ -106,4 +110,3 @@ class NandTitle extern NandTitle titles; #endif // NANDTITLE_H - diff --git a/source/wad/utils.h b/source/wad/utils.h index 14bea927..a7d4737a 100644 --- a/source/wad/utils.h +++ b/source/wad/utils.h @@ -8,16 +8,16 @@ extern "C" /* Constants */ #define KB_SIZE 1024.0 #define MB_SIZE 1048576.0 -#define GB_SIZE 1073741824.0 - - /* Macros */ -#define round_up(x,n) (-(-(x) & -(n))) - - /* Prototypes */ - u32 swap32( u32 ); - -#ifdef __cplusplus -} -#endif - -#endif +#define GB_SIZE 1073741824.0 + + /* Macros */ +#define round_up(x,n) (-(-(x) & -(n))) + + /* Prototypes */ + u32 swap32(u32); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/source/wad/wad.cpp b/source/wad/wad.cpp index 69150965..9b1fb95c 100644 --- a/source/wad/wad.cpp +++ b/source/wad/wad.cpp @@ -10,8 +10,6 @@ #include "nandtitle.h" - - #include "prompts/PromptWindows.h" #include "libwiigui/gui.h" #include "language/gettext.h" @@ -23,62 +21,57 @@ extern void HaltGui(); /*** Extern variables ***/ 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; -} ATTRIBUTE_PACKED wadHeader; + /* 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 __Wad_ReadFile(FILE *fp, void *outbuf, u32 offset, u32 len) { s32 ret; /* Seek to offset */ - fseek( fp, offset, SEEK_SET ); + fseek(fp, offset, SEEK_SET); /* Read data */ - ret = fread( outbuf, len, 1, fp ); - if ( ret < 0 ) - return ret; + ret = fread(outbuf, len, 1, fp); + if (ret < 0) return ret; return 0; } -s32 __Wad_ReadAlloc( FILE *fp, void **outbuf, u32 offset, u32 len ) +s32 __Wad_ReadAlloc(FILE *fp, void **outbuf, u32 offset, u32 len) { void *buffer = NULL; - s32 ret; + s32 ret; /* Allocate memory */ - buffer = memalign( 32, len ); - if ( !buffer ) - return -1; + buffer = memalign(32, len); + if (!buffer) return -1; /* Read file */ - ret = __Wad_ReadFile( fp, buffer, offset, len ); - if ( ret < 0 ) + ret = __Wad_ReadFile(fp, buffer, offset, len); + if (ret < 0) { - free( buffer ); + free(buffer); return ret; } @@ -87,257 +80,246 @@ s32 __Wad_ReadAlloc( FILE *fp, void **outbuf, u32 offset, u32 len ) return 0; } -s32 __Wad_GetTitleID( FILE *fp, wadHeader *header, u64 *tid ) +s32 __Wad_GetTitleID(FILE *fp, wadHeader *header, u64 *tid) { //signed_blob *p_tik = NULL; - void *p_tik = NULL; - tik *tik_data = NULL; + void *p_tik = NULL; + tik *tik_data = NULL; 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 ); + 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; + 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 ); + tik_data = (tik *) SIGNATURE_PAYLOAD((signed_blob *) p_tik); /* Copy title ID */ *tid = tik_data->titleid; -out: + out: /* Free memory */ - if ( p_tik ) - free( p_tik ); + if (p_tik) free(p_tik); return ret; } -s32 Wad_Install( FILE *fp ) +s32 Wad_Install(FILE *fp) { //////start the gui shit - GuiWindow promptWindow( 472, 320 ); - promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - promptWindow.SetPosition( 0, -10 ); + 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 ); + 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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", Settings.theme_path ); - GuiImageData dialogBox( imgPath, dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", Settings.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiImage dialogBoxImg( &dialogBox ); - if ( Settings.wsprompt == yes ) + GuiImage dialogBoxImg(&dialogBox); + if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen( Settings.widescreen ); + dialogBoxImg.SetWidescreen(Settings.widescreen); } - GuiText btn1Txt( tr( "OK" ), 22, THEME.prompttext ); - GuiImage btn1Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn1Txt(tr( "OK" ), 22, THEME.prompttext); + GuiImage btn1Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn1Txt.SetWidescreen( Settings.widescreen ); - btn1Img.SetWidescreen( Settings.widescreen ); + btn1Txt.SetWidescreen(Settings.widescreen); + btn1Img.SetWidescreen(Settings.widescreen); } - GuiButton btn1( &btn1Img, &btn1Img, 2, 4, 0, -35, &trigA, &btnSoundOver, btnClick2, 1 ); - btn1.SetLabel( &btn1Txt ); - btn1.SetState( STATE_SELECTED ); + 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", Settings.theme_path ); - GuiImageData progressbarOutline( imgPath, progressbar_outline_png ); - GuiImage progressbarOutlineImg( &progressbarOutline ); - if ( Settings.wsprompt == yes ) + snprintf(imgPath, sizeof(imgPath), "%sprogressbar_outline.png", Settings.theme_path); + GuiImageData progressbarOutline(imgPath, progressbar_outline_png); + GuiImage progressbarOutlineImg(&progressbarOutline); + if (Settings.wsprompt == yes) { - progressbarOutlineImg.SetWidescreen( Settings.widescreen ); + progressbarOutlineImg.SetWidescreen(Settings.widescreen); } - progressbarOutlineImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - progressbarOutlineImg.SetPosition( 25, 50 ); + progressbarOutlineImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + progressbarOutlineImg.SetPosition(25, 50); - snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_empty.png", Settings.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", Settings.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", Settings.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", Settings.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, " "); // sprintf(msg, "%s", tr("Initializing Network")); - GuiText msg1Txt( ( char* )NULL, 20, THEME.prompttext ); - msg1Txt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - msg1Txt.SetPosition( 50, 75 ); -// char msg2[50] = " "; - GuiText msg2Txt( ( char* )NULL, 20, THEME.prompttext ); - msg2Txt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - msg2Txt.SetPosition( 50, 98 ); + GuiText msg1Txt((char*) NULL, 20, THEME.prompttext); + msg1Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg1Txt.SetPosition(50, 75); + // char msg2[50] = " "; + GuiText msg2Txt((char*) NULL, 20, THEME.prompttext); + msg2Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg2Txt.SetPosition(50, 98); - GuiText msg3Txt( ( char* )NULL, 20, THEME.prompttext ); - msg3Txt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - msg3Txt.SetPosition( 50, 121 ); + GuiText msg3Txt((char*) NULL, 20, THEME.prompttext); + msg3Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg3Txt.SetPosition(50, 121); - GuiText msg4Txt( ( char* )NULL, 20, THEME.prompttext ); - msg4Txt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - msg4Txt.SetPosition( 50, 144 ); + GuiText msg4Txt((char*) NULL, 20, THEME.prompttext); + msg4Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg4Txt.SetPosition(50, 144); - GuiText msg5Txt( ( char* )NULL, 20, THEME.prompttext ); - msg5Txt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - msg5Txt.SetPosition( 50, 167 ); + GuiText msg5Txt((char*) NULL, 20, THEME.prompttext); + msg5Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg5Txt.SetPosition(50, 167); - GuiText prTxt( ( char* )NULL, 26, THEME.prompttext ); - prTxt.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - prTxt.SetPosition( 0, 50 ); + GuiText prTxt((char*) NULL, 26, THEME.prompttext); + prTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); + prTxt.SetPosition(0, 50); - - if ( ( Settings.wsprompt == yes ) && ( Settings.widescreen ) ) /////////////adjust for widescreen + if ((Settings.wsprompt == yes) && (Settings.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 ); + 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); HaltGui(); - mainWindow->SetState( STATE_DISABLED ); - mainWindow->Append( &promptWindow ); - mainWindow->ChangeFocus( &promptWindow ); + mainWindow->SetState(STATE_DISABLED); + mainWindow->Append(&promptWindow); + mainWindow->ChangeFocus(&promptWindow); //sleep(1); ///start the wad shit bool fail = false; - wadHeader *header = NULL; - void *pvoid; + 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; - ResumeGui(); - msg1Txt.SetText( tr( ">> Reading WAD data..." ) ); + 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 ) ); + ret = __Wad_ReadAlloc(fp, &pvoid, offset, sizeof(wadHeader)); - if ( ret < 0 ) - goto err; + 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; + 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 - if ( header->crl_len ) + 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; + 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; + 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; + 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..." ) ); + 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; + 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..." ) ); + 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; + 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 ); + tmd_data = (tmd *) SIGNATURE_PAYLOAD(p_tmd); // Install contents //ResumeGui(); //HaltGui(); - promptWindow.Append( &progressbarEmptyImg ); - promptWindow.Append( &progressbarImg ); - promptWindow.Append( &progressbarOutlineImg ); - promptWindow.Append( &prTxt ); + 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++ ) + msg3Txt.SetText(tr( "Installing title... Ok!" )); + for (cnt = 0; cnt < tmd_data->num_contents; cnt++) { tmd_content *content = &tmd_data->contents[cnt]; @@ -351,16 +333,16 @@ s32 Wad_Install( FILE *fp ) len = round_up( content->size, 64 ); // Install content - cfd = ES_AddContentStart( tmd_data->title_id, content->cid ); - if ( cfd < 0 ) + 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 ); + snprintf(imgPath, sizeof(imgPath), "%s%d...", tr( ">> Installing content #" ), content->cid); + msg4Txt.SetText(imgPath); // Install content data - while ( idx < len ) + while (idx < len) { //VIDEO_WaitVSync (); @@ -368,64 +350,58 @@ s32 Wad_Install( FILE *fp ) u32 size; // Data length - size = ( len - idx ); - if ( size > BLOCK_SIZE ) - size = BLOCK_SIZE; + size = (len - idx); + if (size > BLOCK_SIZE) size = BLOCK_SIZE; // Read data - ret = __Wad_ReadFile( fp, &wadBuffer, offset, size ); - if ( ret < 0 ) - goto err; + 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; + ret = ES_AddContentData(cfd, wadBuffer, size); + if (ret < 0) goto err; // Increase variables - idx += size; + idx += size; offset += size; //snprintf(imgPath, sizeof(imgPath), "%s%d (%d)...",tr(">> Installing content #"),content->cid,idx); //msg4Txt.SetText(imgPath); - prTxt.SetTextf( "%i%%", 100*( cnt*len + idx ) / ( tmd_data->num_contents*len ) ); - if ( ( Settings.wsprompt == yes ) && ( Settings.widescreen ) ) + prTxt.SetTextf("%i%%", 100 * (cnt * len + idx) / (tmd_data->num_contents * len)); + if ((Settings.wsprompt == yes) && (Settings.widescreen)) { - progressbarImg.SetTile( 78*( cnt*len + idx ) / ( tmd_data->num_contents*len ) ); + progressbarImg.SetTile(78 * (cnt * len + idx) / (tmd_data->num_contents * len)); } else { - progressbarImg.SetTile( 100*( cnt*len + idx ) / ( tmd_data->num_contents*len ) ); + progressbarImg.SetTile(100 * (cnt * len + idx) / (tmd_data->num_contents * len)); } } // Finish content installation - ret = ES_AddContentFinish( cfd ); - if ( ret < 0 ) - goto err; + 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 ) + if (ret >= 0) { -// printf(" OK!\n"); + // printf(" OK!\n"); goto out; } -err: + err: //char titties[100]; ResumeGui(); - prTxt.SetTextf( "%s%d", tr( "Error..." ), ret ); - promptWindow.Append( &prTxt ); + prTxt.SetTextf("%s%d", tr( "Error..." ), ret); + promptWindow.Append(&prTxt); fail = true; //snprintf(titties, sizeof(titties), "%d", ret); //printf(" ERROR! (ret = %d)\n", ret); @@ -435,249 +411,233 @@ err: goto exit; //return ret; -out: + 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 ); + 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 ) + exit: if (!fail) msg5Txt.SetText(tr( "Finishing installation... Ok!" )); + promptWindow.Append(&btn1); + while (btn1.GetState() != STATE_CLICKED) { } - HaltGui(); - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); return ret; } - -s32 Wad_Uninstall( FILE *fp ) +s32 Wad_Uninstall(FILE *fp) { //////start the gui shit - GuiWindow promptWindow( 472, 320 ); - promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - promptWindow.SetPosition( 0, -10 ); + 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 ); + 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 ); + 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", Settings.theme_path ); - GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", Settings.theme_path ); - GuiImageData dialogBox( imgPath, dialogue_box_png ); + snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", Settings.theme_path); + GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", Settings.theme_path); + GuiImageData dialogBox(imgPath, dialogue_box_png); GuiTrigger trigA; - trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiImage dialogBoxImg( &dialogBox ); - if ( Settings.wsprompt == yes ) + GuiImage dialogBoxImg(&dialogBox); + if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen( Settings.widescreen ); + dialogBoxImg.SetWidescreen(Settings.widescreen); } - GuiText btn1Txt( tr( "OK" ), 22, THEME.prompttext ); - GuiImage btn1Img( &btnOutline ); - if ( Settings.wsprompt == yes ) + GuiText btn1Txt(tr( "OK" ), 22, THEME.prompttext); + GuiImage btn1Img(&btnOutline); + if (Settings.wsprompt == yes) { - btn1Txt.SetWidescreen( Settings.widescreen ); - btn1Img.SetWidescreen( Settings.widescreen ); + btn1Txt.SetWidescreen(Settings.widescreen); + btn1Img.SetWidescreen(Settings.widescreen); } - GuiButton btn1( &btn1Img, &btn1Img, 2, 4, 0, -55, &trigA, &btnSoundOver, btnClick2, 1 ); - btn1.SetLabel( &btn1Txt ); - btn1.SetState( STATE_SELECTED ); + 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( ( char* )NULL, 18, THEME.prompttext ); - msg1Txt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - msg1Txt.SetPosition( 50, 75 ); + GuiText msg1Txt((char*) NULL, 18, THEME.prompttext); + msg1Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg1Txt.SetPosition(50, 75); - GuiText msg2Txt( ( char* )NULL, 18, THEME.prompttext ); - msg2Txt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - msg2Txt.SetPosition( 50, 98 ); + GuiText msg2Txt((char*) NULL, 18, THEME.prompttext); + msg2Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg2Txt.SetPosition(50, 98); - GuiText msg3Txt( ( char* )NULL, 18, THEME.prompttext ); - msg3Txt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - msg3Txt.SetPosition( 50, 121 ); + GuiText msg3Txt((char*) NULL, 18, THEME.prompttext); + msg3Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg3Txt.SetPosition(50, 121); - GuiText msg4Txt( ( char* )NULL, 18, THEME.prompttext ); - msg4Txt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - msg4Txt.SetPosition( 50, 144 ); + GuiText msg4Txt((char*) NULL, 18, THEME.prompttext); + msg4Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg4Txt.SetPosition(50, 144); - GuiText msg5Txt( ( char* )NULL, 18, THEME.prompttext ); - msg5Txt.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - msg5Txt.SetPosition( 50, 167 ); + GuiText msg5Txt((char*) NULL, 18, THEME.prompttext); + msg5Txt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + msg5Txt.SetPosition(50, 167); - - - if ( ( Settings.wsprompt == yes ) && ( Settings.widescreen ) ) /////////////adjust for widescreen + if ((Settings.wsprompt == yes) && (Settings.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 ); + 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; + wadHeader *header = NULL; + void *pvoid = NULL; + tikview *viewData = NULL; 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 ) + 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 ); + 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 ) + 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 ); + 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 = titles.GetTicketViews( tid, &viewData, &viewCnt ); - if ( ret < 0 ) + ret = titles.GetTicketViews(tid, &viewData, &viewCnt); + if (ret < 0) { char errTxt[50]; - sprintf( errTxt, "%sret = %d", tr( ">> Deleting tickets...ERROR! " ), ret ); - msg2Txt.SetText( errTxt ); + sprintf(errTxt, "%sret = %d", tr( ">> Deleting tickets...ERROR! " ), ret); + msg2Txt.SetText(errTxt); //printf(" ERROR! (ret = %d)\n", ret); } // Delete tickets - if ( ret >= 0 ) + if (ret >= 0) { u32 cnt; // Delete all tickets - for ( cnt = 0; cnt < viewCnt; cnt++ ) + for (cnt = 0; cnt < viewCnt; cnt++) { - ret = ES_DeleteTicket( &viewData[cnt] ); - if ( ret < 0 ) - break; + ret = ES_DeleteTicket(&viewData[cnt]); + if (ret < 0) break; } - if ( ret < 0 ) + if (ret < 0) { char errTxt[50]; - sprintf( errTxt, "%sret = %d", tr( ">> Deleting tickets...ERROR! " ), ret ); - msg2Txt.SetText( errTxt ); + 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! " ) ); + //printf(" OK!\n"); + msg2Txt.SetText(tr( ">> Deleting tickets...Ok! " )); } - msg3Txt.SetText( tr( ">> Deleting title contents..." ) ); + msg3Txt.SetText(tr( ">> Deleting title contents..." )); //WindowPrompt(">> Deleting title contents...",0,"Back",0,0); // Delete title contents - ret = ES_DeleteTitleContent( tid ); - if ( ret < 0 ) + ret = ES_DeleteTitleContent(tid); + if (ret < 0) { char errTxt[50]; - sprintf( errTxt, "%sret = %d", tr( ">> Deleting title contents...ERROR! " ), ret ); - msg3Txt.SetText( errTxt ); + 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!" ) ); + //printf(" OK!\n"); + msg3Txt.SetText(tr( ">> Deleting title contents...Ok!" )); - msg4Txt.SetText( tr( ">> Deleting title..." ) ); + msg4Txt.SetText(tr( ">> Deleting title..." )); // Delete title - ret = ES_DeleteTitle( tid ); - if ( ret < 0 ) + ret = ES_DeleteTitle(tid); + if (ret < 0) { char errTxt[50]; - sprintf( errTxt, "%sret = %d", tr( ">> Deleting title ...ERROR! " ), ret ); - msg4Txt.SetText( errTxt ); + 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!" ) ); + //printf(" OK!\n"); + msg4Txt.SetText(tr( ">> Deleting title ...Ok!" )); -out: + out: // Free memory - if ( header ) - free( header ); + if (header) free(header); goto exit; - -exit: - msg5Txt.SetText( tr( "Done!" ) ); - promptWindow.Append( &btn1 ); - while ( btn1.GetState() != STATE_CLICKED ) + exit: msg5Txt.SetText(tr( "Done!" )); + promptWindow.Append(&btn1); + while (btn1.GetState() != STATE_CLICKED) { } - HaltGui(); - mainWindow->Remove( &promptWindow ); - mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove(&promptWindow); + mainWindow->SetState(STATE_DEFAULT); ResumeGui(); return ret; diff --git a/source/wad/wad.h b/source/wad/wad.h index 672283c4..89dd7358 100644 --- a/source/wad/wad.h +++ b/source/wad/wad.h @@ -5,7 +5,7 @@ #define BLOCK_SIZE 1024 -s32 Wad_Install( FILE * ); -s32 Wad_Uninstall( FILE * ); +s32 Wad_Install(FILE *); +s32 Wad_Uninstall(FILE *); #endif diff --git a/source/wpad.c b/source/wpad.c index 64631390..f4a0a4a3 100644 --- a/source/wpad.c +++ b/source/wpad.c @@ -1,127 +1,125 @@ #include -#include -#include - -#include "sys.h" -#include "wpad.h" - -/* Constants */ -#define MAX_WIIMOTES 4 - -extern u8 shutdown; - -void __Wpad_PowerCallback( s32 chan ) -{ - /* Poweroff console */ - shutdown = 1; -} - -void WPad_SetIdleTime( u32 seconds ) -{ - /*Set idle time for wiimote*/ - WPAD_SetIdleTimeout( seconds ); -} - -s32 Wpad_Init( void ) -{ - s32 ret; - - /* Initialize Wiimote subsystem */ - ret = WPAD_Init(); - if ( ret < 0 ) - return ret; - - /* Set POWER button callback */ - WPAD_SetPowerButtonCallback( __Wpad_PowerCallback ); - - return ret; -} - -void Wpad_Disconnect( void ) -{ - u32 cnt; - - /* Disconnect Wiimotes */ - for ( cnt = 0; cnt < MAX_WIIMOTES; cnt++ ) - WPAD_Disconnect( cnt ); - - /* Shutdown Wiimote subsystem */ - WPAD_Shutdown(); -} - -bool IsWpadConnected() -{ - int i = 0; - u32 test = 0; - int notconnected = 0; - for ( i = 0; i < 4; i++ ) - { - if ( WPAD_Probe( i, &test ) == WPAD_ERR_NO_CONTROLLER ) - { - notconnected++; - } - } - if ( notconnected < 4 ) - return true; - else - return false; -} - -u32 ButtonsHold( void ) -{ - - int i; - u32 buttons = 0; - - WPAD_ScanPads(); - PAD_ScanPads(); - - for ( i = 3; i >= 0; i-- ) - { - buttons |= PAD_ButtonsHeld( i ); - buttons |= WPAD_ButtonsHeld( i ); - } - return buttons; -} - -u32 ButtonsPressed( void ) -{ - - int i; - u32 buttons = 0; - - WPAD_ScanPads(); - PAD_ScanPads(); - - for ( i = 3; i >= 0; i-- ) - { - buttons |= PAD_ButtonsDown( i ); - buttons |= WPAD_ButtonsDown( i ); - } - return buttons; - +#include +#include + +#include "sys.h" +#include "wpad.h" + +/* Constants */ +#define MAX_WIIMOTES 4 + +extern u8 shutdown; + +void __Wpad_PowerCallback(s32 chan) +{ + /* Poweroff console */ + shutdown = 1; +} + +void WPad_SetIdleTime(u32 seconds) +{ + /*Set idle time for wiimote*/ + WPAD_SetIdleTimeout(seconds); +} + +s32 Wpad_Init(void) +{ + s32 ret; + + /* Initialize Wiimote subsystem */ + ret = WPAD_Init(); + if (ret < 0) return ret; + + /* Set POWER button callback */ + WPAD_SetPowerButtonCallback(__Wpad_PowerCallback); + + return ret; +} + +void Wpad_Disconnect(void) +{ + u32 cnt; + + /* Disconnect Wiimotes */ + for (cnt = 0; cnt < MAX_WIIMOTES; cnt++) + WPAD_Disconnect(cnt); + + /* Shutdown Wiimote subsystem */ + WPAD_Shutdown(); +} + +bool IsWpadConnected() +{ + int i = 0; + u32 test = 0; + int notconnected = 0; + for (i = 0; i < 4; i++) + { + if (WPAD_Probe(i, &test) == WPAD_ERR_NO_CONTROLLER) + { + notconnected++; + } + } + if (notconnected < 4) + return true; + else return false; +} + +u32 ButtonsHold(void) +{ + + int i; + u32 buttons = 0; + + WPAD_ScanPads(); + PAD_ScanPads(); + + for (i = 3; i >= 0; i--) + { + buttons |= PAD_ButtonsHeld(i); + buttons |= WPAD_ButtonsHeld(i); + } + return buttons; +} + +u32 ButtonsPressed(void) +{ + + int i; + u32 buttons = 0; + + WPAD_ScanPads(); + PAD_ScanPads(); + + for (i = 3; i >= 0; i--) + { + buttons |= PAD_ButtonsDown(i); + buttons |= WPAD_ButtonsDown(i); + } + return buttons; + /* Don't remove this commented out code it might be useful for checking which buttons were pressed/hold - - if(buttons & (PAD_BUTTON_LEFT | PAD_BUTTON_RIGHT | PAD_BUTTON_DOWN | PAD_BUTTON_UP - | PAD_BUTTON_A | PAD_BUTTON_B | PAD_BUTTON_X | PAD_BUTTON_Y | PAD_BUTTON_MENU - | PAD_BUTTON_START | WPAD_BUTTON_2 | WPAD_BUTTON_1 - | WPAD_BUTTON_B | WPAD_BUTTON_A | WPAD_BUTTON_MINUS - | WPAD_BUTTON_HOME | WPAD_BUTTON_LEFT | WPAD_BUTTON_RIGHT - | WPAD_BUTTON_DOWN | WPAD_BUTTON_UP | WPAD_BUTTON_PLUS - | WPAD_NUNCHUK_BUTTON_Z | WPAD_NUNCHUK_BUTTON_C - | WPAD_CLASSIC_BUTTON_UP | WPAD_CLASSIC_BUTTON_LEFT - | WPAD_CLASSIC_BUTTON_ZR | WPAD_CLASSIC_BUTTON_X - | WPAD_CLASSIC_BUTTON_A | WPAD_CLASSIC_BUTTON_Y - | WPAD_CLASSIC_BUTTON_B | WPAD_CLASSIC_BUTTON_ZL - | WPAD_CLASSIC_BUTTON_FULL_R | WPAD_CLASSIC_BUTTON_PLUS - | WPAD_CLASSIC_BUTTON_HOME | WPAD_CLASSIC_BUTTON_MINUS - | WPAD_CLASSIC_BUTTON_FULL_L | WPAD_CLASSIC_BUTTON_DOWN - | WPAD_CLASSIC_BUTTON_RIGHT | WPAD_GUITAR_HERO_3_BUTTON_STRUM_UP - | WPAD_GUITAR_HERO_3_BUTTON_YELLOW | WPAD_GUITAR_HERO_3_BUTTON_GREEN - | WPAD_GUITAR_HERO_3_BUTTON_BLUE | WPAD_GUITAR_HERO_3_BUTTON_RED - | WPAD_GUITAR_HERO_3_BUTTON_ORANGE | WPAD_GUITAR_HERO_3_BUTTON_PLUS - | WPAD_GUITAR_HERO_3_BUTTON_MINUS | WPAD_GUITAR_HERO_3_BUTTON_STRUM_DOWN) - ) - */ - -} + + if(buttons & (PAD_BUTTON_LEFT | PAD_BUTTON_RIGHT | PAD_BUTTON_DOWN | PAD_BUTTON_UP + | PAD_BUTTON_A | PAD_BUTTON_B | PAD_BUTTON_X | PAD_BUTTON_Y | PAD_BUTTON_MENU + | PAD_BUTTON_START | WPAD_BUTTON_2 | WPAD_BUTTON_1 + | WPAD_BUTTON_B | WPAD_BUTTON_A | WPAD_BUTTON_MINUS + | WPAD_BUTTON_HOME | WPAD_BUTTON_LEFT | WPAD_BUTTON_RIGHT + | WPAD_BUTTON_DOWN | WPAD_BUTTON_UP | WPAD_BUTTON_PLUS + | WPAD_NUNCHUK_BUTTON_Z | WPAD_NUNCHUK_BUTTON_C + | WPAD_CLASSIC_BUTTON_UP | WPAD_CLASSIC_BUTTON_LEFT + | WPAD_CLASSIC_BUTTON_ZR | WPAD_CLASSIC_BUTTON_X + | WPAD_CLASSIC_BUTTON_A | WPAD_CLASSIC_BUTTON_Y + | WPAD_CLASSIC_BUTTON_B | WPAD_CLASSIC_BUTTON_ZL + | WPAD_CLASSIC_BUTTON_FULL_R | WPAD_CLASSIC_BUTTON_PLUS + | WPAD_CLASSIC_BUTTON_HOME | WPAD_CLASSIC_BUTTON_MINUS + | WPAD_CLASSIC_BUTTON_FULL_L | WPAD_CLASSIC_BUTTON_DOWN + | WPAD_CLASSIC_BUTTON_RIGHT | WPAD_GUITAR_HERO_3_BUTTON_STRUM_UP + | WPAD_GUITAR_HERO_3_BUTTON_YELLOW | WPAD_GUITAR_HERO_3_BUTTON_GREEN + | WPAD_GUITAR_HERO_3_BUTTON_BLUE | WPAD_GUITAR_HERO_3_BUTTON_RED + | WPAD_GUITAR_HERO_3_BUTTON_ORANGE | WPAD_GUITAR_HERO_3_BUTTON_PLUS + | WPAD_GUITAR_HERO_3_BUTTON_MINUS | WPAD_GUITAR_HERO_3_BUTTON_STRUM_DOWN) + ) + */ + +} diff --git a/source/wpad.h b/source/wpad.h index ba6b7ef1..85fc2acd 100644 --- a/source/wpad.h +++ b/source/wpad.h @@ -9,15 +9,15 @@ extern "C" #endif /* Prototypes */ - s32 Wpad_Init( void ); - void Wpad_Disconnect( void ); - u32 ButtonsPressed( void ); - u32 ButtonsHold( void ); + s32 Wpad_Init(void); + void Wpad_Disconnect(void); + u32 ButtonsPressed(void); + u32 ButtonsHold(void); bool IsWpadConnected(); - void WPad_SetIdleTime( u32 seconds ); - -#ifdef __cplusplus -} -#endif - -#endif + void WPad_SetIdleTime(u32 seconds); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/source/wstring.cpp b/source/wstring.cpp index 86dda7c8..06fc8082 100644 --- a/source/wstring.cpp +++ b/source/wstring.cpp @@ -3,167 +3,160 @@ using namespace std; -wString::wString( const wchar_t *s ) : - std::basic_string, std::allocator >( s ) +wString::wString(const wchar_t *s) : + std::basic_string, std::allocator >(s) { } -wString::wString( const basic_string, allocator > &ws ) : - basic_string, allocator >( ws ) +wString::wString(const basic_string , allocator > &ws) : + basic_string , allocator > (ws) { } -wString::wString( const string &s ) +wString::wString(const string &s) { std::string::size_type size; size = s.size(); - resize( size ); - for ( std::string::size_type i = 0; i < size; ++i ) - ( *this )[i] = ( unsigned char )s[i]; + resize(size); + for (std::string::size_type i = 0; i < size; ++i) + (*this)[i] = (unsigned char) s[i]; } -wString &wString::operator=( const string & s ) +wString &wString::operator=(const string & s) { std::string::size_type size; size = s.size(); - this->resize( size ); - for ( std::string::size_type i = 0; i < size; ++i ) - ( *this )[i] = ( unsigned char )s[i]; + this->resize(size); + for (std::string::size_type i = 0; i < size; ++i) + (*this)[i] = (unsigned char) s[i]; return *this; } -void wString::fromUTF8( const char *s ) +void wString::fromUTF8(const char *s) { - size_t len = utf8Len( s ); + size_t len = utf8Len(s); clear(); - if ( len == 0 ) - return; - reserve( len ); - for ( int i = 0; s[i] != 0; ) + if (len == 0) return; + reserve(len); + for (int i = 0; s[i] != 0;) { - if ( ( s[i] & 0xF8 ) == 0xF0 ) + if ((s[i] & 0xF8) == 0xF0) { - push_back( ( ( wchar_t )( s[i] & 0x07 ) << 18 ) | ( ( wchar_t )( s[i + 1] & 0x3F ) << 12 ) | ( ( wchar_t )( s[i + 2] & 0x3F ) << 6 ) | ( wchar_t )( s[i + 3] & 0x3F ) ); + push_back(((wchar_t) (s[i] & 0x07) << 18) | ((wchar_t) (s[i + 1] & 0x3F) << 12) | ((wchar_t) (s[i + 2] + & 0x3F) << 6) | (wchar_t) (s[i + 3] & 0x3F)); i += 4; } - else if ( ( s[i] & 0xF0 ) == 0xE0 ) + else if ((s[i] & 0xF0) == 0xE0) { - push_back( ( ( wchar_t )( s[i] & 0x0F ) << 12 ) | ( ( wchar_t )( s[i + 1] & 0x3F ) << 6 ) | ( wchar_t )( s[i + 2] & 0x3F ) ); + push_back(((wchar_t) (s[i] & 0x0F) << 12) | ((wchar_t) (s[i + 1] & 0x3F) << 6) + | (wchar_t) (s[i + 2] & 0x3F)); i += 3; } - else if ( ( s[i] & 0xE0 ) == 0xC0 ) + else if ((s[i] & 0xE0) == 0xC0) { - push_back( ( ( wchar_t )( s[i] & 0x1F ) << 6 ) | ( wchar_t )( s[i + 1] & 0x3F ) ); + push_back(((wchar_t) (s[i] & 0x1F) << 6) | (wchar_t) (s[i + 1] & 0x3F)); i += 2; } else { - push_back( ( wchar_t )s[i] ); + push_back((wchar_t) s[i]); ++i; } } } -string wString::toUTF8( void ) const +string wString::toUTF8(void) const { string s; size_t len = 0; wchar_t wc; - for ( size_t i = 0; i < size(); ++i ) + for (size_t i = 0; i < size(); ++i) { - wc = operator[]( i ); - if ( wc < 0x80 ) + wc = operator[](i); + if (wc < 0x80) ++len; - else if ( wc < 0x800 ) + else if (wc < 0x800) len += 2; - else if ( wc < 0x10000 ) + else if (wc < 0x10000) len += 3; - else - len += 4; + else len += 4; } - s.reserve( len ); - for ( size_t i = 0; i < size(); ++i ) + s.reserve(len); + for (size_t i = 0; i < size(); ++i) { - wc = operator[]( i ); - if ( wc < 0x80 ) - s.push_back( ( char )wc ); - else if ( wc < 0x800 ) + wc = operator[](i); + if (wc < 0x80) + s.push_back((char) wc); + else if (wc < 0x800) { - s.push_back( ( char )( ( wc >> 6 ) | 0xC0 ) ); - s.push_back( ( char )( ( wc & 0x3F ) | 0x80 ) ); + s.push_back((char) ((wc >> 6) | 0xC0)); + s.push_back((char) ((wc & 0x3F) | 0x80)); } - else if ( wc < 0x10000 ) + else if (wc < 0x10000) { - s.push_back( ( char )( ( wc >> 12 ) | 0xE0 ) ); - s.push_back( ( char )( ( ( wc >> 6 ) & 0x3F ) | 0x80 ) ); - s.push_back( ( char )( ( wc & 0x3F ) | 0x80 ) ); + s.push_back((char) ((wc >> 12) | 0xE0)); + s.push_back((char) (((wc >> 6) & 0x3F) | 0x80)); + s.push_back((char) ((wc & 0x3F) | 0x80)); } else { - s.push_back( ( char )( ( ( wc >> 18 ) & 0x07 ) | 0xF0 ) ); - s.push_back( ( char )( ( ( wc >> 12 ) & 0x3F ) | 0x80 ) ); - s.push_back( ( char )( ( ( wc >> 6 ) & 0x3F ) | 0x80 ) ); - s.push_back( ( char )( ( wc & 0x3F ) | 0x80 ) ); + s.push_back((char) (((wc >> 18) & 0x07) | 0xF0)); + s.push_back((char) (((wc >> 12) & 0x3F) | 0x80)); + s.push_back((char) (((wc >> 6) & 0x3F) | 0x80)); + s.push_back((char) ((wc & 0x3F) | 0x80)); } } return s; } -size_t utf8Len( const char *s ) +size_t utf8Len(const char *s) { size_t len = 0; - for ( int i = 0; s[i] != 0; ) + for (int i = 0; s[i] != 0;) { - if ( ( s[i] & 0xF8 ) == 0xF0 ) + if ((s[i] & 0xF8) == 0xF0) { - if ( ( ( s[i + 1] & 0xC0 ) != 0x80 ) || ( ( s[i + 2] & 0xC0 ) != 0x80 ) || ( ( s[i + 3] & 0xC0 ) != 0x80 ) ) - return 0; + if (((s[i + 1] & 0xC0) != 0x80) || ((s[i + 2] & 0xC0) != 0x80) || ((s[i + 3] & 0xC0) != 0x80)) return 0; ++len; i += 4; } - else if ( ( s[i] & 0xF0 ) == 0xE0 ) + else if ((s[i] & 0xF0) == 0xE0) { - if ( ( ( s[i + 1] & 0xC0 ) != 0x80 ) || ( ( s[i + 2] & 0xC0 ) != 0x80 ) ) - return 0; + if (((s[i + 1] & 0xC0) != 0x80) || ((s[i + 2] & 0xC0) != 0x80)) return 0; ++len; i += 3; } - else if ( ( s[i] & 0xE0 ) == 0xC0 ) + else if ((s[i] & 0xE0) == 0xC0) { - if ( ( ( s[i + 1] & 0xC0 ) != 0x80 ) ) - return 0; + if (((s[i + 1] & 0xC0) != 0x80)) return 0; ++len; i += 2; } - else if ( ( s[i] & 0x80 ) == 0x00 ) + else if ((s[i] & 0x80) == 0x00) { ++len; ++i; } - else - return 0; + else return 0; } return len; } -int wcsnicmp( const wchar_t *s1, const wchar_t *s2, int len ) +int wcsnicmp(const wchar_t *s1, const wchar_t *s2, int len) { - if ( len <= 0 ) - return ( 0 ); + if (len <= 0) return (0); do { - int r = towupper( *s1 ) - towupper( *s2++ ); - if ( r ) return r; - if ( *s1++ == 0 ) - break; - } - while ( --len != 0 ); + int r = towupper(*s1) - towupper(*s2++); + if (r) return r; + if (*s1++ == 0) break; + } while (--len != 0); - return ( 0 ); + return (0); } diff --git a/source/wstring.hpp b/source/wstring.hpp index 381eda5b..e2d79b86 100644 --- a/source/wstring.hpp +++ b/source/wstring.hpp @@ -7,20 +7,21 @@ #include -class wString : public std::basic_string, std::allocator > +class wString: public std::basic_string, std::allocator > { -public: - wString(void) { } - wString(const wchar_t *s); - wString(const std::basic_string, std::allocator > &ws); - wString(const std::string &s); - wString &operator=(const std::string &s); - void fromUTF8(const char *s); - std::string toUTF8(void) const; + public: + wString(void) + { + } + wString(const wchar_t *s); + wString(const std::basic_string, std::allocator > &ws); + wString(const std::string &s); + wString &operator=(const std::string &s); + void fromUTF8(const char *s); + std::string toUTF8(void) const; }; size_t utf8Len(const char *s); int wcsnicmp(const wchar_t *s1, const wchar_t *s2, int len); - #endif // !defined(__WSTRING_HPP) diff --git a/source/xml/xml.cpp b/source/xml/xml.cpp index 7b4a94d6..b39420ee 100644 --- a/source/xml/xml.cpp +++ b/source/xml/xml.cpp @@ -1,18 +1,19 @@ /* -Load game information from XML - Lustar + Load game information from XML - Lustar - Mini-XML by Michael Sweet - MiniZip adapted by Tantric -*/ + */ #include #include "unzip/unzip.h" #include "settings/CSettings.h" #include "xml/xml.h" -extern "C" { -extern void title_set( char *id, char *title ); -extern char* trimcopy( char *dest, char *src, int size ); -extern char game_partition[6]; +extern "C" +{ + extern void title_set(char *id, char *title); + extern char* trimcopy(char *dest, char *src, int size); + extern char game_partition[6]; } /* config */ @@ -20,35 +21,16 @@ static bool xmldebug = false; static char xmlcfg_filename[100] = "wiitdb"; static int xmlmaxsize = 1572864; - struct gameXMLinfo gameinfo; struct gameXMLinfo gameinfo_reset; -static char langlist[11][22] = {{"Console Default"}, - {"Japanese"}, - {"English"}, - {"German"}, - {"French"}, - {"Spanish"}, - {"Italian"}, - {"Dutch"}, - {"S. Chinese"}, - {"T. Chinese"}, - {"Korean"} -}; +static char langlist[11][22] = { { "Console Default" }, { "Japanese" }, { "English" }, { "German" }, { "French" }, { + "Spanish" }, { "Italian" }, { "Dutch" }, { "S. Chinese" }, { "T. Chinese" }, { "Korean" } }; -static char langcodes[11][5] = {{""}, - {"JA"}, - {"EN"}, - {"DE"}, - {"FR"}, - {"ES"}, - {"IT"}, - {"NL"}, - {"ZHCN"}, // People's Republic of China - {"ZHTW"}, // Taiwan - {"KO"} -}; +static char langcodes[11][5] = { { "" }, { "JA" }, { "EN" }, { "DE" }, { "FR" }, { "ES" }, { "IT" }, { "NL" }, + { "ZHCN" }, // People's Republic of China + { "ZHTW" }, // Taiwan + { "KO" } }; static char element_text[5000]; static mxml_node_t *nodetree = NULL; @@ -59,40 +41,39 @@ static mxml_node_t *nodefound = NULL; static mxml_index_t *nodeindex = NULL; static mxml_index_t *nodeindextmp = NULL; int xmlloadtime = 0; -char * get_nodetext( mxml_node_t *node, char *buffer, int buflen ); +char * get_nodetext(mxml_node_t *node, char *buffer, int buflen); bool xml_loaded = false; - /* load renamed titles from proper names and game info XML, needs to be after cfg_load_games */ -bool OpenXMLDatabase( char* xmlfilepath, char* argdblang, bool argJPtoEN, bool openfile, bool loadtitles, bool keepopen ) +bool OpenXMLDatabase(char* xmlfilepath, char* argdblang, bool argJPtoEN, bool openfile, bool loadtitles, bool keepopen) { - if ( !xml_loaded ) + if (!xml_loaded) { bool opensuccess = false; char pathname[200]; - snprintf( pathname, sizeof( pathname ), "%s", xmlfilepath ); - if ( xmlfilepath[strlen( xmlfilepath ) - 1] != '/' ) snprintf( pathname, sizeof( pathname ), "%s/", pathname ); - 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%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 ), "%swiitdb.zip", pathname ); - if ( openfile ) opensuccess = OpenXMLFile( 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); } - if ( !opensuccess && openfile ) + if (!opensuccess && openfile) { CloseXMLDatabase(); return false; } - if ( loadtitles ) LoadTitlesFromXML( argdblang, argJPtoEN ); - if ( !keepopen ) CloseXMLDatabase(); + if (loadtitles) LoadTitlesFromXML(argdblang, argJPtoEN); + if (!keepopen) CloseXMLDatabase(); } else { - if ( loadtitles ) LoadTitlesFromXML( argdblang, argJPtoEN ); - if ( !keepopen ) CloseXMLDatabase(); + if (loadtitles) LoadTitlesFromXML(argdblang, argJPtoEN); + if (!keepopen) CloseXMLDatabase(); } return true; } @@ -100,45 +81,42 @@ bool OpenXMLDatabase( char* xmlfilepath, char* argdblang, bool argJPtoEN, bool o void CloseXMLDatabase() { /* free memory */ - if ( xml_loaded ) + if (xml_loaded) { - mxmlDelete( nodedata ); - mxmlDelete( nodetree ); + mxmlDelete(nodedata); + mxmlDelete(nodetree); xml_loaded = false; } } - -void GetTextFromNode( mxml_node_t *currentnode, mxml_node_t *topnode, const char *nodename, - const char *attributename, char *value, int descend, char *dest, int destsize ) +void GetTextFromNode(mxml_node_t *currentnode, mxml_node_t *topnode, const char *nodename, const char *attributename, + char *value, int descend, char *dest, int destsize) { *element_text = 0; - nodefound = mxmlFindElement( currentnode, topnode, nodename, attributename, value, descend ); - if ( nodefound != NULL ) + nodefound = mxmlFindElement(currentnode, topnode, nodename, attributename, value, descend); + if (nodefound != NULL) { - if ( attributename != NULL ) + if (attributename != NULL) { - strlcpy( dest, mxmlElementGetAttr( nodefound, attributename ), destsize ); + strlcpy(dest, mxmlElementGetAttr(nodefound, attributename), destsize); } else { - get_nodetext( nodefound, element_text, sizeof( element_text ) ); - strlcpy( dest, element_text, destsize ); + get_nodetext(nodefound, element_text, sizeof(element_text)); + strlcpy(dest, element_text, destsize); } } else { - strcpy( dest, "" ); + strcpy(dest, ""); } } - -bool OpenXMLFile( char *filename ) +bool OpenXMLFile(char *filename) { //if (xmldebug) dbg_time1(); - if ( xml_loaded ) - return false; + if (xml_loaded) return false; gameinfo = gameinfo_reset; nodedata = NULL; @@ -147,59 +125,56 @@ bool OpenXMLFile( char *filename ) nodeidtmp = NULL; nodefound = NULL; - char* strresult = strstr( filename, ".zip" ); - if ( strresult == NULL ) + char* strresult = strstr(filename, ".zip"); + if (strresult == NULL) { /* Load XML file */ FILE *filexml; - filexml = fopen( filename, "rb" ); - if ( !filexml ) - return false; + filexml = fopen(filename, "rb"); + if (!filexml) return false; - nodetree = mxmlLoadFile( NULL, filexml, MXML_OPAQUE_CALLBACK ); - fclose( filexml ); + nodetree = mxmlLoadFile(NULL, filexml, MXML_OPAQUE_CALLBACK); + fclose(filexml); } else { /* load zipped XML file */ - unzFile unzfile = unzOpen( filename ); - if ( unzfile == NULL ) - return false; - unzOpenCurrentFile( unzfile ); + unzFile unzfile = unzOpen(filename); + if (unzfile == NULL) return false; + unzOpenCurrentFile(unzfile); unz_file_info zipfileinfo; - unzGetCurrentFileInfo( unzfile, &zipfileinfo, NULL, 0, NULL, 0, NULL, 0 ); + unzGetCurrentFileInfo(unzfile, &zipfileinfo, NULL, 0, NULL, 0, NULL, 0); int zipfilebuffersize = zipfileinfo.uncompressed_size; - if ( zipfilebuffersize >= xmlmaxsize ) + if (zipfilebuffersize >= xmlmaxsize) { - unzCloseCurrentFile( unzfile ); - unzClose( unzfile ); + unzCloseCurrentFile(unzfile); + unzClose(unzfile); return false; } - char * zipfilebuffer = (char *) malloc( zipfilebuffersize ); - memset( zipfilebuffer, 0, zipfilebuffersize ); - if ( zipfilebuffer == NULL ) + char * zipfilebuffer = (char *) malloc(zipfilebuffersize); + memset(zipfilebuffer, 0, zipfilebuffersize); + if (zipfilebuffer == NULL) { - unzCloseCurrentFile( unzfile ); - unzClose( unzfile ); + unzCloseCurrentFile(unzfile); + unzClose(unzfile); return false; } - unzReadCurrentFile( unzfile, zipfilebuffer, zipfilebuffersize ); - unzCloseCurrentFile( unzfile ); - unzClose( unzfile ); + unzReadCurrentFile(unzfile, zipfilebuffer, zipfilebuffersize); + unzCloseCurrentFile(unzfile); + unzClose(unzfile); - nodetree = mxmlLoadString( NULL, zipfilebuffer, MXML_OPAQUE_CALLBACK ); - free( zipfilebuffer ); + nodetree = mxmlLoadString(NULL, zipfilebuffer, MXML_OPAQUE_CALLBACK); + free(zipfilebuffer); } - if ( nodetree == NULL ) - return false; + if (nodetree == NULL) return false; - nodedata = mxmlFindElement( nodetree, nodetree, "datafile", NULL, NULL, MXML_DESCEND ); - if ( nodedata == NULL ) + nodedata = mxmlFindElement(nodetree, nodetree, "datafile", NULL, NULL, MXML_DESCEND); + if (nodedata == NULL) { return false; } @@ -211,14 +186,12 @@ bool OpenXMLFile( char *filename ) } } - - -char *GetLangSettingFromGame( char *gameid ) +char *GetLangSettingFromGame(char *gameid) { int langcode; struct Game_CFG *game_cfg = NULL; - game_cfg = CFG_get_game_opt( ( u8* )gameid ); - if ( game_cfg ) + game_cfg = CFG_get_game_opt((u8*) gameid); + if (game_cfg) { langcode = game_cfg->language; } @@ -231,232 +204,208 @@ char *GetLangSettingFromGame( char *gameid ) return langtxt; } - /* convert language text into ISO 639 two-letter language code (+ZHTW/ZHCN) */ -const char *ConvertLangTextToCode( char *languagetxt ) +const 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; + if (strlen(languagetxt) <= 4) return languagetxt; int i; - for ( i = 0; i <= 10; i++ ) + for (i = 0; i <= 10; i++) { - if ( !strcasecmp( languagetxt, langlist[i] ) ) // case insensitive comparison - return langcodes[i]; + if (!strcasecmp(languagetxt, langlist[i])) // case insensitive comparison + return langcodes[i]; } return ""; } - -char ConvertRatingToIndex( char *ratingtext ) +char ConvertRatingToIndex(char *ratingtext) { int type = -1; - if ( !strcmp( ratingtext, "CERO" ) ) + if (!strcmp(ratingtext, "CERO")) { type = 0; } - if ( !strcmp( ratingtext, "ESRB" ) ) + if (!strcmp(ratingtext, "ESRB")) { type = 1; } - if ( !strcmp( ratingtext, "PEGI" ) ) + if (!strcmp(ratingtext, "PEGI")) { type = 2; } return type; } -void ConvertRating( char *ratingvalue, char *fromrating, const char *torating, char *destvalue, int destsize ) +void ConvertRating(char *ratingvalue, char *fromrating, const char *torating, char *destvalue, int destsize) { - if ( !strcmp( fromrating, torating ) ) + if (!strcmp(fromrating, torating)) { - strlcpy( destvalue, ratingvalue, destsize ); + strlcpy(destvalue, ratingvalue, destsize); return; } - strcpy( destvalue, "" ); + strcpy(destvalue, ""); int type = -1; int desttype = -1; - type = ConvertRatingToIndex( fromrating ); - desttype = ConvertRatingToIndex( (char *) torating ); - if ( type == -1 || desttype == -1 ) - return; + type = ConvertRatingToIndex(fromrating); + desttype = ConvertRatingToIndex((char *) torating); + if (type == -1 || desttype == -1) return; /* rating conversion table */ /* the list is ordered to pick the most likely value first: */ /* EC and AO are less likely to be used so they are moved down to only be picked up when converting ESRB to PEGI or CERO */ /* the conversion can never be perfect because ratings can differ between regions for the same game */ - char ratingtable[12][3][5] = - { - {{"A"}, {"E"}, {"3"}}, - {{"A"}, {"E"}, {"4"}}, - {{"A"}, {"E"}, {"6"}}, - {{"A"}, {"E"}, {"7"}}, - {{"A"}, {"EC"}, {"3"}}, - {{"A"}, {"E10+"}, {"7"}}, - {{"B"}, {"T"}, {"12"}}, - {{"D"}, {"M"}, {"18"}}, - {{"D"}, {"M"}, {"16"}}, - {{"C"}, {"T"}, {"16"}}, - {{"C"}, {"T"}, {"15"}}, - {{"Z"}, {"AO"}, {"18"}}, - }; + char ratingtable[12][3][5] = { { { "A" }, { "E" }, { "3" } }, { { "A" }, { "E" }, { "4" } }, { { "A" }, { "E" }, { + "6" } }, { { "A" }, { "E" }, { "7" } }, { { "A" }, { "EC" }, { "3" } }, { { "A" }, { "E10+" }, { "7" } }, { + { "B" }, { "T" }, { "12" } }, { { "D" }, { "M" }, { "18" } }, { { "D" }, { "M" }, { "16" } }, { { "C" }, { + "T" }, { "16" } }, { { "C" }, { "T" }, { "15" } }, { { "Z" }, { "AO" }, { "18" } }, }; int i; - for ( i = 0; i <= 11; i++ ) + for (i = 0; i <= 11; i++) { - if ( !strcmp( ratingtable[i][type], ratingvalue ) ) + if (!strcmp(ratingtable[i][type], ratingvalue)) { - strlcpy( destvalue, ratingtable[i][desttype], destsize ); + strlcpy(destvalue, ratingtable[i][desttype], destsize); return; } } } - -void LoadTitlesFromXML( char *langtxt, bool forcejptoen ) +void LoadTitlesFromXML(char *langtxt, bool forcejptoen) /* langtxt: set to "English","French","German", to force language for all titles, or "" to load title depending on each game's setting */ /* forcejptoen: set to true to load English title instead of Japanese title when game is set to Japanese */ { - if ( nodedata == NULL ) - return; + if (nodedata == NULL) return; bool forcelang = false; - if ( strcmp( langtxt, "" ) ) - forcelang = true; + if (strcmp(langtxt, "")) forcelang = true; char langcode[10] = ""; - if ( forcelang ) - strcpy( langcode, ConvertLangTextToCode( langtxt ) ); /* convert language text into ISO 639 two-letter language code */ + if (forcelang) strcpy(langcode, ConvertLangTextToCode(langtxt)); /* convert language text into ISO 639 two-letter language code */ /* create index of elements */ - nodeindex = mxmlIndexNew( nodedata, "id", NULL ); - nodeid = mxmlIndexReset( nodeindex ); + nodeindex = mxmlIndexNew(nodedata, "id", NULL); + nodeid = mxmlIndexReset(nodeindex); *element_text = 0; char id_text[10]; char title_text[200] = ""; char title_text_EN[200] = ""; /* search index of id elements, load all id/titles text */ - while ( nodeid != NULL ) + while (nodeid != NULL) { - nodeid = mxmlIndexFind( nodeindex, "id", NULL ); - if ( nodeid != NULL ) + nodeid = mxmlIndexFind(nodeindex, "id", NULL); + if (nodeid != NULL) { - strcpy( title_text, "" ); - strcpy( title_text_EN, "" ); + strcpy(title_text, ""); + strcpy(title_text_EN, ""); - get_nodetext( nodeid, element_text, sizeof( element_text ) ); - snprintf( id_text, 7, "%s", element_text ); + get_nodetext(nodeid, element_text, sizeof(element_text)); + snprintf(id_text, 7, "%s", element_text); // if language is not forced, use game language setting from config - if ( !forcelang ) + if (!forcelang) { - langtxt = GetLangSettingFromGame( id_text ); - strcpy( langcode, ConvertLangTextToCode( langtxt ) ); + langtxt = GetLangSettingFromGame(id_text); + strcpy(langcode, ConvertLangTextToCode(langtxt)); } /* if enabled, force English title for all games set to Japanese */ - if ( forcejptoen && ( !strcmp( langcode, "JA" ) ) ) - strcpy( langcode, "EN" ); + if (forcejptoen && (!strcmp(langcode, "JA"))) strcpy(langcode, "EN"); /* load title from nodes */ - nodefound = mxmlFindElement( nodeid, nodedata, "locale", "lang", "EN", MXML_NO_DESCEND ); - if ( nodefound != NULL ) + nodefound = mxmlFindElement(nodeid, nodedata, "locale", "lang", "EN", MXML_NO_DESCEND); + if (nodefound != NULL) { - GetTextFromNode( nodefound, nodedata, "title", NULL, NULL, MXML_DESCEND, title_text_EN, sizeof( title_text_EN ) ); + GetTextFromNode(nodefound, nodedata, "title", NULL, NULL, MXML_DESCEND, title_text_EN, + sizeof(title_text_EN)); } - nodefound = mxmlFindElement( nodeid, nodedata, "locale", "lang", langcode, MXML_NO_DESCEND ); - if ( nodefound != NULL ) + nodefound = mxmlFindElement(nodeid, nodedata, "locale", "lang", langcode, MXML_NO_DESCEND); + if (nodefound != NULL) { - GetTextFromNode( nodefound, nodedata, "title", NULL, NULL, MXML_DESCEND, title_text, sizeof( title_text ) ); + GetTextFromNode(nodefound, nodedata, "title", NULL, NULL, MXML_DESCEND, title_text, sizeof(title_text)); } /* fall back to English title if prefered language was not found */ - if ( !strcmp( title_text, "" ) ) + if (!strcmp(title_text, "")) { - strcpy( title_text, title_text_EN ); + strcpy(title_text, title_text_EN); } - snprintf( id_text, 7, "%s", id_text ); - title_set( id_text, title_text ); + snprintf(id_text, 7, "%s", id_text); + title_set(id_text, title_text); } } // free memory - mxmlIndexDelete( nodeindex ); + mxmlIndexDelete(nodeindex); //if (xmldebug) xmlloadtime = dbg_time2(NULL); } - -void GetPublisherFromGameid( char *idtxt, char *dest, int destsize ) +void GetPublisherFromGameid(char *idtxt, char *dest, int destsize) { /* guess publisher from company list using last two characters from game id */ - nodeindextmp = mxmlIndexNew( nodedata, "company", NULL ); - nodeidtmp = mxmlIndexReset( nodeindextmp ); + nodeindextmp = mxmlIndexNew(nodedata, "company", NULL); + nodeidtmp = mxmlIndexReset(nodeindextmp); *element_text = 0; char publishercode[3]; - sprintf( publishercode, "%c%c", idtxt[4], idtxt[5] ); + sprintf(publishercode, "%c%c", idtxt[4], idtxt[5]); - while ( strcmp( element_text, publishercode ) != 0 ) + while (strcmp(element_text, publishercode) != 0) { - nodeidtmp = mxmlIndexFind( nodeindextmp, "company", NULL ); - if ( nodeidtmp != NULL ) + nodeidtmp = mxmlIndexFind(nodeindextmp, "company", NULL); + if (nodeidtmp != NULL) { - strlcpy( element_text, mxmlElementGetAttr( nodeidtmp, "code" ), sizeof( element_text ) ); + strlcpy(element_text, mxmlElementGetAttr(nodeidtmp, "code"), sizeof(element_text)); } else { break; } } - if ( !strcmp( element_text, publishercode ) ) + if (!strcmp(element_text, publishercode)) { - strlcpy( dest, mxmlElementGetAttr( nodeidtmp, "name" ), destsize ); + strlcpy(dest, mxmlElementGetAttr(nodeidtmp, "name"), destsize); } else { - strcpy( dest, "" ); + strcpy(dest, ""); } // free memory - mxmlIndexDelete( nodeindextmp ); + mxmlIndexDelete(nodeindextmp); } - - -bool LoadGameInfoFromXML( char* gameid, char* langtxt ) +bool LoadGameInfoFromXML(char* gameid, char* langtxt) /* gameid: full game id */ /* langtxt: "English","French","German" */ { bool exist = false; - if ( !xml_loaded || nodedata == NULL ) - return exist; + if (!xml_loaded || nodedata == NULL) return exist; // load game info using forced language, or game individual setting, or main language setting char langcode[100] = ""; - if ( !strcmp( langtxt, "" ) ) - langtxt = GetLangSettingFromGame( gameid ); - strlcpy( langcode, ConvertLangTextToCode( langtxt ), sizeof( langcode ) ); + if (!strcmp(langtxt, "")) langtxt = GetLangSettingFromGame(gameid); + strlcpy(langcode, ConvertLangTextToCode(langtxt), sizeof(langcode)); /* reset all game info */ gameinfo = gameinfo_reset; /* index all IDs */ - nodeindex = mxmlIndexNew( nodedata, "id", NULL ); - nodeid = mxmlIndexReset( nodeindex ); + nodeindex = mxmlIndexNew(nodedata, "id", NULL); + nodeid = mxmlIndexReset(nodeindex); *element_text = 0; /* search for game matching gameid */ - while ( 1 ) + while (1) { - nodeid = mxmlIndexFind( nodeindex, "id", NULL ); - if ( nodeid != NULL ) + nodeid = mxmlIndexFind(nodeindex, "id", NULL); + if (nodeid != NULL) { - get_nodetext( nodeid, element_text, sizeof( element_text ) ); - if ( !strcmp( element_text, gameid ) ) + get_nodetext(nodeid, element_text, sizeof(element_text)); + if (!strcmp(element_text, gameid)) { break; } @@ -467,173 +416,196 @@ bool LoadGameInfoFromXML( char* gameid, char* langtxt ) } } - if ( !strcmp( element_text, gameid ) ) + if (!strcmp(element_text, gameid)) { /* text from elements */ - strlcpy( gameinfo.id, element_text, sizeof( gameinfo.id ) ); - GetTextFromNode( nodeid, nodedata, "region", NULL, NULL, MXML_NO_DESCEND, gameinfo.region, sizeof( gameinfo.region ) ); - GetTextFromNode( nodeid, nodedata, "version", NULL, NULL, MXML_NO_DESCEND, gameinfo.version, sizeof( gameinfo.version ) ); - GetTextFromNode( nodeid, nodedata, "genre", NULL, NULL, MXML_NO_DESCEND, gameinfo.genre, sizeof( gameinfo.genre ) ); - GetTextFromNode( nodeid, nodedata, "developer", NULL, NULL, MXML_NO_DESCEND, gameinfo.developer, sizeof( gameinfo.developer ) ); - GetTextFromNode( nodeid, nodedata, "publisher", NULL, NULL, MXML_NO_DESCEND, gameinfo.publisher, sizeof( gameinfo.publisher ) ); - GetPublisherFromGameid( gameid, gameinfo.publisherfromid, sizeof( gameinfo.publisherfromid ) ); + strlcpy(gameinfo.id, element_text, sizeof(gameinfo.id)); + GetTextFromNode(nodeid, nodedata, "region", NULL, NULL, MXML_NO_DESCEND, gameinfo.region, + sizeof(gameinfo.region)); + GetTextFromNode(nodeid, nodedata, "version", NULL, NULL, MXML_NO_DESCEND, gameinfo.version, + sizeof(gameinfo.version)); + GetTextFromNode(nodeid, nodedata, "genre", NULL, NULL, MXML_NO_DESCEND, gameinfo.genre, sizeof(gameinfo.genre)); + GetTextFromNode(nodeid, nodedata, "developer", NULL, NULL, MXML_NO_DESCEND, gameinfo.developer, + sizeof(gameinfo.developer)); + GetTextFromNode(nodeid, nodedata, "publisher", NULL, NULL, MXML_NO_DESCEND, gameinfo.publisher, + sizeof(gameinfo.publisher)); + GetPublisherFromGameid(gameid, gameinfo.publisherfromid, sizeof(gameinfo.publisherfromid)); /* text from attributes */ - GetTextFromNode( nodeid, nodedata, "date", "year", NULL, MXML_NO_DESCEND, gameinfo.year, sizeof( gameinfo.year ) ); - GetTextFromNode( nodeid, nodedata, "date", "month", NULL, MXML_NO_DESCEND, gameinfo.month, sizeof( gameinfo.month ) ); - GetTextFromNode( nodeid, nodedata, "date", "day", NULL, MXML_NO_DESCEND, gameinfo.day, sizeof( gameinfo.day ) ); - GetTextFromNode( nodeid, nodedata, "rating", "type", NULL, MXML_NO_DESCEND, gameinfo.ratingtype, sizeof( gameinfo.ratingtype ) ); - GetTextFromNode( nodeid, nodedata, "rating", "value", NULL, MXML_NO_DESCEND, gameinfo.ratingvalue, sizeof( gameinfo.ratingvalue ) ); - GetTextFromNode( nodeid, nodedata, "rom", "crc", NULL, MXML_NO_DESCEND, gameinfo.iso_crc, sizeof( gameinfo.iso_crc ) ); - GetTextFromNode( nodeid, nodedata, "rom", "md5", NULL, MXML_NO_DESCEND, gameinfo.iso_md5, sizeof( gameinfo.iso_md5 ) ); - GetTextFromNode( nodeid, nodedata, "rom", "sha1", NULL, MXML_NO_DESCEND, gameinfo.iso_sha1, sizeof( gameinfo.iso_sha1 ) ); + GetTextFromNode(nodeid, nodedata, "date", "year", NULL, MXML_NO_DESCEND, gameinfo.year, sizeof(gameinfo.year)); + GetTextFromNode(nodeid, nodedata, "date", "month", NULL, MXML_NO_DESCEND, gameinfo.month, + sizeof(gameinfo.month)); + GetTextFromNode(nodeid, nodedata, "date", "day", NULL, MXML_NO_DESCEND, gameinfo.day, sizeof(gameinfo.day)); + GetTextFromNode(nodeid, nodedata, "rating", "type", NULL, MXML_NO_DESCEND, gameinfo.ratingtype, + sizeof(gameinfo.ratingtype)); + GetTextFromNode(nodeid, nodedata, "rating", "value", NULL, MXML_NO_DESCEND, gameinfo.ratingvalue, + sizeof(gameinfo.ratingvalue)); + GetTextFromNode(nodeid, nodedata, "rom", "crc", NULL, MXML_NO_DESCEND, gameinfo.iso_crc, + sizeof(gameinfo.iso_crc)); + GetTextFromNode(nodeid, nodedata, "rom", "md5", NULL, MXML_NO_DESCEND, gameinfo.iso_md5, + sizeof(gameinfo.iso_md5)); + GetTextFromNode(nodeid, nodedata, "rom", "sha1", NULL, MXML_NO_DESCEND, gameinfo.iso_sha1, + sizeof(gameinfo.iso_sha1)); /* text from child elements */ - nodefound = mxmlFindElement( nodeid, nodedata, "locale", "lang", "EN", MXML_NO_DESCEND ); - if ( nodefound != NULL ) + nodefound = mxmlFindElement(nodeid, nodedata, "locale", "lang", "EN", MXML_NO_DESCEND); + if (nodefound != NULL) { - GetTextFromNode( nodefound, nodedata, "title", NULL, NULL, MXML_DESCEND, gameinfo.title_EN, sizeof( gameinfo.title_EN ) ); - GetTextFromNode( nodefound, nodedata, "synopsis", NULL, NULL, MXML_DESCEND, gameinfo.synopsis_EN, sizeof( gameinfo.synopsis_EN ) ); + GetTextFromNode(nodefound, nodedata, "title", NULL, NULL, MXML_DESCEND, gameinfo.title_EN, + sizeof(gameinfo.title_EN)); + GetTextFromNode(nodefound, nodedata, "synopsis", NULL, NULL, MXML_DESCEND, gameinfo.synopsis_EN, + sizeof(gameinfo.synopsis_EN)); } - nodefound = mxmlFindElement( nodeid, nodedata, "locale", "lang", langcode, MXML_NO_DESCEND ); - if ( nodefound != NULL ) + nodefound = mxmlFindElement(nodeid, nodedata, "locale", "lang", langcode, MXML_NO_DESCEND); + if (nodefound != NULL) { - GetTextFromNode( nodefound, nodedata, "title", NULL, NULL, MXML_DESCEND, gameinfo.title, sizeof( gameinfo.title ) ); - GetTextFromNode( nodefound, nodedata, "synopsis", NULL, NULL, MXML_DESCEND, gameinfo.synopsis, sizeof( gameinfo.synopsis ) ); + GetTextFromNode(nodefound, nodedata, "title", NULL, NULL, MXML_DESCEND, gameinfo.title, + sizeof(gameinfo.title)); + GetTextFromNode(nodefound, nodedata, "synopsis", NULL, NULL, MXML_DESCEND, gameinfo.synopsis, + sizeof(gameinfo.synopsis)); } // fall back to English title and synopsis if prefered language was not found - if ( !strcmp( gameinfo.title, "" ) ) + if (!strcmp(gameinfo.title, "")) { - strlcpy( gameinfo.title, gameinfo.title_EN, sizeof( gameinfo.title ) ); + strlcpy(gameinfo.title, gameinfo.title_EN, sizeof(gameinfo.title)); } - if ( !strcmp( gameinfo.synopsis, "" ) ) + if (!strcmp(gameinfo.synopsis, "")) { - strlcpy( gameinfo.synopsis, gameinfo.synopsis_EN, sizeof( gameinfo.synopsis ) ); + strlcpy(gameinfo.synopsis, gameinfo.synopsis_EN, sizeof(gameinfo.synopsis)); } /* list locale lang attributes */ - nodefound = mxmlFindElement( nodeid, nodedata, "locale", "lang", NULL, MXML_NO_DESCEND ); - if ( nodefound != NULL ) + nodefound = mxmlFindElement(nodeid, nodedata, "locale", "lang", NULL, MXML_NO_DESCEND); + if (nodefound != NULL) { int incr = 0; - while ( nodefound != NULL ) + while (nodefound != NULL) { ++incr; - strlcpy( gameinfo.locales[incr], mxmlElementGetAttr( nodefound, "lang" ), sizeof( gameinfo.locales[incr] ) ); - nodefound = mxmlWalkNext( nodefound, nodedata, MXML_NO_DESCEND ); - if ( nodefound != NULL ) + strlcpy(gameinfo.locales[incr], mxmlElementGetAttr(nodefound, "lang"), sizeof(gameinfo.locales[incr])); + nodefound = mxmlWalkNext(nodefound, nodedata, MXML_NO_DESCEND); + if (nodefound != NULL) { - nodefound = mxmlFindElement( nodefound, nodedata, "locale", "lang", NULL, MXML_NO_DESCEND ); + nodefound = mxmlFindElement(nodefound, nodedata, "locale", "lang", NULL, MXML_NO_DESCEND); } } } /* unbounded child elements */ - GetTextFromNode( nodeid, nodedata, "wi-fi", "players", NULL, MXML_NO_DESCEND, gameinfo.wifiplayers, sizeof( gameinfo.wifiplayers ) ); - nodefound = mxmlFindElement( nodeid, nodedata, "wi-fi", NULL, NULL, MXML_NO_DESCEND ); - if ( nodefound != NULL ) + GetTextFromNode(nodeid, nodedata, "wi-fi", "players", NULL, MXML_NO_DESCEND, gameinfo.wifiplayers, + sizeof(gameinfo.wifiplayers)); + nodefound = mxmlFindElement(nodeid, nodedata, "wi-fi", NULL, NULL, MXML_NO_DESCEND); + if (nodefound != NULL) { gameinfo.wifiCnt = 0; - nodeindextmp = mxmlIndexNew( nodefound, "feature", NULL ); - nodeidtmp = mxmlIndexReset( nodeindextmp ); - while ( nodeidtmp != NULL ) + nodeindextmp = mxmlIndexNew(nodefound, "feature", NULL); + nodeidtmp = mxmlIndexReset(nodeindextmp); + while (nodeidtmp != NULL) { - nodeidtmp = mxmlIndexFind( nodeindextmp, "feature", NULL ); - if ( nodeidtmp != NULL ) + nodeidtmp = mxmlIndexFind(nodeindextmp, "feature", NULL); + if (nodeidtmp != NULL) { ++gameinfo.wifiCnt; - GetTextFromNode( nodeidtmp, nodedata, "feature", NULL, NULL, MXML_DESCEND, gameinfo.wififeatures[gameinfo.wifiCnt], - sizeof( gameinfo.wififeatures[gameinfo.wifiCnt] ) ); - gameinfo.wififeatures[gameinfo.wifiCnt][0] = toupper( ( int )gameinfo.wififeatures[gameinfo.wifiCnt][0] ); - if ( gameinfo.wifiCnt == XML_ELEMMAX ) - break; + GetTextFromNode(nodeidtmp, nodedata, "feature", NULL, NULL, MXML_DESCEND, + gameinfo.wififeatures[gameinfo.wifiCnt], sizeof(gameinfo.wififeatures[gameinfo.wifiCnt])); + gameinfo.wififeatures[gameinfo.wifiCnt][0] = toupper( + (int) gameinfo.wififeatures[gameinfo.wifiCnt][0]); + if (gameinfo.wifiCnt == XML_ELEMMAX) break; } } - mxmlIndexDelete( nodeindextmp ); // placed after each mxmlIndexNew to prevent memory leak + mxmlIndexDelete(nodeindextmp); // placed after each mxmlIndexNew to prevent memory leak } - nodefound = mxmlFindElement( nodeid, nodedata, "rating", NULL, NULL, MXML_NO_DESCEND ); - if ( nodefound != NULL ) + nodefound = mxmlFindElement(nodeid, nodedata, "rating", NULL, NULL, MXML_NO_DESCEND); + if (nodefound != NULL) { gameinfo.descriptorCnt = 0; - nodeindextmp = mxmlIndexNew( nodefound, "descriptor", NULL ); - nodeidtmp = mxmlIndexReset( nodeindextmp ); - while ( nodeidtmp != NULL ) + nodeindextmp = mxmlIndexNew(nodefound, "descriptor", NULL); + nodeidtmp = mxmlIndexReset(nodeindextmp); + while (nodeidtmp != NULL) { - nodeidtmp = mxmlIndexFind( nodeindextmp, "descriptor", NULL ); - if ( nodeidtmp != NULL ) + nodeidtmp = mxmlIndexFind(nodeindextmp, "descriptor", NULL); + if (nodeidtmp != NULL) { ++gameinfo.descriptorCnt; - GetTextFromNode( nodeidtmp, nodedata, "descriptor", NULL, NULL, MXML_DESCEND, - gameinfo.ratingdescriptors[gameinfo.descriptorCnt], sizeof( gameinfo.ratingdescriptors[gameinfo.descriptorCnt] ) ); - if ( gameinfo.descriptorCnt == XML_ELEMMAX ) - break; + GetTextFromNode(nodeidtmp, nodedata, "descriptor", NULL, NULL, MXML_DESCEND, + gameinfo.ratingdescriptors[gameinfo.descriptorCnt], + sizeof(gameinfo.ratingdescriptors[gameinfo.descriptorCnt])); + if (gameinfo.descriptorCnt == XML_ELEMMAX) break; } } - mxmlIndexDelete( nodeindextmp ); + mxmlIndexDelete(nodeindextmp); } - GetTextFromNode( nodeid, nodedata, "input", "players", NULL, MXML_NO_DESCEND, gameinfo.players, sizeof( gameinfo.players ) ); - nodefound = mxmlFindElement( nodeid, nodedata, "input", NULL, NULL, MXML_NO_DESCEND ); - if ( nodefound != NULL ) + GetTextFromNode(nodeid, nodedata, "input", "players", NULL, MXML_NO_DESCEND, gameinfo.players, + sizeof(gameinfo.players)); + nodefound = mxmlFindElement(nodeid, nodedata, "input", NULL, NULL, MXML_NO_DESCEND); + if (nodefound != NULL) { gameinfo.accessoryCnt = 0; gameinfo.accessoryReqCnt = 0; - nodeindextmp = mxmlIndexNew( nodefound, "control", NULL ); - nodeidtmp = mxmlIndexReset( nodeindextmp ); - while ( nodeidtmp != NULL ) + nodeindextmp = mxmlIndexNew(nodefound, "control", NULL); + nodeidtmp = mxmlIndexReset(nodeindextmp); + while (nodeidtmp != NULL) { - nodeidtmp = mxmlIndexFind( nodeindextmp, "control", NULL ); - if ( nodeidtmp != NULL ) + nodeidtmp = mxmlIndexFind(nodeindextmp, "control", NULL); + if (nodeidtmp != NULL) { - if ( !strcmp( mxmlElementGetAttr( nodeidtmp, "required" ), "true" ) && gameinfo.accessoryReqCnt < XML_ELEMMAX ) + if (!strcmp(mxmlElementGetAttr(nodeidtmp, "required"), "true") && gameinfo.accessoryReqCnt + < XML_ELEMMAX) { ++gameinfo.accessoryReqCnt; - strlcpy( gameinfo.accessoriesReq[gameinfo.accessoryReqCnt], mxmlElementGetAttr( nodeidtmp, "type" ), - sizeof( gameinfo.accessoriesReq[gameinfo.accessoryReqCnt] ) ); + strlcpy(gameinfo.accessoriesReq[gameinfo.accessoryReqCnt], + mxmlElementGetAttr(nodeidtmp, "type"), + sizeof(gameinfo.accessoriesReq[gameinfo.accessoryReqCnt])); } - else if ( gameinfo.accessoryCnt < XML_ELEMMAX ) + else if (gameinfo.accessoryCnt < XML_ELEMMAX) { ++gameinfo.accessoryCnt; - strlcpy( gameinfo.accessories[gameinfo.accessoryCnt], mxmlElementGetAttr( nodeidtmp, "type" ), - sizeof( gameinfo.accessories[gameinfo.accessoryCnt] ) ); + strlcpy(gameinfo.accessories[gameinfo.accessoryCnt], mxmlElementGetAttr(nodeidtmp, "type"), + sizeof(gameinfo.accessories[gameinfo.accessoryCnt])); } } } - mxmlIndexDelete( nodeindextmp ); + mxmlIndexDelete(nodeindextmp); } /* convert rating value */ - ConvertRating( gameinfo.ratingvalue, gameinfo.ratingtype, "CERO", gameinfo.ratingvalueCERO, sizeof( gameinfo.ratingvalueCERO ) ); - ConvertRating( gameinfo.ratingvalue, gameinfo.ratingtype, "ESRB", gameinfo.ratingvalueESRB, sizeof( gameinfo.ratingvalueESRB ) ); - ConvertRating( gameinfo.ratingvalue, gameinfo.ratingtype, "PEGI", gameinfo.ratingvaluePEGI, sizeof( gameinfo.ratingvaluePEGI ) ); + ConvertRating(gameinfo.ratingvalue, gameinfo.ratingtype, "CERO", gameinfo.ratingvalueCERO, + sizeof(gameinfo.ratingvalueCERO)); + ConvertRating(gameinfo.ratingvalue, gameinfo.ratingtype, "ESRB", gameinfo.ratingvalueESRB, + sizeof(gameinfo.ratingvalueESRB)); + ConvertRating(gameinfo.ratingvalue, gameinfo.ratingtype, "PEGI", gameinfo.ratingvaluePEGI, + sizeof(gameinfo.ratingvaluePEGI)); /* provide genre as an array: gameinfo.genresplit */ - if ( strcmp( gameinfo.genre, "" ) != 0 ) + if (strcmp(gameinfo.genre, "") != 0) { gameinfo.genreCnt = 0; const char *delimgenre = ",;"; char genretxt[200]; - strlcpy( genretxt, gameinfo.genre, sizeof( genretxt ) ); + strlcpy(genretxt, gameinfo.genre, sizeof(genretxt)); char *splitresult; - splitresult = strtok( genretxt, delimgenre ); - if ( splitresult != NULL ) + splitresult = strtok(genretxt, delimgenre); + if (splitresult != NULL) { ++gameinfo.genreCnt; - trimcopy( splitresult, splitresult, strlen( splitresult ) + 1 ); - strlcpy( gameinfo.genresplit[gameinfo.genreCnt], splitresult, sizeof( gameinfo.genresplit[gameinfo.genreCnt] ) ); - gameinfo.genresplit[gameinfo.genreCnt][0] = toupper( ( int )gameinfo.genresplit[gameinfo.genreCnt][0] ); - while ( splitresult != NULL ) + trimcopy(splitresult, splitresult, strlen(splitresult) + 1); + strlcpy(gameinfo.genresplit[gameinfo.genreCnt], splitresult, + sizeof(gameinfo.genresplit[gameinfo.genreCnt])); + gameinfo.genresplit[gameinfo.genreCnt][0] = toupper((int) gameinfo.genresplit[gameinfo.genreCnt][0]); + while (splitresult != NULL) { - splitresult = strtok( NULL, delimgenre ); - if ( splitresult != NULL && strcmp( splitresult, "" ) != 0 ) + splitresult = strtok(NULL, delimgenre); + if (splitresult != NULL && strcmp(splitresult, "") != 0) { ++gameinfo.genreCnt; - trimcopy( splitresult, splitresult, strlen( splitresult ) + 1 ); - strlcpy( gameinfo.genresplit[gameinfo.genreCnt], splitresult, sizeof( gameinfo.genresplit[gameinfo.genreCnt] ) ); - gameinfo.genresplit[gameinfo.genreCnt][0] = toupper( ( int )gameinfo.genresplit[gameinfo.genreCnt][0] ); - if ( gameinfo.genreCnt == XML_ELEMMAX ) - break; + trimcopy(splitresult, splitresult, strlen(splitresult) + 1); + strlcpy(gameinfo.genresplit[gameinfo.genreCnt], splitresult, + sizeof(gameinfo.genresplit[gameinfo.genreCnt])); + gameinfo.genresplit[gameinfo.genreCnt][0] = toupper( + (int) gameinfo.genresplit[gameinfo.genreCnt][0]); + if (gameinfo.genreCnt == XML_ELEMMAX) break; } } } @@ -650,41 +622,40 @@ bool LoadGameInfoFromXML( char* gameid, char* langtxt ) // if game was not found or info is missing // guess publisher from game id in case it is missing - if ( !strcmp( gameinfo.publisher, "" ) ) + if (!strcmp(gameinfo.publisher, "")) { - GetPublisherFromGameid( gameid, gameinfo.publisherfromid, sizeof( gameinfo.publisherfromid ) ); - strlcpy( gameinfo.publisher, gameinfo.publisherfromid, sizeof( gameinfo.publisher ) ); + GetPublisherFromGameid(gameid, gameinfo.publisherfromid, sizeof(gameinfo.publisherfromid)); + strlcpy(gameinfo.publisher, gameinfo.publisherfromid, sizeof(gameinfo.publisher)); } // if missing, get region from game ID - if ( !strcmp( gameinfo.region, "" ) ) + if (!strcmp(gameinfo.region, "")) { - if ( gameid[3] == 'E' ) strlcpy( gameinfo.region, "NTSC-U", sizeof( gameinfo.region ) ); - if ( gameid[3] == 'J' ) strlcpy( gameinfo.region, "NTSC-J", sizeof( gameinfo.region ) ); - if ( gameid[3] == 'W' ) strlcpy( gameinfo.region, "NTSC-J", sizeof( gameinfo.region ) ); - if ( gameid[3] == 'K' ) strlcpy( gameinfo.region, "NTSC-K", sizeof( gameinfo.region ) ); - if ( gameid[3] == 'P' ) strlcpy( gameinfo.region, "PAL", sizeof( gameinfo.region ) ); - if ( gameid[3] == 'D' ) strlcpy( gameinfo.region, "PAL", sizeof( gameinfo.region ) ); - if ( gameid[3] == 'F' ) strlcpy( gameinfo.region, "PAL", sizeof( gameinfo.region ) ); - if ( gameid[3] == 'I' ) strlcpy( gameinfo.region, "PAL", sizeof( gameinfo.region ) ); - 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] == 'Y' ) strlcpy( gameinfo.region, "PAL", sizeof( gameinfo.region ) ); - if ( gameid[3] == 'Z' ) strlcpy( gameinfo.region, "PAL", sizeof( gameinfo.region ) ); + if (gameid[3] == 'E') strlcpy(gameinfo.region, "NTSC-U", sizeof(gameinfo.region)); + if (gameid[3] == 'J') strlcpy(gameinfo.region, "NTSC-J", sizeof(gameinfo.region)); + if (gameid[3] == 'W') strlcpy(gameinfo.region, "NTSC-J", sizeof(gameinfo.region)); + if (gameid[3] == 'K') strlcpy(gameinfo.region, "NTSC-K", sizeof(gameinfo.region)); + if (gameid[3] == 'P') strlcpy(gameinfo.region, "PAL", sizeof(gameinfo.region)); + if (gameid[3] == 'D') strlcpy(gameinfo.region, "PAL", sizeof(gameinfo.region)); + if (gameid[3] == 'F') strlcpy(gameinfo.region, "PAL", sizeof(gameinfo.region)); + if (gameid[3] == 'I') strlcpy(gameinfo.region, "PAL", sizeof(gameinfo.region)); + 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] == 'Y') strlcpy(gameinfo.region, "PAL", sizeof(gameinfo.region)); + if (gameid[3] == 'Z') strlcpy(gameinfo.region, "PAL", sizeof(gameinfo.region)); } // free memory - mxmlIndexDelete( nodeindex ); + mxmlIndexDelete(nodeindex); return exist; } - -void PrintGameInfo( bool showfullinfo ) +void PrintGameInfo(bool showfullinfo) { - if ( showfullinfo ) + if (showfullinfo) { //Con_Clear(); @@ -692,44 +663,44 @@ void PrintGameInfo( bool showfullinfo ) //printf("id: %s version: %s region: %s",gameinfo.id, gameinfo.version, gameinfo.region); //printf("title: %s\n",gameinfo.title); int i; - printf( "languages:" ); - for ( i = 1; strcmp( gameinfo.locales[i], "" ) != 0; i++ ) + printf("languages:"); + for (i = 1; strcmp(gameinfo.locales[i], "") != 0; i++) { - printf( " %s", gameinfo.locales[i] ); + printf(" %s", gameinfo.locales[i]); } - printf( "\n" ); + printf("\n"); //printf("developer: %s\n",gameinfo.developer); //printf("publisher: %s\n",gameinfo.publisher); //printf("publisher from ID: %s\n",gameinfo.publisherfromid); - printf( "year:%s month:%s day:%s\n", gameinfo.year, gameinfo.month, gameinfo.day ); - printf( "genre: %s\n", gameinfo.genre ); + printf("year:%s month:%s day:%s\n", gameinfo.year, gameinfo.month, gameinfo.day); + printf("genre: %s\n", gameinfo.genre); //printf("rating: %s %s (CERO: %s ESRB: %s PEGI: %s)\n",gameinfo.ratingtype, gameinfo.ratingvalue, // gameinfo.ratingvalueCERO,gameinfo.ratingvalueESRB,gameinfo.ratingvaluePEGI); - printf( "content descriptors:" ); - for ( i = 1; strcmp( gameinfo.wififeatures[i], "" ) != 0; i++ ) + printf("content descriptors:"); + for (i = 1; strcmp(gameinfo.wififeatures[i], "") != 0; i++) { - printf( " %s", gameinfo.ratingdescriptors[i] ); + printf(" %s", gameinfo.ratingdescriptors[i]); } - printf( "\n" ); - printf( "players: %s online: %s\n", gameinfo.players, gameinfo.wifiplayers ); - printf( "online features:" ); - for ( i = 1; strcmp( gameinfo.wififeatures[i], "" ) != 0; i++ ) + printf("\n"); + printf("players: %s online: %s\n", gameinfo.players, gameinfo.wifiplayers); + printf("online features:"); + for (i = 1; strcmp(gameinfo.wififeatures[i], "") != 0; i++) { - printf( " %s", gameinfo.wififeatures[i] ); + printf(" %s", gameinfo.wififeatures[i]); } - printf( "\n" ); - printf( "required accessories:" ); - for ( i = 1; strcmp( gameinfo.accessoriesReq[i], "" ) != 0; i++ ) + printf("\n"); + printf("required accessories:"); + for (i = 1; strcmp(gameinfo.accessoriesReq[i], "") != 0; i++) { - printf( " %s", gameinfo.accessoriesReq[i] ); + printf(" %s", gameinfo.accessoriesReq[i]); } - printf( "\n" ); - printf( "accessories:" ); - for ( i = 1; strcmp( gameinfo.accessories[i], "" ) != 0; i++ ) + printf("\n"); + printf("accessories:"); + for (i = 1; strcmp(gameinfo.accessories[i], "") != 0; i++) { - printf( " %s", gameinfo.accessories[i] ); + printf(" %s", gameinfo.accessories[i]); } - printf( "\n" ); + printf("\n"); //printf("iso_crc: %s iso_md5: %s\n",gameinfo.iso_crc,gameinfo.iso_md5); //printf("iso_sha1: %s\n",gameinfo.iso_sha1); //printf("synopsis: %s\n",gameinfo.synopsis); @@ -740,61 +711,56 @@ void PrintGameInfo( bool showfullinfo ) char linebuf[1000] = ""; - if ( xmldebug ) + if (xmldebug) { //char xmltime[100]; //sprintf(xmltime,"%d",xmlloadtime); //printf("xml load time: %s\n",xmltime); /* - printf("xml forcelang: %s\n",CFG.db_lang); - printf("xml url: %s\n",CFG.db_url); - printf("xml file: %s\n",CFG.db_filename); - char xmljptoen[100]; - sprintf(xmljptoen,"%d",CFG.db_JPtoEN); - printf("xml JPtoEN: %s\n",xmljptoen); - */ - printf( MemInfo() ); // guidebug + printf("xml forcelang: %s\n",CFG.db_lang); + printf("xml url: %s\n",CFG.db_url); + printf("xml file: %s\n",CFG.db_filename); + char xmljptoen[100]; + sprintf(xmljptoen,"%d",CFG.db_JPtoEN); + printf("xml JPtoEN: %s\n",xmljptoen); + */ + printf(MemInfo()); // guidebug } //printf("%s: ",gameidfull); //printf("%s\n",gameinfo.title); - if ( strcmp( gameinfo.year, "" ) != 0 ) - snprintf( linebuf, sizeof( linebuf ), "%s ", gameinfo.year ); - if ( strcmp( gameinfo.publisher, "" ) != 0 ) - snprintf( linebuf, sizeof( linebuf ), "%s%s", linebuf, gameinfo.publisher ); - if ( strcmp( gameinfo.developer, "" ) != 0 && strcmp( gameinfo.developer, gameinfo.publisher ) != 0 ) - snprintf( linebuf, sizeof( linebuf ), "%s / %s", linebuf, gameinfo.developer ); - if ( strlen( linebuf ) >= 100 ) + if (strcmp(gameinfo.year, "") != 0) snprintf(linebuf, sizeof(linebuf), "%s ", gameinfo.year); + if (strcmp(gameinfo.publisher, "") != 0) snprintf(linebuf, sizeof(linebuf), "%s%s", linebuf, gameinfo.publisher); + if (strcmp(gameinfo.developer, "") != 0 && strcmp(gameinfo.developer, gameinfo.publisher) != 0) snprintf( + linebuf, sizeof(linebuf), "%s / %s", linebuf, gameinfo.developer); + if (strlen(linebuf) >= 100) { char buffer[200] = ""; - strlcpy( buffer, linebuf, 100 ); - strcat( buffer, "..." ); - snprintf( linebuf, sizeof( linebuf ), "%s", buffer ); + strlcpy(buffer, linebuf, 100); + strcat(buffer, "..."); + snprintf(linebuf, sizeof(linebuf), "%s", buffer); } - printf( "%s\n", linebuf ); - strcpy( linebuf, "" ); + printf("%s\n", linebuf); + strcpy(linebuf, ""); - if ( strcmp( gameinfo.ratingvalue, "" ) != 0 ) + if (strcmp(gameinfo.ratingvalue, "") != 0) { - snprintf( linebuf, sizeof( linebuf ), "rated %s", gameinfo.ratingvalue ); - if ( !strcmp( gameinfo.ratingtype, "PEGI" ) ) - snprintf( linebuf, sizeof( linebuf ), "%s+ ", linebuf ); - snprintf( linebuf, sizeof( linebuf ), "%s ", linebuf ); + snprintf(linebuf, sizeof(linebuf), "rated %s", gameinfo.ratingvalue); + if (!strcmp(gameinfo.ratingtype, "PEGI")) snprintf(linebuf, sizeof(linebuf), "%s+ ", linebuf); + snprintf(linebuf, sizeof(linebuf), "%s ", linebuf); } - if ( strcmp( gameinfo.players, "" ) != 0 ) + if (strcmp(gameinfo.players, "") != 0) { - snprintf( linebuf, sizeof( linebuf ), "%sfor %s player", linebuf, gameinfo.players ); - if ( atoi( gameinfo.players ) > 1 ) - snprintf( linebuf, sizeof( linebuf ), "%ss", linebuf ); - if ( atoi( gameinfo.wifiplayers ) > 1 ) - snprintf( linebuf, sizeof( linebuf ), "%s (%s online)", linebuf, gameinfo.wifiplayers ); + snprintf(linebuf, sizeof(linebuf), "%sfor %s player", linebuf, gameinfo.players); + if (atoi(gameinfo.players) > 1) snprintf(linebuf, sizeof(linebuf), "%ss", linebuf); + if (atoi(gameinfo.wifiplayers) > 1) snprintf(linebuf, sizeof(linebuf), "%s (%s online)", linebuf, + gameinfo.wifiplayers); } - printf( "%s\n", linebuf ); - strcpy( linebuf, "" ); + printf("%s\n", linebuf); + strcpy(linebuf, ""); } } - char *MemInfo() { char linebuf[300] = ""; @@ -803,70 +769,65 @@ char *MemInfo() char memnotinuse[20]; char memcanbefreed[20]; struct mallinfo mymallinfo = mallinfo(); - sprintf( memtotal, "%d", mymallinfo.arena / 1024 ); - sprintf( memused, "%d", mymallinfo.uordblks / 1024 ); - sprintf( memnotinuse, "%d", mymallinfo.fordblks / 1024 ); - sprintf( memcanbefreed, "%d", mymallinfo.keepcost / 1024 ); - snprintf( linebuf, sizeof( linebuf ), "all:%sKB used:%sKB notused:%sKB canfree:%sKB", memtotal, memused, memnotinuse, memcanbefreed ); + sprintf(memtotal, "%d", mymallinfo.arena / 1024); + sprintf(memused, "%d", mymallinfo.uordblks / 1024); + sprintf(memnotinuse, "%d", mymallinfo.fordblks / 1024); + sprintf(memcanbefreed, "%d", mymallinfo.keepcost / 1024); + snprintf(linebuf, sizeof(linebuf), "all:%sKB used:%sKB notused:%sKB canfree:%sKB", memtotal, memused, memnotinuse, + memcanbefreed); char *minfo[300]; *minfo = linebuf; return *minfo; } - - /*-------------------------------------------------------------------------------------*/ /* get_nodetext() - Get the text for a node, taken from mini-mxml example mxmldoc.c */ -char * get_nodetext( mxml_node_t *node, char *buffer, int buflen ) /* O - Text in node, I - Node to get, I - Buffer, I - Size of buffer */ +char * get_nodetext(mxml_node_t *node, char *buffer, int buflen) /* O - Text in node, I - Node to get, I - Buffer, I - Size of buffer */ { - char *ptr, *end; /* Pointer into buffer, End of buffer */ - int len; /* Length of node */ - mxml_node_t *current; /* Current node */ + char *ptr, *end; /* Pointer into buffer, End of buffer */ + int len; /* Length of node */ + mxml_node_t *current; /* Current node */ ptr = buffer; end = buffer + buflen - 1; - for ( current = node->child; current && ptr < end; current = current->next ) + for (current = node->child; current && ptr < end; current = current->next) { - if ( current->type == MXML_TEXT ) + if (current->type == MXML_TEXT) { - if ( current->value.text.whitespace ) - *ptr++ = ' '; - len = ( int )strlen( current->value.text.string ); - if ( len > ( int )( end - ptr ) ) - len = ( int )( end - ptr ); - memcpy( ptr, current->value.text.string, len ); + if (current->value.text.whitespace) *ptr++ = ' '; + len = (int) strlen(current->value.text.string); + if (len > (int) (end - ptr)) len = (int) (end - ptr); + memcpy(ptr, current->value.text.string, len); ptr += len; } - else if ( current->type == MXML_OPAQUE ) + else if (current->type == MXML_OPAQUE) { - len = ( int )strlen( current->value.opaque ); - if ( len > ( int )( end - ptr ) ) - len = ( int )( end - ptr ); - memcpy( ptr, current->value.opaque, len ); + len = (int) strlen(current->value.opaque); + if (len > (int) (end - ptr)) len = (int) (end - ptr); + memcpy(ptr, current->value.opaque, len); ptr += len; } } *ptr = '\0'; - return ( buffer ); + return (buffer); } -int GetRatingForGame( char *gameid ) +int GetRatingForGame(char *gameid) { int retval = -1; - if ( !xml_loaded || nodedata == NULL ) - return -1; + if (!xml_loaded || nodedata == NULL) return -1; /* index all IDs */ - nodeindex = mxmlIndexNew( nodedata, "id", NULL ); - nodeid = mxmlIndexReset( nodeindex ); + nodeindex = mxmlIndexNew(nodedata, "id", NULL); + nodeid = mxmlIndexReset(nodeindex); *element_text = 0; /* search for game matching gameid */ - while ( 1 ) + while (1) { - nodeid = mxmlIndexFind( nodeindex, "id", NULL ); - if ( nodeid != NULL ) + nodeid = mxmlIndexFind(nodeindex, "id", NULL); + if (nodeid != NULL) { - get_nodetext( nodeid, element_text, sizeof( element_text ) ); - if ( !strcmp( element_text, gameid ) ) + get_nodetext(nodeid, element_text, sizeof(element_text)); + if (!strcmp(element_text, gameid)) { break; } @@ -877,15 +838,15 @@ int GetRatingForGame( char *gameid ) } } - if ( !strcmp( element_text, gameid ) ) + if (!strcmp(element_text, gameid)) { 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 ) ); + 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 ); + retval = atoi(dest); } return retval; } diff --git a/source/xml/xml.h b/source/xml/xml.h index 89428550..2bb09ee1 100644 --- a/source/xml/xml.h +++ b/source/xml/xml.h @@ -1,69 +1,67 @@ - #ifndef _XML_H_ #define _XML_H_ #include - // open database, close database, load info for a game -bool OpenXMLDatabase( char* xmlfilepath, char* argdblang, bool argJPtoEN, bool openfile, bool loadtitles, bool keepopen ); +bool OpenXMLDatabase(char* xmlfilepath, char* argdblang, bool argJPtoEN, bool openfile, bool loadtitles, bool keepopen); void CloseXMLDatabase(); -bool LoadGameInfoFromXML( char* gameid, char* langcode ); +bool LoadGameInfoFromXML(char* gameid, char* langcode); #define XML_ELEMMAX 15 #define XML_SYNOPSISLEN 4000 - struct gameXMLinfo - { - char id[7]; - char version[50]; - char region[7]; - char title[200]; - char synopsis[XML_SYNOPSISLEN]; - char title_EN[200]; - char synopsis_EN[XML_SYNOPSISLEN]; - char locales[XML_ELEMMAX+1][5]; - int localeCnt; - char developer[75]; - char publisher[75]; - char publisherfromid[75]; - char year[5]; - char month[3]; - char day[3]; - char genre[75]; - char genresplit[XML_ELEMMAX+1][20]; - int genreCnt; - char ratingtype[5]; - char ratingvalue[5]; - char ratingdescriptors[XML_ELEMMAX+1][40]; - int descriptorCnt; - char ratingvalueCERO[5]; - char ratingvalueESRB[5]; - char ratingvaluePEGI[5]; - char wifiplayers[4]; - char wififeatures[XML_ELEMMAX+1][20]; - int wifiCnt; - char players[4]; - char accessories[XML_ELEMMAX+1][20]; - int accessoryCnt; - char accessoriesReq[XML_ELEMMAX+1][20]; - int accessoryReqCnt; - char iso_crc[9]; - char iso_md5[33]; - char iso_sha1[41]; - } ; +struct gameXMLinfo +{ + char id[7]; + char version[50]; + char region[7]; + char title[200]; + char synopsis[XML_SYNOPSISLEN]; + char title_EN[200]; + char synopsis_EN[XML_SYNOPSISLEN]; + char locales[XML_ELEMMAX + 1][5]; + int localeCnt; + char developer[75]; + char publisher[75]; + char publisherfromid[75]; + char year[5]; + char month[3]; + char day[3]; + char genre[75]; + char genresplit[XML_ELEMMAX + 1][20]; + int genreCnt; + char ratingtype[5]; + char ratingvalue[5]; + char ratingdescriptors[XML_ELEMMAX + 1][40]; + int descriptorCnt; + char ratingvalueCERO[5]; + char ratingvalueESRB[5]; + char ratingvaluePEGI[5]; + char wifiplayers[4]; + char wififeatures[XML_ELEMMAX + 1][20]; + int wifiCnt; + char players[4]; + char accessories[XML_ELEMMAX + 1][20]; + int accessoryCnt; + char accessoriesReq[XML_ELEMMAX + 1][20]; + int accessoryReqCnt; + char iso_crc[9]; + char iso_md5[33]; + char iso_sha1[41]; +}; - bool OpenXMLFile( char* filename ); - void LoadTitlesFromXML( char *langcode, bool forcejptoen ); - void GetPublisherFromGameid( char *idtxt, char *dest, int destsize ); - const char *ConvertLangTextToCode( char *langtext ); - void ConvertRating( char *ratingvalue, char *fromrating, const char *torating, char *destvalue, int destsize ); - void PrintGameInfo( bool showfullinfo ); - char *MemInfo(); - void GetTextFromNode( mxml_node_t *currentnode, mxml_node_t *topnode, const char *nodename, - const 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 ); +bool OpenXMLFile(char* filename); +void LoadTitlesFromXML(char *langcode, bool forcejptoen); +void GetPublisherFromGameid(char *idtxt, char *dest, int destsize); +const char *ConvertLangTextToCode(char *langtext); +void ConvertRating(char *ratingvalue, char *fromrating, const char *torating, char *destvalue, int destsize); +void PrintGameInfo(bool showfullinfo); +char *MemInfo(); +void GetTextFromNode(mxml_node_t *currentnode, mxml_node_t *topnode, const char *nodename, const 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); #endif