From 9e79c9d99b128a3a44f9966d2f345261c7ce839c Mon Sep 17 00:00:00 2001 From: giantpune Date: Sat, 18 Sep 2010 23:16:05 +0000 Subject: [PATCH] * remove little unused code * code cleanup --- HBC/META.XML | 4 +- data/magic_patcher.o | Bin 0 -> 2164 bytes source/FontSystem.cpp | 36 +- source/FontSystem.h | 2 +- source/FreeTypeGX.cpp | 600 +- source/FreeTypeGX.h | 116 +- source/ZipFile.cpp | 65 +- source/ZipFile.h | 22 +- source/audio.cpp | 12 +- source/banner/MD5.c | 837 +- source/banner/MD5.h | 452 +- source/banner/banner.c | 157 +- source/banner/banner.h | 2 +- source/banner/gui_banner.cpp | 135 +- source/banner/gui_banner.h | 36 +- source/banner/openingbnr.c | 808 +- source/banner/openingbnr.h | 40 +- source/bannersound.cpp | 302 +- source/bannersound.h | 2 +- source/cheats/cheatmenu.cpp | 261 +- source/cheats/cheatmenu.h | 2 +- source/cheats/gct.cpp | 238 +- source/cheats/gct.h | 111 +- source/fatmounter.c | 251 +- source/fatmounter.h | 37 +- source/filelist.h | 642 +- source/gecko.c | 78 +- source/gecko.h | 19 +- source/homebrewboot/BootHomebrew.cpp | 142 +- source/homebrewboot/BootHomebrew.h | 8 +- source/homebrewboot/HomebrewBrowse.cpp | 1761 +-- source/homebrewboot/HomebrewBrowse.h | 2 +- source/homebrewboot/HomebrewFiles.cpp | 104 +- source/homebrewboot/HomebrewFiles.h | 56 +- source/homebrewboot/HomebrewXML.cpp | 44 +- source/homebrewboot/HomebrewXML.h | 4 +- source/homebrewboot/dolloader.c | 42 +- source/homebrewboot/dolloader.h | 9 +- source/input.cpp | 136 +- source/input.h | 6 +- source/language/UpdateLanguage.cpp | 47 +- source/language/gettext.c | 262 +- source/language/gettext.h | 9 +- source/libfat/bit_ops.h | 28 +- source/libfat/cache.h | 58 +- source/libfat/directory.c | 2000 +-- source/libfat/directory.h | 102 +- source/libfat/disc.h | 57 +- source/libfat/disc_fat.c | 33 +- source/libfat/disc_fat.h | 47 +- source/libfat/fat.h | 71 +- source/libfat/fat_cache.c | 461 +- source/libfat/fat_cache.h | 58 +- source/libfat/fatdir.c | 1161 +- source/libfat/fatdir.h | 35 +- source/libfat/fatfile.c | 2238 ++-- source/libfat/fatfile.h | 78 +- source/libfat/file_allocation_table.c | 493 +- source/libfat/file_allocation_table.h | 40 +- source/libfat/filetime.c | 107 +- source/libfat/filetime.h | 6 +- source/libfat/libfat.c | 274 +- source/libfat/libfatversion.h | 6 +- source/libfat/lock.h | 32 +- source/libfat/mem_allocate.h | 15 +- source/libfat/partition.c | 445 +- source/libfat/partition.h | 58 +- source/libntfs/acls.c | 7811 ++++++------ source/libntfs/acls.h | 159 +- source/libntfs/attrib.c | 10786 +++++++++-------- source/libntfs/attrib.h | 389 +- source/libntfs/attrib_frag.c | 9791 ++++++++------- source/libntfs/attrlist.c | 440 +- source/libntfs/attrlist.h | 22 +- source/libntfs/bit_ops.h | 30 +- source/libntfs/bitmap.c | 378 +- source/libntfs/bitmap.h | 34 +- source/libntfs/bootsect.c | 409 +- source/libntfs/bootsect.h | 10 +- source/libntfs/cache.c | 1002 +- source/libntfs/cache.h | 152 +- source/libntfs/cache2.c | 501 +- source/libntfs/cache2.h | 44 +- source/libntfs/collate.c | 306 +- source/libntfs/collate.h | 2 +- source/libntfs/compat.c | 169 +- source/libntfs/compat.h | 22 +- source/libntfs/compress.c | 3316 ++--- source/libntfs/compress.h | 20 +- source/libntfs/debug.c | 60 +- source/libntfs/debug.h | 16 +- source/libntfs/device.c | 809 +- source/libntfs/device.h | 121 +- source/libntfs/device_io.h | 21 +- source/libntfs/dir.c | 4517 +++---- source/libntfs/dir.h | 82 +- source/libntfs/efs.c | 742 +- source/libntfs/efs.h | 8 +- source/libntfs/endians.h | 158 +- source/libntfs/gekko_io.c | 458 +- source/libntfs/gekko_io.h | 3 +- source/libntfs/index.c | 3207 ++--- source/libntfs/index.h | 121 +- source/libntfs/inode.c | 2419 ++-- source/libntfs/inode.h | 252 +- source/libntfs/layout.h | 3453 +++--- source/libntfs/lcnalloc.c | 1273 +- source/libntfs/lcnalloc.h | 25 +- source/libntfs/logfile.c | 1144 +- source/libntfs/logfile.h | 567 +- source/libntfs/logging.c | 572 +- source/libntfs/logging.h | 74 +- source/libntfs/mem_allocate.h | 23 +- source/libntfs/mft.c | 3048 ++--- source/libntfs/mft.h | 84 +- source/libntfs/misc.c | 32 +- source/libntfs/misc.h | 6 +- source/libntfs/mst.c | 292 +- source/libntfs/mst.h | 6 +- source/libntfs/ntfs.c | 645 +- source/libntfs/ntfs.h | 174 +- source/libntfs/ntfsdir.c | 372 +- source/libntfs/ntfsdir.h | 30 +- source/libntfs/ntfsfile.c | 355 +- source/libntfs/ntfsfile.h | 21 +- source/libntfs/ntfsfile_frag.c | 410 +- source/libntfs/ntfsinternal.c | 510 +- source/libntfs/ntfsinternal.h | 72 +- source/libntfs/ntfstime.h | 54 +- source/libntfs/object_id.c | 922 +- source/libntfs/object_id.h | 10 +- source/libntfs/param.h | 67 +- source/libntfs/reparse.c | 2050 ++-- source/libntfs/reparse.h | 16 +- source/libntfs/runlist.c | 3119 ++--- source/libntfs/runlist.h | 61 +- source/libntfs/security.c | 8945 +++++++------- source/libntfs/security.h | 420 +- source/libntfs/support.h | 34 +- source/libntfs/types.h | 38 +- source/libntfs/unistr.c | 1987 +-- source/libntfs/unistr.h | 74 +- source/libntfs/volume.c | 2610 ++-- source/libntfs/volume.h | 309 +- source/libwbfs/libwbfs.c | 1412 +-- source/libwbfs/libwbfs.h | 265 +- source/libwbfs/libwbfs_os.h | 30 +- source/libwbfs/rijndael.c | 481 +- source/libwbfs/wiidisc.c | 619 +- source/libwbfs/wiidisc.h | 76 +- source/libwiigui/Text.cpp | 196 +- source/libwiigui/gui.h | 1985 +-- source/libwiigui/gui_bgm.cpp | 128 +- source/libwiigui/gui_bgm.h | 12 +- source/libwiigui/gui_button.cpp | 799 +- source/libwiigui/gui_customoptionbrowser.cpp | 1089 +- source/libwiigui/gui_customoptionbrowser.h | 163 +- source/libwiigui/gui_diskcover.cpp | 100 +- source/libwiigui/gui_diskcover.h | 36 +- source/libwiigui/gui_element.cpp | 975 +- source/libwiigui/gui_filebrowser.cpp | 740 +- source/libwiigui/gui_gamebrowser.cpp | 961 +- source/libwiigui/gui_gamebrowser.h | 102 +- source/libwiigui/gui_gamecarousel.cpp | 687 +- source/libwiigui/gui_gamecarousel.h | 76 +- source/libwiigui/gui_gamegrid.cpp | 1635 +-- source/libwiigui/gui_gamegrid.h | 92 +- source/libwiigui/gui_image.cpp | 646 +- source/libwiigui/gui_image_async.cpp | 258 +- source/libwiigui/gui_image_async.h | 24 +- source/libwiigui/gui_imagedata.cpp | 586 +- source/libwiigui/gui_keyboard.cpp | 1299 +- source/libwiigui/gui_numpad.cpp | 297 +- source/libwiigui/gui_optionbrowser.cpp | 1130 +- source/libwiigui/gui_searchbar.cpp | 260 +- source/libwiigui/gui_searchbar.h | 56 +- source/libwiigui/gui_sound.cpp | 607 +- source/libwiigui/gui_sound_decoder.h | 118 +- source/libwiigui/gui_sound_decoder_aiff.cpp | 246 +- source/libwiigui/gui_sound_decoder_bns.cpp | 424 +- source/libwiigui/gui_sound_decoder_mpg.cpp | 356 +- source/libwiigui/gui_sound_decoder_ogg.cpp | 471 +- source/libwiigui/gui_sound_decoder_wav.cpp | 394 +- source/libwiigui/gui_text.cpp | 596 +- source/libwiigui/gui_tooltip.cpp | 90 +- source/libwiigui/gui_trigger.cpp | 320 +- source/libwiigui/gui_window.cpp | 638 +- source/listfiles.c | 232 +- source/listfiles.h | 15 +- source/lstub.c | 152 - source/lstub.cpp | 124 +- source/lstub.h | 6 +- source/main.cpp | 91 +- source/memory.h | 41 +- source/memory/mem2.cpp | 320 +- source/memory/mem2.h | 19 +- source/memory/mem2alloc.cpp | 354 +- source/menu.cpp | 745 +- source/menu.h | 11 +- source/menu/menu_check.cpp | 212 +- source/menu/menu_disclist.cpp | 2503 ++-- source/menu/menu_format.cpp | 235 +- source/menu/menu_install.cpp | 149 +- source/mload/dip_plugin.c | 743 +- source/mload/fatffs_util.c | 379 +- source/mload/fatffs_util.h | 16 +- source/mload/mload.c | 625 +- source/mload/mload.h | 179 +- source/mload/mload_modules.c | 763 +- source/mload/mload_modules.h | 21 +- source/network/HTML_Stream.cpp | 130 +- source/network/HTML_Stream.h | 66 +- source/network/URL_List.cpp | 94 +- source/network/URL_List.h | 42 +- source/network/dns.c | 67 +- source/network/dns.h | 7 +- source/network/http.c | 140 +- source/network/http.h | 10 +- source/network/networkops.cpp | 269 +- source/network/networkops.h | 14 +- source/network/update.cpp | 82 +- source/network/update.h | 60 +- source/patches/codehandler.h | 543 +- source/patches/codehandleronly.h | 349 +- source/patches/dolpatcher.c | 12 +- source/patches/dolpatcher.h | 2 +- source/patches/dvd_broadway.c | 1014 +- source/patches/dvd_broadway.h | 47 +- source/patches/fst.c | 1395 +-- source/patches/fst.h | 9 +- source/patches/fwrite_patch.h | 27 +- source/patches/gamepatches.c | 243 +- source/patches/gamepatches.h | 8 +- source/patches/geckomenu.h | 14 +- source/patches/kenobiwii.h | 517 +- source/patches/multidol.c | 61 +- source/patches/patchcode.c | 552 +- source/patches/patchcode.h | 19 +- source/patches/ppc.h | 144 +- source/patches/wip.c | 110 +- source/patches/wip.h | 6 +- source/prompts/DiscBrowser.cpp | 782 +- source/prompts/DiscBrowser.h | 8 +- source/prompts/ProgressWindow.cpp | 370 +- source/prompts/ProgressWindow.h | 11 +- source/prompts/PromptWindows.cpp | 4885 ++++---- source/prompts/PromptWindows.h | 26 +- source/prompts/TitleBrowser.cpp | 735 +- source/prompts/filebrowser.cpp | 859 +- source/prompts/filebrowser.h | 45 +- source/prompts/gameinfo.cpp | 1536 +-- source/prompts/gameinfo.h | 6 +- source/ramdisk/ramdisk.cpp | 1538 +-- source/ramdisk/ramdisk.h | 120 +- source/settings/Settings.cpp | 5872 ++++----- source/settings/Settings.h | 2 +- source/settings/SettingsPrompts.cpp | 392 +- source/settings/cfg.c | 2440 ++-- source/settings/cfg.h | 807 +- source/settings/newtitles.cpp | 287 +- source/settings/newtitles.h | 51 +- source/svnrev.h | 3 +- source/sys.cpp | 430 +- source/sys.h | 22 +- source/themes/Theme_Downloader.cpp | 618 +- source/themes/Theme_List.cpp | 194 +- source/themes/Theme_List.h | 14 +- source/unzip/crypt.h | 63 +- source/unzip/inflate.c | 59 +- source/unzip/inflate.h | 5 +- source/unzip/ioapi.c | 125 +- source/unzip/ioapi.h | 22 +- source/unzip/miniunz.c | 290 +- source/unzip/miniunz.h | 9 +- source/unzip/mztools.c | 270 +- source/unzip/mztools.h | 13 +- source/unzip/unzip.c | 1175 +- source/unzip/unzip.h | 122 +- source/usbloader/GameList.cpp | 290 +- source/usbloader/GameList.h | 12 +- source/usbloader/alternatedol.c | 211 +- source/usbloader/alternatedol.h | 11 +- source/usbloader/apploader.c | 105 +- source/usbloader/apploader.h | 9 +- source/usbloader/disc.c | 456 +- source/usbloader/disc.h | 79 +- source/usbloader/frag.c | 275 +- source/usbloader/frag.h | 51 +- source/usbloader/fstfile.c | 42 +- source/usbloader/fstfile.h | 14 +- source/usbloader/partition_usbloader.c | 583 +- source/usbloader/partition_usbloader.h | 108 +- source/usbloader/sdhc.c | 302 +- source/usbloader/sdhc.h | 15 +- source/usbloader/splits.c | 544 +- source/usbloader/splits.h | 53 +- source/usbloader/usbstorage2.c | 512 +- source/usbloader/usbstorage2.h | 31 +- source/usbloader/utils.c | 5 +- source/usbloader/utils.h | 19 +- source/usbloader/wbfs.cpp | 373 +- source/usbloader/wbfs.h | 79 +- source/usbloader/wbfs/wbfs_base.cpp | 126 +- source/usbloader/wbfs/wbfs_base.h | 72 +- source/usbloader/wbfs/wbfs_fat.cpp | 1402 ++- source/usbloader/wbfs/wbfs_fat.h | 78 +- source/usbloader/wbfs/wbfs_ntfs.cpp | 30 +- source/usbloader/wbfs/wbfs_ntfs.h | 10 +- source/usbloader/wbfs/wbfs_rw.c | 99 +- source/usbloader/wbfs/wbfs_rw.h | 19 +- source/usbloader/wbfs/wbfs_wbfs.cpp | 165 +- source/usbloader/wbfs/wbfs_wbfs.h | 28 +- source/usbloader/wdvd.c | 293 +- source/usbloader/wdvd.h | 41 +- source/video.cpp | 460 +- source/video.h | 12 +- source/wad/nandtitle.cpp | 340 +- source/wad/nandtitle.h | 114 +- source/wad/utils.h | 17 +- source/wad/wad.cpp | 993 +- source/wad/wad.h | 6 +- source/wpad.c | 133 +- source/wpad.h | 17 +- source/wstring.cpp | 291 +- source/xml/xml.c | 885 +- source/xml/xml.h | 30 +- 326 files changed, 87736 insertions(+), 80266 deletions(-) create mode 100644 data/magic_patcher.o delete mode 100644 source/lstub.c diff --git a/HBC/META.XML b/HBC/META.XML index e8baccec..24776d34 100644 --- a/HBC/META.XML +++ b/HBC/META.XML @@ -2,8 +2,8 @@ USB Loader GX USB Loader GX Team - 1.0 r950 - 201009182245 + 1.0 r951 + 201009182308 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/data/magic_patcher.o b/data/magic_patcher.o new file mode 100644 index 0000000000000000000000000000000000000000..a7de9a0319eee3518f110a1ebc76d0ceb710e20e GIT binary patch literal 2164 zcmb7EU1%It6#ga|lS!ItfA%3*!HH3tl`?6QZJm?^Hi^ci##&7>M=*_XF)6#eEV=34;Sw|k+_jV%GUAt4IovzgLL{X5=ETbvvV*@ zxUASI`dHkC0!f|V6^82W+14Xp$*{$f6JrC}8{Mr%o`;D!h`aLH( z)>+9*4t=kG1F%uQGWrRAv)Rt)9bxVf^MeiIh{+UG&BNQk@ILuIF!T`lJb3~rcfhE; zPq_x8{3%dLLN9+u{dejH^vX5pwH`b!+r9q5f6}^*5y0U6q%&r;_mTnrjI%L3D?Mz#xwcxCt zNq<$}N`Hh5&r2_M!m0-Ac^@6f3DSDsMjYc4azTBkI1FX zowNGb#*f1?cmX#&^1Hr(qJvWH}5;sl)e|rIi>mTiVthX@f}#x%geCDLHt5)YTBJ$^xP@W zb!OsjXV!PUsdv4+??&z=$Is0T4!~kLPMF|D=T<(K6~D`z-lA+^ja#Wp*5v^^755B^ z=Sti&AfC&xa*Olx?gFc0JC@`7UVi$v&vgHb&JivDZ(Fn~{BxTrBqr2D7M-skpyP0S z`7p@;g}Xq^;eF#d^|89wsYN`R3_}@B1^&T?L|4IN3+(R1N8= zKz@YGR~^K_eF%eNJ(nh=BHP*h-5F} zuNUj}zm=1?Z>cAmc7PG{G+Esl)s~<5`GKrRatXzH5VI{y7a6C>l0*6xos%k_uYH^L zELoAtr)(t~ejW8cl~W{(Ys4ZuI`a_4c&z@wP-hTQGT0vhQfI=mOvh}g|E0(tW?brj zEwr^=+U=N^u`(6R8`raPXigMr(IlZ3O^|<0vA_|ZUutq47+1lLV>}LZeiJNR>DSn% a(ytSv?%-wmmHrCxN`EtknT`29h5rXGN;)k7 literal 0 HcmV?d00001 diff --git a/source/FontSystem.cpp b/source/FontSystem.cpp index ac78ee60..66b12ca0 100644 --- a/source/FontSystem.cpp +++ b/source/FontSystem.cpp @@ -27,55 +27,55 @@ #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) + if ( fontSystem ) delete fontSystem; fontSystem = NULL; - if(MainFont != (FT_Byte *) font_ttf) + if ( MainFont != ( FT_Byte * ) font_ttf ) { - if(MainFont != NULL) + if ( MainFont != NULL ) delete [] MainFont; - MainFont = (FT_Byte *) font_ttf; + 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 e68b43a9..9bd679f4 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 747740a6..317674ca 100644 --- a/source/FreeTypeGX.cpp +++ b/source/FreeTypeGX.cpp @@ -30,44 +30,44 @@ using namespace std; * This routine converts a supplied short character string into a wide character string. * Note that it is the user's responsibility to clear the returned buffer once it is no longer needed. * - * @param strChar Character string to be converted. + * @param strChar Character string to be converted. * @return Wide character representation of supplied character string. */ -wchar_t* charToWideChar(const char* strChar) +wchar_t* charToWideChar( const char* strChar ) { - if(!strChar) + 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) - { - strWChar[bt] = 0; - return strWChar; - } + int bt = mbstowcs( strWChar, strChar, strlen( strChar ) ); + if ( bt > 0 ) + { + strWChar[bt] = 0; + return strWChar; + } - wchar_t *tempDest = strWChar; - while((*tempDest++ = *strChar++)); + wchar_t *tempDest = strWChar; + while ( ( *tempDest++ = *strChar++ ) ); - return strWChar; + return strWChar; } /** * 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); - ftKerningEnabled = FT_HAS_KERNING(ftFace); + setVertexFormat( GX_VTXFMT1 ); + ftKerningEnabled = FT_HAS_KERNING( ftFace ); } /** @@ -75,9 +75,9 @@ FreeTypeGX::FreeTypeGX(const uint8_t* fontBuffer, FT_Long bufferSize) */ FreeTypeGX::~FreeTypeGX() { - unloadFont(); - FT_Done_Face(ftFace); - FT_Done_FreeType(ftLibrary); + unloadFont(); + FT_Done_Face( ftFace ); + FT_Done_FreeType( ftLibrary ); } /** @@ -87,14 +87,14 @@ FreeTypeGX::~FreeTypeGX() * Note that this function should not need to be called except if the vertex formats are cleared or the specified * 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. + * @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); + 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 ); } /** @@ -104,22 +104,22 @@ 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(itr2 = itr->second.begin(); itr2 != itr->second.end(); itr2++) - free(itr2->second.glyphDataTexture); + for ( itr = fontData.begin(); itr != fontData.end(); itr++ ) + { + for ( itr2 = itr->second.begin(); itr2 != itr->second.end(); itr2++ ) + free( itr2->second.glyphDataTexture ); itr->second.clear(); - } + } - fontData.clear(); - ftgxAlign.clear(); + fontData.clear(); + ftgxAlign.clear(); } /** @@ -128,70 +128,70 @@ void FreeTypeGX::unloadFont() * This routine renders and stores the requested glyph's bitmap and relevant information into its own quickly addressible * structure within an instance-specific map. * - * @param charCode The requested glyph's character code. + * @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; } } - FT_UInt gIndex; - uint16_t textureWidth = 0, textureHeight = 0; + FT_UInt gIndex; + uint16_t textureWidth = 0, textureHeight = 0; - if(ftPointSize != pixelSize) - { - ftPointSize = pixelSize; - FT_Set_Pixel_Sizes(ftFace, 0, ftPointSize); + if ( ftPointSize != pixelSize ) + { + ftPointSize = pixelSize; + 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) - { - if(ftFace->glyph->format == FT_GLYPH_FORMAT_BITMAP) - { - FT_Bitmap *glyphBitmap = &ftFace->glyph->bitmap; + 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 ) + { + 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].glyphDataTexture = NULL; + 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]; - } - } - return NULL; + return &fontData[pixelSize][charCode]; + } + } + return NULL; } /** @@ -200,19 +200,19 @@ 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; + uint32_t i = 0; + FT_UInt gIndex; - 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 ); - } - return (uint16_t)(i); + 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 ); + } + return ( uint16_t )( i ); } /** @@ -221,40 +221,40 @@ uint16_t FreeTypeGX::cacheGlyphDataComplete(int16_t pixelSize) * This routine does a simple byte-wise copy of the glyph's rendered 8-bit grayscale bitmap into the structure's buffer. * Each byte is converted from the bitmap's intensity value into the a uint32_t RGBA value. * - * @param bmp A pointer to the most recently rendered glyph's bitmap. - * @param charData A pointer to an allocated ftgxCharData structure whose data represent that of the last rendered glyph. + * @param bmp A pointer to the most recently rendered glyph's bitmap. + * @param charData A pointer to an allocated ftgxCharData structure whose data represent that of the last rendered glyph. * * * 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) + 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; - uint32_t offset; + uint8_t *src = ( uint8_t * )bmp->buffer; + uint32_t offset; - for (int imagePosY = 0; imagePosY < bmp->rows; ++imagePosY) - { - for (int imagePosX = 0; imagePosX < bmp->width; ++imagePosX) - { - 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; - ++src; - } - } - DCFlushRange(glyphData, length); + for ( int imagePosY = 0; imagePosY < bmp->rows; ++imagePosY ) + { + for ( int imagePosX = 0; imagePosX < bmp->width; ++imagePosX ) + { + 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; + ++src; + } + } + DCFlushRange( glyphData, length ); - charData->glyphDataTexture = glyphData; + charData->glyphDataTexture = glyphData; } /** @@ -262,18 +262,18 @@ void FreeTypeGX::loadGlyphData(FT_Bitmap *bmp, ftgxCharData *charData) * * This routine calculates the x offset of the rendered string based off of a supplied positional format parameter. * - * @param width Current pixel width of the string. - * @param format Positional format of the string. + * @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) - return 0; - else if (format & FTGX_JUSTIFY_CENTER) - return -(width >> 1); - else if (format & FTGX_JUSTIFY_RIGHT) - return -width; - return 0; + if ( format & FTGX_JUSTIFY_LEFT ) + return 0; + else if ( format & FTGX_JUSTIFY_CENTER ) + return -( width >> 1 ); + else if ( format & FTGX_JUSTIFY_RIGHT ) + return -width; + return 0; } /** @@ -281,40 +281,40 @@ int16_t FreeTypeGX::getStyleOffsetWidth(uint16_t width, uint16_t format) * * This routine calculates the y offset of the rendered string based off of a supplied positional format parameter. * - * @param offset Current pixel offset data of the string. - * @param format Positional format of the string. + * @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()) + map::iterator itrAlign = ftgxAlign.find( pixelSize ); + if ( itrAlign == ftgxAlign.end() ) return 0; - switch(format & FTGX_ALIGN_MASK) - { - case FTGX_ALIGN_TOP: - return itrAlign->second.ascender; + 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; + case FTGX_ALIGN_MIDDLE: + default: + return ( itrAlign->second.ascender + itrAlign->second.descender + 1 ) >> 1; - case FTGX_ALIGN_BOTTOM: - return itrAlign->second.descender; + case FTGX_ALIGN_BOTTOM: + return itrAlign->second.descender; - case FTGX_ALIGN_BASELINE: - return 0; + case FTGX_ALIGN_BASELINE: + return 0; - case FTGX_ALIGN_GLYPH_TOP: - return itrAlign->second.max; + case FTGX_ALIGN_GLYPH_TOP: + return itrAlign->second.max; - case FTGX_ALIGN_GLYPH_MIDDLE: - return (itrAlign->second.max + itrAlign->second.min + 1) >> 1; + case FTGX_ALIGN_GLYPH_MIDDLE: + return ( itrAlign->second.max + itrAlign->second.min + 1 ) >> 1; - case FTGX_ALIGN_GLYPH_BOTTOM: - return itrAlign->second.min; - } - return 0; + case FTGX_ALIGN_GLYPH_BOTTOM: + return itrAlign->second.min; + } + return 0; } /** @@ -323,77 +323,77 @@ int16_t FreeTypeGX::getStyleOffsetHeight(int16_t format, uint16_t pixelSize) * This routine processes each character of the supplied text string, loads the relevant preprocessed bitmap buffer, * a texture from said buffer, and loads the resultant texture into the EFB. * - * @param x Screen X coordinate at which to output the text. + * @param x Screen X coordinate at which to output the text. * @param y Screen Y coordinate at which to output the text. Note that this value corresponds to the text string origin and not the top or bottom of the glyphs. - * @param text NULL terminated string to output. - * @param color Optional color to apply to the text characters. If not specified default value is ftgxWhite: (GXColor){0xff, 0xff, 0xff, 0xff} - * @param textStyle Flags which specify any styling which should be applied to the rendered string. + * @param text NULL terminated string to output. + * @param color Optional color to apply to the text characters. If not specified default value is ftgxWhite: (GXColor){0xff, 0xff, 0xff, 0xff} + * @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) + if ( !text ) return 0; - 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; + 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) - { - x_offset = getStyleOffsetWidth(fullTextWidth, textStyle); - } - if(textStyle & FTGX_ALIGN_MASK) - { - y_offset = getStyleOffsetHeight(textStyle, pixelSize); - } + if ( textStyle & FTGX_JUSTIFY_MASK ) + { + x_offset = getStyleOffsetWidth( fullTextWidth, textStyle ); + } + if ( textStyle & FTGX_ALIGN_MASK ) + { + y_offset = getStyleOffsetHeight( textStyle, pixelSize ); + } - int i = 0; + int i = 0; - while (text[i]) - { - if(widthLimit > 0 && (x_pos-x) > widthLimit) + while ( text[i] ) + { + if ( widthLimit > 0 && ( x_pos - x ) > widthLimit ) break; - ftgxCharData* glyphData = cacheGlyphData(text[i], pixelSize); + ftgxCharData* glyphData = cacheGlyphData( text[i], pixelSize ); - if (glyphData != NULL) - { - if (ftKerningEnabled && i > 0) - { - FT_Get_Kerning(ftFace, fontData[pixelSize][text[i - 1]].glyphIndex, glyphData->glyphIndex, FT_KERNING_DEFAULT, &pairDelta); - x_pos += pairDelta.x >> 6; - } + if ( glyphData != NULL ) + { + if ( ftKerningEnabled && i > 0 ) + { + 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; - } - ++i; - } + x_pos += glyphData->glyphAdvanceX; + ++printed; + } + ++i; + } - if(textStyle & FTGX_STYLE_MASK) - { - getOffset(text, pixelSize, widthLimit); - drawTextFeature(x + x_offset, y + y_offset, z, pixelSize, fullTextWidth, &ftgxAlign[pixelSize], textStyle, color); - } + if ( textStyle & FTGX_STYLE_MASK ) + { + getOffset( text, pixelSize, widthLimit ); + drawTextFeature( x + x_offset, y + y_offset, z, pixelSize, fullTextWidth, &ftgxAlign[pixelSize], textStyle, color ); + } - return printed; + 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; + 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 ); } /** @@ -402,57 +402,57 @@ void FreeTypeGX::drawTextFeature(int16_t x, int16_t y, int16_t z, int16_t pixelS * This routine processes each character of the supplied text string and calculates the width of the entire string. * Note that if precaching of the entire font set is not enabled any uncached glyph will be cached after the call to this function. * - * @param text NULL terminated string to calculate. + * @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) + if ( !text ) return 0; - uint16_t strWidth = 0; - FT_Vector pairDelta; + uint16_t strWidth = 0; + FT_Vector pairDelta; - int i = 0; - while (text[i]) - { - ftgxCharData* glyphData = cacheGlyphData(text[i], pixelSize); + int i = 0; + while ( text[i] ) + { + ftgxCharData* glyphData = cacheGlyphData( text[i], pixelSize ); - if (glyphData != NULL) - { - if (ftKerningEnabled && (i > 0)) - { - FT_Get_Kerning(ftFace, fontData[pixelSize][text[i - 1]].glyphIndex, glyphData->glyphIndex, FT_KERNING_DEFAULT, &pairDelta); - strWidth += pairDelta.x >> 6; - } + if ( glyphData != NULL ) + { + if ( ftKerningEnabled && ( i > 0 ) ) + { + FT_Get_Kerning( ftFace, fontData[pixelSize][text[i - 1]].glyphIndex, glyphData->glyphIndex, FT_KERNING_DEFAULT, &pairDelta ); + strWidth += pairDelta.x >> 6; + } - strWidth += glyphData->glyphAdvanceX; - } - ++i; - } - return strWidth; + strWidth += glyphData->glyphAdvanceX; + } + ++i; + } + return strWidth; } /** * 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; } - return strWidth; + return strWidth; } /** @@ -461,14 +461,14 @@ uint16_t FreeTypeGX::getCharWidth(const wchar_t wChar, int16_t pixelSize, const * This routine processes each character of the supplied text string and calculates the height of the entire string. * Note that if precaching of the entire font set is not enabled any uncached glyph will be cached after the call to this function. * - * @param text NULL terminated string to calculate. + * @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; + return ftgxAlign[pixelSize].max - ftgxAlign[pixelSize].min; } /** @@ -477,47 +477,47 @@ uint16_t FreeTypeGX::getHeight(const wchar_t *text, int16_t pixelSize) * This function calculates the maximum pixel height above the font origin line and the minimum * pixel height below the font origin line and returns the values in an addressible structure. * - * @param text NULL terminated string to calculate. + * @param text NULL terminated string to calculate. * @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()) + if ( ftgxAlign.find( pixelSize ) != ftgxAlign.end() ) return; - int16_t strMax = 0, strMin = 9999; - uint16_t currWidth = 0; + int16_t strMax = 0, strMin = 9999; + uint16_t currWidth = 0; - int i = 0; + int i = 0; - while (text[i]) - { - if(widthLimit > 0 && currWidth >= widthLimit) + while ( text[i] ) + { + if ( widthLimit > 0 && currWidth >= widthLimit ) break; - ftgxCharData* glyphData = cacheGlyphData(text[i], pixelSize); + ftgxCharData* glyphData = cacheGlyphData( text[i], pixelSize ); - if(glyphData != NULL) - { - strMax = glyphData->renderOffsetMax > strMax ? glyphData->renderOffsetMax : strMax; - strMin = glyphData->renderOffsetMin < strMin ? glyphData->renderOffsetMin : strMin; - currWidth += glyphData->glyphAdvanceX; - } + if ( glyphData != NULL ) + { + strMax = glyphData->renderOffsetMax > strMax ? glyphData->renderOffsetMax : strMax; + strMin = glyphData->renderOffsetMin < strMin ? glyphData->renderOffsetMin : strMin; + currWidth += glyphData->glyphAdvanceX; + } - ++i; - } + ++i; + } - if(ftPointSize != pixelSize) - { - ftPointSize = pixelSize; - FT_Set_Pixel_Sizes(ftFace, 0, ftPointSize); - } + if ( ftPointSize != pixelSize ) + { + ftPointSize = pixelSize; + FT_Set_Pixel_Sizes( ftFace, 0, ftPointSize ); + } - ftgxAlign[pixelSize].ascender = ftFace->size->metrics.ascender>>6; - ftgxAlign[pixelSize].descender = ftFace->size->metrics.descender>>6; - ftgxAlign[pixelSize].max = strMax; - ftgxAlign[pixelSize].min = strMin; + ftgxAlign[pixelSize].ascender = ftFace->size->metrics.ascender >> 6; + ftgxAlign[pixelSize].descender = ftFace->size->metrics.descender >> 6; + ftgxAlign[pixelSize].max = strMax; + ftgxAlign[pixelSize].min = strMin; } /** @@ -525,41 +525,41 @@ void FreeTypeGX::getOffset(const wchar_t *text, int16_t pixelSize, uint16_t widt * * This routine uses the in-built GX quad builder functions to define the texture bounds and location on the EFB target. * - * @param texObj A pointer to the glyph's initialized texture object. - * @param texWidth The pixel width of the texture object. - * @param texHeight The pixel height of the texture object. - * @param screenX The screen X coordinate at which to output the rendered texture. - * @param screenY The screen Y coordinate at which to output the rendered texture. - * @param color Color to apply to the texture. + * @param texObj A pointer to the glyph's initialized texture object. + * @param texWidth The pixel width of the texture object. + * @param texHeight The pixel height of the texture object. + * @param screenX The screen X coordinate at which to output the rendered texture. + * @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_InvalidateTexAll(); + 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_End(); + 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 ); } /** @@ -567,31 +567,31 @@ void FreeTypeGX::copyTextureToFramebuffer(GXTexObj *texObj, f32 texWidth, f32 te * * This function creates a simple quad for displaying underline or strikeout text styling. * - * @param featureWidth The pixel width of the quad. - * @param featureHeight The pixel height of the quad. - * @param screenX The screen X coordinate at which to output the quad. - * @param screenY The screen Y coordinate at which to output the quad. - * @param color Color to apply to the texture. + * @param featureWidth The pixel width of the quad. + * @param featureHeight The pixel height of the quad. + * @param screenX The screen X coordinate at which to output the quad. + * @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_End(); + 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 8b2f7a13..6c639a99 100644 --- a/source/FreeTypeGX.h +++ b/source/FreeTypeGX.h @@ -37,30 +37,32 @@ * * Font face character glyph relevant data structure. */ -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. */ +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. */ - 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_ * * Offset structure which hold both a maximum and minimum value. */ -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. */ +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. */ } ftgxDataOffset; typedef struct ftgxCharData_ ftgxCharData; @@ -68,28 +70,28 @@ typedef struct ftgxDataOffset_ ftgxDataOffset; #define _TEXT(t) L ## t /**< Unicode helper macro. */ -#define FTGX_NULL 0x0000 -#define FTGX_JUSTIFY_LEFT 0x0001 -#define FTGX_JUSTIFY_CENTER 0x0002 -#define FTGX_JUSTIFY_RIGHT 0x0004 -#define FTGX_JUSTIFY_MASK 0x000f +#define FTGX_NULL 0x0000 +#define FTGX_JUSTIFY_LEFT 0x0001 +#define FTGX_JUSTIFY_CENTER 0x0002 +#define FTGX_JUSTIFY_RIGHT 0x0004 +#define FTGX_JUSTIFY_MASK 0x000f -#define FTGX_ALIGN_TOP 0x0010 -#define FTGX_ALIGN_MIDDLE 0x0020 -#define FTGX_ALIGN_BOTTOM 0x0040 -#define FTGX_ALIGN_BASELINE 0x0080 -#define FTGX_ALIGN_GLYPH_TOP 0x0100 -#define FTGX_ALIGN_GLYPH_MIDDLE 0x0200 -#define FTGX_ALIGN_GLYPH_BOTTOM 0x0400 -#define FTGX_ALIGN_MASK 0x0ff0 +#define FTGX_ALIGN_TOP 0x0010 +#define FTGX_ALIGN_MIDDLE 0x0020 +#define FTGX_ALIGN_BOTTOM 0x0040 +#define FTGX_ALIGN_BASELINE 0x0080 +#define FTGX_ALIGN_GLYPH_TOP 0x0100 +#define FTGX_ALIGN_GLYPH_MIDDLE 0x0200 +#define FTGX_ALIGN_GLYPH_BOTTOM 0x0400 +#define FTGX_ALIGN_MASK 0x0ff0 -#define FTGX_STYLE_UNDERLINE 0x1000 -#define FTGX_STYLE_STRIKE 0x2000 -#define FTGX_STYLE_MASK 0xf000 +#define FTGX_STYLE_UNDERLINE 0x1000 +#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. @@ -102,41 +104,41 @@ wchar_t* charToWideChar(const char* p); */ class FreeTypeGX { - private: + 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. */ - std::map > fontData; /**< Map which holds the glyph data structures for the corresponding characters in one size. */ + 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); + void unloadFont(); + ftgxCharData *cacheGlyphData( wchar_t charCode, int16_t pixelSize ); + uint16_t cacheGlyphDataComplete( int16_t pixelSize ); + void loadGlyphData( FT_Bitmap *bmp, ftgxCharData *charData ); - void setDefaultMode(); + 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(); + public: + 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 d1e27709..8e093249 100644 --- a/source/ZipFile.cpp +++ b/source/ZipFile.cpp @@ -39,16 +39,16 @@ #include "ZipFile.h" #include "language/gettext.h" -ZipFile::ZipFile(const char *filepath) +ZipFile::ZipFile( const char *filepath ) { - File = unzOpen(filepath); - if(File) + File = unzOpen( filepath ); + if ( File ) this->LoadList(); } ZipFile::~ZipFile() { - unzClose(File); + unzClose( File ); } bool ZipFile::LoadList() @@ -56,78 +56,79 @@ bool ZipFile::LoadList() return true; } -bool ZipFile::ExtractAll(const char *dest) +bool ZipFile::ExtractAll( const char *dest ) { - if(!File) + if ( !File ) return false; bool Stop = false; - u32 blocksize = 1024*50; + u32 blocksize = 1024 * 50; u8 *buffer = new u8[blocksize]; - if(!buffer) + 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) + 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) + 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, '/'); - int position = pointer-writepath+2; + 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) + if ( uncompressed_size - done < blocksize ) blocksize = uncompressed_size - done; - ret = unzReadCurrentFile(File, buffer, blocksize); + ret = unzReadCurrentFile( File, buffer, blocksize ); - if(ret == 0) + 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) + if ( unzGoToNextFile( File ) != UNZ_OK ) Stop = true; } diff --git a/source/ZipFile.h b/source/ZipFile.h index 88487565..302aa77a 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); - //!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); + //!Constructor + ZipFile( const char *filepath ); + //!Destructor + ~ZipFile(); + //!Extract all files from a zip file to a directory + //!\param dest Destination path to where to extract + bool ExtractAll( const char *dest ); protected: bool LoadList(); unzFile File; diff --git a/source/audio.cpp b/source/audio.cpp index b8e301ad..0a2431ef 100644 --- a/source/audio.cpp +++ b/source/audio.cpp @@ -15,10 +15,11 @@ * * Initializes the Wii's audio subsystem ***************************************************************************/ -void InitAudio() { - AUDIO_Init(NULL); +void InitAudio() +{ + AUDIO_Init( NULL ); ASND_Init(); - ASND_Pause(0); + ASND_Pause( 0 ); } /**************************************************************************** @@ -27,7 +28,8 @@ void InitAudio() { * Shuts down audio subsystem. Useful to avoid unpleasant sounds if a * crash occurs during shutdown. ***************************************************************************/ -void ShutdownAudio() { - ASND_Pause(1); +void ShutdownAudio() +{ + ASND_Pause( 1 ); ASND_End(); } diff --git a/source/banner/MD5.c b/source/banner/MD5.c index 0aeb6bc9..4c0b98c7 100644 --- a/source/banner/MD5.c +++ b/source/banner/MD5.c @@ -7,10 +7,10 @@ * * Email: crh@ubiqx.mn.org * - * $Id: MD5.c,v 0.6 2005/06/08 18:35:59 crh Exp $ + * $Id: MD5.c,v 0.6 2005/06/08 18:35:59 crh Exp $ * - * - * Modifications and additions by dimok + * + * Modifications and additions by dimok * * -------------------------------------------------------------------------- ** * @@ -75,14 +75,14 @@ * * ========================================================================== ** */ - -#include -#include -#include -#include -#include -#include -#include + +#include +#include +#include +#include +#include +#include +#include #include "MD5.h" @@ -111,28 +111,28 @@ */ 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 uint32_t T[4][16] = - { +{ { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, /* Round 1 */ - 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, - 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, - 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 }, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 }, { 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, /* Round 2 */ 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, @@ -148,7 +148,7 @@ static const uint32_t T[4][16] = 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }, - }; +}; /* -------------------------------------------------------------------------- ** @@ -168,8 +168,8 @@ static const uint32_t T[4][16] = #define md5H( X, Y, Z ) ( (X) ^ (Y) ^ (Z) ) #define md5I( X, Y, Z ) ( (Y) ^ ((X) | (~(Z))) ) -#define GetLongByte( L, idx ) ((unsigned char)(( L >> (((idx) & 0x03) << 3) ) & 0xFF)) - +#define GetLongByte( L, idx ) ((unsigned char)(( L >> (((idx) & 0x03) << 3) ) & 0xFF)) + #define STR2HEX(x) ((x >= 0x30) && (x <= 0x39)) ? x - 0x30 : toupper((int)x)-0x37 @@ -178,122 +178,122 @@ static const uint32_t T[4][16] = */ static void Permute( uint32_t ABCD[4], const unsigned char block[64] ) - /* ------------------------------------------------------------------------ ** - * Permute the ABCD "registers" using the 64-byte as a driver. - * - * Input: ABCD - Pointer to an array of four unsigned longwords. - * block - An array of bytes, 64 bytes in size. - * - * Output: none. - * - * Notes: The MD5 algorithm operates on a set of four longwords stored - * (conceptually) in four "registers". It is easy to imagine a - * simple MD4/5 chip that would operate this way. In any case, - * the mangling of the contents of those registers is driven by - * the input message. The message is chopped and finally padded - * into 64-byte chunks and each chunk is used to manipulate the - * contents of the registers. - * - * The MD5 Algorithm calls for padding the input to ensure that - * it is a multiple of 64 bytes in length. The last 16 bytes - * of the padding space are used to store the message length - * (the length of the original message, before padding, expressed - * in terms of bits). If there is not enough room for 16 bytes - * worth of bitcount (eg., if the original message was 122 bytes - * long) then the block is padded to the end with zeros and - * passed to this function. Then *another* block is filled with - * zeros except for the last 16 bytes which contain the length. - * - * Oh... and the algorithm requires that there be at least one - * padding byte. The first padding byte has a value of 0x80, - * and any others are 0x00. - * - * ------------------------------------------------------------------------ ** - */ - { - int round; - int i, j; - uint8_t s; - uint32_t a, b, c, d; - uint32_t KeepABCD[4]; - uint32_t X[16]; +/* ------------------------------------------------------------------------ ** + * Permute the ABCD "registers" using the 64-byte as a driver. + * + * Input: ABCD - Pointer to an array of four unsigned longwords. + * block - An array of bytes, 64 bytes in size. + * + * Output: none. + * + * Notes: The MD5 algorithm operates on a set of four longwords stored + * (conceptually) in four "registers". It is easy to imagine a + * simple MD4/5 chip that would operate this way. In any case, + * the mangling of the contents of those registers is driven by + * the input message. The message is chopped and finally padded + * into 64-byte chunks and each chunk is used to manipulate the + * contents of the registers. + * + * The MD5 Algorithm calls for padding the input to ensure that + * it is a multiple of 64 bytes in length. The last 16 bytes + * of the padding space are used to store the message length + * (the length of the original message, before padding, expressed + * in terms of bits). If there is not enough room for 16 bytes + * worth of bitcount (eg., if the original message was 122 bytes + * long) then the block is padded to the end with zeros and + * passed to this function. Then *another* block is filled with + * zeros except for the last 16 bytes which contain the length. + * + * Oh... and the algorithm requires that there be at least one + * padding byte. The first padding byte has a value of 0x80, + * and any others are 0x00. + * + * ------------------------------------------------------------------------ ** + */ +{ + int round; + int i, j; + uint8_t s; + uint32_t a, b, c, d; + uint32_t KeepABCD[4]; + uint32_t X[16]; - /* Store the current ABCD values for later re-use. - */ - for( i = 0; i < 4; i++ ) - KeepABCD[i] = ABCD[i]; + /* Store the current ABCD values for later re-use. + */ + for ( i = 0; i < 4; i++ ) + KeepABCD[i] = ABCD[i]; - /* Convert the input block into an array of unsigned longs, taking care - * to read the block in Little Endian order (the algorithm assumes this). - * The uint32_t values are then handled in host order. - */ - for( i = 0, j = 0; i < 16; i++ ) + /* Convert the input block into an array of unsigned longs, taking care + * to read the block in Little Endian order (the algorithm assumes this). + * The uint32_t values are then handled in host order. + */ + for ( i = 0, j = 0; i < 16; i++ ) { - X[i] = (uint32_t)block[j++]; - X[i] |= ((uint32_t)block[j++] << 8); - X[i] |= ((uint32_t)block[j++] << 16); - X[i] |= ((uint32_t)block[j++] << 24); + X[i] = ( uint32_t )block[j++]; + X[i] |= ( ( uint32_t )block[j++] << 8 ); + X[i] |= ( ( uint32_t )block[j++] << 16 ); + X[i] |= ( ( uint32_t )block[j++] << 24 ); } - /* This loop performs the four rounds of permutations. - * The rounds are each very similar. The differences are in three areas: - * - The function (F, G, H, or I) used to perform bitwise permutations - * on the registers, - * - The order in which values from X[] are chosen. - * - Changes to the number of bits by which the registers are rotated. - * This implementation uses a switch statement to deal with some of the - * differences between rounds. Other differences are handled by storing - * values in arrays and using the round number to select the correct set - * of values. - * - * (My implementation appears to be a poor compromise between speed, size, - * and clarity. Ugh. [crh]) - */ - for( round = 0; round < 4; round++ ) + /* This loop performs the four rounds of permutations. + * The rounds are each very similar. The differences are in three areas: + * - The function (F, G, H, or I) used to perform bitwise permutations + * on the registers, + * - The order in which values from X[] are chosen. + * - Changes to the number of bits by which the registers are rotated. + * This implementation uses a switch statement to deal with some of the + * differences between rounds. Other differences are handled by storing + * values in arrays and using the round number to select the correct set + * of values. + * + * (My implementation appears to be a poor compromise between speed, size, + * and clarity. Ugh. [crh]) + */ + for ( round = 0; round < 4; round++ ) { - for( i = 0; i < 16; i++ ) - { - j = (4 - (i % 4)) & 0x3; /* handles the rotation of ABCD. */ - s = S[round][i%4]; /* is the bit shift for this iteration. */ - - b = ABCD[(j+1) & 0x3]; /* Copy the b,c,d values per ABCD rotation. */ - c = ABCD[(j+2) & 0x3]; /* This isn't really necessary, it just looks */ - d = ABCD[(j+3) & 0x3]; /* clean & will hopefully be optimized away. */ - - /* The actual perumation function. - * This is broken out to minimize the code within the switch(). - */ - switch( round ) + for ( i = 0; i < 16; i++ ) { - case 0: - /* round 1 */ - a = md5F( b, c, d ) + X[i]; - break; - case 1: - /* round 2 */ - a = md5G( b, c, d ) + X[ K[0][i] ]; - break; - case 2: - /* round 3 */ - a = md5H( b, c, d ) + X[ K[1][i] ]; - break; - default: - /* round 4 */ - a = md5I( b, c, d ) + X[ K[2][i] ]; - break; + 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. */ + + /* The actual perumation function. + * This is broken out to minimize the code within the switch(). + */ + switch ( round ) + { + case 0: + /* round 1 */ + a = md5F( b, c, d ) + X[i]; + break; + case 1: + /* round 2 */ + a = md5G( b, c, d ) + X[ K[0][i] ]; + break; + case 2: + /* round 3 */ + a = md5H( b, c, d ) + X[ K[1][i] ]; + break; + default: + /* round 4 */ + a = md5I( b, c, d ) + X[ K[2][i] ]; + break; + } + a = 0xFFFFFFFF & ( ABCD[j] + a + T[round][i] ); + ABCD[j] = b + ( 0xFFFFFFFF & ( ( a << s ) | ( a >> ( 32 - s ) ) ) ); } - a = 0xFFFFFFFF & ( ABCD[j] + a + T[round][i] ); - ABCD[j] = b + (0xFFFFFFFF & (( a << s ) | ( a >> (32 - s) ))); - } } - /* Use the stored original A, B, C, D values to perform - * one last convolution. - */ - for( i = 0; i < 4; i++ ) - ABCD[i] = 0xFFFFFFFF & ( ABCD[i] + KeepABCD[i] ); + /* Use the stored original A, B, C, D values to perform + * one last convolution. + */ + for ( i = 0; i < 4; i++ ) + ABCD[i] = 0xFFFFFFFF & ( ABCD[i] + KeepABCD[i] ); - } /* Permute */ +} /* Permute */ /* -------------------------------------------------------------------------- ** @@ -301,330 +301,333 @@ static void Permute( uint32_t ABCD[4], const unsigned char block[64] ) */ auth_md5Ctx *auth_md5InitCtx( auth_md5Ctx *ctx ) - /* ------------------------------------------------------------------------ ** - * Initialize an MD5 context. - * - * Input: ctx - A pointer to the MD5 context structure to be initialized. - * Contexts are typically created thusly: - * ctx = (auth_md5Ctx *)malloc( sizeof(auth_md5Ctx) ); - * - * Output: A pointer to the initialized context (same as ). - * - * Notes: The purpose of the context is to make it possible to generate - * an MD5 Message Digest in stages, rather than having to pass a - * single large block to a single MD5 function. The context - * structure keeps track of various bits of state information. - * - * Once the context is initialized, the blocks of message data - * are passed to the function. Once the - * final bit of data has been handed to the - * context can be closed out by calling , - * which also calculates the final MD5 result. - * - * Don't forget to free an allocated context structure when - * you've finished using it. - * - * See Also: , - * - * ------------------------------------------------------------------------ ** - */ - { - ctx->len = 0; - ctx->b_used = 0; +/* ------------------------------------------------------------------------ ** + * Initialize an MD5 context. + * + * Input: ctx - A pointer to the MD5 context structure to be initialized. + * Contexts are typically created thusly: + * ctx = (auth_md5Ctx *)malloc( sizeof(auth_md5Ctx) ); + * + * Output: A pointer to the initialized context (same as ). + * + * Notes: The purpose of the context is to make it possible to generate + * an MD5 Message Digest in stages, rather than having to pass a + * single large block to a single MD5 function. The context + * structure keeps track of various bits of state information. + * + * Once the context is initialized, the blocks of message data + * are passed to the function. Once the + * final bit of data has been handed to the + * context can be closed out by calling , + * which also calculates the final MD5 result. + * + * Don't forget to free an allocated context structure when + * you've finished using it. + * + * See Also: , + * + * ------------------------------------------------------------------------ ** + */ +{ + ctx->len = 0; + ctx->b_used = 0; - ctx->ABCD[0] = 0x67452301; /* The array ABCD[] contains the four 4-byte */ - ctx->ABCD[1] = 0xefcdab89; /* "registers" that are manipulated to */ - ctx->ABCD[2] = 0x98badcfe; /* produce the MD5 digest. The input acts */ - ctx->ABCD[3] = 0x10325476; /* upon the registers, not the other way */ - /* 'round. The initial values are those */ - /* given in RFC 1321 (pg. 4). Note, however, that RFC 1321 */ - /* provides these values as bytes, not as longwords, and the */ - /* bytes are arranged in little-endian order as if they were */ - /* the bytes of (little endian) 32-bit ints. That's */ - /* confusing as all getout (to me, anyway). The values given */ - /* here are provided as 32-bit values in C language format, */ - /* so they are endian-agnostic. */ - return( ctx ); - } /* auth_md5InitCtx */ + ctx->ABCD[0] = 0x67452301; /* The array ABCD[] contains the four 4-byte */ + ctx->ABCD[1] = 0xefcdab89; /* "registers" that are manipulated to */ + ctx->ABCD[2] = 0x98badcfe; /* produce the MD5 digest. The input acts */ + ctx->ABCD[3] = 0x10325476; /* upon the registers, not the other way */ + /* 'round. The initial values are those */ + /* given in RFC 1321 (pg. 4). Note, however, that RFC 1321 */ + /* provides these values as bytes, not as longwords, and the */ + /* bytes are arranged in little-endian order as if they were */ + /* the bytes of (little endian) 32-bit ints. That's */ + /* confusing as all getout (to me, anyway). The values given */ + /* here are provided as 32-bit values in C language format, */ + /* so they are endian-agnostic. */ + return( ctx ); +} /* auth_md5InitCtx */ auth_md5Ctx *auth_md5SumCtx( auth_md5Ctx *ctx, const unsigned char *src, const int len ) - /* ------------------------------------------------------------------------ ** - * Build an MD5 Message Digest within the given context. - * - * Input: ctx - Pointer to the context in which the MD5 sum is being - * built. - * src - A chunk of source data. This will be used to drive - * the MD5 algorithm. - * len - The number of bytes in . - * - * Output: A pointer to the updated context (same as ). - * - * See Also: , , - * - * ------------------------------------------------------------------------ ** - */ - { - int i; +/* ------------------------------------------------------------------------ ** + * Build an MD5 Message Digest within the given context. + * + * Input: ctx - Pointer to the context in which the MD5 sum is being + * built. + * src - A chunk of source data. This will be used to drive + * the MD5 algorithm. + * len - The number of bytes in . + * + * Output: A pointer to the updated context (same as ). + * + * See Also: , , + * + * ------------------------------------------------------------------------ ** + */ +{ + int i; - /* Add the new block's length to the total length. - */ - ctx->len += (uint32_t)len; + /* Add the new block's length to the total length. + */ + ctx->len += ( uint32_t )len; - /* Copy the new block's data into the context block. - * Call the Permute() function whenever the context block is full. - */ - for( i = 0; i < len; i++ ) + /* Copy the new block's data into the context block. + * Call the Permute() function whenever the context block is full. + */ + for ( i = 0; i < len; i++ ) { - ctx->block[ ctx->b_used ] = src[i]; - (ctx->b_used)++; - if( 64 == ctx->b_used ) - { - Permute( ctx->ABCD, ctx->block ); - ctx->b_used = 0; - } + ctx->block[ ctx->b_used ] = src[i]; + ( ctx->b_used )++; + if ( 64 == ctx->b_used ) + { + Permute( ctx->ABCD, ctx->block ); + ctx->b_used = 0; + } } - /* Return the updated context. - */ - return( ctx ); - } /* auth_md5SumCtx */ + /* Return the updated context. + */ + return( ctx ); +} /* auth_md5SumCtx */ auth_md5Ctx *auth_md5CloseCtx( auth_md5Ctx *ctx, unsigned char *dst ) - /* ------------------------------------------------------------------------ ** - * Close an MD5 Message Digest context and generate the final MD5 sum. - * - * Input: ctx - Pointer to the context in which the MD5 sum is being - * built. - * dst - A pointer to at least 16 bytes of memory, which will - * receive the finished MD5 sum. - * - * Output: A pointer to the closed context (same as ). - * You might use this to free a malloc'd context structure. :) - * - * Notes: The context () is returned in an undefined state. - * It must be re-initialized before re-use. - * - * See Also: , - * - * ------------------------------------------------------------------------ ** - */ - { - int i; - uint32_t l; +/* ------------------------------------------------------------------------ ** + * Close an MD5 Message Digest context and generate the final MD5 sum. + * + * Input: ctx - Pointer to the context in which the MD5 sum is being + * built. + * dst - A pointer to at least 16 bytes of memory, which will + * receive the finished MD5 sum. + * + * Output: A pointer to the closed context (same as ). + * You might use this to free a malloc'd context structure. :) + * + * Notes: The context () is returned in an undefined state. + * It must be re-initialized before re-use. + * + * See Also: , + * + * ------------------------------------------------------------------------ ** + */ +{ + int i; + uint32_t l; - /* Add the required 0x80 padding initiator byte. - * The auth_md5SumCtx() function always permutes and resets the context - * block when it gets full, so we know that there must be at least one - * free byte in the context block. - */ - ctx->block[ctx->b_used] = 0x80; - (ctx->b_used)++; + /* Add the required 0x80 padding initiator byte. + * The auth_md5SumCtx() function always permutes and resets the context + * block when it gets full, so we know that there must be at least one + * free byte in the context block. + */ + ctx->block[ctx->b_used] = 0x80; + ( ctx->b_used )++; - /* Zero out any remaining free bytes in the context block. - */ - for( i = ctx->b_used; i < 64; i++ ) - ctx->block[i] = 0; + /* Zero out any remaining free bytes in the context block. + */ + for ( i = ctx->b_used; i < 64; i++ ) + ctx->block[i] = 0; - /* We need 8 bytes to store the length field. - * If we don't have 8, call Permute() and reset the context block. - */ - if( 56 < ctx->b_used ) + /* We need 8 bytes to store the length field. + * If we don't have 8, call Permute() and reset the context block. + */ + if ( 56 < ctx->b_used ) { + Permute( ctx->ABCD, ctx->block ); + for ( i = 0; i < 64; i++ ) + ctx->block[i] = 0; + } + + /* Add the total length and perform the final perumation. + * Note: The 60'th byte is read from the *original* len> value + * and shifted to the correct position. This neatly avoids + * any MAXINT numeric overflow issues. + */ + l = ctx->len << 3; + for ( i = 0; i < 4; i++ ) + ctx->block[56+i] |= GetLongByte( l, i ); + ctx->block[60] = ( ( GetLongByte( ctx->len, 3 ) & 0xE0 ) >> 5 ); /* See Above! */ Permute( ctx->ABCD, ctx->block ); - for( i = 0; i < 64; i++ ) - ctx->block[i] = 0; - } - /* Add the total length and perform the final perumation. - * Note: The 60'th byte is read from the *original* len> value - * and shifted to the correct position. This neatly avoids - * any MAXINT numeric overflow issues. - */ - l = ctx->len << 3; - for( i = 0; i < 4; i++ ) - ctx->block[56+i] |= GetLongByte( l, i ); - ctx->block[60] = ((GetLongByte( ctx->len, 3 ) & 0xE0) >> 5); /* See Above! */ - Permute( ctx->ABCD, ctx->block ); - - /* Now copy the result into the output buffer and we're done. - */ - for( i = 0; i < 4; i++ ) + /* Now copy the result into the output buffer and we're done. + */ + for ( i = 0; i < 4; i++ ) { - dst[ 0+i] = GetLongByte( ctx->ABCD[0], i ); - dst[ 4+i] = GetLongByte( ctx->ABCD[1], i ); - dst[ 8+i] = GetLongByte( ctx->ABCD[2], i ); - dst[12+i] = GetLongByte( ctx->ABCD[3], i ); + dst[ 0+i] = GetLongByte( ctx->ABCD[0], i ); + dst[ 4+i] = GetLongByte( ctx->ABCD[1], i ); + dst[ 8+i] = GetLongByte( ctx->ABCD[2], i ); + dst[12+i] = GetLongByte( ctx->ABCD[3], i ); } - /* Return the context. - * This is done for compatibility with the other auth_md5*Ctx() functions. - */ - return( ctx ); - } /* auth_md5CloseCtx */ + /* Return the context. + * This is done for compatibility with the other auth_md5*Ctx() functions. + */ + return( ctx ); +} /* auth_md5CloseCtx */ -unsigned char * MD5(unsigned char *dst, const unsigned char *src, const int len ) - /* ------------------------------------------------------------------------ ** - * Compute an MD5 message digest. - * - * Input: dst - Destination buffer into which the result will be written. - * Must be 16 bytes, minimum. - * src - Source data block to be MD5'd. - * len - The length, in bytes, of the source block. - * (Note that the length is given in bytes, not bits.) - * - * Output: A pointer to , which will contain the calculated 16-byte - * MD5 message digest. - * - * Notes: This function is a shortcut. It takes a single input block. - * For more drawn-out operations, see . - * - * This function is interface-compatible with the - * function in the MD4 module. - * - * The MD5 algorithm is designed to work on data with an - * arbitrary *bit* length. Most implementations, this one - * included, handle the input data in byte-sized chunks. - * - * The MD5 algorithm does much of its work using four-byte - * words, and so can be tuned for speed based on the endian-ness - * of the host. This implementation is intended to be - * endian-neutral, which may make it a teeny bit slower than - * others. ...maybe. - * - * See Also: - * - * ------------------------------------------------------------------------ ** - */ - { - auth_md5Ctx ctx[1]; +unsigned char * MD5( unsigned char *dst, const unsigned char *src, const int len ) +/* ------------------------------------------------------------------------ ** + * Compute an MD5 message digest. + * + * Input: dst - Destination buffer into which the result will be written. + * Must be 16 bytes, minimum. + * src - Source data block to be MD5'd. + * len - The length, in bytes, of the source block. + * (Note that the length is given in bytes, not bits.) + * + * Output: A pointer to , which will contain the calculated 16-byte + * MD5 message digest. + * + * Notes: This function is a shortcut. It takes a single input block. + * For more drawn-out operations, see . + * + * This function is interface-compatible with the + * function in the MD4 module. + * + * The MD5 algorithm is designed to work on data with an + * arbitrary *bit* length. Most implementations, this one + * included, handle the input data in byte-sized chunks. + * + * The MD5 algorithm does much of its work using four-byte + * words, and so can be tuned for speed based on the endian-ness + * of the host. This implementation is intended to be + * endian-neutral, which may make it a teeny bit slower than + * others. ...maybe. + * + * See Also: + * + * ------------------------------------------------------------------------ ** + */ +{ + auth_md5Ctx ctx[1]; - (void)auth_md5InitCtx( ctx ); /* Open a context. */ - (void)auth_md5SumCtx( ctx, src, len ); /* Pass only one block. */ - (void)auth_md5CloseCtx( ctx, dst ); /* Close the context. */ + ( void )auth_md5InitCtx( ctx ); /* Open a context. */ + ( void )auth_md5SumCtx( ctx, src, len ); /* Pass only one block. */ + ( void )auth_md5CloseCtx( ctx, dst ); /* Close the context. */ - return( dst ); /* Makes life easy. */ - } /* auth_md5Sum */ - - - -unsigned char * MD5fromFile(unsigned char *dst, const char *src) - /* ------------------------------------------------------------------------ ** - * Compute an MD5 message digest. - * - * Input: dst - Destination buffer into which the result will be written. - * Must be 16 bytes, minimum. - * src - filepath of the file to be checked - * - * Output: A pointer to , which will contain the calculated 16-byte - * MD5 message digest. - * - * Notes: This function is a shortcut. It takes a single input block. - * For more drawn-out operations, see . - * - * This function is interface-compatible with the - * function in the MD4 module. - * - * The MD5 algorithm is designed to work on data with an - * arbitrary *bit* length. Most implementations, this one - * included, handle the input data in byte-sized chunks. - * - * The MD5 algorithm does much of its work using four-byte - * words, and so can be tuned for speed based on the endian-ness - * of the host. This implementation is intended to be - * endian-neutral, which may make it a teeny bit slower than - * others. ...maybe. - * - * See Also: - * - * ------------------------------------------------------------------------ ** - */ - { - auth_md5Ctx ctx[1]; - - FILE * file; - unsigned int blksize = 0; - unsigned int read = 0; - - file = fopen(src, "rb"); + return( dst ); /* Makes life easy. */ +} /* auth_md5Sum */ - if (file==NULL){ + + +unsigned char * MD5fromFile( unsigned char *dst, const char *src ) +/* ------------------------------------------------------------------------ ** + * Compute an MD5 message digest. + * + * Input: dst - Destination buffer into which the result will be written. + * Must be 16 bytes, minimum. + * src - filepath of the file to be checked + * + * Output: A pointer to , which will contain the calculated 16-byte + * MD5 message digest. + * + * Notes: This function is a shortcut. It takes a single input block. + * For more drawn-out operations, see . + * + * This function is interface-compatible with the + * function in the MD4 module. + * + * The MD5 algorithm is designed to work on data with an + * arbitrary *bit* length. Most implementations, this one + * included, handle the input data in byte-sized chunks. + * + * The MD5 algorithm does much of its work using four-byte + * words, and so can be tuned for speed based on the endian-ness + * of the host. This implementation is intended to be + * endian-neutral, which may make it a teeny bit slower than + * others. ...maybe. + * + * See Also: + * + * ------------------------------------------------------------------------ ** + */ +{ + auth_md5Ctx ctx[1]; + + FILE * file; + unsigned int blksize = 0; + unsigned int read = 0; + + file = fopen( src, "rb" ); + + if ( file == NULL ) + { return NULL; } - (void)auth_md5InitCtx( ctx ); /* Open a context. */ - - fseek (file , 0 , SEEK_END); - unsigned long long filesize = ftell(file); - rewind (file); - - if(filesize < 1048576) //1MB cache for files bigger than 1 MB - blksize = filesize; - else - blksize = 1048576; - - unsigned char * buffer = malloc(blksize); - - if(buffer == NULL){ - //no memory - fclose(file); - return NULL; - } - - do - { - read = fread(buffer, 1, blksize, file); - (void)auth_md5SumCtx( ctx, buffer, read ); /* Pass only one block. */ - - } while(read > 0); - - fclose(file); - free(buffer); + ( void )auth_md5InitCtx( ctx ); /* Open a context. */ - (void)auth_md5CloseCtx( ctx, dst ); /* Close the context. */ + fseek ( file , 0 , SEEK_END ); + unsigned long long filesize = ftell( file ); + rewind ( file ); + + if ( filesize < 1048576 ) //1MB cache for files bigger than 1 MB + blksize = filesize; + else + blksize = 1048576; + + unsigned char * buffer = malloc( blksize ); + + if ( buffer == NULL ) + { + //no memory + fclose( file ); + return NULL; + } + + do + { + read = fread( buffer, 1, blksize, file ); + ( void )auth_md5SumCtx( ctx, buffer, read ); /* Pass only one block. */ + + } + while ( read > 0 ); + + fclose( file ); + free( buffer ); + + ( void )auth_md5CloseCtx( ctx, dst ); /* Close the context. */ return( dst ); /* Makes life easy. */ - } /* auth_md5Sum */ - - -const char * MD5ToString(const unsigned char * hash, char * dst) -{ - char hexchar[3]; - short i = 0, n = 0; - - for (i = 0; i < 16; i++) - { - sprintf(hexchar, "%02X", hash[i]); - - dst[n++] = hexchar[0]; - dst[n++] = hexchar[1]; - } - - dst[n] = 0x00; - - return dst; -} - -unsigned char * StringToMD5(const char * hash, unsigned char * dst) -{ - char hexchar[2]; - short i = 0, n = 0; - - for (i = 0; i < 16; i++) - { - hexchar[0] = hash[n++]; - hexchar[1] = hash[n++]; - - dst[i] = STR2HEX(hexchar[0]); - dst[i] <<= 4; - dst[i] += STR2HEX(hexchar[1]); - } - - return dst; +} /* auth_md5Sum */ + + +const char * MD5ToString( const unsigned char * hash, char * dst ) +{ + char hexchar[3]; + short i = 0, n = 0; + + for ( i = 0; i < 16; i++ ) + { + sprintf( hexchar, "%02X", hash[i] ); + + dst[n++] = hexchar[0]; + dst[n++] = hexchar[1]; + } + + dst[n] = 0x00; + + return dst; +} + +unsigned char * StringToMD5( const char * hash, unsigned char * dst ) +{ + char hexchar[2]; + short i = 0, n = 0; + + for ( i = 0; i < 16; i++ ) + { + hexchar[0] = hash[n++]; + hexchar[1] = hash[n++]; + + dst[i] = STR2HEX( hexchar[0] ); + dst[i] <<= 4; + dst[i] += STR2HEX( hexchar[1] ); + } + + return dst; } diff --git a/source/banner/MD5.h b/source/banner/MD5.h index fb67ab25..df4d9e6b 100644 --- a/source/banner/MD5.h +++ b/source/banner/MD5.h @@ -1,246 +1,246 @@ -#ifndef MD5_H +#ifndef MD5_H #define MD5_H #ifdef __cplusplus extern "C" { -#endif -/* ========================================================================== ** - * - * MD5.h - * - * Copyright: - * Copyright (C) 2003-2005 by Christopher R. Hertel - * - * Email: crh@ubiqx.mn.org - * - * $Id: MD5.h,v 0.6 2005/06/08 18:35:59 crh Exp $ - * - * Modifications and additions by dimok - * - * -------------------------------------------------------------------------- ** - * - * Description: - * Implements the MD5 hash algorithm, as described in RFC 1321. - * - * -------------------------------------------------------------------------- ** - * - * License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * -------------------------------------------------------------------------- ** - * - * Notes: - * - * None of this will make any sense unless you're studying RFC 1321 as you - * read the code. - * - * MD5 is described in RFC 1321. - * The MD*4* algorithm is described in RFC 1320 (that's 1321 - 1). - * MD5 is very similar to MD4, but not quite similar enough to justify - * putting the two into a single module. Besides, I wanted to add a few - * extra functions to this one to expand its usability. - * - * There are three primary motivations for this particular implementation. - * 1) Programmer's pride. I wanted to be able to say I'd done it, and I - * wanted to learn from the experience. - * 2) Portability. I wanted an implementation that I knew to be portable - * to a reasonable number of platforms. In particular, the algorithm is - * designed with little-endian platforms in mind, but I wanted an - * endian-agnostic implementation. - * 3) Compactness. While not an overriding goal, I thought it worth-while - * to see if I could reduce the overall size of the result. This is in - * keeping with my hopes that this library will be suitable for use in - * some embedded environments. - * Beyond that, cleanliness and clarity are always worth pursuing. - * - * As mentioned above, the code really only makes sense if you are familiar - * with the MD5 algorithm or are using RFC 1321 as a guide. This code is - * quirky, however, so you'll want to be reading carefully. - * - * Yeah...most of the comments are cut-and-paste from my MD4 implementation. - * - * -------------------------------------------------------------------------- ** - * - * References: - * IETF RFC 1321: The MD5 Message-Digest Algorithm - * Ron Rivest. IETF, April, 1992 - * - * ========================================================================== ** - */ -/* -------------------------------------------------------------------------- ** - * Typedefs: - */ +#endif + /* ========================================================================== ** + * + * MD5.h + * + * Copyright: + * Copyright (C) 2003-2005 by Christopher R. Hertel + * + * Email: crh@ubiqx.mn.org + * + * $Id: MD5.h,v 0.6 2005/06/08 18:35:59 crh Exp $ + * + * Modifications and additions by dimok + * + * -------------------------------------------------------------------------- ** + * + * Description: + * Implements the MD5 hash algorithm, as described in RFC 1321. + * + * -------------------------------------------------------------------------- ** + * + * License: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * -------------------------------------------------------------------------- ** + * + * Notes: + * + * None of this will make any sense unless you're studying RFC 1321 as you + * read the code. + * + * MD5 is described in RFC 1321. + * The MD*4* algorithm is described in RFC 1320 (that's 1321 - 1). + * MD5 is very similar to MD4, but not quite similar enough to justify + * putting the two into a single module. Besides, I wanted to add a few + * extra functions to this one to expand its usability. + * + * There are three primary motivations for this particular implementation. + * 1) Programmer's pride. I wanted to be able to say I'd done it, and I + * wanted to learn from the experience. + * 2) Portability. I wanted an implementation that I knew to be portable + * to a reasonable number of platforms. In particular, the algorithm is + * designed with little-endian platforms in mind, but I wanted an + * endian-agnostic implementation. + * 3) Compactness. While not an overriding goal, I thought it worth-while + * to see if I could reduce the overall size of the result. This is in + * keeping with my hopes that this library will be suitable for use in + * some embedded environments. + * Beyond that, cleanliness and clarity are always worth pursuing. + * + * As mentioned above, the code really only makes sense if you are familiar + * with the MD5 algorithm or are using RFC 1321 as a guide. This code is + * quirky, however, so you'll want to be reading carefully. + * + * Yeah...most of the comments are cut-and-paste from my MD4 implementation. + * + * -------------------------------------------------------------------------- ** + * + * References: + * IETF RFC 1321: The MD5 Message-Digest Algorithm + * Ron Rivest. IETF, April, 1992 + * + * ========================================================================== ** + */ + /* -------------------------------------------------------------------------- ** + * Typedefs: + */ -typedef struct - { - unsigned int len; - unsigned int ABCD[4]; - int b_used; - unsigned char block[64]; - } auth_md5Ctx; + typedef struct + { + unsigned int len; + unsigned int ABCD[4]; + int b_used; + unsigned char block[64]; + } auth_md5Ctx; -/* -------------------------------------------------------------------------- ** - * Functions: - */ + /* -------------------------------------------------------------------------- ** + * Functions: + */ -auth_md5Ctx *auth_md5InitCtx( auth_md5Ctx *ctx ); - /* ------------------------------------------------------------------------ ** - * Initialize an MD5 context. - * - * Input: ctx - A pointer to the MD5 context structure to be initialized. - * Contexts are typically created thusly: - * ctx = (auth_md5Ctx *)malloc( sizeof(auth_md5Ctx) ); - * - * Output: A pointer to the initialized context (same as ). - * - * Notes: The purpose of the context is to make it possible to generate - * an MD5 Message Digest in stages, rather than having to pass a - * single large block to a single MD5 function. The context - * structure keeps track of various bits of state information. - * - * Once the context is initialized, the blocks of message data - * are passed to the function. Once the - * final bit of data has been handed to the - * context can be closed out by calling , - * which also calculates the final MD5 result. - * - * Don't forget to free an allocated context structure when - * you've finished using it. - * - * See Also: , - * - * ------------------------------------------------------------------------ ** - */ + auth_md5Ctx *auth_md5InitCtx( auth_md5Ctx *ctx ); + /* ------------------------------------------------------------------------ ** + * Initialize an MD5 context. + * + * Input: ctx - A pointer to the MD5 context structure to be initialized. + * Contexts are typically created thusly: + * ctx = (auth_md5Ctx *)malloc( sizeof(auth_md5Ctx) ); + * + * Output: A pointer to the initialized context (same as ). + * + * Notes: The purpose of the context is to make it possible to generate + * an MD5 Message Digest in stages, rather than having to pass a + * single large block to a single MD5 function. The context + * structure keeps track of various bits of state information. + * + * Once the context is initialized, the blocks of message data + * are passed to the function. Once the + * final bit of data has been handed to the + * context can be closed out by calling , + * which also calculates the final MD5 result. + * + * Don't forget to free an allocated context structure when + * you've finished using it. + * + * See Also: , + * + * ------------------------------------------------------------------------ ** + */ -auth_md5Ctx *auth_md5SumCtx( auth_md5Ctx *ctx, - const unsigned char *src, - const int len ); - /* ------------------------------------------------------------------------ ** - * Build an MD5 Message Digest within the given context. - * - * Input: ctx - Pointer to the context in which the MD5 sum is being - * built. - * src - A chunk of source data. This will be used to drive - * the MD5 algorithm. - * len - The number of bytes in . - * - * Output: A pointer to the updated context (same as ). - * - * See Also: , , - * - * ------------------------------------------------------------------------ ** - */ + auth_md5Ctx *auth_md5SumCtx( auth_md5Ctx *ctx, + const unsigned char *src, + const int len ); + /* ------------------------------------------------------------------------ ** + * Build an MD5 Message Digest within the given context. + * + * Input: ctx - Pointer to the context in which the MD5 sum is being + * built. + * src - A chunk of source data. This will be used to drive + * the MD5 algorithm. + * len - The number of bytes in . + * + * Output: A pointer to the updated context (same as ). + * + * See Also: , , + * + * ------------------------------------------------------------------------ ** + */ -auth_md5Ctx *auth_md5CloseCtx( auth_md5Ctx *ctx, unsigned char *dst ); - /* ------------------------------------------------------------------------ ** - * Close an MD5 Message Digest context and generate the final MD5 sum. - * - * Input: ctx - Pointer to the context in which the MD5 sum is being - * built. - * dst - A pointer to at least 16 bytes of memory, which will - * receive the finished MD5 sum. - * - * Output: A pointer to the closed context (same as ). - * You might use this to free a malloc'd context structure. :) - * - * Notes: The context () is returned in an undefined state. - * It must be re-initialized before re-use. - * - * See Also: , - * - * ------------------------------------------------------------------------ ** - */ + auth_md5Ctx *auth_md5CloseCtx( auth_md5Ctx *ctx, unsigned char *dst ); + /* ------------------------------------------------------------------------ ** + * Close an MD5 Message Digest context and generate the final MD5 sum. + * + * Input: ctx - Pointer to the context in which the MD5 sum is being + * built. + * dst - A pointer to at least 16 bytes of memory, which will + * receive the finished MD5 sum. + * + * Output: A pointer to the closed context (same as ). + * You might use this to free a malloc'd context structure. :) + * + * Notes: The context () is returned in an undefined state. + * It must be re-initialized before re-use. + * + * See Also: , + * + * ------------------------------------------------------------------------ ** + */ -unsigned char * MD5(unsigned char * hash, const unsigned char *src, const int len ); - /* ------------------------------------------------------------------------ ** - * Compute an MD5 message digest. - * - * Input: dst - Destination buffer into which the result will be written. - * Must be 16 bytes, minimum. - * src - Source data block to be MD5'd. - * len - The length, in bytes, of the source block. - * (Note that the length is given in bytes, not bits.) - * - * Output: A pointer to , which will contain the calculated 16-byte - * MD5 message digest. - * - * Notes: This function is a shortcut. It takes a single input block. - * For more drawn-out operations, see . - * - * This function is interface-compatible with the - * function in the MD4 module. - * - * The MD5 algorithm is designed to work on data with an - * arbitrary *bit* length. Most implementations, this one - * included, handle the input data in byte-sized chunks. - * - * The MD5 algorithm does much of its work using four-byte - * words, and so can be tuned for speed based on the endian-ness - * of the host. This implementation is intended to be - * endian-neutral, which may make it a teeny bit slower than - * others. ...maybe. - * - * See Also: - * - * ------------------------------------------------------------------------ ** - */ + unsigned char * MD5( unsigned char * hash, const unsigned char *src, const int len ); + /* ------------------------------------------------------------------------ ** + * Compute an MD5 message digest. + * + * Input: dst - Destination buffer into which the result will be written. + * Must be 16 bytes, minimum. + * src - Source data block to be MD5'd. + * len - The length, in bytes, of the source block. + * (Note that the length is given in bytes, not bits.) + * + * Output: A pointer to , which will contain the calculated 16-byte + * MD5 message digest. + * + * Notes: This function is a shortcut. It takes a single input block. + * For more drawn-out operations, see . + * + * This function is interface-compatible with the + * function in the MD4 module. + * + * The MD5 algorithm is designed to work on data with an + * arbitrary *bit* length. Most implementations, this one + * included, handle the input data in byte-sized chunks. + * + * The MD5 algorithm does much of its work using four-byte + * words, and so can be tuned for speed based on the endian-ness + * of the host. This implementation is intended to be + * endian-neutral, which may make it a teeny bit slower than + * others. ...maybe. + * + * See Also: + * + * ------------------------------------------------------------------------ ** + */ -unsigned char * MD5fromFile(unsigned char *dst, const char *src); - /* ------------------------------------------------------------------------ ** - * Compute an MD5 message digest. - * - * Input: dst - Destination buffer into which the result will be written. - * Must be 16 bytes, minimum. - * src - filepath to the file to be MD5'd. - * - * Output: A pointer to , which will contain the calculated 16-byte - * MD5 message digest. - * - * Notes: This function is a shortcut. It takes a single input block. - * For more drawn-out operations, see . - * - * This function is interface-compatible with the - * function in the MD4 module. - * - * The MD5 algorithm is designed to work on data with an - * arbitrary *bit* length. Most implementations, this one - * included, handle the input data in byte-sized chunks. - * - * The MD5 algorithm does much of its work using four-byte - * words, and so can be tuned for speed based on the endian-ness - * of the host. This implementation is intended to be - * endian-neutral, which may make it a teeny bit slower than - * others. ...maybe. - * - * See Also: - * - * ------------------------------------------------------------------------ ** - */ + unsigned char * MD5fromFile( unsigned char *dst, const char *src ); + /* ------------------------------------------------------------------------ ** + * Compute an MD5 message digest. + * + * Input: dst - Destination buffer into which the result will be written. + * Must be 16 bytes, minimum. + * src - filepath to the file to be MD5'd. + * + * Output: A pointer to , which will contain the calculated 16-byte + * MD5 message digest. + * + * Notes: This function is a shortcut. It takes a single input block. + * For more drawn-out operations, see . + * + * This function is interface-compatible with the + * function in the MD4 module. + * + * The MD5 algorithm is designed to work on data with an + * arbitrary *bit* length. Most implementations, this one + * included, handle the input data in byte-sized chunks. + * + * The MD5 algorithm does much of its work using four-byte + * words, and so can be tuned for speed based on the endian-ness + * of the host. This implementation is intended to be + * endian-neutral, which may make it a teeny bit slower than + * others. ...maybe. + * + * See Also: + * + * ------------------------------------------------------------------------ ** + */ -const char * MD5ToString(const unsigned char *hash, char *dst); -unsigned char * StringToMD5(const char * hash, unsigned char * dst); + const char * MD5ToString( const unsigned char *hash, char *dst ); + unsigned char * StringToMD5( const char * hash, unsigned char * dst ); -/* ========================================================================== */ - -#ifdef __cplusplus -} + /* ========================================================================== */ + +#ifdef __cplusplus +} #endif #endif /* AUTH_MD5_H */ diff --git a/source/banner/banner.c b/source/banner/banner.c index 62340b83..e7ce9dca 100644 --- a/source/banner/banner.c +++ b/source/banner/banner.c @@ -22,106 +22,107 @@ #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); + // Mount the disc + //Disc_SetWBFS(1, (u8*)discid); + Disc_SetUSB( discid ); - Disc_Open(); + Disc_Open(); - u64 offset; - s32 ret; + u64 offset; + s32 ret; - ret = __Disc_FindPartition(&offset); - if (ret < 0) - return ret; + ret = __Disc_FindPartition( &offset ); + if ( ret < 0 ) + return ret; - ret = WDVD_OpenPartition(offset); + ret = WDVD_OpenPartition( offset ); - if (ret < 0) { - //printf("ERROR: OpenPartition(0x%llx) %d\n", offset, ret); - return ret; - } + if ( ret < 0 ) + { + //printf("ERROR: OpenPartition(0x%llx) %d\n", offset, ret); + return ret; + } - // Read where to find the fst.bin - u32 *buffer = memalign(32, 0x20); + // Read where to find the fst.bin + u32 *buffer = memalign( 32, 0x20 ); - if (buffer == NULL) - { - //Out of memory - return -1; - } + if ( buffer == NULL ) + { + //Out of memory + return -1; + } - ret = WDVD_Read(buffer, 0x20, 0x420); - if (ret < 0) - return ret; + ret = WDVD_Read( buffer, 0x20, 0x420 ); + if ( ret < 0 ) + return ret; - // Read fst.bin - void *fstbuffer = memalign(32, buffer[2]*4); - FST_ENTRY *fst = (FST_ENTRY *)fstbuffer; + // Read fst.bin + void *fstbuffer = memalign( 32, buffer[2] * 4 ); + FST_ENTRY *fst = ( FST_ENTRY * )fstbuffer; - if (fst == NULL) - { - //Out of memory - free(buffer); - return -1; - } + if ( fst == NULL ) + { + //Out of memory + free( buffer ); + return -1; + } - ret = WDVD_Read(fstbuffer, buffer[2]*4, buffer[1]*4); - if (ret < 0) - return ret; + ret = WDVD_Read( fstbuffer, buffer[2] * 4, buffer[1] * 4 ); + if ( ret < 0 ) + return ret; - free(buffer); + free( buffer ); - // Search the fst.bin - u32 count = fst[0].filelen; - int i; - u32 index = 0; + // Search the fst.bin + u32 count = fst[0].filelen; + int i; + u32 index = 0; - for (i=1;iIsVisible()) - return; - - float currScale = this->GetScale(); - 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(); -} +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 d372baaf..85dfd5af 100644 --- a/source/banner/gui_banner.h +++ b/source/banner/gui_banner.h @@ -12,24 +12,24 @@ class GuiBanner : public GuiImage { -public: - //!Constructor - //!\param tplfilepath Path of the tpl file - 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); - //!Destructor - ~GuiBanner(); - void Draw(); -protected: - void * memory; - bool filecheck; - u32 tplfilesize; - GXTexObj texObj; + public: + //!Constructor + //!\param tplfilepath Path of the tpl file + 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 ); + //!Destructor + ~GuiBanner(); + void Draw(); + protected: + void * memory; + bool filecheck; + u32 tplfilesize; + GXTexObj texObj; }; #endif /* _GUIBANNER_H_ */ diff --git a/source/banner/openingbnr.c b/source/banner/openingbnr.c index 26b502d6..5edc1545 100644 --- a/source/banner/openingbnr.c +++ b/source/banner/openingbnr.c @@ -28,51 +28,52 @@ #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; + 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 { +typedef struct +{ u8 zeroes[0x40]; u32 imet; // "IMET" u8 zero_six_zero_three[8]; // fixed, unknown purpose @@ -89,441 +90,474 @@ typedef struct { u8 crypto[0x10]; } imet_data_t; -typedef struct { - u32 imd5_tag; // 0x494D4435 "IMD5"; - u32 size; // size of the rest of part B, starting from next field. - u8 zeroes[8]; - u8 md5[16]; - u32 payload_tag; // 0x4C5A3737 "LZ77" if this is lz77 - u32 payload_data; +typedef struct +{ + u32 imd5_tag; // 0x494D4435 "IMD5"; + u32 size; // size of the rest of part B, starting from next field. + u8 zeroes[8]; + u8 md5[16]; + u32 payload_tag; // 0x4C5A3737 "LZ77" if this is lz77 + u32 payload_data; } imd5_header_t; typedef struct { - u16 type; - u16 name_offset; - u32 data_offset; // == absolut offset från U.8- headerns början - u32 size; // last included file num for directories + u16 type; + u16 name_offset; + u32 data_offset; // == absolut offset från U.8- headerns början + u32 size; // last included file num for directories } U8_node; typedef struct { - u32 tag; // 0x55AA382D "U.8-" - u32 rootnode_offset; // offset to root_node, always 0x20. - u32 header_size; // size of header from root_node to end of string table. - u32 data_offset; // offset to data -- this is rootnode_offset + header_size, aligned to 0x40. - u8 zeroes[16]; + u32 tag; // 0x55AA382D "U.8-" + u32 rootnode_offset; // offset to root_node, always 0x20. + u32 header_size; // size of header from root_node to end of string table. + u32 data_offset; // offset to data -- this is rootnode_offset + header_size, aligned to 0x40. + u8 zeroes[16]; } U8_archive_header; -static int write_file(void* data, size_t size, char* name) +static int write_file( void* data, size_t size, char* name ) { - size_t written=0; - FILE *out; - out = fopen(name, "wb"); - if(out) - { - written = fwrite(data, 1, size, out); - fclose(out); - } - return (written == size) ? 1 : -1; + size_t written = 0; + FILE *out; + out = fopen( name, "wb" ); + if ( out ) + { + written = fwrite( data, 1, size, out ); + fclose( out ); + } + return ( written == size ) ? 1 : -1; } -u8* decompress_lz77(u8 *data, size_t data_size, size_t* decompressed_size) +u8* decompress_lz77( u8 *data, size_t data_size, size_t* decompressed_size ) { - u8 *data_end; - u8 *decompressed_data; - size_t unpacked_size; - u8 *in_ptr; - u8 *out_ptr; - u8 *out_end; + u8 *data_end; + u8 *decompressed_data; + size_t unpacked_size; + u8 *in_ptr; + u8 *out_ptr; + u8 *out_end; - in_ptr = data; - data_end = data + data_size; + in_ptr = data; + data_end = data + data_size; - // Assume this for now and grow when needed - unpacked_size = data_size; + // Assume this for now and grow when needed + unpacked_size = data_size; - decompressed_data = malloc(unpacked_size); - out_end = decompressed_data + unpacked_size; + decompressed_data = malloc( unpacked_size ); + out_end = decompressed_data + unpacked_size; - out_ptr = decompressed_data; + out_ptr = decompressed_data; - while (in_ptr < data_end) { - int bit; - u8 bitmask = *in_ptr; + while ( in_ptr < data_end ) + { + int bit; + u8 bitmask = *in_ptr; - in_ptr++; - for (bit = 0x80; bit != 0; bit >>= 1) { - if (bitmask & bit) { - // Next section is compressed - u8 rep_length; - u16 rep_offset; + in_ptr++; + for ( bit = 0x80; bit != 0; bit >>= 1 ) + { + if ( bitmask & bit ) + { + // Next section is compressed + u8 rep_length; + u16 rep_offset; - rep_length = (*in_ptr >> 4) + 3; - rep_offset = *in_ptr & 0x0f; - in_ptr++; - rep_offset = *in_ptr | (rep_offset << 8); - in_ptr++; - if (out_ptr-decompressed_data < rep_offset) { - return NULL; - } + rep_length = ( *in_ptr >> 4 ) + 3; + rep_offset = *in_ptr & 0x0f; + in_ptr++; + rep_offset = *in_ptr | ( rep_offset << 8 ); + in_ptr++; + if ( out_ptr - decompressed_data < rep_offset ) + { + return NULL; + } - for ( ; rep_length > 0; rep_length--) { - *out_ptr = out_ptr[-rep_offset-1]; - out_ptr++; - if (out_ptr >= out_end) { - // Need to grow buffer - decompressed_data = realloc(decompressed_data, unpacked_size*2); - out_ptr = decompressed_data + unpacked_size; - unpacked_size *= 2; - out_end = decompressed_data + unpacked_size; - } + for ( ; rep_length > 0; rep_length-- ) + { + *out_ptr = out_ptr[-rep_offset-1]; + out_ptr++; + if ( out_ptr >= out_end ) + { + // Need to grow buffer + decompressed_data = realloc( decompressed_data, unpacked_size * 2 ); + out_ptr = decompressed_data + unpacked_size; + unpacked_size *= 2; + out_end = decompressed_data + unpacked_size; + } + } + } + else + { + // Just copy byte + *out_ptr = *in_ptr; + out_ptr++; + if ( out_ptr >= out_end ) + { + // Need to grow buffer + decompressed_data = realloc( decompressed_data, unpacked_size * 2 ); + out_ptr = decompressed_data + unpacked_size; + unpacked_size *= 2; + out_end = decompressed_data + unpacked_size; + } + in_ptr++; + } } - } else { - // Just copy byte - *out_ptr = *in_ptr; - out_ptr++; - if (out_ptr >= out_end) { - // Need to grow buffer - decompressed_data = realloc(decompressed_data, unpacked_size*2); - out_ptr = decompressed_data + unpacked_size; - unpacked_size *= 2; - out_end = decompressed_data + unpacked_size; - } - in_ptr++; - } - } - } + } - *decompressed_size = (out_ptr - decompressed_data); - return decompressed_data; + *decompressed_size = ( out_ptr - decompressed_data ); + return decompressed_data; } -static int write_imd5_lz77(u8* data, size_t size, char* outname) +static int write_imd5_lz77( u8* data, size_t size, char* outname ) { - imd5_header_t* header = (imd5_header_t*) data; - u32 tag; - u32 size_in_imd5; + imd5_header_t* header = ( imd5_header_t* ) data; + u32 tag; + u32 size_in_imd5; u8 md5_calc[16]; - u8 *decompressed_data; - size_t decompressed_size; + u8 *decompressed_data; + size_t decompressed_size; - tag = be32((u8*) &header->imd5_tag); - if (tag != 0x494D4435) { - return -4; - } + tag = be32( ( u8* ) & header->imd5_tag ); + if ( tag != 0x494D4435 ) + { + return -4; + } - md5(data+32, size-32, md5_calc); - if (memcmp(&header->md5, md5_calc, 0x10)) { - return -5; - } + md5( data + 32, size - 32, md5_calc ); + if ( memcmp( &header->md5, md5_calc, 0x10 ) ) + { + return -5; + } - size_in_imd5 = be32((u8*) &header->size); - if (size_in_imd5 != size - 32) { - return -6; - } + size_in_imd5 = be32( ( u8* ) & header->size ); + if ( size_in_imd5 != size - 32 ) + { + return -6; + } - tag = be32((u8*) &header->payload_tag); - if (tag == 0x4C5A3737) { - // "LZ77" - uncompress - decompressed_data = decompress_lz77(data + sizeof(imd5_header_t), size - sizeof(imd5_header_t), &decompressed_size); - if(decompressed_data == NULL) - return -7; - write_file(decompressed_data, decompressed_size, outname); - //printf(", uncompressed %d bytes, md5 ok", decompressed_size); + tag = be32( ( u8* ) & header->payload_tag ); + if ( tag == 0x4C5A3737 ) + { + // "LZ77" - uncompress + decompressed_data = decompress_lz77( data + sizeof( imd5_header_t ), size - sizeof( imd5_header_t ), &decompressed_size ); + if ( decompressed_data == NULL ) + return -7; + write_file( decompressed_data, decompressed_size, outname ); + //printf(", uncompressed %d bytes, md5 ok", decompressed_size); - free(decompressed_data); - } else { - write_file(&header->payload_tag, size-32, outname); - //printf(", md5 ok"); - } - return 0; + free( decompressed_data ); + } + else + { + write_file( &header->payload_tag, size - 32, outname ); + //printf(", md5 ok"); + } + return 0; } -static int do_U8_archive(FILE *fp) +static int do_U8_archive( FILE *fp ) { - U8_archive_header header; - U8_node root_node; - u32 tag; - u32 num_nodes; - U8_node* nodes; - u8* string_table; - size_t rest_size; - unsigned int i; - u32 data_offset; - u32 current_offset; - u16 dir_stack[16]; - int dir_index = 0; + U8_archive_header header; + U8_node root_node; + u32 tag; + u32 num_nodes; + U8_node* nodes; + u8* string_table; + size_t rest_size; + unsigned int i; + u32 data_offset; + u32 current_offset; + u16 dir_stack[16]; + int dir_index = 0; - fread(&header, 1, sizeof header, fp); - tag = be32((u8*) &header.tag); - if (tag != 0x55AA382D) { - return -1; - } + fread( &header, 1, sizeof header, fp ); + tag = be32( ( u8* ) & header.tag ); + if ( tag != 0x55AA382D ) + { + return -1; + } - fread(&root_node, 1, sizeof(root_node), fp); - num_nodes = be32((u8*) &root_node.size) - 1; - //printf("Number of files: %d\n", num_nodes); + fread( &root_node, 1, sizeof( root_node ), fp ); + num_nodes = be32( ( u8* ) & root_node.size ) - 1; + //printf("Number of files: %d\n", num_nodes); - nodes = malloc(sizeof(U8_node) * (num_nodes)); - fread(nodes, 1, num_nodes * sizeof(U8_node), fp); + nodes = malloc( sizeof( U8_node ) * ( num_nodes ) ); + fread( nodes, 1, num_nodes * sizeof( U8_node ), fp ); - data_offset = be32((u8*) &header.data_offset); - rest_size = data_offset - sizeof(header) - (num_nodes+1)*sizeof(U8_node); + data_offset = be32( ( u8* ) & header.data_offset ); + rest_size = data_offset - sizeof( header ) - ( num_nodes + 1 ) * sizeof( U8_node ); - string_table = malloc(rest_size); - fread(string_table, 1, rest_size, fp); + string_table = malloc( rest_size ); + fread( string_table, 1, rest_size, fp ); current_offset = data_offset; - for (i = 0; i < num_nodes; i++) { - U8_node* node = &nodes[i]; - u16 type = be16((u8*)&node->type); - u16 name_offset = be16((u8*)&node->name_offset); - u32 my_data_offset = be32((u8*)&node->data_offset); - u32 size = be32((u8*)&node->size); - char* name = (char*) &string_table[name_offset]; - u8* file_data; + for ( i = 0; i < num_nodes; i++ ) + { + U8_node* node = &nodes[i]; + u16 type = be16( ( u8* ) & node->type ); + u16 name_offset = be16( ( u8* ) & node->name_offset ); + u32 my_data_offset = be32( ( u8* ) & node->data_offset ); + u32 size = be32( ( u8* ) & node->size ); + char* name = ( char* ) & string_table[name_offset]; + u8* file_data; - if (type == 0x0100) { - // Directory - mkdir(name, 0777); - chdir(name); - dir_stack[++dir_index] = size; - //printf("%*s%s/\n", dir_index, "", name); - } else { - // Normal file - u8 padding[32]; - - if (type != 0x0000) { - free(string_table); - return -2; - } - - if (current_offset < my_data_offset) { - int diff = my_data_offset - current_offset; - - if (diff > 32) { - free(string_table); - return -3; + if ( type == 0x0100 ) + { + // Directory + mkdir( name, 0777 ); + chdir( name ); + dir_stack[++dir_index] = size; + //printf("%*s%s/\n", dir_index, "", name); } - fread(padding, 1, diff, fp); - current_offset += diff; - } + else + { + // Normal file + u8 padding[32]; - file_data = malloc(size); - fread(file_data, 1, size, fp); - //printf("%*s %s (%d bytes", dir_index, "", name, size); - int result; - result = write_imd5_lz77(file_data, size, name); - if(result < 0) - {free(string_table); - return result; - } - //printf(")\n"); - current_offset += size; + if ( type != 0x0000 ) + { + free( string_table ); + return -2; + } + + if ( current_offset < my_data_offset ) + { + int diff = my_data_offset - current_offset; + + if ( diff > 32 ) + { + free( string_table ); + return -3; + } + fread( padding, 1, diff, fp ); + current_offset += diff; + } + + file_data = malloc( size ); + fread( file_data, 1, size, fp ); + //printf("%*s %s (%d bytes", dir_index, "", name, size); + int result; + result = write_imd5_lz77( file_data, size, name ); + if ( result < 0 ) + { + free( string_table ); + return result; + } + //printf(")\n"); + current_offset += size; + } + + while ( dir_stack[dir_index] == i + 2 && dir_index > 0 ) + { + chdir( ".." ); + dir_index--; + } + } + free( string_table ); + return 0; +} + +static void do_imet_header( FILE *fp ) +{ + imet_data_t header; + + fread( &header, 1, sizeof header, fp ); + + write_file( &header, sizeof( header ), "header.imet" ); +} + +void do_U8_archivebanner( FILE *fp ) +{ + U8_archive_header header; + U8_node root_node; + u32 tag; + u32 num_nodes; + U8_node* nodes; + u8* string_table; + size_t rest_size; + unsigned int i; + u32 data_offset; + u16 dir_stack[16]; + int dir_index = 0; + + fread( &header, 1, sizeof header, fp ); + tag = be32( ( u8* ) & header.tag ); + if ( tag != 0x55AA382D ) + { + //printf("No U8 tag"); + exit( 0 ); } - while (dir_stack[dir_index] == i+2 && dir_index > 0) { - chdir(".."); - dir_index--; + fread( &root_node, 1, sizeof( root_node ), fp ); + num_nodes = be32( ( u8* ) & root_node.size ) - 1; + printf( "Number of files: %d\n", num_nodes ); + + nodes = malloc( sizeof( U8_node ) * ( num_nodes ) ); + fread( nodes, 1, num_nodes * sizeof( U8_node ), fp ); + + data_offset = be32( ( u8* ) & header.data_offset ); + rest_size = data_offset - sizeof( header ) - ( num_nodes + 1 ) * sizeof( U8_node ); + + string_table = malloc( rest_size ); + fread( string_table, 1, rest_size, fp ); + + for ( i = 0; i < num_nodes; i++ ) + { + U8_node* node = &nodes[i]; + u16 type = be16( ( u8* ) & node->type ); + u16 name_offset = be16( ( u8* ) & node->name_offset ); + u32 my_data_offset = be32( ( u8* ) & node->data_offset ); + u32 size = be32( ( u8* ) & node->size ); + char* name = ( char* ) & string_table[name_offset]; + u8* file_data; + + if ( type == 0x0100 ) + { + // Directory + mkdir( name, 0777 ); + chdir( name ); + dir_stack[++dir_index] = size; + //printf("%*s%s/\n", dir_index, "", name); + } + else + { + // Normal file + + if ( type != 0x0000 ) + { + printf( "Unknown type" ); + exit( 0 ); + } + + fseek( fp, my_data_offset, SEEK_SET ); + file_data = malloc( size ); + fread( file_data, 1, size, fp ); + write_file( file_data, size, name ); + free( file_data ); + //printf("%*s %s (%d bytes)\n", dir_index, "", name, size); + } + + while ( dir_stack[dir_index] == i + 2 && dir_index > 0 ) + { + chdir( ".." ); + dir_index--; + } } - } - free(string_table); - return 0; + free( string_table ); } -static void do_imet_header(FILE *fp) -{ - imet_data_t header; - - fread(&header, 1, sizeof header, fp); - - write_file(&header, sizeof(header), "header.imet"); -} - -void do_U8_archivebanner(FILE *fp) -{ - U8_archive_header header; - U8_node root_node; - u32 tag; - u32 num_nodes; - U8_node* nodes; - u8* string_table; - size_t rest_size; - unsigned int i; - u32 data_offset; - u16 dir_stack[16]; - int dir_index = 0; - - fread(&header, 1, sizeof header, fp); - tag = be32((u8*) &header.tag); - if (tag != 0x55AA382D) { - //printf("No U8 tag"); - exit(0); - } - - fread(&root_node, 1, sizeof(root_node), fp); - num_nodes = be32((u8*) &root_node.size) - 1; - printf("Number of files: %d\n", num_nodes); - - nodes = malloc(sizeof(U8_node) * (num_nodes)); - fread(nodes, 1, num_nodes * sizeof(U8_node), fp); - - data_offset = be32((u8*) &header.data_offset); - rest_size = data_offset - sizeof(header) - (num_nodes+1)*sizeof(U8_node); - - string_table = malloc(rest_size); - fread(string_table, 1, rest_size, fp); - - for (i = 0; i < num_nodes; i++) { - U8_node* node = &nodes[i]; - u16 type = be16((u8*)&node->type); - u16 name_offset = be16((u8*)&node->name_offset); - u32 my_data_offset = be32((u8*)&node->data_offset); - u32 size = be32((u8*)&node->size); - char* name = (char*) &string_table[name_offset]; - u8* file_data; - - if (type == 0x0100) { - // Directory - mkdir(name, 0777); - chdir(name); - dir_stack[++dir_index] = size; - //printf("%*s%s/\n", dir_index, "", name); - } else { - // Normal file - - if (type != 0x0000) { - printf("Unknown type"); - exit(0); - } - - fseek(fp, my_data_offset, SEEK_SET); - file_data = malloc(size); - fread(file_data, 1, size, fp); - write_file(file_data, size, name); - free(file_data); - //printf("%*s %s (%d bytes)\n", dir_index, "", name, size); - } - - while (dir_stack[dir_index] == i+2 && dir_index > 0) { - chdir(".."); - dir_index--; - } - } - free(string_table); -} - -int extractbnrfile(const char * filepath, const char * destpath) +int extractbnrfile( const char * filepath, const char * destpath ) { int ret = -1; - FILE *fp = fopen(filepath, "rb"); - if(fp) - { - subfoldercreate(destpath); - chdir(destpath); + FILE *fp = fopen( filepath, "rb" ); + if ( fp ) + { + subfoldercreate( destpath ); + chdir( destpath ); - do_imet_header(fp); - ret = do_U8_archive(fp); + do_imet_header( fp ); + ret = do_U8_archive( fp ); - fclose(fp); - } - return ret; + fclose( fp ); + } + return ret; } -int unpackBin(const char * filename,const char * outdir) +int unpackBin( const char * filename, const char * outdir ) { - FILE *fp = fopen(filename,"rb");; - if(fp) - { - subfoldercreate(outdir); - chdir(outdir); + FILE *fp = fopen( filename, "rb" );; + if ( fp ) + { + subfoldercreate( outdir ); + chdir( outdir ); - do_U8_archivebanner(fp); - fclose(fp); - return 1; - } - return 0; + do_U8_archivebanner( fp ); + fclose( fp ); + return 1; + } + return 0; } #define TMP_PATH(s) "BANNER:/dump"s //#define TMP_PATH(s) "SD:/dump"s -int unpackBanner(const u8 *gameid, int what, const char *outdir) +int unpackBanner( const u8 *gameid, int what, const char *outdir ) { - char path[256]; - if(!ramdiskMount("BANNER", NULL)) return -1; + char path[256]; + if ( !ramdiskMount( "BANNER", NULL ) ) return -1; - subfoldercreate(TMP_PATH("/")); - s32 ret = dump_banner(gameid, TMP_PATH("/opening.bnr")); - if (ret != 1) - { - ret = -1; - goto error2; - } + subfoldercreate( TMP_PATH( "/" ) ); + s32 ret = dump_banner( gameid, TMP_PATH( "/opening.bnr" ) ); + if ( ret != 1 ) + { + ret = -1; + goto error2; + } - ret = extractbnrfile(TMP_PATH("/opening.bnr"), TMP_PATH("/")); - if (ret != 0) - { - ret = -1; - goto error2; - } + ret = extractbnrfile( TMP_PATH( "/opening.bnr" ), TMP_PATH( "/" ) ); + if ( ret != 0 ) + { + ret = -1; + goto error2; + } - if(what & UNPACK_BANNER_BIN) - { - snprintf(path, sizeof(path),"%sbanner/", outdir); - ret = unpackBin(TMP_PATH("/meta/banner.bin"), path); - if (ret != 1) - { - ret = -1; - goto error2; - } - } - if(what & UNPACK_ICON_BIN) - { - snprintf(path, sizeof(path),"%sicon/", outdir); - ret = unpackBin(TMP_PATH("/meta/icon.bin"), path); - if (ret != 1) - { - ret = -1; - goto error2; - } - } - if(what & UNPACK_SOUND_BIN) - { - snprintf(path, sizeof(path),"%ssound.bin", outdir); - FILE *fp = fopen(TMP_PATH("/meta/sound.bin"), "rb"); - if(fp) - { - size_t size; - u8 *data; - fseek(fp, 0, SEEK_END); - size = ftell(fp); - if(!size) - { - ret = -1; - goto error; - } - fseek(fp, 0, SEEK_SET); - data = (u8 *)malloc(size); - if(!data) - { - ret = -1; - goto error; - } - if(fread(data, 1, size, fp) != size) - { - ret = -1; - goto error; - } - ret = write_file(data, size, path); - } -error: fclose(fp); - } - ramdiskUnmount("BANNER"); + if ( what & UNPACK_BANNER_BIN ) + { + snprintf( path, sizeof( path ), "%sbanner/", outdir ); + ret = unpackBin( TMP_PATH( "/meta/banner.bin" ), path ); + if ( ret != 1 ) + { + ret = -1; + goto error2; + } + } + if ( what & UNPACK_ICON_BIN ) + { + snprintf( path, sizeof( path ), "%sicon/", outdir ); + ret = unpackBin( TMP_PATH( "/meta/icon.bin" ), path ); + if ( ret != 1 ) + { + ret = -1; + goto error2; + } + } + if ( what & UNPACK_SOUND_BIN ) + { + snprintf( path, sizeof( path ), "%ssound.bin", outdir ); + FILE *fp = fopen( TMP_PATH( "/meta/sound.bin" ), "rb" ); + if ( fp ) + { + size_t size; + u8 *data; + fseek( fp, 0, SEEK_END ); + size = ftell( fp ); + if ( !size ) + { + ret = -1; + goto error; + } + fseek( fp, 0, SEEK_SET ); + data = ( u8 * )malloc( size ); + if ( !data ) + { + ret = -1; + goto error; + } + if ( fread( data, 1, size, fp ) != size ) + { + ret = -1; + goto error; + } + ret = write_file( data, size, path ); + } +error: fclose( fp ); + } + ramdiskUnmount( "BANNER" ); error2: - if(ret < 0) - return ret; - return 1; + if ( ret < 0 ) + return ret; + return 1; } diff --git a/source/banner/openingbnr.h b/source/banner/openingbnr.h index 3142fba0..806327cd 100644 --- a/source/banner/openingbnr.h +++ b/source/banner/openingbnr.h @@ -13,32 +13,32 @@ 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); -#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 */ + int extractbnrfile( const char * filepath, const char * destpath ); + int unpackBin( const char * filename, const char * outdir ); +#define UNPACK_BANNER_BIN 1 /* extract banner.bin to outdir/banner/ */ +#define UNPACK_ICON_BIN 2 /* extract icon.bin to outdir/icon/ */ +#define UNPACK_SOUND_BIN 4 /* copies sound.bin to outdir/sound.bin */ #define UNPACK_ALL (UNPACK_SOUND_BIN | UNPACK_ICON_BIN | UNPACK_BANNER_BIN) -int unpackBanner(const u8 * gameid, int what, const char *outdir); + int unpackBanner( const u8 * gameid, int what, const char *outdir ); //! Extract the lz77 compressed banner, icon and sound .bin -u8* decompress_lz77(u8 *data, size_t data_size, size_t* decompressed_size); + u8* decompress_lz77( u8 *data, size_t data_size, size_t* decompressed_size ); -u16 be16(const u8 *p); -u32 be32(const u8 *p); + u16 be16( const u8 *p ); + u32 be32( const u8 *p ); #ifdef __cplusplus } diff --git a/source/bannersound.cpp b/source/bannersound.cpp index 3abe5f0f..4ef64f32 100644 --- a/source/bannersound.cpp +++ b/source/bannersound.cpp @@ -13,197 +13,197 @@ 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); + u8 *buffer = NULL; + if ( inLength <= 0x8 || *( ( const u32 * )inBuf ) != 0x4C5A3737 /*"LZ77"*/ || inBuf[4] != 0x10 ) + return NULL; + u32 uncSize = le32( ( ( const u32 * )inBuf )[1] << 8 ); - const u8 *inBufEnd = inBuf + inLength; - inBuf += 8; - buffer = new(std::nothrow) u8[uncSize]; - if (!buffer) - return buffer; + const u8 *inBufEnd = inBuf + inLength; + inBuf += 8; + buffer = new( std::nothrow ) u8[uncSize]; + if ( !buffer ) + return buffer; - u8 *bufCur = buffer; - u8 *bufEnd = buffer + uncSize; + u8 *bufCur = buffer; + u8 *bufEnd = buffer + uncSize; - while (bufCur < bufEnd && inBuf < inBufEnd) - { - u8 flags = *inBuf; - ++inBuf; - for (int i = 0; i < 8 && bufCur < bufEnd && inBuf < inBufEnd; ++i) - { - if ((flags & 0x80) != 0) - { - const LZ77Info &info = *(const LZ77Info *)inBuf; - inBuf += sizeof (LZ77Info); - int length = info.length + 3; - if (bufCur - info.offset - 1 < buffer || bufCur + length > bufEnd) - return buffer; - memcpy(bufCur, bufCur - info.offset - 1, length); - bufCur += length; - } - else - { - *bufCur = *inBuf; - ++inBuf; - ++bufCur; - } - flags <<= 1; - } - } - size = uncSize; - return buffer; + while ( bufCur < bufEnd && inBuf < inBufEnd ) + { + u8 flags = *inBuf; + ++inBuf; + for ( int i = 0; i < 8 && bufCur < bufEnd && inBuf < inBufEnd; ++i ) + { + if ( ( flags & 0x80 ) != 0 ) + { + const LZ77Info &info = *( const LZ77Info * )inBuf; + inBuf += sizeof ( LZ77Info ); + int length = info.length + 3; + if ( bufCur - info.offset - 1 < buffer || bufCur + length > bufEnd ) + return buffer; + memcpy( bufCur, bufCur - info.offset - 1, length ); + bufCur += length; + } + else + { + *bufCur = *inBuf; + ++inBuf; + ++bufCur; + } + flags <<= 1; + } + } + size = uncSize; + return buffer; } -const u8 *LoadBannerSound(const u8 *discid, u32 *size) +const u8 *LoadBannerSound( const u8 *discid, u32 *size ) { - if(!discid) + if ( !discid ) return NULL; - Disc_SetUSB(NULL); - wbfs_disc_t *disc = WBFS_OpenDisc((u8 *) discid); - if(!disc) - { - // WindowPrompt(tr("Can't find disc"), 0, tr("OK")); + Disc_SetUSB( NULL ); + wbfs_disc_t *disc = WBFS_OpenDisc( ( u8 * ) discid ); + if ( !disc ) + { + // WindowPrompt(tr("Can't find disc"), 0, tr("OK")); return NULL; - } - wiidisc_t *wdisc = wd_open_disc((int (*)(void *, u32, u32, void *))wbfs_disc_read, disc); - if(!wdisc) - { - //WindowPrompt(tr("Could not open Disc"), 0, tr("OK")); + } + wiidisc_t *wdisc = wd_open_disc( ( int ( * )( void *, u32, u32, void * ) )wbfs_disc_read, disc ); + if ( !wdisc ) + { + //WindowPrompt(tr("Could not open Disc"), 0, tr("OK")); return NULL; - } - u8 * opening_bnr = wd_extract_file(wdisc, ALL_PARTITIONS, (char *) "opening.bnr"); - if(!opening_bnr) - { - //WindowPrompt(tr("ERROR"), tr("Failed to extract opening.bnr"), tr("OK")); + } + u8 * opening_bnr = wd_extract_file( wdisc, ALL_PARTITIONS, ( char * ) "opening.bnr" ); + if ( !opening_bnr ) + { + //WindowPrompt(tr("ERROR"), tr("Failed to extract opening.bnr"), tr("OK")); return NULL; - } + } - wd_close_disc(wdisc); - WBFS_CloseDisc(disc); + wd_close_disc( wdisc ); + WBFS_CloseDisc( disc ); - const U8Entry *fst; + const U8Entry *fst; - const IMETHeader *imetHdr = (IMETHeader *)opening_bnr; - if ( imetHdr->fcc != 0x494D4554 /*"IMET"*/ ) - { - // WindowPrompt(tr("IMET Header wrong."), 0, tr("OK")); - free(opening_bnr); + const IMETHeader *imetHdr = ( IMETHeader * )opening_bnr; + if ( imetHdr->fcc != 0x494D4554 /*"IMET"*/ ) + { + // WindowPrompt(tr("IMET Header wrong."), 0, tr("OK")); + free( opening_bnr ); return NULL; - } - const U8Header *bnrArcHdr = (U8Header *)(imetHdr + 1); + } + const U8Header *bnrArcHdr = ( U8Header * )( imetHdr + 1 ); - fst = (const U8Entry *)( ((const u8 *)bnrArcHdr) + bnrArcHdr->rootNodeOffset); - u32 i; - for (i = 1; i < fst[0].numEntries; ++i) - if (fst[i].fileType == 0 && strcasecmp(u8Filename(fst, i), "sound.bin") == 0) - break; - if (i >= fst[0].numEntries) - { - /* Not all games have a sound.bin and this message is annoying **/ - //WindowPrompt(tr("sound.bin not found."), 0, tr("OK")); - free(opening_bnr); + fst = ( const U8Entry * )( ( ( const u8 * )bnrArcHdr ) + bnrArcHdr->rootNodeOffset ); + u32 i; + for ( i = 1; i < fst[0].numEntries; ++i ) + if ( fst[i].fileType == 0 && strcasecmp( u8Filename( fst, i ), "sound.bin" ) == 0 ) + break; + if ( i >= fst[0].numEntries ) + { + /* Not all games have a sound.bin and this message is annoying **/ + //WindowPrompt(tr("sound.bin not found."), 0, tr("OK")); + free( opening_bnr ); return NULL; - } - const u8 *sound_bin = ((const u8 *)bnrArcHdr) + fst[i].fileOffset; - if ( ((IMD5Header *)sound_bin)->fcc != 0x494D4435 /*"IMD5"*/ ) - { - // WindowPrompt(tr("IMD5 Header not right."), 0, tr("OK")); - free(opening_bnr); + } + const u8 *sound_bin = ( ( const u8 * )bnrArcHdr ) + fst[i].fileOffset; + if ( ( ( IMD5Header * )sound_bin )->fcc != 0x494D4435 /*"IMD5"*/ ) + { + // WindowPrompt(tr("IMD5 Header not right."), 0, tr("OK")); + free( opening_bnr ); return NULL; - } - const u8 *soundChunk = sound_bin + sizeof (IMD5Header);; - u32 soundChunkSize = fst[i].fileLength - sizeof (IMD5Header); + } + const u8 *soundChunk = sound_bin + sizeof ( IMD5Header );; + u32 soundChunkSize = fst[i].fileLength - sizeof ( IMD5Header ); - if ( *((u32*)soundChunk) == 0x4C5A3737 /*"LZ77"*/ ) - { - u32 uncSize = NULL; - u8 * uncompressed_data = uncompressLZ77(soundChunk, soundChunkSize, uncSize); - if (!uncompressed_data) - { - // WindowPrompt(tr("Can't decompress LZ77"), 0, tr("OK")); - free(opening_bnr); - return NULL; - } - if(size) *size=uncSize; - free(opening_bnr); - return uncompressed_data; - } - u8 *out = new(std::nothrow) u8[soundChunkSize]; - if(out) - { - memcpy(out, soundChunk, soundChunkSize); - if(size) *size=soundChunkSize; - } - free(opening_bnr); - return out; + if ( *( ( u32* )soundChunk ) == 0x4C5A3737 /*"LZ77"*/ ) + { + u32 uncSize = NULL; + u8 * uncompressed_data = uncompressLZ77( soundChunk, soundChunkSize, uncSize ); + if ( !uncompressed_data ) + { + // WindowPrompt(tr("Can't decompress LZ77"), 0, tr("OK")); + free( opening_bnr ); + return NULL; + } + if ( size ) *size = uncSize; + free( opening_bnr ); + return uncompressed_data; + } + u8 *out = new( std::nothrow ) u8[soundChunkSize]; + if ( out ) + { + memcpy( out, soundChunk, soundChunkSize ); + if ( size ) *size = soundChunkSize; + } + free( opening_bnr ); + return out; } diff --git a/source/bannersound.h b/source/bannersound.h index 6cf7b526..a91223f9 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 43b0db2a..012245f9 100644 --- a/source/cheats/cheatmenu.cpp +++ b/source/cheats/cheatmenu.cpp @@ -23,143 +23,160 @@ extern GuiWindow * mainWindow; /**************************************************************************** * CheatMenu ***************************************************************************/ -int CheatMenu(const char * gameID) { - int choice = 0; - bool exit = false; - int ret = 1; +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); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path); - GuiImageData settingsbg(imgPath, settings_background_png); - GuiImage settingsbackground(&settingsbg); + char imgPath[100]; + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%ssettings_background.png", CFG.theme_path ); + GuiImageData settingsbg( imgPath, settings_background_png ); + GuiImage settingsbackground( &settingsbg ); - GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiTrigger trigB; - trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); + GuiTrigger trigA; + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + GuiTrigger trigB; + trigB.SetButtonOnlyTrigger( -1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B ); - GuiText backBtnTxt(tr("Back") , 22, THEME.prompttext); - backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); - GuiImage backBtnImg(&btnOutline); - GuiButton backBtn(&backBtnImg,&backBtnImg, 2, 3, -140, 400, &trigA, NULL, btnClick2,1); - backBtn.SetLabel(&backBtnTxt); - backBtn.SetTrigger(&trigB); + GuiText backBtnTxt( tr( "Back" ) , 22, THEME.prompttext ); + backBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); + GuiImage backBtnImg( &btnOutline ); + GuiButton backBtn( &backBtnImg, &backBtnImg, 2, 3, -140, 400, &trigA, NULL, btnClick2, 1 ); + backBtn.SetLabel( &backBtnTxt ); + backBtn.SetTrigger( &trigB ); - GuiText createBtnTxt(tr("Create") , 22, THEME.prompttext); - createBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); - GuiImage createBtnImg(&btnOutline); - GuiButton createBtn(&createBtnImg,&createBtnImg, 2, 3, 160, 400, &trigA, NULL, btnClick2,1); - createBtn.SetLabel(&createBtnTxt); + GuiText createBtnTxt( tr( "Create" ) , 22, THEME.prompttext ); + createBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); + GuiImage createBtnImg( &btnOutline ); + GuiButton createBtn( &createBtnImg, &createBtnImg, 2, 3, 160, 400, &trigA, NULL, btnClick2, 1 ); + createBtn.SetLabel( &createBtnTxt ); - char txtfilename[55]; - snprintf(txtfilename,sizeof(txtfilename),"%s%s.txt",Settings.TxtCheatcodespath,gameID); + char txtfilename[55]; + snprintf( txtfilename, sizeof( txtfilename ), "%s%s.txt", Settings.TxtCheatcodespath, gameID ); - GCTCheats c; - int check = c.openTxtfile(txtfilename); + GCTCheats c; + int check = c.openTxtfile( txtfilename ); - int download =0; + int download = 0; - switch (check) { - case -1: - WindowPrompt(tr("Error"),tr("Cheatfile is blank"),tr("OK")); - break; - case 0: - download = WindowPrompt(tr("Error"),tr("No Cheatfile found"),tr("Download Now"),tr("Cancel")); - if (download==1) - { - download = CodeDownload(gameID); - if(download < 0 || c.openTxtfile(txtfilename) != 1) - break; - } - else - break; - case 1: - int cntcheats = c.getCnt(); - customOptionList cheatslst(cntcheats); - GuiCustomOptionBrowser chtBrowser(400, 280, &cheatslst, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, 1, 90); - chtBrowser.SetPosition(0, 90); - chtBrowser.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - chtBrowser.SetClickable(true); + switch ( check ) + { + case -1: + WindowPrompt( tr( "Error" ), tr( "Cheatfile is blank" ), tr( "OK" ) ); + break; + case 0: + download = WindowPrompt( tr( "Error" ), tr( "No Cheatfile found" ), tr( "Download Now" ), tr( "Cancel" ) ); + if ( download == 1 ) + { + download = CodeDownload( gameID ); + if ( download < 0 || c.openTxtfile( txtfilename ) != 1 ) + break; + } + else + break; + case 1: + int cntcheats = c.getCnt(); + customOptionList cheatslst( cntcheats ); + GuiCustomOptionBrowser chtBrowser( 400, 280, &cheatslst, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, 1, 90 ); + chtBrowser.SetPosition( 0, 90 ); + chtBrowser.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + chtBrowser.SetClickable( true ); - GuiText titleTxt(c.getGameName().c_str(), 28, (GXColor) {0, 0, 0, 255}); - titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - titleTxt.SetMaxWidth(350, 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++) { - cheatslst.SetValue(i, "%s",c.getCheatName(i).c_str()); - cheatslst.SetName(i, "OFF"); - } + for ( int i = 0; i <= cntcheats; i++ ) + { + cheatslst.SetValue( i, "%s", c.getCheatName( i ).c_str() ); + cheatslst.SetName( i, "OFF" ); + } - HaltGui(); - GuiWindow w(screenwidth, screenheight); - w.Append(&settingsbackground); - w.Append(&titleTxt); - w.Append(&backBtn); - w.Append(&createBtn); - w.Append(&chtBrowser); - mainWindow->SetState(STATE_DISABLED); - mainWindow->ChangeFocus(&w); - mainWindow->Append(&w); - ResumeGui(); + HaltGui(); + GuiWindow w( screenwidth, screenheight ); + w.Append( &settingsbackground ); + w.Append( &titleTxt ); + w.Append( &backBtn ); + w.Append( &createBtn ); + w.Append( &chtBrowser ); + mainWindow->SetState( STATE_DISABLED ); + mainWindow->ChangeFocus( &w ); + mainWindow->Append( &w ); + ResumeGui(); - while (!exit) { - VIDEO_WaitVSync (); + while ( !exit ) + { + VIDEO_WaitVSync (); - ret = chtBrowser.GetClickedOption(); - if (ret != -1) { - const char *strCheck = cheatslst.GetName(ret); - if (strncmp(strCheck,"ON",2) == 0) { - cheatslst.SetName(ret,"%s","OFF"); - } else if (strncmp(strCheck,"OFF",3) == 0) { - cheatslst.SetName(ret,"%s","ON"); - } - } + ret = chtBrowser.GetClickedOption(); + if ( ret != -1 ) + { + const char *strCheck = cheatslst.GetName( ret ); + if ( strncmp( strCheck, "ON", 2 ) == 0 ) + { + cheatslst.SetName( ret, "%s", "OFF" ); + } + else if ( strncmp( strCheck, "OFF", 3 ) == 0 ) + { + cheatslst.SetName( ret, "%s", "ON" ); + } + } - if (createBtn.GetState() == STATE_CLICKED) { - createBtn.ResetState(); - if (cntcheats > 0) { - int selectednrs[30]; - int x = 0; - for (int i = 0; i <= cntcheats; i++) { - const char *strCheck = cheatslst.GetName(i); - if (strncmp(strCheck,"ON",2) == 0) { - selectednrs[x] = i; - x++; - } - } - if (x == 0) { - WindowPrompt(tr("Error"),tr("No cheats were selected"),tr("OK")); - } else { - subfoldercreate(Settings.Cheatcodespath); - string chtpath = Settings.Cheatcodespath; - string gctfname = chtpath + c.getGameID() + ".gct"; - c.createGCT(selectednrs,x,gctfname.c_str()); - WindowPrompt(tr("GCT File created"),NULL,tr("OK")); - exit = true; - break; - } - } else WindowPrompt(tr("Error"),tr("Could not create GCT file"),tr("OK")); - } + if ( createBtn.GetState() == STATE_CLICKED ) + { + createBtn.ResetState(); + if ( cntcheats > 0 ) + { + int selectednrs[30]; + int x = 0; + for ( int i = 0; i <= cntcheats; i++ ) + { + const char *strCheck = cheatslst.GetName( i ); + if ( strncmp( strCheck, "ON", 2 ) == 0 ) + { + selectednrs[x] = i; + x++; + } + } + if ( x == 0 ) + { + WindowPrompt( tr( "Error" ), tr( "No cheats were selected" ), tr( "OK" ) ); + } + else + { + subfoldercreate( Settings.Cheatcodespath ); + string chtpath = Settings.Cheatcodespath; + string gctfname = chtpath + c.getGameID() + ".gct"; + c.createGCT( selectednrs, x, gctfname.c_str() ); + WindowPrompt( tr( "GCT File created" ), NULL, tr( "OK" ) ); + exit = true; + break; + } + } + else WindowPrompt( tr( "Error" ), tr( "Could not create GCT file" ), tr( "OK" ) ); + } - if (backBtn.GetState() == STATE_CLICKED) { - backBtn.ResetState(); - exit = true; - break; - } - } - HaltGui(); - mainWindow->SetState(STATE_DEFAULT); - mainWindow->Remove(&w); - ResumeGui(); - break; - } + if ( backBtn.GetState() == STATE_CLICKED ) + { + backBtn.ResetState(); + exit = true; + break; + } + } + HaltGui(); + mainWindow->SetState( STATE_DEFAULT ); + mainWindow->Remove( &w ); + ResumeGui(); + break; + } - return choice; + return choice; } diff --git a/source/cheats/cheatmenu.h b/source/cheats/cheatmenu.h index d087d9c6..6755be86 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 38530747..aef475bd 100644 --- a/source/cheats/gct.cpp +++ b/source/cheats/gct.cpp @@ -12,96 +12,116 @@ #define ERRORRANGE "Error: CheatNr out of range" -GCTCheats::GCTCheats(void) { +GCTCheats::GCTCheats( void ) +{ iCntCheats = 0; } -GCTCheats::~GCTCheats(void) { +GCTCheats::~GCTCheats( void ) +{ - string sGameID =""; + string sGameID = ""; string sGameTitle = ""; /*string sCheatName[MAXCHEATS]; string sCheats[MAXCHEATS]; string sCheatComment[MAXCHEATS];*/ } -int GCTCheats::getCnt() { +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) { - if (nr <= (iCntCheats-1)) { +string GCTCheats::getCheat( int nr ) +{ + if ( nr <= ( iCntCheats - 1 ) ) + { return sCheats[nr]; - } else { + } + else + { return ERRORRANGE; } } -string GCTCheats::getCheatName(int nr) { - if (nr <= (iCntCheats-1)) { +string GCTCheats::getCheatName( int nr ) +{ + if ( nr <= ( iCntCheats - 1 ) ) + { return sCheatName[nr]; - } else { + } + else + { return ERRORRANGE; } } -string GCTCheats::getCheatComment(int nr) { - if (nr <= (iCntCheats-1)) { +string GCTCheats::getCheatComment( int nr ) +{ + if ( nr <= ( iCntCheats - 1 ) ) + { return sCheatComment[nr]; - } else { + } + else + { return ERRORRANGE; } } -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()) + 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}; - 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) { - string temp = buf.substr(x,2); - li = strtol(temp.c_str(),NULL,16); + while ( x < len ) + { + string temp = buf.substr( x, 2 ); + li = strtol( temp.c_str(), NULL, 16 ); temp = li; - filestr.write(temp.c_str(),1); - x +=2; + 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()) + if ( filestr.fail() ) return 0; //Header and Footer @@ -109,146 +129,162 @@ int GCTCheats::createGCT(const char * chtbuffer,const char * filename) { 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) { - string temp = buf.substr(x,2); - li = strtol(temp.c_str(),NULL,16); + while ( x < len ) + { + string temp = buf.substr( x, 2 ); + li = strtol( temp.c_str(), NULL, 16 ); temp = li; - filestr.write(temp.c_str(),1); - x +=2; + 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()) + 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}; - 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) { - string temp = buf.substr(x,2); - li = strtol(temp.c_str(),NULL,16); + while ( x < len ) + { + string temp = buf.substr( x, 2 ); + li = strtol( temp.c_str(), NULL, 16 ); temp = li; - filestr.write(temp.c_str(),1); - x +=2; + 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()) + 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()) { - getline(filestr,sCheatName[i]); // '\n' delimiter by default - if (sCheatName[i][sCheatName[i].length() - 1] == '\r') - sCheatName[i].erase(sCheatName[i].length() - 1); + 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 ); string cheatdata; bool emptyline = false; - do { - getline(filestr,str); - if (str[str.length() - 1] == '\r') - str.erase(str.length() - 1); + do + { + 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)) { - // remove any garbage (comment) after code - while (str.size() > 17) { - str.erase(str.length() - 1); - } - cheatdata.append(str); - size_t found=cheatdata.find(' '); - cheatdata.replace(found,1,""); - } else { + if ( IsCode( str ) ) + { + // remove any garbage (comment) after code + while ( str.size() > 17 ) + { + str.erase( str.length() - 1 ); + } + cheatdata.append( str ); + size_t found = cheatdata.find( ' ' ); + cheatdata.replace( found, 1, "" ); + } + else + { //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; + i++; + if ( i == MAXCHEATS ) break; } iCntCheats = i; filestr.close(); return 1; } -bool GCTCheats::IsCode(const std::string& str) { - if (str[8] == ' ' && str.size() >= 17) { - // accept strings longer than 17 in case there is a comment on the same line as the code - char part1[9]; - char part2[9]; - snprintf(part1,sizeof(part1),"%c%c%c%c%c%c%c%c",str[0],str[1],str[2],str[3],str[4],str[5],str[6],str[7]); - snprintf(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; - } - } - return false; +bool GCTCheats::IsCode( const std::string& str ) +{ + if ( str[8] == ' ' && str.size() >= 17 ) + { + // accept strings longer than 17 in case there is a comment on the same line as the code + char part1[9]; + char part2[9]; + snprintf( part1, sizeof( part1 ), "%c%c%c%c%c%c%c%c", str[0], str[1], str[2], str[3], str[4], str[5], str[6], str[7] ); + snprintf( 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; + } + } + return false; } diff --git a/source/cheats/gct.h b/source/cheats/gct.h index 3dca78ae..0206f5fe 100644 --- a/source/cheats/gct.h +++ b/source/cheats/gct.h @@ -1,7 +1,7 @@ /* * gct.h * Class to handle Ocarina TXT Cheatfiles - * + * */ #ifndef _GCT_H @@ -14,61 +14,62 @@ using namespace std; //!Handles Ocarina TXT Cheatfiles -class GCTCheats { -private: - string sGameID; - string sGameTitle; - string sCheatName[MAXCHEATS]; - string sCheats[MAXCHEATS]; - string sCheatComment[MAXCHEATS]; - int iCntCheats; +class GCTCheats +{ + private: + string sGameID; + string sGameTitle; + string sCheatName[MAXCHEATS]; + string sCheats[MAXCHEATS]; + string sCheatComment[MAXCHEATS]; + int iCntCheats; -public: - //!Constructor - GCTCheats(void); - //!Destructor - ~GCTCheats(void); - //!Open txt file with cheats - //!\param filename name of TXT file - //!\return error code - 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); - //!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); - //!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); - //!Gets Count cheats - //!\return Count cheats - int getCnt(); - //!Gets Game Name - //!\return Game Name - string getGameName(void); - //!Gets GameID - //!\return GameID - string getGameID(void); - //!Gets cheat data - //!\return cheat data - string getCheat(int nr); - //!Gets Cheat Name - //!\return Cheat Name - string getCheatName(int nr); - //!Gets Cheat Comment - //!\return Cheat Comment - string getCheatComment(int nr); - //!Check if string is a code - //!\return true/false - bool IsCode(const std::string& s); + public: + //!Constructor + GCTCheats( void ); + //!Destructor + ~GCTCheats( void ); + //!Open txt file with cheats + //!\param filename name of TXT file + //!\return error code + 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 ); + //!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 ); + //!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 ); + //!Gets Count cheats + //!\return Count cheats + int getCnt(); + //!Gets Game Name + //!\return Game Name + string getGameName( void ); + //!Gets GameID + //!\return GameID + string getGameID( void ); + //!Gets cheat data + //!\return cheat data + string getCheat( int nr ); + //!Gets Cheat Name + //!\return Cheat Name + string getCheatName( int nr ); + //!Gets Cheat Comment + //!\return Cheat Comment + string getCheatComment( int nr ); + //!Check if string is a code + //!\return true/false + bool IsCode( const std::string& s ); }; #endif /* _GCT_H */ diff --git a/source/fatmounter.c b/source/fatmounter.c index 8744cd70..5b97167e 100644 --- a/source/fatmounter.c +++ b/source/fatmounter.c @@ -44,198 +44,219 @@ sec_t fat_wbfs_sec = 0; int fs_ntfs_mount = 0; sec_t fs_ntfs_sec = 0; -int USBDevice_Init() { +int USBDevice_Init() +{ #ifdef DEBUG_FAT - gprintf("\nUSBDevice_Init()"); + gprintf( "\nUSBDevice_Init()" ); #endif - //closing all open Files write back the cache and then shutdown em! - fatUnmount("USB:/"); + //closing all open Files write back the cache and then shutdown em! + fatUnmount( "USB:/" ); //right now mounts first FAT-partition - //try first mount with cIOS + //try first mount with cIOS // if (!fatMount("USB", &__io_wiiums, 0, CACHE, SECTORS)) { -// //try now mount with libogc - if (!fatMount("USB", &__io_usbstorage2, 0, CACHE, SECTORS)) { +// //try now mount with libogc + if ( !fatMount( "USB", &__io_usbstorage2, 0, CACHE, SECTORS ) ) + { #ifdef DEBUG_FAT - gprintf(":-1"); + gprintf( ":-1" ); #endif - return -1; - } -// } + return -1; + } +// } - fat_usb_mount = 1; - fat_usb_sec = _FAT_startSector; + fat_usb_mount = 1; + fat_usb_sec = _FAT_startSector; #ifdef DEBUG_FAT - gprintf(":0"); + gprintf( ":0" ); #endif - return 0; + return 0; } -void USBDevice_deInit() { +void USBDevice_deInit() +{ #ifdef DEBUG_FAT - gprintf("\nUSBDevice_deInit()"); + gprintf( "\nUSBDevice_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; + fat_usb_mount = 0; + fat_usb_sec = 0; } -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 + //try first mount with cIOS // if (!fatMount("WBFS", &__io_wiiums, 0, CACHE, SECTORS)) { - //try now mount with libogc - if (!fatMount("WBFS", &__io_usbstorage2, 0, CACHE, SECTORS)) { - return -1; - } -// } + //try now mount with libogc + 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) { - // This is an error situation...actually, but is ignored in Config loader also - // Should ask Oggzee about it... - } - return 0; + fat_wbfs_mount = 1; + fat_wbfs_sec = _FAT_startSector; + if ( sector && fat_wbfs_sec != sector ) + { + // This is an error situation...actually, but is ignored in Config loader also + // Should ask Oggzee about it... + } + return 0; } -void WBFSDevice_deInit() { +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; + fat_wbfs_mount = 0; + fat_wbfs_sec = 0; } -int isInserted(const char *path) { - if (!strncmp(path, "USB:", 4)) +int isInserted( const char *path ) +{ + if ( !strncmp( path, "USB:", 4 ) ) return 1; return __io_sdhc.isInserted() || __io_wiisd.isInserted(); } -int SDCard_Init() { +int SDCard_Init() +{ #ifdef DEBUG_FAT - gprintf("\nSDCard_Init()"); + gprintf( "\nSDCard_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)) { - fat_sd_mount = MOUNT_SD; - fat_sd_sec = _FAT_startSector; + if ( fatMount( "SD", &__io_wiisd, 0, CACHE, SECTORS ) ) + { + fat_sd_mount = MOUNT_SD; + fat_sd_sec = _FAT_startSector; #ifdef DEBUG_FAT - gprintf(":1"); + gprintf( ":1" ); #endif - return 1; - } - else if (fatMount("SD", &__io_sdhc, 0, CACHE, SDHC_SECTOR_SIZE)) { - fat_sd_mount = MOUNT_SDHC; - fat_sd_sec = _FAT_startSector; + return 1; + } + else if ( fatMount( "SD", &__io_sdhc, 0, CACHE, SDHC_SECTOR_SIZE ) ) + { + fat_sd_mount = MOUNT_SDHC; + fat_sd_sec = _FAT_startSector; #ifdef DEBUG_FAT - gprintf(":1"); + gprintf( ":1" ); #endif - return 1; - } + return 1; + } #ifdef DEBUG_FAT - gprintf(":-1"); + gprintf( ":-1" ); #endif - return -1; + return -1; } -void SDCard_deInit() { +void SDCard_deInit() +{ #ifdef DEBUG_FAT - gprintf("\nSDCard_deInit()"); + gprintf( "\nSDCard_deInit()" ); #endif //closing all open Files write back the cache and then shutdown em! - fatUnmount("SD:/"); + fatUnmount( "SD:/" ); - fat_sd_mount = MOUNT_NONE; - fat_sd_sec = 0; + fat_sd_mount = MOUNT_NONE; + fat_sd_sec = 0; } void ntfsInit(); -s32 MountNTFS(u32 sector) +s32 MountNTFS( u32 sector ) { - s32 ret; + s32 ret; - if (fs_ntfs_mount) return 0; - //printf("mounting NTFS\n"); - //Wpad_WaitButtons(); - _FAT_mem_init(); + if ( fs_ntfs_mount ) return 0; + //printf("mounting NTFS\n"); + //Wpad_WaitButtons(); + _FAT_mem_init(); - ntfsInit(); // Call ntfs init here, to prevent locale resets + ntfsInit(); // Call ntfs init here, to prevent locale resets - // ntfsInit resets locale settings - // which breaks unicode in console - // so we change it back to C-UTF-8 - setlocale(LC_CTYPE, "C-UTF-8"); - setlocale(LC_MESSAGES, "C-UTF-8"); + // ntfsInit resets locale settings + // which breaks unicode in console + // so we change it back to C-UTF-8 + setlocale( LC_CTYPE, "C-UTF-8" ); + setlocale( LC_MESSAGES, "C-UTF-8" ); - if (wbfsDev == WBFS_DEVICE_USB) { - /* Initialize WBFS interface */ -// if (!__io_wiiums.startup()) { - ret = __io_usbstorage2.startup(); - if (!ret) { - return -1; - } -// } - /* Mount device */ -// if (!ntfsMount("NTFS", &__io_wiiums, sector, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER)) { - ret = ntfsMount("NTFS", &__io_usbstorage2, sector, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_READ_ONLY | NTFS_RECOVER); - if (!ret) { - return -2; - } -// } - } else if (wbfsDev == WBFS_DEVICE_SDHC) { - if (sdhc_mode_sd == 0) { - ret = ntfsMount("NTFS", &__io_sdhc, 0, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_READ_ONLY | NTFS_RECOVER); - } else { - ret = ntfsMount("NTFS", &__io_sdhc, 0, CACHE, SECTORS_SD, NTFS_SHOW_HIDDEN_FILES | NTFS_READ_ONLY | NTFS_RECOVER); - } - if (!ret) { - return -5; - } - } + if ( wbfsDev == WBFS_DEVICE_USB ) + { + /* Initialize WBFS interface */ +// if (!__io_wiiums.startup()) { + ret = __io_usbstorage2.startup(); + if ( !ret ) + { + return -1; + } +// } + /* Mount device */ +// if (!ntfsMount("NTFS", &__io_wiiums, sector, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_RECOVER)) { + ret = ntfsMount( "NTFS", &__io_usbstorage2, sector, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_READ_ONLY | NTFS_RECOVER ); + if ( !ret ) + { + return -2; + } +// } + } + else if ( wbfsDev == WBFS_DEVICE_SDHC ) + { + if ( sdhc_mode_sd == 0 ) + { + ret = ntfsMount( "NTFS", &__io_sdhc, 0, CACHE, SECTORS, NTFS_SHOW_HIDDEN_FILES | NTFS_READ_ONLY | NTFS_RECOVER ); + } + else + { + ret = ntfsMount( "NTFS", &__io_sdhc, 0, CACHE, SECTORS_SD, NTFS_SHOW_HIDDEN_FILES | NTFS_READ_ONLY | NTFS_RECOVER ); + } + if ( !ret ) + { + return -5; + } + } - fs_ntfs_mount = 1; - fs_ntfs_sec = sector; //_FAT_startSector; + fs_ntfs_mount = 1; + fs_ntfs_sec = sector; //_FAT_startSector; - return 0; + return 0; } -s32 UnmountNTFS(void) +s32 UnmountNTFS( void ) { - /* Unmount device */ - ntfsUnmount("NTFS:/", true); + /* Unmount device */ + ntfsUnmount( "NTFS:/", true ); - fs_ntfs_mount = 0; - fs_ntfs_sec = 0; + fs_ntfs_mount = 0; + fs_ntfs_sec = 0; - return 0; + return 0; } void _FAT_mem_init() { } -void* _FAT_mem_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 e9ac30ba..3ced2ab1 100644 --- a/source/fatmounter.h +++ b/source/fatmounter.h @@ -2,33 +2,34 @@ #define _FATMOUNTER_H_ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif - extern int fat_sd_mount; - extern sec_t fat_sd_sec; - extern int fat_usb_mount; - extern sec_t fat_usb_sec; - extern int fat_wbfs_mount; - extern sec_t fat_wbfs_sec; + extern int fat_sd_mount; + extern sec_t fat_sd_sec; + extern int fat_usb_mount; + extern sec_t fat_usb_sec; + extern int fat_wbfs_mount; + extern sec_t fat_wbfs_sec; int USBDevice_Init(); void USBDevice_deInit(); - 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); - extern int fat_usb_mount; - extern sec_t fat_usb_sec; - extern int fat_wbfs_mount; - extern sec_t fat_wbfs_sec; - extern int fs_ntfs_mount; - extern sec_t fs_ntfs_sec; + s32 MountNTFS( u32 sector ); + s32 UnmountNTFS( void ); + + extern int fat_usb_mount; + extern sec_t fat_usb_sec; + extern int fat_wbfs_mount; + extern sec_t fat_wbfs_sec; + extern int fs_ntfs_mount; + extern sec_t fs_ntfs_sec; #ifdef __cplusplus } diff --git a/source/filelist.h b/source/filelist.h index fa4f31c1..2640d7f1 100644 --- a/source/filelist.h +++ b/source/filelist.h @@ -11,23 +11,23 @@ #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; @@ -35,50 +35,50 @@ extern const u32 Wifi_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; @@ -95,11 +95,11 @@ 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 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; @@ -116,29 +116,29 @@ extern const u32 settings_background_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_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 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; @@ -170,380 +170,380 @@ 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 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 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 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_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 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; #endif diff --git a/source/gecko.c b/source/gecko.c index f75fc2f4..7f6817ae 100644 --- a/source/gecko.c +++ b/source/gecko.c @@ -12,67 +12,67 @@ bool textVideoInit = false; //using the gprintf from crediar because it is smaller than mine void gprintf( const char *str, ... ) { - if (!(geckoinit))return; + if ( !( geckoinit ) )return; - char astr[4096]; + char astr[4096]; - va_list ap; - va_start(ap,str); + va_list ap; + va_start( ap, str ); - vsprintf( astr, str, ap ); + vsprintf( astr, str, ap ); - va_end(ap); + va_end( ap ); - usb_sendbuffer( 1, astr, strlen(astr) ); - //usb_sendbuffer_safe( 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) - { - usb_flush(EXI_CHANNEL_1); - CON_EnableGecko( 1, true ); - return true; - } - else return false; + u32 geckoattached = usb_isgeckoalive( EXI_CHANNEL_1 ); + if ( geckoattached ) + { + 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) - 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" ); } } diff --git a/source/gecko.h b/source/gecko.h index 8efb00cf..e4dacd41 100644 --- a/source/gecko.h +++ b/source/gecko.h @@ -4,20 +4,21 @@ #define _GECKO_H_ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif - char ascii(char s); + char ascii( char s ); #ifndef NO_DEBUG - //use this just like printf(); - void gprintf(const char *str, ...); - bool InitGecko(); - void hexdump(void *d, int len); + //use this just like printf(); + void gprintf( const char *str, ... ); + bool InitGecko(); + void hexdump( void *d, int len ); #else - #define gprintf(...) - #define InitGecko() false - #define hexdump( x, y ) +#define gprintf(...) +#define InitGecko() false +#define hexdump( x, y ) #endif /* NO_DEBUG */ diff --git a/source/homebrewboot/BootHomebrew.cpp b/source/homebrewboot/BootHomebrew.cpp index 6774a8bd..36412251 100644 --- a/source/homebrewboot/BootHomebrew.cpp +++ b/source/homebrewboot/BootHomebrew.cpp @@ -14,62 +14,62 @@ #include "fatmounter.h" #include "sys.h" -extern const u8 app_booter_dol[]; +extern const u8 app_booter_dol[]; extern const u32 app_booter_dol_size; -static u8 *homebrewbuffer = (u8 *) 0x92000000; +static u8 *homebrewbuffer = ( u8 * ) 0x92000000; static int homebrewsize = 0; static std::vector Arguments; -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; } -static int SetupARGV(struct __argv * args) +static int SetupARGV( struct __argv * args ) { - if(!args) + 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; + stringlength += Arguments[i].size() + 1; } args->length = stringlength; - args->commandLine = (char*) malloc(args->length); - if (!args->commandLine) + args->commandLine = ( char* ) malloc( args->length ); + 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()); - position += Arguments[i].size()+1; + strcpy( &args->commandLine[position], Arguments[i].c_str() ); + position += Arguments[i].size() + 1; argc++; } @@ -86,7 +86,7 @@ static int SetupARGV(struct __argv * args) int BootHomebrew() { - if(homebrewsize <= 0) + if ( homebrewsize <= 0 ) Sys_BackToLoader(); SDCard_deInit(); @@ -94,43 +94,43 @@ int BootHomebrew() USBStorage2_Deinit(); struct __argv args; - SetupARGV(&args); + SetupARGV( &args ); u32 cpu_isr; - entrypoint entry = (entrypoint) load_dol(app_booter_dol, &args); + entrypoint entry = ( entrypoint ) load_dol( app_booter_dol, &args ); - if (!entry) + if ( !entry ) Sys_BackToLoader(); - VIDEO_SetBlack(true); + VIDEO_SetBlack( true ); VIDEO_Flush(); VIDEO_WaitVSync(); - SYS_ResetSystem(SYS_SHUTDOWN, 0, 0); - _CPU_ISR_Disable (cpu_isr); + SYS_ResetSystem( SYS_SHUTDOWN, 0, 0 ); + _CPU_ISR_Disable ( cpu_isr ); __exception_closeall(); entry(); - _CPU_ISR_Restore (cpu_isr); + _CPU_ISR_Restore ( cpu_isr ); return 0; } -int BootHomebrew(const char * filepath) +int BootHomebrew( const char * filepath ) { - FILE * file = fopen(filepath, "rb"); - if(!file) + FILE * file = fopen( filepath, "rb" ); + if ( !file ) Sys_BackToLoader(); - fseek(file, 0, SEEK_END); + fseek( file, 0, SEEK_END ); - int size = ftell(file); - rewind(file); + int size = ftell( file ); + rewind( file ); - homebrewsize = fread(homebrewbuffer, 1, size, file); - fclose(file); + homebrewsize = fread( homebrewbuffer, 1, size, file ); + fclose( file ); - AddBootArgument(filepath); + AddBootArgument( filepath ); return BootHomebrew(); } @@ -155,11 +155,11 @@ int BootHomebrew(const char * filepath) 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 ) { @@ -167,7 +167,7 @@ int AllocHomebrewMemory( u32 filesize ) innetbuffer = malloc( filesize ); if ( !innetbuffer ) - return -1; + return -1; homebrewsize = filesize; return 1; @@ -182,7 +182,7 @@ void AddBootArgument( const char * argv ) int CopyHomebrewMemory( u8 *temp, u32 pos, u32 len ) { homebrewsize += len; - memcpy(( homebrewbuffer ) + pos, temp, len ); + memcpy( ( homebrewbuffer ) + pos, temp, len ); return 1; } @@ -194,8 +194,8 @@ void FreeHomebrewBuffer() if ( innetbuffer ) { - free( innetbuffer ); - innetbuffer = NULL; + free( innetbuffer ); + innetbuffer = NULL; } Arguments.clear(); @@ -204,7 +204,7 @@ void FreeHomebrewBuffer() static int SetupARGV( struct __argv * args ) { if ( !args ) - return -1; + return -1; bzero( args, sizeof( struct __argv ) ); args->argvMagic = ARGV_MAGIC; @@ -214,14 +214,14 @@ static int SetupARGV( struct __argv * args ) /** Append Arguments **/ for ( u32 i = 0; i < Arguments.size(); i++ ) { - stringlength += Arguments[i].size() + 1; + stringlength += Arguments[i].size() + 1; } args->length = stringlength; args->commandLine = ( char* ) malloc( args->length ); if ( !args->commandLine ) - return -1; + return -1; u32 argc = 0; u32 position = 0; @@ -229,9 +229,9 @@ static int SetupARGV( struct __argv * args ) /** Append Arguments **/ for ( u32 i = 0; i < Arguments.size(); i++ ) { - strcpy( &args->commandLine[position], Arguments[i].c_str() ); - position += Arguments[i].size() + 1; - argc++; + strcpy( &args->commandLine[position], Arguments[i].c_str() ); + position += Arguments[i].size() + 1; + argc++; } args->argc = argc; @@ -248,19 +248,19 @@ static int SetupARGV( struct __argv * args ) static int RunAppbooter() { if ( homebrewsize == 0 ) - return -1; + return -1; struct __argv 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 ) { - FreeHomebrewBuffer(); - return -1; + FreeHomebrewBuffer(); + return -1; } u64 currentStub = getStubDest(); @@ -268,13 +268,13 @@ static int RunAppbooter() if ( Set_Stub_Split( 0x00010001, "UNEO" ) < 0 ) { - if ( Set_Stub_Split( 0x00010001, "ULNR" ) < 0 ) - { - if ( !currentStub ) - currentStub = 0x100000002ULL; + if ( Set_Stub_Split( 0x00010001, "ULNR" ) < 0 ) + { + if ( !currentStub ) + currentStub = 0x100000002ULL; - Set_Stub( currentStub ); - } + Set_Stub( currentStub ); + } } SDCard_deInit(); @@ -301,7 +301,7 @@ int BootHomebrew( char * filepath ) FILE *file = fopen( filepath, "rb" ); if ( !file ) - Sys_BackToLoader(); + Sys_BackToLoader(); fseek( file, 0, SEEK_END ); filesize = ftell( file ); @@ -311,21 +311,21 @@ int BootHomebrew( char * filepath ) if ( fread( buffer, 1, filesize, file ) != filesize ) { - fclose( file ); - free( buffer ); - SDCard_deInit(); - USBDevice_deInit(); - Sys_BackToLoader(); + fclose( file ); + free( buffer ); + SDCard_deInit(); + USBDevice_deInit(); + Sys_BackToLoader(); } fclose( file ); - CopyHomebrewMemory(( u8* ) buffer, 0, filesize ); + CopyHomebrewMemory( ( u8* ) buffer, 0, filesize ); if ( buffer ) { - free( buffer ); - buffer = NULL; + free( buffer ); + buffer = NULL; } AddBootArgument( filepath ); @@ -338,13 +338,13 @@ int BootHomebrewFromMem() if ( !innetbuffer ) { - gprintf( "!innetbuffer\n" ); - SDCard_deInit(); - USBDevice_deInit(); - Sys_BackToLoader(); + gprintf( "!innetbuffer\n" ); + SDCard_deInit(); + USBDevice_deInit(); + Sys_BackToLoader(); } - CopyHomebrewMemory(( u8* ) innetbuffer, 0, homebrewsize ); + CopyHomebrewMemory( ( u8* ) innetbuffer, 0, homebrewsize ); free( innetbuffer ); return RunAppbooter(); diff --git a/source/homebrewboot/BootHomebrew.h b/source/homebrewboot/BootHomebrew.h index c3b66301..1ab47762 100644 --- a/source/homebrewboot/BootHomebrew.h +++ b/source/homebrewboot/BootHomebrew.h @@ -3,11 +3,11 @@ //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 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 fdc9adb1..c50e1be7 100644 --- a/source/homebrewboot/HomebrewBrowse.cpp +++ b/source/homebrewboot/HomebrewBrowse.cpp @@ -48,924 +48,1031 @@ u8 boothomebrew = 0; /**************************************************************************** * roundup Function ***************************************************************************/ -int roundup(float number) { - if (number == (int) number) - return (int) number; +int roundup( float number ) +{ + if ( number == ( int ) number ) + return ( int ) number; else - return (int) (number+1); + return ( int ) ( number + 1 ); } /**************************************************************************** * MenuHomebrewBrowse ***************************************************************************/ -int MenuHomebrewBrowse() { +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) { - WindowPrompt(tr("No .dol or .elf files found."),0, tr("OK")); - return MENU_DISCLIST; + if ( !filecount ) + { + WindowPrompt( tr( "No .dol or .elf files found." ), 0, tr( "OK" ) ); + return MENU_DISCLIST; } - enum { - FADE, - LEFT, - RIGHT + enum + { + 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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - GuiSound btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnClick1( button_click_pcm, button_click_pcm_size, Settings.sfxvolume ); /*** Image Variables ***/ char imgPath[150]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path); - GuiImageData bgData(imgPath, settings_background_png); + snprintf( imgPath, sizeof( imgPath ), "%ssettings_background.png", CFG.theme_path ); + GuiImageData bgData( imgPath, settings_background_png ); - snprintf(imgPath, sizeof(imgPath), "%ssettings_title.png", CFG.theme_path); - GuiImageData MainButtonImgData(imgPath, settings_title_png); + snprintf( imgPath, sizeof( imgPath ), "%ssettings_title.png", CFG.theme_path ); + GuiImageData MainButtonImgData( imgPath, settings_title_png ); - snprintf(imgPath, sizeof(imgPath), "%ssettings_title_over.png", CFG.theme_path); - GuiImageData MainButtonImgOverData(imgPath, settings_title_over_png); + snprintf( imgPath, sizeof( imgPath ), "%ssettings_title_over.png", CFG.theme_path ); + GuiImageData MainButtonImgOverData( imgPath, settings_title_over_png ); - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", CFG.theme_path); - GuiImageData arrow_left(imgPath, startgame_arrow_left_png); + snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_left.png", CFG.theme_path ); + GuiImageData arrow_left( imgPath, startgame_arrow_left_png ); - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", CFG.theme_path); - GuiImageData arrow_right(imgPath, startgame_arrow_right_png); + snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_right.png", CFG.theme_path ); + GuiImageData arrow_right( imgPath, startgame_arrow_right_png ); - snprintf(imgPath, sizeof(imgPath), "%sWifi_btn.png", CFG.theme_path); - GuiImageData wifiImgData(imgPath, Wifi_btn_png); + snprintf( imgPath, sizeof( imgPath ), "%sWifi_btn.png", CFG.theme_path ); + GuiImageData wifiImgData( imgPath, Wifi_btn_png ); - snprintf(imgPath, sizeof(imgPath), "%sChannel_btn.png", CFG.theme_path); - GuiImageData channelImgData(imgPath, Channel_btn_png); + snprintf( imgPath, sizeof( imgPath ), "%sChannel_btn.png", CFG.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++) { - IconData[i] = NULL; - IconImg[i] = NULL; + 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) { - backBtnTxt.SetWidescreen(CFG.widescreen); - backBtnImg.SetWidescreen(CFG.widescreen); + GuiText backBtnTxt( tr( "Back" ) , 22, THEME.prompttext ); + backBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); + GuiImage backBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + backBtnTxt.SetWidescreen( CFG.widescreen ); + backBtnImg.SetWidescreen( CFG.widescreen ); } - GuiButton backBtn(&backBtnImg,&backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2,1); - backBtn.SetLabel(&backBtnTxt); - backBtn.SetTrigger(&trigB); + GuiButton 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) { - wifiImg.SetWidescreen(CFG.widescreen); + GuiImage wifiImg( &wifiImgData ); + if ( Settings.wsprompt == yes ) + { + wifiImg.SetWidescreen( CFG.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(CFG.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( CFG.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); - bool wifi_btn_loaded=false; - - while (menu == MENU_NONE) { //set pageToDisplay to 0 to quit - VIDEO_WaitVSync (); - - menu = MENU_NONE; - bool changed = false; - int fileoffset = pageToDisplay*4-4; - - /** Standard procedure made in all pages **/ - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); - - if (slidedirection == RIGHT) { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 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) { - 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(); - - mainWindow->RemoveAll(); - - /** Set new icons **/ - for (int i = 0; i < 4; i++) { - if (IconData[i] != NULL) { - delete IconData[i]; - IconData[i] = NULL; - } - if (IconImg[i] != NULL) { - delete IconImg[i]; - IconImg[i] = NULL; - } - 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()) { - 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); - - 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); - - if (pageToDisplay == pages) { - int buttonsleft = filecount-(pages-1)*4; - char * shortpath = NULL; - char temp[200]; - - if (buttonsleft > 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); - } 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); - } - w.Append(&MainButton1); - } - if (buttonsleft > 1) { - 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); - } 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); - } - w.Append(&MainButton2); - } - if (buttonsleft > 2) { - 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); - } 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); - } - w.Append(&MainButton3); - } - if (buttonsleft > 3) { - 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); - } 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); - } - w.Append(&MainButton4); - } - } else { - char temp[200]; - char *shortpath = NULL; - - 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); - } 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); - } - - w.Append(&MainButton1); - - 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); - } 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); - } - - w.Append(&MainButton2); - - 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); - } 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); - } - w.Append(&MainButton3); - - 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); - } 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); - } - - w.Append(&MainButton4); - } - - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); - - MainButton1.SetEffectGrow(); - MainButton2.SetEffectGrow(); - MainButton3.SetEffectGrow(); - MainButton4.SetEffectGrow(); - - if (slidedirection == FADE) { - MainButton1.SetEffect(EFFECT_FADE, 20); - MainButton2.SetEffect(EFFECT_FADE, 20); - MainButton3.SetEffect(EFFECT_FADE, 20); - MainButton4.SetEffect(EFFECT_FADE, 20); - } else if (slidedirection == LEFT) { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 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) { - 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); - - ResumeGui(); - - while (MainButton1.GetEffect() > 0) usleep(50); - - while (!changed) { - VIDEO_WaitVSync (); - - if (MainButton1.GetState() == STATE_CLICKED) { - char temp[200]; - char iconpath[200]; - char metapath[200]; - char * shortpath = NULL; - - //write iconpath - snprintf(metapath, sizeof(metapath), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset)); - - //write iconpath - snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset)); - - //get filesize - 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)); - - 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)); - break; - } - MainButton1.ResetState(); - } else if (MainButton2.GetState() == STATE_CLICKED) { - char temp[200]; - char iconpath[200]; - char metapath[200]; - char * shortpath = NULL; - - //write iconpath - snprintf(metapath, sizeof(metapath), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset+1)); - - //write iconpath - snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset+1)); - - //get filesize - 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)); - - 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)); - break; - } - MainButton2.ResetState(); - } else if (MainButton3.GetState() == STATE_CLICKED) { - char temp[200]; - char iconpath[200]; - char metapath[200]; - char * shortpath = NULL; - - //write iconpath - snprintf(metapath, sizeof(metapath), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset+2)); - - //write iconpath - snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset+2)); - - //get filesize - 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)); - - 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)); - break; - } - MainButton3.ResetState(); - } else if (MainButton4.GetState() == STATE_CLICKED) { - char temp[200]; - char iconpath[200]; - char metapath[200]; - char * shortpath = NULL; - - //write iconpath - snprintf(metapath, sizeof(metapath), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset+3)); - - //write iconpath - snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset+3)); - - //get filesize - 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)); - - 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)); - break; - } - MainButton4.ResetState(); - } - - else if (shutdown == 1) - Sys_Shutdown(); - else if (reset == 1) - Sys_Reboot(); - - else if (backBtn.GetState() == STATE_CLICKED) { - menu = MENU_DISCLIST; - changed = true; - } - - else if (GoLeftBtn.GetState() == STATE_CLICKED) { - pageToDisplay--; - /** Change direction of the flying buttons **/ - if (pageToDisplay < 1) - pageToDisplay = pages; - slidedirection = LEFT; - changed = true; - GoLeftBtn.ResetState(); - } - - else if (GoRightBtn.GetState() == STATE_CLICKED) { - pageToDisplay++; - /** Change direction of the flying buttons **/ - if (pageToDisplay > pages) - pageToDisplay = 1; - slidedirection = RIGHT; - changed = true; - GoRightBtn.ResetState(); - } - - else if (wifiBtn.GetState() == STATE_CLICKED) { - - ResumeNetworkWait(); - wifiBtn.ResetState(); - } - - else if (homo.GetState() == STATE_CLICKED) { - cfg_save_global(); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - - if (choice == 3) { - Sys_LoadMenu(); // Back to System Menu - } else if (choice == 2) { - Sys_BackToLoader(); - } else { - homo.ResetState(); - } - } - - 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); - - snprintf(temp, sizeof(temp), tr("Load file from: %s ?"), GetIncommingIP()); - - int choice = WindowPrompt(filesizetxt, temp, tr("OK"), tr("Cancel")); - - if (choice == 1) { - - int res = AllocHomebrewMemory(infilesize); - - if (res < 0) { - CloseConnection(); - WindowPrompt(tr("Not enough free memory."), 0, tr("OK")); - } else { - u32 read = 0; - u8 *temp = NULL; - int len = NETWORKBLOCKSIZE; - temp = (u8 *) malloc(infilesize); - - bool error = false; - u8 *ptr = temp; - while (read < infilesize) { - - ShowProgress(tr("Receiving file from:"), GetIncommingIP(), NULL, read, infilesize, true); - - if (infilesize - read < (u32) len) - len = infilesize-read; - else - len = NETWORKBLOCKSIZE; - - int result = network_read(ptr, len); - - if (result < 0) { - WindowPrompt(tr("Error while transfering data."), 0, tr("OK")); - error = true; - break; - } - if (!result) { - break; - } - - ptr += result; - - read += result; - } - - char filename[101]; - if (!error) { - - network_read((u8*) &filename, 100); - - // Do we need to unzip this thing? - if (wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4) { - - // We need to unzip... - if (temp[0] == 'P' && temp[1] == 'K' && temp[2] == 0x03 && temp[3] == 0x04) { - // It's a zip file, unzip to the apps directory - - // Zip archive, ask for permission to install the zip - char zippath[255]; - sprintf((char *) &zippath, "%s%s", Settings.homebrewapps_path, filename); - - FILE *fp = fopen(zippath, "wb"); - if (fp != NULL) - { - fwrite(temp, 1, infilesize, fp); - fclose(fp); - - // Now unzip the zip file... - unzFile uf = unzOpen(zippath); - if (uf==NULL) { - error = true; - } else { - extractZip(uf,0,1,0, Settings.homebrewapps_path); - unzCloseCurrentFile(uf); - - remove(zippath); - - // Reload this menu here... - menu = MENU_HOMEBREWBROWSE; - break; - } - } else { - error = true; - } - } else if (uncfilesize != 0) { // if uncfilesize == 0, it's not compressed - // It's compressed, uncompress - u8 *unc = (u8 *) malloc(uncfilesize); - uLongf f = uncfilesize; - error = uncompress(unc, &f, temp, infilesize) != Z_OK; - uncfilesize = f; - homebrewsize = uncfilesize; - - free(temp); - temp = unc; - } - } - - if (!error && strstr(filename,".zip") == NULL) { - innetbuffer = temp; - - } - } - - ProgressStop(); - - if (error || read != infilesize) { - 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")) { - boothomebrew = 2; - AddBootArgument( filename ); - menu = MENU_EXIT; - CloseConnection(); - break; - } else if (strstr(filename,".zip")) { - 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")); - } - } - } - } - CloseConnection(); - ResumeNetworkWait(); - } - - else if (channelBtn.GetState() == STATE_CLICKED) { - 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); - channelBtn.ResetState(); - - - } - - if (IsNetworkInit()) { - if (!wifi_btn_loaded) { - wifiBtn.SetAlpha(255); - - titleTT = new GuiTooltip(GetNetworkIP()); - titleTT->SetAlpha(THEME.tooltipAlpha); - wifiBtn.SetToolTip(titleTT,0,-50,0,5); - wifi_btn_loaded=true; - } - } - } + const int pages = roundup( filecount / 4.0f ); + bool wifi_btn_loaded = false; + + while ( menu == MENU_NONE ) //set pageToDisplay to 0 to quit + { + VIDEO_WaitVSync (); + + menu = MENU_NONE; + bool changed = false; + int fileoffset = pageToDisplay * 4 - 4; + + /** Standard procedure made in all pages **/ + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); + + if ( slidedirection == RIGHT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 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 ) + { + 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(); + + mainWindow->RemoveAll(); + + /** Set new icons **/ + for ( int i = 0; i < 4; i++ ) + { + if ( IconData[i] != NULL ) + { + delete IconData[i]; + IconData[i] = NULL; + } + if ( IconImg[i] != NULL ) + { + delete IconImg[i]; + IconImg[i] = NULL; + } + 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() ) + { + 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 ); + + 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 ); + + if ( pageToDisplay == pages ) + { + int buttonsleft = filecount - ( pages - 1 ) * 4; + char * shortpath = NULL; + char temp[200]; + + if ( buttonsleft > 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 ); + } + 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 ); + } + w.Append( &MainButton1 ); + } + if ( buttonsleft > 1 ) + { + 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 ); + } + 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 ); + } + w.Append( &MainButton2 ); + } + if ( buttonsleft > 2 ) + { + 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 ); + } + 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 ); + } + w.Append( &MainButton3 ); + } + if ( buttonsleft > 3 ) + { + 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 ); + } + 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 ); + } + w.Append( &MainButton4 ); + } + } + else + { + char temp[200]; + char *shortpath = NULL; + + 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 ); + } + 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 ); + } + + w.Append( &MainButton1 ); + + 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 ); + } + 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 ); + } + + w.Append( &MainButton2 ); + + 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 ); + } + 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 ); + } + w.Append( &MainButton3 ); + + 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 ); + } + 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 ); + } + + w.Append( &MainButton4 ); + } + + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); + + MainButton1.SetEffectGrow(); + MainButton2.SetEffectGrow(); + MainButton3.SetEffectGrow(); + MainButton4.SetEffectGrow(); + + if ( slidedirection == FADE ) + { + MainButton1.SetEffect( EFFECT_FADE, 20 ); + MainButton2.SetEffect( EFFECT_FADE, 20 ); + MainButton3.SetEffect( EFFECT_FADE, 20 ); + MainButton4.SetEffect( EFFECT_FADE, 20 ); + } + else if ( slidedirection == LEFT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 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 ) + { + 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 ); + + ResumeGui(); + + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + + while ( !changed ) + { + VIDEO_WaitVSync (); + + if ( MainButton1.GetState() == STATE_CLICKED ) + { + char temp[200]; + char iconpath[200]; + char metapath[200]; + char * shortpath = NULL; + + //write iconpath + snprintf( metapath, sizeof( metapath ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset ) ); + + //write iconpath + snprintf( iconpath, sizeof( iconpath ), "%sicon.png", HomebrewFiles.GetFilepath( fileoffset ) ); + + //get filesize + 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 ) ); + + 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 ) ); + break; + } + MainButton1.ResetState(); + } + else if ( MainButton2.GetState() == STATE_CLICKED ) + { + char temp[200]; + char iconpath[200]; + char metapath[200]; + char * shortpath = NULL; + + //write iconpath + snprintf( metapath, sizeof( metapath ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset + 1 ) ); + + //write iconpath + snprintf( iconpath, sizeof( iconpath ), "%sicon.png", HomebrewFiles.GetFilepath( fileoffset + 1 ) ); + + //get filesize + 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 ) ); + + 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 ) ); + break; + } + MainButton2.ResetState(); + } + else if ( MainButton3.GetState() == STATE_CLICKED ) + { + char temp[200]; + char iconpath[200]; + char metapath[200]; + char * shortpath = NULL; + + //write iconpath + snprintf( metapath, sizeof( metapath ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset + 2 ) ); + + //write iconpath + snprintf( iconpath, sizeof( iconpath ), "%sicon.png", HomebrewFiles.GetFilepath( fileoffset + 2 ) ); + + //get filesize + 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 ) ); + + 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 ) ); + break; + } + MainButton3.ResetState(); + } + else if ( MainButton4.GetState() == STATE_CLICKED ) + { + char temp[200]; + char iconpath[200]; + char metapath[200]; + char * shortpath = NULL; + + //write iconpath + snprintf( metapath, sizeof( metapath ), "%smeta.xml", HomebrewFiles.GetFilepath( fileoffset + 3 ) ); + + //write iconpath + snprintf( iconpath, sizeof( iconpath ), "%sicon.png", HomebrewFiles.GetFilepath( fileoffset + 3 ) ); + + //get filesize + 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 ) ); + + 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 ) ); + break; + } + MainButton4.ResetState(); + } + + else if ( shutdown == 1 ) + Sys_Shutdown(); + else if ( reset == 1 ) + Sys_Reboot(); + + else if ( backBtn.GetState() == STATE_CLICKED ) + { + menu = MENU_DISCLIST; + changed = true; + } + + else if ( GoLeftBtn.GetState() == STATE_CLICKED ) + { + pageToDisplay--; + /** Change direction of the flying buttons **/ + if ( pageToDisplay < 1 ) + pageToDisplay = pages; + slidedirection = LEFT; + changed = true; + GoLeftBtn.ResetState(); + } + + else if ( GoRightBtn.GetState() == STATE_CLICKED ) + { + pageToDisplay++; + /** Change direction of the flying buttons **/ + if ( pageToDisplay > pages ) + pageToDisplay = 1; + slidedirection = RIGHT; + changed = true; + GoRightBtn.ResetState(); + } + + else if ( wifiBtn.GetState() == STATE_CLICKED ) + { + + ResumeNetworkWait(); + wifiBtn.ResetState(); + } + + else if ( homo.GetState() == STATE_CLICKED ) + { + cfg_save_global(); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + + if ( choice == 3 ) + { + Sys_LoadMenu(); // Back to System Menu + } + else if ( choice == 2 ) + { + Sys_BackToLoader(); + } + else + { + homo.ResetState(); + } + } + + 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 ); + + snprintf( temp, sizeof( temp ), tr( "Load file from: %s ?" ), GetIncommingIP() ); + + int choice = WindowPrompt( filesizetxt, temp, tr( "OK" ), tr( "Cancel" ) ); + + if ( choice == 1 ) + { + + int res = AllocHomebrewMemory( infilesize ); + + if ( res < 0 ) + { + CloseConnection(); + WindowPrompt( tr( "Not enough free memory." ), 0, tr( "OK" ) ); + } + else + { + u32 read = 0; + u8 *temp = NULL; + int len = NETWORKBLOCKSIZE; + temp = ( u8 * ) malloc( infilesize ); + + bool error = false; + u8 *ptr = temp; + while ( read < infilesize ) + { + + ShowProgress( tr( "Receiving file from:" ), GetIncommingIP(), NULL, read, infilesize, true ); + + if ( infilesize - read < ( u32 ) len ) + len = infilesize - read; + else + len = NETWORKBLOCKSIZE; + + int result = network_read( ptr, len ); + + if ( result < 0 ) + { + WindowPrompt( tr( "Error while transfering data." ), 0, tr( "OK" ) ); + error = true; + break; + } + if ( !result ) + { + break; + } + + ptr += result; + + read += result; + } + + char filename[101]; + if ( !error ) + { + + network_read( ( u8* ) &filename, 100 ); + + // Do we need to unzip this thing? + if ( wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4 ) + { + + // We need to unzip... + if ( temp[0] == 'P' && temp[1] == 'K' && temp[2] == 0x03 && temp[3] == 0x04 ) + { + // It's a zip file, unzip to the apps directory + + // Zip archive, ask for permission to install the zip + char zippath[255]; + sprintf( ( char * ) &zippath, "%s%s", Settings.homebrewapps_path, filename ); + + FILE *fp = fopen( zippath, "wb" ); + if ( fp != NULL ) + { + fwrite( temp, 1, infilesize, fp ); + fclose( fp ); + + // Now unzip the zip file... + unzFile uf = unzOpen( zippath ); + if ( uf == NULL ) + { + error = true; + } + else + { + extractZip( uf, 0, 1, 0, Settings.homebrewapps_path ); + unzCloseCurrentFile( uf ); + + remove( zippath ); + + // Reload this menu here... + menu = MENU_HOMEBREWBROWSE; + break; + } + } + else + { + error = true; + } + } + else if ( uncfilesize != 0 ) // if uncfilesize == 0, it's not compressed + { + // It's compressed, uncompress + u8 *unc = ( u8 * ) malloc( uncfilesize ); + uLongf f = uncfilesize; + error = uncompress( unc, &f, temp, infilesize ) != Z_OK; + uncfilesize = f; + homebrewsize = uncfilesize; + + free( temp ); + temp = unc; + } + } + + if ( !error && strstr( filename, ".zip" ) == NULL ) + { + innetbuffer = temp; + + } + } + + ProgressStop(); + + if ( error || read != infilesize ) + { + 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" ) ) + { + boothomebrew = 2; + AddBootArgument( filename ); + menu = MENU_EXIT; + CloseConnection(); + break; + } + else if ( strstr( filename, ".zip" ) ) + { + 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" ) ); + } + } + } + } + CloseConnection(); + ResumeNetworkWait(); + } + + else if ( channelBtn.GetState() == STATE_CLICKED ) + { + 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 ); + channelBtn.ResetState(); + + + } + + if ( IsNetworkInit() ) + { + if ( !wifi_btn_loaded ) + { + wifiBtn.SetAlpha( 255 ); + + 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++) { - if (IconData[i] != NULL) { - delete IconData[i]; - IconData[i] = NULL; - } - if (IconImg[i] != NULL) { - delete IconImg[i]; - IconImg[i] = NULL; - } + for ( int i = 0; i < 4; i++ ) + { + if ( IconData[i] != NULL ) + { + delete IconData[i]; + IconData[i] = NULL; + } + if ( IconImg[i] != NULL ) + { + delete IconImg[i]; + IconImg[i] = NULL; + } } 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 f1605bb3..8253aaa7 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 2b43ad71..f4a89ab8 100644 --- a/source/homebrewboot/HomebrewFiles.cpp +++ b/source/homebrewboot/HomebrewFiles.cpp @@ -9,108 +9,128 @@ #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) { - free(FileInfo); +HomebrewFiles::~HomebrewFiles() +{ + if ( 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) { - if ((st.st_mode & S_IFDIR) != 0) { - if (strcmp(filename,".") != 0 && strcmp(filename,"..") != 0) { + while ( dirnext( dir, filename, &st ) == 0 ) + { + if ( ( st.st_mode & S_IFDIR ) != 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 { + } + else + { char temp[5]; - for (int i = 0; i < 5; i++) { - temp[i] = filename[strlen(filename)-4+i]; + for ( int i = 0; i < 5; 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) { - free(FileInfo); + if ( !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) { - if (ind > filecount) +char * HomebrewFiles::GetFilename( int ind ) +{ + if ( ind > filecount ) return NULL; else return FileInfo[ind].FileName; } -char * HomebrewFiles::GetFilepath(int ind) { - if (ind > filecount) +char * HomebrewFiles::GetFilepath( int ind ) +{ + if ( ind > filecount ) return NULL; else return FileInfo[ind].FilePath; } -unsigned int HomebrewFiles::GetFilesize(int ind) { - if (ind > filecount || !filecount || !FileInfo) +unsigned int HomebrewFiles::GetFilesize( int ind ) +{ + if ( ind > filecount || !filecount || !FileInfo ) return NULL; else return FileInfo[ind].FileSize; } -int HomebrewFiles::GetFilecount() { +int HomebrewFiles::GetFilecount() +{ return filecount; } -static int ListCompare(const void *a, const void *b) { - FileInfos *ab = (FileInfos*) a; - FileInfos *bb = (FileInfos*) b; +static int ListCompare( const void *a, const void *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); +void HomebrewFiles::SortList() +{ + qsort( FileInfo, filecount, sizeof( FileInfos ), ListCompare ); } diff --git a/source/homebrewboot/HomebrewFiles.h b/source/homebrewboot/HomebrewFiles.h index c1d73d92..17f4e1a2 100644 --- a/source/homebrewboot/HomebrewFiles.h +++ b/source/homebrewboot/HomebrewFiles.h @@ -7,38 +7,40 @@ #define MAXHOMEBREWS 500 -typedef struct { +typedef struct +{ char FileName[100]; char FilePath[150]; unsigned int FileSize; } FileInfos; -class HomebrewFiles { -public: - //!Constructor - //!\param path Path where to check for homebrew files - 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); - //! Get the a filename of the list - //!\param list index - char * GetFilename(int index); - //! Get the a filepath of the list - //!\param list index - char * GetFilepath(int index); - //! Get the a filesize of the list - //!\param list index - unsigned int GetFilesize(int index); - //! Get the filecount of the whole list - int GetFilecount(); - //! Sort list by filepath - void SortList(); -protected: - int filecount; - FileInfos *FileInfo; +class HomebrewFiles +{ + public: + //!Constructor + //!\param path Path where to check for homebrew files + 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 ); + //! Get the a filename of the list + //!\param list index + char * GetFilename( int index ); + //! Get the a filepath of the list + //!\param list index + char * GetFilepath( int index ); + //! Get the a filesize of the list + //!\param list index + unsigned int GetFilesize( int index ); + //! Get the filecount of the whole list + int GetFilecount(); + //! Sort list by filepath + void SortList(); + protected: + int filecount; + FileInfos *FileInfo; }; #endif diff --git a/source/homebrewboot/HomebrewXML.cpp b/source/homebrewboot/HomebrewXML.cpp index 4225bab1..eb02bc47 100644 --- a/source/homebrewboot/HomebrewXML.cpp +++ b/source/homebrewboot/HomebrewXML.cpp @@ -11,58 +11,58 @@ #define ENTRIE_SIZE 8192 -int HomebrewXML::LoadHomebrewXMLData(const char* filename) +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) + 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) + if ( nodetreeHB == NULL ) return -2; - nodedataHB = mxmlFindElement(nodetreeHB, nodetreeHB, "app", NULL, NULL, MXML_DESCEND); - if (nodedataHB == NULL) + 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]); + 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); + snprintf( Entrie, ENTRIE_SIZE, "%s", Entrie ); Releasedate = Entrie; - free(nodedataHB); - free(nodetreeHB); + free( nodedataHB ); + free( nodetreeHB ); delete [] Entrie; diff --git a/source/homebrewboot/HomebrewXML.h b/source/homebrewboot/HomebrewXML.h index 3255ddf3..05bec500 100644 --- a/source/homebrewboot/HomebrewXML.h +++ b/source/homebrewboot/HomebrewXML.h @@ -16,7 +16,7 @@ class HomebrewXML //!Destructor ~HomebrewXML() { }; //!\param filename Filepath of the XML file - int LoadHomebrewXMLData(const char* filename); + int LoadHomebrewXMLData( const char* filename ); //! Get name const char * GetName() { return Name.c_str(); }; //! Get coder @@ -30,7 +30,7 @@ class HomebrewXML //! Get longdescription const char * GetLongDescription() { return LongDescription.c_str(); }; //! Set Name - void SetName(char * newName) { Name = newName; }; + void SetName( char * newName ) { Name = newName; }; protected: std::string Name; std::string Coder; diff --git a/source/homebrewboot/dolloader.c b/source/homebrewboot/dolloader.c index 5edce25d..4784798c 100644 --- a/source/homebrewboot/dolloader.c +++ b/source/homebrewboot/dolloader.c @@ -8,7 +8,8 @@ #include "dolloader.h" -typedef struct _dolheader { +typedef struct _dolheader +{ u32 text_pos[7]; u32 data_pos[11]; u32 text_start[7]; @@ -20,31 +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) { - 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 ( dolstart ) + { + 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] ); } - 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]); + 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] ); } - 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) { - void *new_argv = (void *)(dolfile->entry_point + 8); - memcpy(new_argv, argv, sizeof(*argv)); - DCFlushRange(new_argv, sizeof(*argv)); + 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 ) ); } return dolfile->entry_point; diff --git a/source/homebrewboot/dolloader.h b/source/homebrewboot/dolloader.h index af644414..4dbd49b6 100644 --- a/source/homebrewboot/dolloader.h +++ b/source/homebrewboot/dolloader.h @@ -2,13 +2,14 @@ #define _DOLLOADER_H_ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -extern void __exception_closeall(); -typedef void (*entrypoint) (void); + extern void __exception_closeall(); + typedef void ( *entrypoint ) ( void ); -u32 load_dol(const void *dolstart, struct __argv *argv); + u32 load_dol( const void *dolstart, struct __argv *argv ); #ifdef __cplusplus diff --git a/source/input.cpp b/source/input.cpp index 2ad140c5..d5fe7194 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,22 @@ 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 ); } } @@ -60,26 +60,28 @@ void UpdatePads() ***************************************************************************/ void SetupPads() { - PAD_Init(); - WPAD_Init(); + PAD_Init(); + 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); + // read wiimote accelerometer and IR data + WPAD_SetDataFormat( WPAD_CHAN_ALL, WPAD_FMT_BTNS_ACC_IR ); + WPAD_SetVRes( WPAD_CHAN_ALL, screenwidth, screenheight ); - for(int i=0; i < 4; i++) - { - userInput[i].chan = i; - } + for ( int i = 0; i < 4; i++ ) + { + userInput[i].chan = i; + } } /**************************************************************************** * ShutoffRumble ***************************************************************************/ -void ShutoffRumble() { - for (int i=0;i<4;i++) { - WPAD_Rumble(i, 0); +void ShutoffRumble() +{ + for ( int i = 0; i < 4; i++ ) + { + WPAD_Rumble( i, 0 ); rumbleCount[i] = 0; } } @@ -88,17 +90,23 @@ void ShutoffRumble() { * DoRumble ***************************************************************************/ -void DoRumble(int i) { - if (rumbleRequest[i] && rumbleCount[i] < 3) { - WPAD_Rumble(i, 1); // rumble on +void DoRumble( int i ) +{ + if ( rumbleRequest[i] && rumbleCount[i] < 3 ) + { + 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]) + } + else + { + if ( rumbleCount[i] ) rumbleCount[i]--; - WPAD_Rumble(i, 0); // rumble off + WPAD_Rumble( i, 0 ); // rumble off } } @@ -108,43 +116,49 @@ 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) { - case WPAD_EXP_NUNCHUK: - case WPAD_EXP_GUITARHERO3: - if (right == 0) { - mag = data->exp.nunchuk.js.mag; - ang = data->exp.nunchuk.js.ang; - } - break; + switch ( data->exp.type ) + { + case WPAD_EXP_NUNCHUK: + case WPAD_EXP_GUITARHERO3: + if ( right == 0 ) + { + mag = data->exp.nunchuk.js.mag; + ang = data->exp.nunchuk.js.ang; + } + break; - case WPAD_EXP_CLASSIC: - if (right == 0) { - mag = data->exp.classic.ljs.mag; - ang = data->exp.classic.ljs.ang; - } else { - mag = data->exp.classic.rjs.mag; - ang = data->exp.classic.rjs.ang; - } - break; + case WPAD_EXP_CLASSIC: + if ( right == 0 ) + { + mag = data->exp.classic.ljs.mag; + ang = data->exp.classic.ljs.ang; + } + else + { + mag = data->exp.classic.rjs.mag; + ang = data->exp.classic.rjs.ang; + } + break; - default: - break; + default: + break; } /* calculate x/y value (angle need to be converted into radian) */ - if (mag > 1.0) mag = 1.0; - else if (mag < -1.0) mag = -1.0; + 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 ce3c54de..94d71139 100644 --- a/source/input.h +++ b/source/input.h @@ -12,14 +12,14 @@ #include #include -#define PI 3.14159265f -#define PADCAL 50 +#define PI 3.14159265f +#define PADCAL 50 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 5478a086..9337fe3b 100644 --- a/source/language/UpdateLanguage.cpp +++ b/source/language/UpdateLanguage.cpp @@ -13,46 +13,53 @@ #include "network/networkops.h" #include "network/http.h" -int updateLanguageFiles() { +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")) { - strcpy(languageFiles[cnt],filename); + strlcpy( filename, GetFileName( cnt ), sizeof( filename ) ); + if ( strcasestr( filename, ".lang" ) ) + { + 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()) { + int done = 0, j = 0; + if ( IsNetworkInit() ) + { //build the URL, save path, and download each file and save it - while (j #include "gettext.h" -typedef struct _MSG { +typedef struct _MSG +{ u32 id; char* msgstr; struct _MSG *next; } MSG; -static MSG *baseMSG=0; +static MSG *baseMSG = 0; #define HASHWORDBITS 32 @@ -18,18 +19,21 @@ static MSG *baseMSG=0; [see Aho/Sethi/Ullman, COMPILERS: Principles, Techniques and Tools, 1986, 1987 Bell Telephone Laboratories, Inc.] */ static inline u32 -hash_string (const char *str_param) { +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 ^= g >> (HASHWORDBITS - 8); + hval += ( u8 ) * str++; + g = hval & ( ( u32 ) 0xf << ( HASHWORDBITS - 4 ) ); + if ( g != 0 ) + { + hval ^= g >> ( HASHWORDBITS - 8 ); hval ^= g; } } @@ -38,88 +42,95 @@ 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') + if ( cp[0] == '\0' ) goto terminate; - do { + do + { /* Here cp[0] == '\\'. */ - switch (*++cp) { - case '\"': /* " */ - *rp++ = '\"'; - ++cp; - break; - case 'a': /* alert */ - *rp++ = '\a'; - ++cp; - break; - case 'b': /* backspace */ - *rp++ = '\b'; - ++cp; - break; - case 'f': /* form feed */ - *rp++ = '\f'; - ++cp; - break; - case 'n': /* new line */ - *rp++ = '\n'; - ++cp; - break; - case 'r': /* carriage return */ - *rp++ = '\r'; - ++cp; - break; - case 't': /* horizontal tab */ - *rp++ = '\t'; - ++cp; - break; - case 'v': /* vertical tab */ - *rp++ = '\v'; - ++cp; - break; - case '\\': - *rp = '\\'; - ++cp; - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': { - int ch = *cp++ - '0'; + switch ( *++cp ) + { + case '\"': /* " */ + *rp++ = '\"'; + ++cp; + break; + case 'a': /* alert */ + *rp++ = '\a'; + ++cp; + break; + case 'b': /* backspace */ + *rp++ = '\b'; + ++cp; + break; + case 'f': /* form feed */ + *rp++ = '\f'; + ++cp; + break; + case 'n': /* new line */ + *rp++ = '\n'; + ++cp; + break; + case 'r': /* carriage return */ + *rp++ = '\r'; + ++cp; + break; + case 't': /* horizontal tab */ + *rp++ = '\t'; + ++cp; + break; + case 'v': /* vertical tab */ + *rp++ = '\v'; + ++cp; + break; + case '\\': + *rp = '\\'; + ++cp; + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + { + int ch = *cp++ - '0'; - if (*cp >= '0' && *cp <= '7') { - ch *= 8; - 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'; + } } + *rp = ch; } - *rp = ch; - } - break; - default: - *rp = '\\'; - break; + 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: @@ -127,95 +138,112 @@ terminate: return retval; } -static MSG *findMSG(u32 id) { +static MSG *findMSG( u32 id ) +{ MSG *msg; - for (msg=baseMSG; msg; msg=msg->next) { - if (msg->id == id) + for ( msg = baseMSG; msg; msg = msg->next ) + { + if ( msg->id == id ) return msg; } return NULL; } -static MSG *setMSG(const char *msgid, const char *msgstr) { - u32 id = hash_string(msgid); - MSG *msg = findMSG(id); - if (!msg) { - msg = (MSG *)malloc(sizeof(MSG)); - msg->id = id; +static MSG *setMSG( const char *msgid, const char *msgstr ) +{ + u32 id = hash_string( msgid ); + MSG *msg = findMSG( id ); + if ( !msg ) + { + msg = ( MSG * )malloc( sizeof( MSG ) ); + msg->id = id; msg->msgstr = NULL; - msg->next = baseMSG; - baseMSG = msg; + msg->next = baseMSG; + baseMSG = msg; } - if (msg) { - if (msgstr) { - if (msg->msgstr) free(msg->msgstr); + if ( msg ) + { + if ( 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) { - while (baseMSG) { - MSG *nextMsg =baseMSG->next; - free(baseMSG->msgstr); - free(baseMSG); +void gettextCleanUp( void ) +{ + while ( baseMSG ) + { + MSG *nextMsg = baseMSG->next; + 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; + char *lastID = NULL; gettextCleanUp(); - f = fopen(langFile, "r"); - if (!f) + 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) { - free(lastID); - lastID=NULL; + if ( 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) + 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); - lastID=NULL; + free( lastID ); + lastID = NULL; } } - fclose(f); + fclose( f ); return true; } -const char *gettext(const char *msgid) { - MSG *msg = findMSG(hash_string(msgid)); - if (msg && msg->msgstr) return msg->msgstr; +const char *gettext( const char *msgid ) +{ + 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 7869d015..d196ce1a 100644 --- a/source/language/gettext.h +++ b/source/language/gettext.h @@ -2,17 +2,18 @@ #define _GETTEXT_H_ #ifdef __cplusplus -extern "C" { +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) diff --git a/source/libfat/bit_ops.h b/source/libfat/bit_ops.h index 8a5fb3e1..0a25597d 100644 --- a/source/libfat/bit_ops.h +++ b/source/libfat/bit_ops.h @@ -34,24 +34,28 @@ /*----------------------------------------------------------------- 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 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/libfat/cache.h b/source/libfat/cache.h index c6e48d07..f7c70afa 100644 --- a/source/libfat/cache.h +++ b/source/libfat/cache.h @@ -42,20 +42,22 @@ #define PAGE_SECTORS 64 #define CACHE_PAGE_SIZE (BYTES_PER_READ * PAGE_SECTORS) -typedef struct { - sec_t sector; - unsigned int count; - unsigned int last_access; - bool dirty; - uint8_t* cache; +typedef struct +{ + 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; +typedef struct +{ + const DISC_INTERFACE* disc; + sec_t endOfPartition; + unsigned int numberOfPages; + unsigned int sectorsPerPage; + CACHE_ENTRY* cacheEntries; } CACHE; /* @@ -65,9 +67,9 @@ 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_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 @@ -77,9 +79,9 @@ 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_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 @@ -89,42 +91,44 @@ 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); +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); +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) { - return _FAT_cache_readPartialSector (cache, buffer, sector, 0, BYTES_PER_READ); +static inline bool _FAT_cache_readSector ( CACHE* cache, void* buffer, sec_t sector ) +{ + return _FAT_cache_readPartialSector ( cache, buffer, sector, 0, BYTES_PER_READ ); } /* Write a full sector to the cache */ -static inline bool _FAT_cache_writeSector (CACHE* cache, const void* buffer, sec_t sector) { - return _FAT_cache_writePartialSector (cache, buffer, sector, 0, BYTES_PER_READ); +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 ); } -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); +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); +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/directory.c b/source/libfat/directory.c index 279a361d..e9f53f50 100644 --- a/source/libfat/directory.c +++ b/source/libfat/directory.c @@ -4,7 +4,7 @@ a FAT partition Copyright (c) 2006 Michael "Chishm" Chisholm - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -51,27 +51,28 @@ typedef unsigned short ucs2_t; // Long file name directory entry -enum LFN_offset { - LFN_offset_ordinal = 0x00, // Position within LFN - LFN_offset_char0 = 0x01, - LFN_offset_char1 = 0x03, - LFN_offset_char2 = 0x05, - LFN_offset_char3 = 0x07, - LFN_offset_char4 = 0x09, - LFN_offset_flag = 0x0B, // Should be equal to ATTRIB_LFN - LFN_offset_reserved1 = 0x0C, // Always 0x00 - LFN_offset_checkSum = 0x0D, // Checksum of short file name (alias) - LFN_offset_char5 = 0x0E, - LFN_offset_char6 = 0x10, - LFN_offset_char7 = 0x12, - LFN_offset_char8 = 0x14, - LFN_offset_char9 = 0x16, - LFN_offset_char10 = 0x18, - LFN_offset_reserved2 = 0x1A, // Always 0x0000 - LFN_offset_char11 = 0x1C, - LFN_offset_char12 = 0x1E +enum LFN_offset +{ + LFN_offset_ordinal = 0x00, // Position within LFN + LFN_offset_char0 = 0x01, + LFN_offset_char1 = 0x03, + LFN_offset_char2 = 0x05, + LFN_offset_char3 = 0x07, + LFN_offset_char4 = 0x09, + LFN_offset_flag = 0x0B, // Should be equal to ATTRIB_LFN + LFN_offset_reserved1 = 0x0C, // Always 0x00 + LFN_offset_checkSum = 0x0D, // Checksum of short file name (alias) + LFN_offset_char5 = 0x0E, + LFN_offset_char6 = 0x10, + LFN_offset_char7 = 0x12, + LFN_offset_char8 = 0x14, + LFN_offset_char9 = 0x16, + LFN_offset_char10 = 0x18, + LFN_offset_reserved2 = 0x1A, // Always 0x0000 + LFN_offset_char11 = 0x1C, + LFN_offset_char12 = 0x1E }; -static const int LFN_offset_table[13]={0x01,0x03,0x05,0x07,0x09,0x0E,0x10,0x12,0x14,0x16,0x18,0x1C,0x1E}; +static const int LFN_offset_table[13] = {0x01, 0x03, 0x05, 0x07, 0x09, 0x0E, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1C, 0x1E}; #define LFN_END 0x40 #define LFN_DEL 0x80 @@ -79,997 +80,1206 @@ static const int LFN_offset_table[13]={0x01,0x03,0x05,0x07,0x09,0x0E,0x10,0x12,0 static const char ILLEGAL_ALIAS_CHARACTERS[] = "\\/:;*?\"<>|&+,=[] "; static const char ILLEGAL_LFN_CHARACTERS[] = "\\/:*?\"<>|"; -/* +/* Returns number of UCS-2 characters needed to encode an LFN Returns -1 if it is an invalid LFN */ #define ABOVE_UCS_RANGE 0xF0 -static int _FAT_directory_lfnLength (const char* name) { - unsigned int i; - size_t nameLength; - int ucsLength; - const char* tempName = name; - - nameLength = strnlen(name, MAX_FILENAME_LENGTH); - // Make sure the name is short enough to be valid - if ( nameLength >= MAX_FILENAME_LENGTH) { - return -1; - } - // Make sure it doesn't contain any invalid characters - if (strpbrk (name, ILLEGAL_LFN_CHARACTERS) != NULL) { - return -1; - } - // Make sure the name doesn't contain any control codes or codes not representable in UCS-2 - for (i = 0; i < nameLength; i++) { - if (name[i] < 0x20 || name[i] >= ABOVE_UCS_RANGE) { - return -1; - } - } - // Convert to UCS-2 and get the resulting length - ucsLength = mbsrtowcs(NULL, &tempName, MAX_LFN_LENGTH, NULL); - if (ucsLength < 0 || ucsLength >= MAX_LFN_LENGTH) { - return -1; - } - - // Otherwise it is valid - return ucsLength; +static int _FAT_directory_lfnLength ( const char* name ) +{ + unsigned int i; + size_t nameLength; + int ucsLength; + const char* tempName = name; + + nameLength = strnlen( name, MAX_FILENAME_LENGTH ); + // Make sure the name is short enough to be valid + if ( nameLength >= MAX_FILENAME_LENGTH ) + { + return -1; + } + // Make sure it doesn't contain any invalid characters + if ( strpbrk ( name, ILLEGAL_LFN_CHARACTERS ) != NULL ) + { + return -1; + } + // Make sure the name doesn't contain any control codes or codes not representable in UCS-2 + for ( i = 0; i < nameLength; i++ ) + { + if ( name[i] < 0x20 || name[i] >= ABOVE_UCS_RANGE ) + { + return -1; + } + } + // Convert to UCS-2 and get the resulting length + ucsLength = mbsrtowcs( NULL, &tempName, MAX_LFN_LENGTH, NULL ); + if ( ucsLength < 0 || ucsLength >= MAX_LFN_LENGTH ) + { + return -1; + } + + // Otherwise it is valid + return ucsLength; } /* 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}; - wchar_t tempChar; - int bytes; - size_t count = 0; +static size_t _FAT_directory_mbstoucs2 ( ucs2_t* dst, const char* src, size_t len ) +{ + mbstate_t ps = {0}; + wchar_t tempChar; + int bytes; + size_t count = 0; - while (count < len-1 && src != '\0') { - bytes = mbrtowc (&tempChar, src, MB_CUR_MAX, &ps); - if (bytes > 0) { - *dst = (ucs2_t)tempChar; - src += bytes; - dst++; - count++; - } else if (bytes == 0) { - break; - } else { - return -1; - } - } - *dst = '\0'; + while ( count < len - 1 && src != '\0' ) + { + bytes = mbrtowc ( &tempChar, src, MB_CUR_MAX, &ps ); + if ( bytes > 0 ) + { + *dst = ( ucs2_t )tempChar; + src += bytes; + dst++; + count++; + } + else if ( bytes == 0 ) + { + break; + } + else + { + return -1; + } + } + *dst = '\0'; - return count; + return count; } /* 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}; - size_t count = 0; - int bytes; - char buff[MB_CUR_MAX]; - int i; - - while (count < len - 1 && *src != '\0') { - bytes = wcrtomb (buff, *src, &ps); - if (bytes < 0) { - return -1; - } - if (count + bytes < len && bytes > 0) { - for (i = 0; i < bytes; i++) { - *dst++ = buff[i]; - } - src++; - count += bytes; - } else { - break; - } - } - *dst = L'\0'; - - return count; +static size_t _FAT_directory_ucs2tombs ( char* dst, const ucs2_t* src, size_t len ) +{ + mbstate_t ps = {0}; + size_t count = 0; + int bytes; + char buff[MB_CUR_MAX]; + int i; + + while ( count < len - 1 && *src != '\0' ) + { + bytes = wcrtomb ( buff, *src, &ps ); + if ( bytes < 0 ) + { + return -1; + } + if ( count + bytes < len && bytes > 0 ) + { + for ( i = 0; i < bytes; i++ ) + { + *dst++ = buff[i]; + } + src++; + count += bytes; + } + else + { + break; + } + } + *dst = L'\0'; + + return count; } /* Case-independent comparison of two multibyte encoded strings */ -static int _FAT_directory_mbsncasecmp (const char* s1, const char* s2, size_t len1) { - wchar_t wc1, wc2; - mbstate_t ps1 = {0}; - mbstate_t ps2 = {0}; - size_t b1 = 0; - size_t b2 = 0; - - if (len1 == 0) { - return 0; - } - - do { - s1 += b1; - s2 += b2; - b1 = mbrtowc(&wc1, s1, MB_CUR_MAX, &ps1); - b2 = mbrtowc(&wc2, s2, MB_CUR_MAX, &ps2); - if ((int)b1 < 0 || (int)b2 < 0) { - break; - } - len1 -= b1; - } while (len1 > 0 && towlower(wc1) == towlower(wc2) && wc1 != 0); - - return towlower(wc1) - towlower(wc2); +static int _FAT_directory_mbsncasecmp ( const char* s1, const char* s2, size_t len1 ) +{ + wchar_t wc1, wc2; + mbstate_t ps1 = {0}; + mbstate_t ps2 = {0}; + size_t b1 = 0; + size_t b2 = 0; + + if ( len1 == 0 ) + { + return 0; + } + + do + { + s1 += b1; + s2 += b2; + b1 = mbrtowc( &wc1, s1, MB_CUR_MAX, &ps1 ); + b2 = mbrtowc( &wc2, s2, MB_CUR_MAX, &ps2 ); + if ( ( int )b1 < 0 || ( int )b2 < 0 ) + { + break; + } + len1 -= b1; + } + while ( len1 > 0 && towlower( wc1 ) == towlower( wc2 ) && wc1 != 0 ); + + return towlower( wc1 ) - towlower( wc2 ); } -static bool _FAT_directory_entryGetAlias (const u8* entryData, char* destName) { - int i=0; - int j=0; +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] == '.') { - destName[0] = '.'; - if (entryData[1] == '.') { - destName[1] = '.'; - destName[2] = '\0'; - } else { - destName[1] = '\0'; - } - } else { - // Copy the filename from the dirEntry to the string - for (i = 0; (i < 8) && (entryData[DIR_ENTRY_name + i] != ' '); i++) { - destName[i] = entryData[DIR_ENTRY_name + i]; - } - // Copy the extension from the dirEntry to the string - if (entryData[DIR_ENTRY_extension] != ' ') { - destName[i++] = '.'; - for ( j = 0; (j < 3) && (entryData[DIR_ENTRY_extension + j] != ' '); j++) { - destName[i++] = entryData[DIR_ENTRY_extension + j]; - } - } - destName[i] = '\0'; - } - } + destName[0] = '\0'; + if ( entryData[0] != DIR_ENTRY_FREE ) + { + if ( entryData[0] == '.' ) + { + destName[0] = '.'; + if ( entryData[1] == '.' ) + { + destName[1] = '.'; + destName[2] = '\0'; + } + else + { + destName[1] = '\0'; + } + } + else + { + // Copy the filename from the dirEntry to the string + for ( i = 0; ( i < 8 ) && ( entryData[DIR_ENTRY_name + i] != ' ' ); i++ ) + { + destName[i] = entryData[DIR_ENTRY_name + i]; + } + // Copy the extension from the dirEntry to the string + if ( entryData[DIR_ENTRY_extension] != ' ' ) + { + destName[i++] = '.'; + for ( j = 0; ( j < 3 ) && ( entryData[DIR_ENTRY_extension + j] != ' ' ); j++ ) + { + destName[i++] = entryData[DIR_ENTRY_extension + j]; + } + } + destName[i] = '\0'; + } + } - return (destName[0] != '\0'); + return ( destName[0] != '\0' ); } -uint32_t _FAT_directory_entryGetCluster (PARTITION* partition, const uint8_t* entryData) { - if (partition->filesysType == FS_FAT32) { - // Only use high 16 bits of start cluster when we are certain they are correctly defined - return u8array_to_u16(entryData,DIR_ENTRY_cluster) | (u8array_to_u16(entryData, DIR_ENTRY_clusterHigh) << 16); - } else { - return u8array_to_u16(entryData,DIR_ENTRY_cluster); - } +uint32_t _FAT_directory_entryGetCluster ( PARTITION* partition, const uint8_t* entryData ) +{ + if ( partition->filesysType == FS_FAT32 ) + { + // Only use high 16 bits of start cluster when we are certain they are correctly defined + return u8array_to_u16( entryData, DIR_ENTRY_cluster ) | ( u8array_to_u16( entryData, DIR_ENTRY_clusterHigh ) << 16 ); + } + else + { + return u8array_to_u16( entryData, DIR_ENTRY_cluster ); + } } -static bool _FAT_directory_incrementDirEntryPosition (PARTITION* partition, DIR_ENTRY_POSITION* entryPosition, bool extendDirectory) { - DIR_ENTRY_POSITION position = *entryPosition; - uint32_t tempCluster; +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 = 0; - // Increment sector when wrapping - ++ position.sector; - // But wrap at the end of a cluster - if ((position.sector == partition->sectorsPerCluster) && (position.cluster != FAT16_ROOT_DIR_CLUSTER)) { - position.sector = 0; - // Move onto the next cluster, making sure there is another cluster to go to - tempCluster = _FAT_fat_nextCluster(partition, position.cluster); - if (tempCluster == CLUSTER_EOF) { - if (extendDirectory) { - tempCluster = _FAT_fat_linkFreeClusterCleared (partition, position.cluster); - if (!_FAT_fat_isValidCluster(partition, tempCluster)) { - return false; // This will only happen if the disc is full - } - } else { - return false; // Got to the end of the directory, not extending it - } - } - position.cluster = tempCluster; - } else if ((position.cluster == FAT16_ROOT_DIR_CLUSTER) && (position.sector == (partition->dataStart - partition->rootDirStart))) { - return false; // Got to end of root directory, can't extend it - } - } - *entryPosition = position; - return true; + // Increment offset, wrapping at the end of a sector + ++ position.offset; + if ( position.offset == BYTES_PER_READ / DIR_ENTRY_DATA_SIZE ) + { + position.offset = 0; + // Increment sector when wrapping + ++ position.sector; + // But wrap at the end of a cluster + if ( ( position.sector == partition->sectorsPerCluster ) && ( position.cluster != FAT16_ROOT_DIR_CLUSTER ) ) + { + position.sector = 0; + // Move onto the next cluster, making sure there is another cluster to go to + tempCluster = _FAT_fat_nextCluster( partition, position.cluster ); + if ( tempCluster == CLUSTER_EOF ) + { + if ( extendDirectory ) + { + tempCluster = _FAT_fat_linkFreeClusterCleared ( partition, position.cluster ); + if ( !_FAT_fat_isValidCluster( partition, tempCluster ) ) + { + return false; // This will only happen if the disc is full + } + } + else + { + return false; // Got to the end of the directory, not extending it + } + } + position.cluster = tempCluster; + } + else if ( ( position.cluster == FAT16_ROOT_DIR_CLUSTER ) && ( position.sector == ( partition->dataStart - partition->rootDirStart ) ) ) + { + return false; // Got to end of root directory, can't extend it + } + } + *entryPosition = position; + return true; } -bool _FAT_directory_getNextEntry (PARTITION* partition, DIR_ENTRY* entry) { - DIR_ENTRY_POSITION entryStart; - DIR_ENTRY_POSITION entryEnd; - uint8_t entryData[0x20]; - ucs2_t lfn[MAX_LFN_LENGTH]; - bool notFound, found; - int lfnPos; - uint8_t lfnChkSum, chkSum; - bool lfnExists; - int i; +bool _FAT_directory_getNextEntry ( PARTITION* partition, DIR_ENTRY* entry ) +{ + DIR_ENTRY_POSITION entryStart; + DIR_ENTRY_POSITION entryEnd; + uint8_t entryData[0x20]; + ucs2_t lfn[MAX_LFN_LENGTH]; + bool notFound, found; + int lfnPos; + uint8_t lfnChkSum, chkSum; + bool lfnExists; + int i; - lfnChkSum = 0; + lfnChkSum = 0; - entryStart = entry->dataEnd; + entryStart = entry->dataEnd; - // Make sure we are using the correct root directory, in case of FAT32 - if (entryStart.cluster == FAT16_ROOT_DIR_CLUSTER) { - entryStart.cluster = partition->rootDirCluster; - } + // Make sure we are using the correct root directory, in case of FAT32 + if ( entryStart.cluster == FAT16_ROOT_DIR_CLUSTER ) + { + entryStart.cluster = partition->rootDirCluster; + } - entryEnd = entryStart; + entryEnd = entryStart; - lfnExists = false; + lfnExists = false; - found = false; - notFound = false; + found = false; + notFound = false; - while (!found && !notFound) { - if (_FAT_directory_incrementDirEntryPosition (partition, &entryEnd, false) == false) { - notFound = true; - } + while ( !found && !notFound ) + { + if ( _FAT_directory_incrementDirEntryPosition ( partition, &entryEnd, false ) == false ) + { + notFound = true; + } - _FAT_cache_readPartialSector (partition->cache, entryData, - _FAT_fat_clusterToSector(partition, entryEnd.cluster) + entryEnd.sector, - entryEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); + _FAT_cache_readPartialSector ( partition->cache, entryData, + _FAT_fat_clusterToSector( partition, entryEnd.cluster ) + entryEnd.sector, + entryEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE ); - if (entryData[DIR_ENTRY_attributes] == ATTRIB_LFN) { - // It's an LFN - if (entryData[LFN_offset_ordinal] & LFN_DEL) { - lfnExists = false; - } else if (entryData[LFN_offset_ordinal] & LFN_END) { - // Last part of LFN, make sure it isn't deleted using previous if(Thanks MoonLight) - entryStart = entryEnd; // This is the start of a directory entry - lfnExists = true; - lfnPos = (entryData[LFN_offset_ordinal] & ~LFN_END) * 13; - if (lfnPos > MAX_LFN_LENGTH - 1) { - lfnPos = MAX_LFN_LENGTH - 1; - } - lfn[lfnPos] = '\0'; // Set end of lfn to null character - lfnChkSum = entryData[LFN_offset_checkSum]; - } if (lfnChkSum != entryData[LFN_offset_checkSum]) { - lfnExists = false; - } - if (lfnExists) { - lfnPos = ((entryData[LFN_offset_ordinal] & ~LFN_END) - 1) * 13; - if (lfnPos > LAST_LFN_POS) { - // Force it within the buffer. Will corrupt the filename but prevent buffer overflows - lfnPos = LAST_LFN_POS; - } - for (i = 0; i < 13; i++) { - lfn[lfnPos + i] = entryData[LFN_offset_table[i]] | (entryData[LFN_offset_table[i]+1] << 8); - } - } - } else if (entryData[DIR_ENTRY_attributes] & ATTRIB_VOL) { - // This is a volume name, don't bother with it - } else if (entryData[0] == DIR_ENTRY_LAST) { - notFound = true; - } else if ((entryData[0] != DIR_ENTRY_FREE) && (entryData[0] > 0x20) && !(entryData[DIR_ENTRY_attributes] & ATTRIB_VOL)) { - if (lfnExists) { - // Calculate file checksum - chkSum = 0; - for (i=0; i < 11; i++) { - // NOTE: The operation is an unsigned char rotate right - chkSum = ((chkSum & 1) ? 0x80 : 0) + (chkSum >> 1) + entryData[i]; - } - if (chkSum != lfnChkSum) { - lfnExists = false; - entry->filename[0] = '\0'; - } - } - - if (lfnExists) { - if (_FAT_directory_ucs2tombs (entry->filename, lfn, MAX_FILENAME_LENGTH) == (size_t)-1) { - // Failed to convert the file name to UTF-8. Maybe the wrong locale is set? - return false; - } - } else { - entryStart = entryEnd; - _FAT_directory_entryGetAlias (entryData, entry->filename); - } - found = true; - } - } + if ( entryData[DIR_ENTRY_attributes] == ATTRIB_LFN ) + { + // It's an LFN + if ( entryData[LFN_offset_ordinal] & LFN_DEL ) + { + lfnExists = false; + } + else if ( entryData[LFN_offset_ordinal] & LFN_END ) + { + // Last part of LFN, make sure it isn't deleted using previous if(Thanks MoonLight) + entryStart = entryEnd; // This is the start of a directory entry + lfnExists = true; + lfnPos = ( entryData[LFN_offset_ordinal] & ~LFN_END ) * 13; + if ( lfnPos > MAX_LFN_LENGTH - 1 ) + { + lfnPos = MAX_LFN_LENGTH - 1; + } + lfn[lfnPos] = '\0'; // Set end of lfn to null character + lfnChkSum = entryData[LFN_offset_checkSum]; + } if ( lfnChkSum != entryData[LFN_offset_checkSum] ) + { + lfnExists = false; + } + if ( lfnExists ) + { + lfnPos = ( ( entryData[LFN_offset_ordinal] & ~LFN_END ) - 1 ) * 13; + if ( lfnPos > LAST_LFN_POS ) + { + // Force it within the buffer. Will corrupt the filename but prevent buffer overflows + lfnPos = LAST_LFN_POS; + } + for ( i = 0; i < 13; i++ ) + { + lfn[lfnPos + i] = entryData[LFN_offset_table[i]] | ( entryData[LFN_offset_table[i] + 1] << 8 ); + } + } + } + else if ( entryData[DIR_ENTRY_attributes] & ATTRIB_VOL ) + { + // This is a volume name, don't bother with it + } + else if ( entryData[0] == DIR_ENTRY_LAST ) + { + notFound = true; + } + else if ( ( entryData[0] != DIR_ENTRY_FREE ) && ( entryData[0] > 0x20 ) && !( entryData[DIR_ENTRY_attributes] & ATTRIB_VOL ) ) + { + if ( lfnExists ) + { + // Calculate file checksum + chkSum = 0; + for ( i = 0; i < 11; i++ ) + { + // NOTE: The operation is an unsigned char rotate right + chkSum = ( ( chkSum & 1 ) ? 0x80 : 0 ) + ( chkSum >> 1 ) + entryData[i]; + } + if ( chkSum != lfnChkSum ) + { + lfnExists = false; + entry->filename[0] = '\0'; + } + } - // If no file is found, return false - if (notFound) { - return false; - } else { - // Fill in the directory entry struct - entry->dataStart = entryStart; - entry->dataEnd = entryEnd; - memcpy (entry->entryData, entryData, DIR_ENTRY_DATA_SIZE); - return true; - } + if ( lfnExists ) + { + if ( _FAT_directory_ucs2tombs ( entry->filename, lfn, MAX_FILENAME_LENGTH ) == ( size_t ) - 1 ) + { + // Failed to convert the file name to UTF-8. Maybe the wrong locale is set? + return false; + } + } + else + { + entryStart = entryEnd; + _FAT_directory_entryGetAlias ( entryData, entry->filename ); + } + found = true; + } + } + + // If no file is found, return false + if ( notFound ) + { + return false; + } + else + { + // Fill in the directory entry struct + entry->dataStart = entryStart; + entry->dataEnd = entryEnd; + memcpy ( entry->entryData, entryData, DIR_ENTRY_DATA_SIZE ); + return true; + } } -bool _FAT_directory_getFirstEntry (PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster) { - entry->dataStart.cluster = dirCluster; - entry->dataStart.sector = 0; - entry->dataStart.offset = -1; // Start before the beginning of the directory +bool _FAT_directory_getFirstEntry ( PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster ) +{ + entry->dataStart.cluster = dirCluster; + entry->dataStart.sector = 0; + entry->dataStart.offset = -1; // Start before the beginning of the directory - entry->dataEnd = entry->dataStart; + entry->dataEnd = entry->dataStart; - return _FAT_directory_getNextEntry (partition, entry); + return _FAT_directory_getNextEntry ( partition, entry ); } -bool _FAT_directory_getRootEntry (PARTITION* partition, DIR_ENTRY* entry) { - entry->dataStart.cluster = 0; - entry->dataStart.sector = 0; - entry->dataStart.offset = 0; - - entry->dataEnd = entry->dataStart; - - memset (entry->filename, '\0', MAX_FILENAME_LENGTH); - entry->filename[0] = '.'; - - memset (entry->entryData, 0, DIR_ENTRY_DATA_SIZE); - memset (entry->entryData, ' ', 11); - entry->entryData[0] = '.'; - - entry->entryData[DIR_ENTRY_attributes] = ATTRIB_DIR; - - u16_to_u8array (entry->entryData, DIR_ENTRY_cluster, partition->rootDirCluster); - u16_to_u8array (entry->entryData, DIR_ENTRY_clusterHigh, partition->rootDirCluster >> 16); - - return true; +bool _FAT_directory_getRootEntry ( PARTITION* partition, DIR_ENTRY* entry ) +{ + entry->dataStart.cluster = 0; + entry->dataStart.sector = 0; + entry->dataStart.offset = 0; + + entry->dataEnd = entry->dataStart; + + memset ( entry->filename, '\0', MAX_FILENAME_LENGTH ); + entry->filename[0] = '.'; + + memset ( entry->entryData, 0, DIR_ENTRY_DATA_SIZE ); + memset ( entry->entryData, ' ', 11 ); + entry->entryData[0] = '.'; + + entry->entryData[DIR_ENTRY_attributes] = ATTRIB_DIR; + + u16_to_u8array ( entry->entryData, DIR_ENTRY_cluster, partition->rootDirCluster ); + u16_to_u8array ( entry->entryData, DIR_ENTRY_clusterHigh, partition->rootDirCluster >> 16 ); + + return true; } -bool _FAT_directory_entryFromPosition (PARTITION* partition, DIR_ENTRY* entry) { - DIR_ENTRY_POSITION entryStart = entry->dataStart; - DIR_ENTRY_POSITION entryEnd = entry->dataEnd; - bool entryStillValid; - bool finished; - ucs2_t lfn[MAX_LFN_LENGTH]; - int i; - int lfnPos; - uint8_t entryData[DIR_ENTRY_DATA_SIZE]; - - memset (entry->filename, '\0', MAX_FILENAME_LENGTH); +bool _FAT_directory_entryFromPosition ( PARTITION* partition, DIR_ENTRY* entry ) +{ + DIR_ENTRY_POSITION entryStart = entry->dataStart; + DIR_ENTRY_POSITION entryEnd = entry->dataEnd; + bool entryStillValid; + bool finished; + ucs2_t lfn[MAX_LFN_LENGTH]; + int i; + int lfnPos; + uint8_t entryData[DIR_ENTRY_DATA_SIZE]; - // Create an empty directory entry to overwrite the old ones with - for ( entryStillValid = true, finished = false; - entryStillValid && !finished; - entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &entryStart, false)) - { - _FAT_cache_readPartialSector (partition->cache, entryData, - _FAT_fat_clusterToSector(partition, entryStart.cluster) + entryStart.sector, - entryStart.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - - if ((entryStart.cluster == entryEnd.cluster) - && (entryStart.sector == entryEnd.sector) - && (entryStart.offset == entryEnd.offset)) { - // Copy the entry data and stop, since this is the last section of the directory entry - memcpy (entry->entryData, entryData, DIR_ENTRY_DATA_SIZE); - finished = true; - } else { - // Copy the long file name data - lfnPos = ((entryData[LFN_offset_ordinal] & ~LFN_END) - 1) * 13; - if (lfnPos > LAST_LFN_POS) { - lfnPos = LAST_LFN_POS_CORRECTION; - } - for (i = 0; i < 13; i++) { - lfn[lfnPos + i] = entryData[LFN_offset_table[i]] | (entryData[LFN_offset_table[i]+1] << 8); - } - } - } + memset ( entry->filename, '\0', MAX_FILENAME_LENGTH ); - if (!entryStillValid) { - return false; - } - - if ((entryStart.cluster == entryEnd.cluster) - && (entryStart.sector == entryEnd.sector) - && (entryStart.offset == entryEnd.offset)) { - // Since the entry doesn't have a long file name, extract the short filename - if (!_FAT_directory_entryGetAlias (entry->entryData, entry->filename)) { - return false; - } - } else { - // Encode the long file name into a multibyte string - if (_FAT_directory_ucs2tombs (entry->filename, lfn, MAX_FILENAME_LENGTH) == (size_t)-1) { - return false; - } - } - - return true; + // Create an empty directory entry to overwrite the old ones with + for ( entryStillValid = true, finished = false; + entryStillValid && !finished; + entryStillValid = _FAT_directory_incrementDirEntryPosition ( partition, &entryStart, false ) ) + { + _FAT_cache_readPartialSector ( partition->cache, entryData, + _FAT_fat_clusterToSector( partition, entryStart.cluster ) + entryStart.sector, + entryStart.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE ); + + if ( ( entryStart.cluster == entryEnd.cluster ) + && ( entryStart.sector == entryEnd.sector ) + && ( entryStart.offset == entryEnd.offset ) ) + { + // Copy the entry data and stop, since this is the last section of the directory entry + memcpy ( entry->entryData, entryData, DIR_ENTRY_DATA_SIZE ); + finished = true; + } + else + { + // Copy the long file name data + lfnPos = ( ( entryData[LFN_offset_ordinal] & ~LFN_END ) - 1 ) * 13; + if ( lfnPos > LAST_LFN_POS ) + { + lfnPos = LAST_LFN_POS_CORRECTION; + } + for ( i = 0; i < 13; i++ ) + { + lfn[lfnPos + i] = entryData[LFN_offset_table[i]] | ( entryData[LFN_offset_table[i] + 1] << 8 ); + } + } + } + + if ( !entryStillValid ) + { + return false; + } + + if ( ( entryStart.cluster == entryEnd.cluster ) + && ( entryStart.sector == entryEnd.sector ) + && ( entryStart.offset == entryEnd.offset ) ) + { + // Since the entry doesn't have a long file name, extract the short filename + if ( !_FAT_directory_entryGetAlias ( entry->entryData, entry->filename ) ) + { + return false; + } + } + else + { + // Encode the long file name into a multibyte string + if ( _FAT_directory_ucs2tombs ( entry->filename, lfn, MAX_FILENAME_LENGTH ) == ( size_t ) - 1 ) + { + return false; + } + } + + return true; } -bool _FAT_directory_entryFromPath (PARTITION* partition, DIR_ENTRY* entry, const char* path, const char* pathEnd) { - size_t dirnameLength; - const char* pathPosition; - const char* nextPathPosition; - uint32_t dirCluster; - bool foundFile; - char alias[MAX_ALIAS_LENGTH]; - bool found, notFound; +bool _FAT_directory_entryFromPath ( PARTITION* partition, DIR_ENTRY* entry, const char* path, const char* pathEnd ) +{ + size_t dirnameLength; + const char* pathPosition; + const char* nextPathPosition; + uint32_t dirCluster; + bool foundFile; + char alias[MAX_ALIAS_LENGTH]; + bool found, notFound; - pathPosition = path; - - found = false; - notFound = false; + pathPosition = path; - if (pathEnd == NULL) { - // Set pathEnd to the end of the path string - pathEnd = strchr (path, '\0'); - } + found = false; + notFound = false; - if (pathPosition[0] == DIR_SEPARATOR) { - // Start at root directory - dirCluster = partition->rootDirCluster; - // Consume separator(s) - while (pathPosition[0] == DIR_SEPARATOR) { - pathPosition++; - } - // If the path is only specifying a directory in the form of "/" return it - if (pathPosition >= pathEnd) { - _FAT_directory_getRootEntry (partition, entry); - found = true; - } - } else { - // Start in current working directory - dirCluster = partition->cwdCluster; - } + if ( pathEnd == NULL ) + { + // Set pathEnd to the end of the path string + pathEnd = strchr ( path, '\0' ); + } - // If the path is only specifying a directory in the form "." - // and this is the root directory, return it - if ((dirCluster == partition->rootDirCluster) && (strcmp(".", pathPosition) == 0)) { - _FAT_directory_getRootEntry (partition, entry); - found = true; - } - - while (!found && !notFound) { - // Get the name of the next required subdirectory within the path - nextPathPosition = strchr (pathPosition, DIR_SEPARATOR); - if (nextPathPosition != NULL) { - dirnameLength = nextPathPosition - pathPosition; - } else { - dirnameLength = strlen(pathPosition); - } + if ( pathPosition[0] == DIR_SEPARATOR ) + { + // Start at root directory + dirCluster = partition->rootDirCluster; + // Consume separator(s) + while ( pathPosition[0] == DIR_SEPARATOR ) + { + pathPosition++; + } + // If the path is only specifying a directory in the form of "/" return it + if ( pathPosition >= pathEnd ) + { + _FAT_directory_getRootEntry ( partition, entry ); + found = true; + } + } + else + { + // Start in current working directory + dirCluster = partition->cwdCluster; + } - if (dirnameLength > MAX_FILENAME_LENGTH) { - // The path is too long to bother with - return false; - } + // If the path is only specifying a directory in the form "." + // and this is the root directory, return it + if ( ( dirCluster == partition->rootDirCluster ) && ( strcmp( ".", pathPosition ) == 0 ) ) + { + _FAT_directory_getRootEntry ( partition, entry ); + found = true; + } - // Look for the directory within the path - foundFile = _FAT_directory_getFirstEntry (partition, entry, dirCluster); + while ( !found && !notFound ) + { + // Get the name of the next required subdirectory within the path + nextPathPosition = strchr ( pathPosition, DIR_SEPARATOR ); + if ( nextPathPosition != NULL ) + { + dirnameLength = nextPathPosition - pathPosition; + } + else + { + dirnameLength = strlen( pathPosition ); + } - while (foundFile && !found && !notFound) { // It hasn't already found the file - // Check if the filename matches - if ((dirnameLength == strnlen(entry->filename, MAX_FILENAME_LENGTH)) - && (_FAT_directory_mbsncasecmp(pathPosition, entry->filename, dirnameLength) == 0)) { - found = true; - } + if ( dirnameLength > MAX_FILENAME_LENGTH ) + { + // The path is too long to bother with + return false; + } - // Check if the alias matches - _FAT_directory_entryGetAlias (entry->entryData, alias); - if ((dirnameLength == strnlen(alias, MAX_ALIAS_LENGTH)) - && (strncasecmp(pathPosition, alias, dirnameLength) == 0)) { - found = true; - } + // Look for the directory within the path + foundFile = _FAT_directory_getFirstEntry ( partition, entry, dirCluster ); - 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; - } + while ( foundFile && !found && !notFound ) // It hasn't already found the file + { + // Check if the filename matches + if ( ( dirnameLength == strnlen( entry->filename, MAX_FILENAME_LENGTH ) ) + && ( _FAT_directory_mbsncasecmp( pathPosition, entry->filename, dirnameLength ) == 0 ) ) + { + found = true; + } - if (!found) { - foundFile = _FAT_directory_getNextEntry (partition, entry); - } - } + // Check if the alias matches + _FAT_directory_entryGetAlias ( entry->entryData, alias ); + if ( ( dirnameLength == strnlen( alias, MAX_ALIAS_LENGTH ) ) + && ( strncasecmp( pathPosition, alias, dirnameLength ) == 0 ) ) + { + found = true; + } - if (!foundFile) { - // Check that the search didn't get to the end of the directory - notFound = true; - found = false; - } else if ((nextPathPosition == NULL) || (nextPathPosition >= pathEnd)) { - // Check that we reached the end of the path - found = true; - } else if (entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR) { - dirCluster = _FAT_directory_entryGetCluster (partition, entry->entryData); - pathPosition = nextPathPosition; - // Consume separator(s) - while (pathPosition[0] == DIR_SEPARATOR) { - pathPosition++; - } - // The requested directory was found - if (pathPosition >= pathEnd) { - found = true; - } else { - found = false; - } - } - } + if ( found && !( 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 && !notFound) { - if (partition->filesysType == FS_FAT32 && (entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR) && - _FAT_directory_entryGetCluster (partition, entry->entryData) == CLUSTER_ROOT) - { - // On FAT32 it should specify an actual cluster for the root entry, - // not cluster 0 as on FAT16 - _FAT_directory_getRootEntry (partition, entry); - } - return true; - } else { - return false; - } + if ( !found ) + { + foundFile = _FAT_directory_getNextEntry ( partition, entry ); + } + } + + if ( !foundFile ) + { + // Check that the search didn't get to the end of the directory + notFound = true; + found = false; + } + else if ( ( nextPathPosition == NULL ) || ( nextPathPosition >= pathEnd ) ) + { + // Check that we reached the end of the path + found = true; + } + else if ( entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR ) + { + dirCluster = _FAT_directory_entryGetCluster ( partition, entry->entryData ); + pathPosition = nextPathPosition; + // Consume separator(s) + while ( pathPosition[0] == DIR_SEPARATOR ) + { + pathPosition++; + } + // The requested directory was found + if ( pathPosition >= pathEnd ) + { + found = true; + } + else + { + found = false; + } + } + } + + if ( found && !notFound ) + { + if ( partition->filesysType == FS_FAT32 && ( entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR ) && + _FAT_directory_entryGetCluster ( partition, entry->entryData ) == CLUSTER_ROOT ) + { + // On FAT32 it should specify an actual cluster for the root entry, + // not cluster 0 as on FAT16 + _FAT_directory_getRootEntry ( partition, entry ); + } + return true; + } + else + { + return false; + } } -bool _FAT_directory_removeEntry (PARTITION* partition, DIR_ENTRY* entry) { - DIR_ENTRY_POSITION entryStart = entry->dataStart; - DIR_ENTRY_POSITION entryEnd = entry->dataEnd; - bool entryStillValid; - bool finished; - uint8_t entryData[DIR_ENTRY_DATA_SIZE]; +bool _FAT_directory_removeEntry ( PARTITION* partition, DIR_ENTRY* entry ) +{ + DIR_ENTRY_POSITION entryStart = entry->dataStart; + DIR_ENTRY_POSITION entryEnd = entry->dataEnd; + bool entryStillValid; + bool finished; + uint8_t entryData[DIR_ENTRY_DATA_SIZE]; - // Create an empty directory entry to overwrite the old ones with - for ( entryStillValid = true, finished = false; - entryStillValid && !finished; - entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &entryStart, false)) - { - _FAT_cache_readPartialSector (partition->cache, entryData, _FAT_fat_clusterToSector(partition, entryStart.cluster) + entryStart.sector, entryStart.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - entryData[0] = DIR_ENTRY_FREE; - _FAT_cache_writePartialSector (partition->cache, entryData, _FAT_fat_clusterToSector(partition, entryStart.cluster) + entryStart.sector, entryStart.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - if ((entryStart.cluster == entryEnd.cluster) && (entryStart.sector == entryEnd.sector) && (entryStart.offset == entryEnd.offset)) { - finished = true; - } - } + // Create an empty directory entry to overwrite the old ones with + for ( entryStillValid = true, finished = false; + entryStillValid && !finished; + entryStillValid = _FAT_directory_incrementDirEntryPosition ( partition, &entryStart, false ) ) + { + _FAT_cache_readPartialSector ( partition->cache, entryData, _FAT_fat_clusterToSector( partition, entryStart.cluster ) + entryStart.sector, entryStart.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE ); + entryData[0] = DIR_ENTRY_FREE; + _FAT_cache_writePartialSector ( partition->cache, entryData, _FAT_fat_clusterToSector( partition, entryStart.cluster ) + entryStart.sector, entryStart.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE ); + if ( ( entryStart.cluster == entryEnd.cluster ) && ( entryStart.sector == entryEnd.sector ) && ( entryStart.offset == entryEnd.offset ) ) + { + finished = true; + } + } - if (!entryStillValid) { - return false; - } + if ( !entryStillValid ) + { + return false; + } - return true; + return true; } -static bool _FAT_directory_findEntryGap (PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster, size_t size) { - DIR_ENTRY_POSITION gapStart; - DIR_ENTRY_POSITION gapEnd; - uint8_t entryData[DIR_ENTRY_DATA_SIZE]; - size_t dirEntryRemain; - bool endOfDirectory, entryStillValid; +static bool _FAT_directory_findEntryGap ( PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster, size_t size ) +{ + DIR_ENTRY_POSITION gapStart; + DIR_ENTRY_POSITION gapEnd; + uint8_t entryData[DIR_ENTRY_DATA_SIZE]; + size_t dirEntryRemain; + bool endOfDirectory, entryStillValid; - // Scan Dir for free entry - gapEnd.offset = 0; - gapEnd.sector = 0; - gapEnd.cluster = dirCluster; + // Scan Dir for free entry + gapEnd.offset = 0; + gapEnd.sector = 0; + gapEnd.cluster = dirCluster; - gapStart = gapEnd; + gapStart = gapEnd; - entryStillValid = true; - dirEntryRemain = size; - endOfDirectory = false; - - while (entryStillValid && !endOfDirectory && (dirEntryRemain > 0)) { - _FAT_cache_readPartialSector (partition->cache, entryData, - _FAT_fat_clusterToSector(partition, gapEnd.cluster) + gapEnd.sector, - gapEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - if (entryData[0] == DIR_ENTRY_LAST) { - gapStart = gapEnd; - -- dirEntryRemain; - endOfDirectory = true; - } else if (entryData[0] == DIR_ENTRY_FREE) { - if (dirEntryRemain == size) { - gapStart = gapEnd; - } - -- dirEntryRemain; - } else { - dirEntryRemain = size; - } - - if (!endOfDirectory && (dirEntryRemain > 0)) { - entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &gapEnd, true); - } - } + entryStillValid = true; + dirEntryRemain = size; + endOfDirectory = false; - // Make sure the scanning didn't fail - if (!entryStillValid) { - return false; - } + while ( entryStillValid && !endOfDirectory && ( dirEntryRemain > 0 ) ) + { + _FAT_cache_readPartialSector ( partition->cache, entryData, + _FAT_fat_clusterToSector( partition, gapEnd.cluster ) + gapEnd.sector, + gapEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE ); + if ( entryData[0] == DIR_ENTRY_LAST ) + { + gapStart = gapEnd; + -- dirEntryRemain; + endOfDirectory = true; + } + else if ( entryData[0] == DIR_ENTRY_FREE ) + { + if ( dirEntryRemain == size ) + { + gapStart = gapEnd; + } + -- dirEntryRemain; + } + else + { + dirEntryRemain = size; + } - // Save the start entry, since we know it is valid - entry->dataStart = gapStart; + if ( !endOfDirectory && ( dirEntryRemain > 0 ) ) + { + entryStillValid = _FAT_directory_incrementDirEntryPosition ( partition, &gapEnd, true ); + } + } - if (endOfDirectory) { - memset (entryData, DIR_ENTRY_LAST, DIR_ENTRY_DATA_SIZE); - dirEntryRemain += 1; // Increase by one to take account of End Of Directory Marker - while ((dirEntryRemain > 0) && entryStillValid) { - // Get the gapEnd before incrementing it, so the second to last one is saved - entry->dataEnd = gapEnd; - // Increment gapEnd, moving onto the next entry - entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &gapEnd, true); - -- dirEntryRemain; - // Fill the entry with blanks - _FAT_cache_writePartialSector (partition->cache, entryData, - _FAT_fat_clusterToSector(partition, gapEnd.cluster) + gapEnd.sector, - gapEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - } - if (!entryStillValid) { - return false; - } - } else { - entry->dataEnd = gapEnd; - } + // Make sure the scanning didn't fail + if ( !entryStillValid ) + { + return false; + } - return true; + // Save the start entry, since we know it is valid + entry->dataStart = gapStart; + + if ( endOfDirectory ) + { + memset ( entryData, DIR_ENTRY_LAST, DIR_ENTRY_DATA_SIZE ); + dirEntryRemain += 1; // Increase by one to take account of End Of Directory Marker + while ( ( dirEntryRemain > 0 ) && entryStillValid ) + { + // Get the gapEnd before incrementing it, so the second to last one is saved + entry->dataEnd = gapEnd; + // Increment gapEnd, moving onto the next entry + entryStillValid = _FAT_directory_incrementDirEntryPosition ( partition, &gapEnd, true ); + -- dirEntryRemain; + // Fill the entry with blanks + _FAT_cache_writePartialSector ( partition->cache, entryData, + _FAT_fat_clusterToSector( partition, gapEnd.cluster ) + gapEnd.sector, + gapEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE ); + } + if ( !entryStillValid ) + { + return false; + } + } + else + { + entry->dataEnd = gapEnd; + } + + return true; } -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; +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) { - return false; - } - - // Make sure the entry doesn't already exist - foundFile = _FAT_directory_getFirstEntry (partition, &tempEntry, dirCluster); + if ( dirnameLength >= MAX_FILENAME_LENGTH ) + { + return false; + } - while (foundFile) { // It hasn't already found the file - // Check if the filename matches - if ((dirnameLength == strnlen(tempEntry.filename, MAX_FILENAME_LENGTH)) - && (_FAT_directory_mbsncasecmp(name, tempEntry.filename, dirnameLength) == 0)) { - return true; - } + // Make sure the entry doesn't already exist + foundFile = _FAT_directory_getFirstEntry ( partition, &tempEntry, dirCluster ); - // Check if the alias matches - _FAT_directory_entryGetAlias (tempEntry.entryData, alias); - if ((strncasecmp(name, alias, MAX_ALIAS_LENGTH) == 0)) { - return true; - } - foundFile = _FAT_directory_getNextEntry (partition, &tempEntry); - } - return false; + while ( foundFile ) // It hasn't already found the file + { + // Check if the filename matches + if ( ( dirnameLength == strnlen( tempEntry.filename, MAX_FILENAME_LENGTH ) ) + && ( _FAT_directory_mbsncasecmp( name, tempEntry.filename, dirnameLength ) == 0 ) ) + { + return true; + } + + // Check if the alias matches + _FAT_directory_entryGetAlias ( tempEntry.entryData, alias ); + if ( ( strncasecmp( name, alias, MAX_ALIAS_LENGTH ) == 0 ) ) + { + return true; + } + foundFile = _FAT_directory_getNextEntry ( partition, &tempEntry ); + } + return false; } -/* -Creates an alias for a long file name. If the alias is not an exact match for the -filename, it returns the number of characters in the alias. If the two names match, +/* +Creates an alias for a long file name. If the alias is not an exact match for the +filename, it returns the number of characters in the alias. If the two names match, it returns 0. If there was an error, it returns -1. */ -static int _FAT_directory_createAlias (char* alias, const char* lfn) { - bool lossyConversion = false; // Set when the alias had to be modified to be valid - int lfnPos = 0; - int aliasPos = 0; - wchar_t lfnChar; - int oemChar; - mbstate_t ps = {0}; - int bytesUsed = 0; - const char* lfnExt; - int aliasExtLen; - - // Strip leading periods - while (lfn[lfnPos] == '.') { - lfnPos ++; - lossyConversion = true; - } - - // Primary portion of alias - while (aliasPos < 8 && lfn[lfnPos] != '.' && lfn[lfnPos] != '\0') { - bytesUsed = mbrtowc(&lfnChar, lfn + lfnPos, MAX_FILENAME_LENGTH - lfnPos, &ps); - if (bytesUsed < 0) { - return -1; - } - oemChar = wctob(towupper((wint_t)lfnChar)); - if (wctob((wint_t)lfnChar) != oemChar) { - // Case of letter was changed - lossyConversion = true; - } - if (oemChar == ' ') { - // Skip spaces in filename - lossyConversion = true; - lfnPos += bytesUsed; - continue; - } - if (oemChar == EOF) { - oemChar = '_'; // Replace unconvertable characters with underscores - lossyConversion = true; - } - if (strchr (ILLEGAL_ALIAS_CHARACTERS, oemChar) != NULL) { - // Invalid Alias character - oemChar = '_'; // Replace illegal characters with underscores - lossyConversion = true; - } - - alias[aliasPos] = (char)oemChar; - aliasPos++; - lfnPos += bytesUsed; - } - - if (lfn[lfnPos] != '.' && lfn[lfnPos] != '\0') { - // Name was more than 8 characters long - lossyConversion = true; - } - - // Alias extension - lfnExt = strrchr (lfn, '.'); - if (lfnExt != NULL && lfnExt != strchr (lfn, '.')) { - // More than one period in name - lossyConversion = true; - } - if (lfnExt != NULL && lfnExt[1] != '\0') { - lfnExt++; - alias[aliasPos] = '.'; - aliasPos++; - memset (&ps, 0, sizeof(ps)); - for (aliasExtLen = 0; aliasExtLen < MAX_ALIAS_EXT_LENGTH && *lfnExt != '\0'; aliasExtLen++) { - bytesUsed = mbrtowc(&lfnChar, lfnExt, MAX_FILENAME_LENGTH - lfnPos, &ps); - if (bytesUsed < 0) { - return -1; - } - oemChar = wctob(towupper((wint_t)lfnChar)); - if (wctob((wint_t)lfnChar) != oemChar) { - // Case of letter was changed - lossyConversion = true; - } - if (oemChar == ' ') { - // Skip spaces in alias - lossyConversion = true; - lfnExt += bytesUsed; - continue; - } - if (oemChar == EOF) { - oemChar = '_'; // Replace unconvertable characters with underscores - lossyConversion = true; - } - if (strchr (ILLEGAL_ALIAS_CHARACTERS, oemChar) != NULL) { - // Invalid Alias character - oemChar = '_'; // Replace illegal characters with underscores - lossyConversion = true; - } - - alias[aliasPos] = (char)oemChar; - aliasPos++; - lfnExt += bytesUsed; - } - if (*lfnExt != '\0') { - // Extension was more than 3 characters long - lossyConversion = true; - } - } - - alias[aliasPos] = '\0'; - if (lossyConversion) { - return aliasPos; - } else { - return 0; - } +static int _FAT_directory_createAlias ( char* alias, const char* lfn ) +{ + bool lossyConversion = false; // Set when the alias had to be modified to be valid + int lfnPos = 0; + int aliasPos = 0; + wchar_t lfnChar; + int oemChar; + mbstate_t ps = {0}; + int bytesUsed = 0; + const char* lfnExt; + int aliasExtLen; + + // Strip leading periods + while ( lfn[lfnPos] == '.' ) + { + lfnPos ++; + lossyConversion = true; + } + + // Primary portion of alias + while ( aliasPos < 8 && lfn[lfnPos] != '.' && lfn[lfnPos] != '\0' ) + { + bytesUsed = mbrtowc( &lfnChar, lfn + lfnPos, MAX_FILENAME_LENGTH - lfnPos, &ps ); + if ( bytesUsed < 0 ) + { + return -1; + } + oemChar = wctob( towupper( ( wint_t )lfnChar ) ); + if ( wctob( ( wint_t )lfnChar ) != oemChar ) + { + // Case of letter was changed + lossyConversion = true; + } + if ( oemChar == ' ' ) + { + // Skip spaces in filename + lossyConversion = true; + lfnPos += bytesUsed; + continue; + } + if ( oemChar == EOF ) + { + oemChar = '_'; // Replace unconvertable characters with underscores + lossyConversion = true; + } + if ( strchr ( ILLEGAL_ALIAS_CHARACTERS, oemChar ) != NULL ) + { + // Invalid Alias character + oemChar = '_'; // Replace illegal characters with underscores + lossyConversion = true; + } + + alias[aliasPos] = ( char )oemChar; + aliasPos++; + lfnPos += bytesUsed; + } + + if ( lfn[lfnPos] != '.' && lfn[lfnPos] != '\0' ) + { + // Name was more than 8 characters long + lossyConversion = true; + } + + // Alias extension + lfnExt = strrchr ( lfn, '.' ); + if ( lfnExt != NULL && lfnExt != strchr ( lfn, '.' ) ) + { + // More than one period in name + lossyConversion = true; + } + if ( lfnExt != NULL && lfnExt[1] != '\0' ) + { + lfnExt++; + alias[aliasPos] = '.'; + aliasPos++; + memset ( &ps, 0, sizeof( ps ) ); + for ( aliasExtLen = 0; aliasExtLen < MAX_ALIAS_EXT_LENGTH && *lfnExt != '\0'; aliasExtLen++ ) + { + bytesUsed = mbrtowc( &lfnChar, lfnExt, MAX_FILENAME_LENGTH - lfnPos, &ps ); + if ( bytesUsed < 0 ) + { + return -1; + } + oemChar = wctob( towupper( ( wint_t )lfnChar ) ); + if ( wctob( ( wint_t )lfnChar ) != oemChar ) + { + // Case of letter was changed + lossyConversion = true; + } + if ( oemChar == ' ' ) + { + // Skip spaces in alias + lossyConversion = true; + lfnExt += bytesUsed; + continue; + } + if ( oemChar == EOF ) + { + oemChar = '_'; // Replace unconvertable characters with underscores + lossyConversion = true; + } + if ( strchr ( ILLEGAL_ALIAS_CHARACTERS, oemChar ) != NULL ) + { + // Invalid Alias character + oemChar = '_'; // Replace illegal characters with underscores + lossyConversion = true; + } + + alias[aliasPos] = ( char )oemChar; + aliasPos++; + lfnExt += bytesUsed; + } + if ( *lfnExt != '\0' ) + { + // Extension was more than 3 characters long + lossyConversion = true; + } + } + + alias[aliasPos] = '\0'; + if ( lossyConversion ) + { + return aliasPos; + } + else + { + return 0; + } } -bool _FAT_directory_addEntry (PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster) { - size_t entrySize; - uint8_t lfnEntry[DIR_ENTRY_DATA_SIZE]; - int i,j; // Must be signed for use when decrementing in for loop - char *tmpCharPtr; - DIR_ENTRY_POSITION curEntryPos; - bool entryStillValid; - uint8_t aliasCheckSum = 0; - char alias [MAX_ALIAS_LENGTH]; - int aliasLen; - int lfnLen; +bool _FAT_directory_addEntry ( PARTITION* partition, DIR_ENTRY* entry, uint32_t dirCluster ) +{ + size_t entrySize; + uint8_t lfnEntry[DIR_ENTRY_DATA_SIZE]; + int i, j; // Must be signed for use when decrementing in for loop + char *tmpCharPtr; + DIR_ENTRY_POSITION curEntryPos; + bool entryStillValid; + uint8_t aliasCheckSum = 0; + char alias [MAX_ALIAS_LENGTH]; + int aliasLen; + int lfnLen; - // Make sure the filename is not 0 length - if (strnlen (entry->filename, MAX_FILENAME_LENGTH) < 1) { - return false; - } + // Make sure the filename is not 0 length + if ( strnlen ( entry->filename, MAX_FILENAME_LENGTH ) < 1 ) + { + return false; + } - // Make sure the filename is at least a valid LFN - lfnLen = _FAT_directory_lfnLength (entry->filename); - if (lfnLen < 0) { - return false; - } + // Make sure the filename is at least a valid LFN + lfnLen = _FAT_directory_lfnLength ( entry->filename ); + if ( lfnLen < 0 ) + { + return false; + } - // Remove trailing spaces - for (i = strlen (entry->filename) - 1; (i > 0) && (entry->filename[i] == ' '); --i) { - entry->filename[i] = '\0'; - } - // Remove leading spaces - for (i = 0; (i < (int)strlen (entry->filename)) && (entry->filename[i] == ' '); ++i) ; - if (i > 0) { - memmove (entry->filename, entry->filename + i, strlen (entry->filename + i)); - } + // Remove trailing spaces + for ( i = strlen ( entry->filename ) - 1; ( i > 0 ) && ( entry->filename[i] == ' ' ); --i ) + { + entry->filename[i] = '\0'; + } + // Remove leading spaces + for ( i = 0; ( i < ( int )strlen ( entry->filename ) ) && ( entry->filename[i] == ' ' ); ++i ) ; + if ( i > 0 ) + { + memmove ( entry->filename, entry->filename + i, strlen ( entry->filename + i ) ); + } - // Remove junk in filename - i = strlen (entry->filename); - memset (entry->filename + i, '\0', MAX_FILENAME_LENGTH - i); + // Remove junk in filename + i = strlen ( entry->filename ); + memset ( entry->filename + i, '\0', MAX_FILENAME_LENGTH - i ); - // Make sure the entry doesn't already exist - if (_FAT_directory_entryExists (partition, entry->filename, dirCluster)) { - return false; - } + // Make sure the entry doesn't already exist + if ( _FAT_directory_entryExists ( partition, entry->filename, dirCluster ) ) + { + return false; + } - // Clear out alias, so we can generate a new one - memset (entry->entryData, ' ', 11); + // Clear out alias, so we can generate a new one + memset ( entry->entryData, ' ', 11 ); - if ( strncmp(entry->filename, ".", MAX_FILENAME_LENGTH) == 0) { - // "." entry - entry->entryData[0] = '.'; - entrySize = 1; - } else if ( strncmp(entry->filename, "..", MAX_FILENAME_LENGTH) == 0) { - // ".." entry - entry->entryData[0] = '.'; - entry->entryData[1] = '.'; - entrySize = 1; - } else { - // Normal file name - aliasLen = _FAT_directory_createAlias (alias, entry->filename); - if (aliasLen < 0) { - return false; - } else if (aliasLen == 0) { - // It's a normal short filename - entrySize = 1; - } else { - // It's a long filename with an alias - entrySize = ((lfnLen + LFN_ENTRY_LENGTH - 1) / LFN_ENTRY_LENGTH) + 1; - - // Generate full alias for all cases except when the alias is simply an upper case version of the LFN - // and there isn't already a file with that name - if (strncasecmp (alias, entry->filename, MAX_ALIAS_LENGTH) != 0 || - _FAT_directory_entryExists (partition, alias, dirCluster)) - { - // expand primary part to 8 characters long by padding the end with underscores - i = MAX_ALIAS_PRI_LENGTH - 1; - // Move extension to last 3 characters - while (alias[i] != '.' && i > 0) i--; - if (i > 0) { - j = MAX_ALIAS_LENGTH - MAX_ALIAS_EXT_LENGTH - 2; // 1 char for '.', one for NUL, 3 for extension - memmove (alias + j, alias + i, strlen(alias) - i); - // Pad primary component - memset (alias + i, '_', j - i); - alias[MAX_ALIAS_LENGTH-1]=0; - } - - // Generate numeric tail - for (i = 1; i <= MAX_NUMERIC_TAIL; i++) { - j = i; - tmpCharPtr = alias + MAX_ALIAS_PRI_LENGTH - 1; - while (j > 0) { - *tmpCharPtr = '0' + (j % 10); // ASCII numeric value - tmpCharPtr--; - j /= 10; - } - *tmpCharPtr = '~'; - if (!_FAT_directory_entryExists (partition, alias, dirCluster)) { - break; - } - } - if (i > MAX_NUMERIC_TAIL) { - // Couldn't get a valid alias - return false; - } - } - } + if ( strncmp( entry->filename, ".", MAX_FILENAME_LENGTH ) == 0 ) + { + // "." entry + entry->entryData[0] = '.'; + entrySize = 1; + } + else if ( strncmp( entry->filename, "..", MAX_FILENAME_LENGTH ) == 0 ) + { + // ".." entry + entry->entryData[0] = '.'; + entry->entryData[1] = '.'; + entrySize = 1; + } + else + { + // Normal file name + aliasLen = _FAT_directory_createAlias ( alias, entry->filename ); + if ( aliasLen < 0 ) + { + return false; + } + else if ( aliasLen == 0 ) + { + // It's a normal short filename + entrySize = 1; + } + else + { + // It's a long filename with an alias + entrySize = ( ( lfnLen + LFN_ENTRY_LENGTH - 1 ) / LFN_ENTRY_LENGTH ) + 1; - // Copy alias or short file name into directory entry data - for (i = 0, j = 0; (j < 8) && (alias[i] != '.') && (alias[i] != '\0'); i++, j++) { - entry->entryData[j] = alias[i]; - } - while (j < 8) { - entry->entryData[j] = ' '; - ++ j; - } - if (alias[i] == '.') { - // Copy extension - ++ i; - while ((alias[i] != '\0') && (j < 11)) { - entry->entryData[j] = alias[i]; - ++ i; - ++ j; - } - } - while (j < 11) { - entry->entryData[j] = ' '; - ++ j; - } - - // Generate alias checksum - for (i=0; i < ALIAS_ENTRY_LENGTH; i++) { - // NOTE: The operation is an unsigned char rotate right - aliasCheckSum = ((aliasCheckSum & 1) ? 0x80 : 0) + (aliasCheckSum >> 1) + entry->entryData[i]; - } - } + // Generate full alias for all cases except when the alias is simply an upper case version of the LFN + // and there isn't already a file with that name + if ( strncasecmp ( alias, entry->filename, MAX_ALIAS_LENGTH ) != 0 || + _FAT_directory_entryExists ( partition, alias, dirCluster ) ) + { + // expand primary part to 8 characters long by padding the end with underscores + i = MAX_ALIAS_PRI_LENGTH - 1; + // Move extension to last 3 characters + while ( alias[i] != '.' && i > 0 ) i--; + if ( i > 0 ) + { + j = MAX_ALIAS_LENGTH - MAX_ALIAS_EXT_LENGTH - 2; // 1 char for '.', one for NUL, 3 for extension + memmove ( alias + j, alias + i, strlen( alias ) - i ); + // Pad primary component + memset ( alias + i, '_', j - i ); + alias[MAX_ALIAS_LENGTH-1] = 0; + } - // Find or create space for the entry - if (_FAT_directory_findEntryGap (partition, entry, dirCluster, entrySize) == false) { - return false; - } + // Generate numeric tail + for ( i = 1; i <= MAX_NUMERIC_TAIL; i++ ) + { + j = i; + tmpCharPtr = alias + MAX_ALIAS_PRI_LENGTH - 1; + while ( j > 0 ) + { + *tmpCharPtr = '0' + ( j % 10 ); // ASCII numeric value + tmpCharPtr--; + j /= 10; + } + *tmpCharPtr = '~'; + if ( !_FAT_directory_entryExists ( partition, alias, dirCluster ) ) + { + break; + } + } + if ( i > MAX_NUMERIC_TAIL ) + { + // Couldn't get a valid alias + return false; + } + } + } - // Write out directory entry - curEntryPos = entry->dataStart; + // Copy alias or short file name into directory entry data + for ( i = 0, j = 0; ( j < 8 ) && ( alias[i] != '.' ) && ( alias[i] != '\0' ); i++, j++ ) + { + entry->entryData[j] = alias[i]; + } + while ( j < 8 ) + { + entry->entryData[j] = ' '; + ++ j; + } + if ( alias[i] == '.' ) + { + // Copy extension + ++ i; + while ( ( alias[i] != '\0' ) && ( j < 11 ) ) + { + entry->entryData[j] = alias[i]; + ++ i; + ++ j; + } + } + while ( j < 11 ) + { + entry->entryData[j] = ' '; + ++ j; + } - { - // 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); + // Generate alias checksum + for ( i = 0; i < ALIAS_ENTRY_LENGTH; i++ ) + { + // NOTE: The operation is an unsigned char rotate right + aliasCheckSum = ( ( aliasCheckSum & 1 ) ? 0x80 : 0 ) + ( aliasCheckSum >> 1 ) + entry->entryData[i]; + } + } - for (entryStillValid = true, i = entrySize; entryStillValid && i > 0; - entryStillValid = _FAT_directory_incrementDirEntryPosition (partition, &curEntryPos, false), -- i ) - { - if (i > 1) { - // Long filename entry - lfnEntry[LFN_offset_ordinal] = (i - 1) | ((size_t)i == entrySize ? LFN_END : 0); - for (j = 0; j < 13; j++) { - if (lfn [(i - 2) * 13 + j] == '\0') { - if ((j > 1) && (lfn [(i - 2) * 13 + (j-1)] == '\0')) { - u16_to_u8array (lfnEntry, LFN_offset_table[j], 0xffff); // Padding - } else { - u16_to_u8array (lfnEntry, LFN_offset_table[j], 0x0000); // Terminating null character - } - } else { - u16_to_u8array (lfnEntry, LFN_offset_table[j], lfn [(i - 2) * 13 + j]); - } - } + // Find or create space for the entry + if ( _FAT_directory_findEntryGap ( partition, entry, dirCluster, entrySize ) == false ) + { + return false; + } - lfnEntry[LFN_offset_checkSum] = aliasCheckSum; - lfnEntry[LFN_offset_flag] = ATTRIB_LFN; - lfnEntry[LFN_offset_reserved1] = 0; - u16_to_u8array (lfnEntry, LFN_offset_reserved2, 0); - _FAT_cache_writePartialSector (partition->cache, lfnEntry, _FAT_fat_clusterToSector(partition, curEntryPos.cluster) + curEntryPos.sector, curEntryPos.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - } else { - // Alias & file data - _FAT_cache_writePartialSector (partition->cache, entry->entryData, _FAT_fat_clusterToSector(partition, curEntryPos.cluster) + curEntryPos.sector, curEntryPos.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - } - } - } + // Write out directory entry + curEntryPos = entry->dataStart; - return true; + { + // lfn is only pushed onto the stack here, reducing overall stack usage + ucs2_t lfn[MAX_LFN_LENGTH] = {0}; + _FAT_directory_mbstoucs2 ( lfn, entry->filename, MAX_LFN_LENGTH ); + + for ( entryStillValid = true, i = entrySize; entryStillValid && i > 0; + entryStillValid = _FAT_directory_incrementDirEntryPosition ( partition, &curEntryPos, false ), -- i ) + { + if ( i > 1 ) + { + // Long filename entry + lfnEntry[LFN_offset_ordinal] = ( i - 1 ) | ( ( size_t )i == entrySize ? LFN_END : 0 ); + for ( j = 0; j < 13; j++ ) + { + if ( lfn [( i - 2 ) * 13 + j] == '\0' ) + { + if ( ( j > 1 ) && ( lfn [( i - 2 ) * 13 + ( j-1 )] == '\0' ) ) + { + u16_to_u8array ( lfnEntry, LFN_offset_table[j], 0xffff ); // Padding + } + else + { + u16_to_u8array ( lfnEntry, LFN_offset_table[j], 0x0000 ); // Terminating null character + } + } + else + { + u16_to_u8array ( lfnEntry, LFN_offset_table[j], lfn [( i - 2 ) * 13 + j] ); + } + } + + lfnEntry[LFN_offset_checkSum] = aliasCheckSum; + lfnEntry[LFN_offset_flag] = ATTRIB_LFN; + lfnEntry[LFN_offset_reserved1] = 0; + u16_to_u8array ( lfnEntry, LFN_offset_reserved2, 0 ); + _FAT_cache_writePartialSector ( partition->cache, lfnEntry, _FAT_fat_clusterToSector( partition, curEntryPos.cluster ) + curEntryPos.sector, curEntryPos.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE ); + } + else + { + // Alias & file data + _FAT_cache_writePartialSector ( partition->cache, entry->entryData, _FAT_fat_clusterToSector( partition, curEntryPos.cluster ) + curEntryPos.sector, curEntryPos.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE ); + } + } + } + + return true; } -bool _FAT_directory_chdir (PARTITION* partition, const char* path) { - DIR_ENTRY entry; +bool _FAT_directory_chdir ( PARTITION* partition, const char* path ) +{ + DIR_ENTRY entry; - if (!_FAT_directory_entryFromPath (partition, &entry, path, NULL)) { - return false; - } + if ( !_FAT_directory_entryFromPath ( partition, &entry, path, NULL ) ) + { + return false; + } - if (!(entry.entryData[DIR_ENTRY_attributes] & ATTRIB_DIR)) { - return false; - } + if ( !( entry.entryData[DIR_ENTRY_attributes] & ATTRIB_DIR ) ) + { + return false; + } - partition->cwdCluster = _FAT_directory_entryGetCluster (partition, entry.entryData); + partition->cwdCluster = _FAT_directory_entryGetCluster ( partition, entry.entryData ); - return true; + return true; } -void _FAT_directory_entryStat (PARTITION* partition, DIR_ENTRY* entry, struct stat *st) { - // Fill in the stat struct - // Some of the values are faked for the sake of compatibility - st->st_dev = _FAT_disc_hostType(partition->disc); // The device is the 32bit ioType value - st->st_ino = (ino_t)(_FAT_directory_entryGetCluster(partition, entry->entryData)); // The file serial number is the start cluster - st->st_mode = (_FAT_directory_isDirectory(entry) ? S_IFDIR : S_IFREG) | - (S_IRUSR | S_IRGRP | S_IROTH) | - (_FAT_directory_isWritable (entry) ? (S_IWUSR | S_IWGRP | S_IWOTH) : 0); // Mode bits based on dirEntry ATTRIB byte - st->st_nlink = 1; // Always one hard link on a FAT file - st->st_uid = 1; // Faked for FAT - st->st_gid = 2; // Faked for FAT - st->st_rdev = st->st_dev; - st->st_size = u8array_to_u32 (entry->entryData, DIR_ENTRY_fileSize); // File size - st->st_atime = _FAT_filetime_to_time_t ( - 0, - u8array_to_u16 (entry->entryData, DIR_ENTRY_aDate) - ); - st->st_spare1 = 0; - st->st_mtime = _FAT_filetime_to_time_t ( - u8array_to_u16 (entry->entryData, DIR_ENTRY_mTime), - u8array_to_u16 (entry->entryData, DIR_ENTRY_mDate) - ); - st->st_spare2 = 0; - st->st_ctime = _FAT_filetime_to_time_t ( - u8array_to_u16 (entry->entryData, DIR_ENTRY_cTime), - u8array_to_u16 (entry->entryData, DIR_ENTRY_cDate) - ); - st->st_spare3 = 0; - st->st_blksize = BYTES_PER_READ; // Prefered file I/O block size - st->st_blocks = (st->st_size + BYTES_PER_READ - 1) / BYTES_PER_READ; // File size in blocks - st->st_spare4[0] = 0; - st->st_spare4[1] = 0; +void _FAT_directory_entryStat ( PARTITION* partition, DIR_ENTRY* entry, struct stat *st ) +{ + // Fill in the stat struct + // Some of the values are faked for the sake of compatibility + st->st_dev = _FAT_disc_hostType( partition->disc ); // The device is the 32bit ioType value + st->st_ino = ( ino_t )( _FAT_directory_entryGetCluster( partition, entry->entryData ) ); // The file serial number is the start cluster + st->st_mode = ( _FAT_directory_isDirectory( entry ) ? S_IFDIR : S_IFREG ) | + ( S_IRUSR | S_IRGRP | S_IROTH ) | + ( _FAT_directory_isWritable ( entry ) ? ( S_IWUSR | S_IWGRP | S_IWOTH ) : 0 ); // Mode bits based on dirEntry ATTRIB byte + st->st_nlink = 1; // Always one hard link on a FAT file + st->st_uid = 1; // Faked for FAT + st->st_gid = 2; // Faked for FAT + st->st_rdev = st->st_dev; + st->st_size = u8array_to_u32 ( entry->entryData, DIR_ENTRY_fileSize ); // File size + st->st_atime = _FAT_filetime_to_time_t ( + 0, + u8array_to_u16 ( entry->entryData, DIR_ENTRY_aDate ) + ); + st->st_spare1 = 0; + st->st_mtime = _FAT_filetime_to_time_t ( + u8array_to_u16 ( entry->entryData, DIR_ENTRY_mTime ), + u8array_to_u16 ( entry->entryData, DIR_ENTRY_mDate ) + ); + st->st_spare2 = 0; + st->st_ctime = _FAT_filetime_to_time_t ( + u8array_to_u16 ( entry->entryData, DIR_ENTRY_cTime ), + u8array_to_u16 ( entry->entryData, DIR_ENTRY_cDate ) + ); + st->st_spare3 = 0; + st->st_blksize = BYTES_PER_READ; // Prefered file I/O block size + st->st_blocks = ( st->st_size + BYTES_PER_READ - 1 ) / BYTES_PER_READ; // File size in blocks + st->st_spare4[0] = 0; + st->st_spare4[1] = 0; } diff --git a/source/libfat/directory.h b/source/libfat/directory.h index 02bd82ff..8e314575 100644 --- a/source/libfat/directory.h +++ b/source/libfat/directory.h @@ -36,8 +36,8 @@ #include "partition.h" #define DIR_ENTRY_DATA_SIZE 0x20 -#define MAX_LFN_LENGTH 256 -#define MAX_FILENAME_LENGTH 768 // 256 UCS-2 characters encoded into UTF-8 can use up to 768 UTF-8 chars +#define MAX_LFN_LENGTH 256 +#define MAX_FILENAME_LENGTH 768 // 256 UCS-2 characters encoded into UTF-8 can use up to 768 UTF-8 chars #define MAX_ALIAS_LENGTH 13 #define LFN_ENTRY_LENGTH 13 #define ALIAS_ENTRY_LENGTH 11 @@ -49,60 +49,66 @@ #define DIR_SEPARATOR '/' // File attributes -#define ATTRIB_ARCH 0x20 // Archive -#define ATTRIB_DIR 0x10 // Directory -#define ATTRIB_LFN 0x0F // Long file name -#define ATTRIB_VOL 0x08 // Volume -#define ATTRIB_SYS 0x04 // System -#define ATTRIB_HID 0x02 // Hidden -#define ATTRIB_RO 0x01 // Read only +#define ATTRIB_ARCH 0x20 // Archive +#define ATTRIB_DIR 0x10 // Directory +#define ATTRIB_LFN 0x0F // Long file name +#define ATTRIB_VOL 0x08 // Volume +#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 struct { - uint32_t cluster; - sec_t sector; - int32_t offset; +typedef struct +{ + 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]; +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]; } DIR_ENTRY; // Directory entry offsets -enum DIR_ENTRY_offset { - DIR_ENTRY_name = 0x00, - DIR_ENTRY_extension = 0x08, - DIR_ENTRY_attributes = 0x0B, - DIR_ENTRY_reserved = 0x0C, - DIR_ENTRY_cTime_ms = 0x0D, - DIR_ENTRY_cTime = 0x0E, - DIR_ENTRY_cDate = 0x10, - DIR_ENTRY_aDate = 0x12, - DIR_ENTRY_clusterHigh = 0x14, - DIR_ENTRY_mTime = 0x16, - DIR_ENTRY_mDate = 0x18, - DIR_ENTRY_cluster = 0x1A, - DIR_ENTRY_fileSize = 0x1C +enum DIR_ENTRY_offset +{ + DIR_ENTRY_name = 0x00, + DIR_ENTRY_extension = 0x08, + DIR_ENTRY_attributes = 0x0B, + DIR_ENTRY_reserved = 0x0C, + DIR_ENTRY_cTime_ms = 0x0D, + DIR_ENTRY_cTime = 0x0E, + DIR_ENTRY_cDate = 0x10, + DIR_ENTRY_aDate = 0x12, + DIR_ENTRY_clusterHigh = 0x14, + DIR_ENTRY_mTime = 0x16, + DIR_ENTRY_mDate = 0x18, + DIR_ENTRY_cluster = 0x1A, + DIR_ENTRY_fileSize = 0x1C }; /* 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); +static inline bool _FAT_directory_isDirectory ( DIR_ENTRY* entry ) +{ + return ( ( entry->entryData[DIR_ENTRY_attributes] & ATTRIB_DIR ) != 0 ); } -static inline bool _FAT_directory_isWritable (DIR_ENTRY* entry) { - return ((entry->entryData[DIR_ENTRY_attributes] & ATTRIB_RO) == 0); +static inline bool _FAT_directory_isWritable ( DIR_ENTRY* entry ) +{ + return ( ( entry->entryData[DIR_ENTRY_attributes] & ATTRIB_RO ) == 0 ); } -static inline bool _FAT_directory_isDot (DIR_ENTRY* entry) { - return ((entry->filename[0] == '.') && ((entry->filename[1] == '\0') || - ((entry->filename[1] == '.') && entry->filename[2] == '\0'))); +static inline bool _FAT_directory_isDot ( DIR_ENTRY* entry ) +{ + return ( ( entry->filename[0] == '.' ) && ( ( entry->filename[1] == '\0' ) || + ( ( entry->filename[1] == '.' ) && entry->filename[2] == '\0' ) ) ); } /* @@ -111,7 +117,7 @@ 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); +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 @@ -119,7 +125,7 @@ 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); +bool _FAT_directory_getNextEntry ( PARTITION* partition, DIR_ENTRY* entry ); /* Gets the directory entry corrsponding to the supplied path @@ -130,20 +136,20 @@ pathEnd specifies the end of the path string, for cutting strings short if neede after pathEND. Returns true on success, false on failure */ -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 ); /* 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); +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); +bool _FAT_directory_removeEntry ( PARTITION* partition, DIR_ENTRY* entry ); /* Add a directory entry to the directory specified by dirCluster @@ -151,23 +157,23 @@ 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); +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); +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); +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); +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 5c955f90..27309f7c 100644 --- a/source/libfat/disc.h +++ b/source/libfat/disc.h @@ -2,9 +2,9 @@ disc.h Interface to the low level disc functions. Used by the higher level file system code. - + 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: @@ -32,12 +32,13 @@ #include "common.h" /* -A list of all default devices to try at startup, +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); +typedef struct +{ + const char* name; + const DISC_INTERFACE* ( *getInterface )( void ); } INTERFACE_ID; extern const INTERFACE_ID _FAT_disc_interfaces[]; @@ -45,66 +46,74 @@ 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) { - return disc->isInserted(); +static inline bool _FAT_disc_isInserted ( const DISC_INTERFACE* disc ) +{ + return disc->isInserted(); } /* -Read numSectors sectors from a disc, starting at sector. +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); +static inline bool _FAT_disc_readSectors ( const DISC_INTERFACE* disc, sec_t sector, sec_t numSectors, void* buffer ) +{ + return disc->readSectors ( sector, numSectors, buffer ); } /* -Write numSectors sectors to a disc, starting at sector. +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); +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 ); } /* Reset the card back to a ready state */ -static inline bool _FAT_disc_clearStatus (const DISC_INTERFACE* disc) { - return disc->clearStatus(); +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) { - return disc->startup(); +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) { - return disc->shutdown(); +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 disc->ioType; +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 disc->features; +static inline uint32_t _FAT_disc_features ( const DISC_INTERFACE* disc ) +{ + return disc->features; } #endif // _DISC_H diff --git a/source/libfat/disc_fat.c b/source/libfat/disc_fat.c index c17ca4c5..d52b2054 100644 --- a/source/libfat/disc_fat.c +++ b/source/libfat/disc_fat.c @@ -43,25 +43,30 @@ The list is terminated by a NULL/NULL entry. #include "usbloader/usbstorage2.h" #include -static const DISC_INTERFACE* get_io_wiisd (void) { - return &__io_wiisd; +static const DISC_INTERFACE* get_io_wiisd ( void ) +{ + return &__io_wiisd; } -static const DISC_INTERFACE* get_io_usbstorage (void) { - return &__io_usbstorage2; +static const DISC_INTERFACE* get_io_usbstorage ( void ) +{ + return &__io_usbstorage2; } -static const DISC_INTERFACE* get_io_gcsda (void) { - return &__io_gcsda; +static const DISC_INTERFACE* get_io_gcsda ( void ) +{ + return &__io_gcsda; } -static const DISC_INTERFACE* get_io_gcsdb (void) { - return &__io_gcsdb; +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 14a323b2..792aa5af 100644 --- a/source/libfat/disc_fat.h +++ b/source/libfat/disc_fat.h @@ -35,9 +35,10 @@ 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); +typedef struct +{ + const char* name; + const DISC_INTERFACE* ( *getInterface )( void ); } INTERFACE_ID; extern const INTERFACE_ID _FAT_disc_interfaces[]; @@ -45,8 +46,9 @@ 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) { - return disc->isInserted(); +static inline bool _FAT_disc_isInserted ( const DISC_INTERFACE* disc ) +{ + return disc->isInserted(); } /* @@ -56,8 +58,9 @@ 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); +static inline bool _FAT_disc_readSectors ( const DISC_INTERFACE* disc, sec_t sector, sec_t numSectors, void* buffer ) +{ + return disc->readSectors ( sector, numSectors, buffer ); } /* @@ -67,44 +70,50 @@ 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); +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 ); } /* Reset the card back to a ready state */ -static inline bool _FAT_disc_clearStatus (const DISC_INTERFACE* disc) { - return disc->clearStatus(); +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) { - return disc->startup(); +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) { - return disc->shutdown(); +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 disc->ioType; +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 disc->features; +static inline uint32_t _FAT_disc_features ( const DISC_INTERFACE* disc ) +{ + return disc->features; } #endif // _DISC_H diff --git a/source/libfat/fat.h b/source/libfat/fat.h index d7b11176..10ff108b 100644 --- a/source/libfat/fat.h +++ b/source/libfat/fat.h @@ -1,6 +1,6 @@ /* - 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 @@ -31,47 +31,48 @@ #define _LIBFAT_H #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #include #include -/* -Initialise any inserted block-devices. -Add the fat device driver to the devoptab, making it available for standard file functions. -cacheSize: The number of pages to allocate for each inserted block-device -setAsDefaultDevice: if true, make this the default device driver for file operations -*/ -extern bool fatInit (uint32_t cacheSize, bool setAsDefaultDevice); + /* + Initialise any inserted block-devices. + Add the fat device driver to the devoptab, making it available for standard file functions. + cacheSize: The number of pages to allocate for each inserted block-device + setAsDefaultDevice: if true, make this the default device driver for file operations + */ + extern bool fatInit ( uint32_t cacheSize, bool setAsDefaultDevice ); -/* -Calls fatInit with setAsDefaultDevice = true and cacheSize optimised for the host system. -*/ -extern bool fatInitDefault (void); + /* + Calls fatInit with setAsDefaultDevice = true and cacheSize optimised for the host system. + */ + extern bool fatInitDefault ( void ); -/* -Mount the device pointed to by interface, and set up a devoptab entry for it as "name:". -You can then access the filesystem using "name:/". -This will mount the active partition or the first valid partition on the disc, -and will use a cache size optimized for the host system. -*/ -extern bool fatMountSimple (const char* name, const DISC_INTERFACE* interface); + /* + Mount the device pointed to by interface, and set up a devoptab entry for it as "name:". + You can then access the filesystem using "name:/". + This will mount the active partition or the first valid partition on the disc, + and will use a cache size optimized for the host system. + */ + extern bool fatMountSimple ( const char* name, const DISC_INTERFACE* interface ); -/* -Mount the device pointed to by interface, and set up a devoptab entry for it as "name:". -You can then access the filesystem using "name:/". -If startSector = 0, it will mount the active partition of the first valid partition on -the disc. Otherwise it will try to mount the partition starting at startSector. -cacheSize specifies the number of pages to allocate for the cache. -This will not startup the disc, so you need to call interface->startup(); first. -*/ -extern bool fatMount (const char* name, const DISC_INTERFACE* interface, sec_t startSector, uint32_t cacheSize, uint32_t SectorsPerPage); -/* -Unmount the partition specified by name. -If there are open files, it will attempt to synchronise them to disc. -*/ -extern void fatUnmount (const char* name); + /* + Mount the device pointed to by interface, and set up a devoptab entry for it as "name:". + You can then access the filesystem using "name:/". + If startSector = 0, it will mount the active partition of the first valid partition on + the disc. Otherwise it will try to mount the partition starting at startSector. + cacheSize specifies the number of pages to allocate for the cache. + This will not startup the disc, so you need to call interface->startup(); first. + */ + extern bool fatMount ( const char* name, const DISC_INTERFACE* interface, sec_t startSector, uint32_t cacheSize, uint32_t SectorsPerPage ); + /* + Unmount the partition specified by name. + If there are open files, it will attempt to synchronise them to disc. + */ + extern void fatUnmount ( const char* name ); #ifdef __cplusplus } diff --git a/source/libfat/fat_cache.c b/source/libfat/fat_cache.c index 422915b8..8e699d21 100644 --- a/source/libfat/fat_cache.c +++ b/source/libfat/fat_cache.c @@ -46,321 +46,356 @@ #define CACHE_FREE UINT_MAX -CACHE* _FAT_cache_constructor (unsigned int numberOfPages, unsigned int sectorsPerPage, const DISC_INTERFACE* discInterface, sec_t endOfPartition) { - CACHE* cache; - unsigned int i; - CACHE_ENTRY* cacheEntries; +CACHE* _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) { - numberOfPages = 2; - } + if ( numberOfPages < 2 ) + { + numberOfPages = 2; + } - if (sectorsPerPage < 8) { - sectorsPerPage = 8; - } + if ( sectorsPerPage < 8 ) + { + sectorsPerPage = 8; + } - cache = (CACHE*) _FAT_mem_allocate (sizeof(CACHE)); - if (cache == NULL) { - return NULL; - } + cache = ( CACHE* ) _FAT_mem_allocate ( sizeof( CACHE ) ); + if ( cache == NULL ) + { + return NULL; + } - cache->disc = discInterface; - cache->endOfPartition = endOfPartition; - cache->numberOfPages = numberOfPages; - cache->sectorsPerPage = sectorsPerPage; + cache->disc = discInterface; + cache->endOfPartition = endOfPartition; + cache->numberOfPages = numberOfPages; + cache->sectorsPerPage = sectorsPerPage; - cacheEntries = (CACHE_ENTRY*) _FAT_mem_allocate ( sizeof(CACHE_ENTRY) * numberOfPages); - if (cacheEntries == NULL) { - _FAT_mem_free (cache); - return NULL; - } + cacheEntries = ( CACHE_ENTRY* ) _FAT_mem_allocate ( sizeof( CACHE_ENTRY ) * numberOfPages ); + if ( cacheEntries == NULL ) + { + _FAT_mem_free ( cache ); + return NULL; + } - for (i = 0; i < numberOfPages; i++) { - cacheEntries[i].sector = CACHE_FREE; - cacheEntries[i].count = 0; - cacheEntries[i].last_access = 0; - cacheEntries[i].dirty = false; - cacheEntries[i].cache = (uint8_t*) _FAT_mem_align ( sectorsPerPage * BYTES_PER_READ ); - } + for ( i = 0; i < numberOfPages; i++ ) + { + cacheEntries[i].sector = CACHE_FREE; + cacheEntries[i].count = 0; + cacheEntries[i].last_access = 0; + cacheEntries[i].dirty = false; + cacheEntries[i].cache = ( uint8_t* ) _FAT_mem_align ( sectorsPerPage * BYTES_PER_READ ); + } - cache->cacheEntries = cacheEntries; + cache->cacheEntries = cacheEntries; - return cache; + return cache; } -void _FAT_cache_destructor (CACHE* cache) { - unsigned int i; - // Clear out cache before destroying it - _FAT_cache_flush(cache); +void _FAT_cache_destructor ( CACHE* cache ) +{ + unsigned int i; + // Clear out cache before destroying it + _FAT_cache_flush( cache ); - // Free memory in reverse allocation order - for (i = 0; i < cache->numberOfPages; i++) { - _FAT_mem_free (cache->cacheEntries[i].cache); - } - _FAT_mem_free (cache->cacheEntries); - _FAT_mem_free (cache); + // Free memory in reverse allocation order + for ( i = 0; i < cache->numberOfPages; i++ ) + { + _FAT_mem_free ( cache->cacheEntries[i].cache ); + } + _FAT_mem_free ( cache->cacheEntries ); + _FAT_mem_free ( cache ); } static u32 accessCounter = 0; -static u32 accessTime(){ - accessCounter++; - return accessCounter; +static u32 accessTime() +{ + accessCounter++; + return accessCounter; } -static CACHE_ENTRY* _FAT_cache_getPage(CACHE *cache,sec_t sector) +static CACHE_ENTRY* _FAT_cache_getPage( CACHE *cache, sec_t sector ) { - unsigned int i; - CACHE_ENTRY* cacheEntries = cache->cacheEntries; - unsigned int numberOfPages = cache->numberOfPages; - unsigned int sectorsPerPage = cache->sectorsPerPage; + unsigned int i; + CACHE_ENTRY* cacheEntries = cache->cacheEntries; + unsigned int numberOfPages = cache->numberOfPages; + unsigned int sectorsPerPage = cache->sectorsPerPage; - bool foundFree = false; - unsigned int oldUsed = 0; - unsigned int oldAccess = UINT_MAX; + bool foundFree = false; + unsigned int oldUsed = 0; + unsigned int oldAccess = UINT_MAX; - for(i=0;i=cacheEntries[i].sector && sector<(cacheEntries[i].sector + cacheEntries[i].count)) { - cacheEntries[i].last_access = accessTime(); - return &(cacheEntries[i]); - } + for ( i = 0; i < numberOfPages; i++ ) + { + if ( sector >= cacheEntries[i].sector && sector < ( cacheEntries[i].sector + cacheEntries[i].count ) ) + { + cacheEntries[i].last_access = accessTime(); + return &( cacheEntries[i] ); + } - if(foundFree==false && (cacheEntries[i].sector==CACHE_FREE || cacheEntries[i].last_accessdisc,cacheEntries[oldUsed].sector,cacheEntries[oldUsed].count,cacheEntries[oldUsed].cache)) return NULL; - cacheEntries[oldUsed].dirty = false; - } + if ( foundFree == false && cacheEntries[oldUsed].dirty == true ) + { + if ( !_FAT_disc_writeSectors( cache->disc, cacheEntries[oldUsed].sector, cacheEntries[oldUsed].count, cacheEntries[oldUsed].cache ) ) return NULL; + cacheEntries[oldUsed].dirty = false; + } - sector = (sector/sectorsPerPage)*sectorsPerPage; // align base sector to page size - sec_t next_page = sector + sectorsPerPage; - if(next_page > cache->endOfPartition) next_page = cache->endOfPartition; + sector = ( sector / sectorsPerPage ) * sectorsPerPage; // align base sector to page size + sec_t next_page = sector + sectorsPerPage; + if ( next_page > cache->endOfPartition ) next_page = cache->endOfPartition; - if(!_FAT_disc_readSectors(cache->disc,sector,next_page-sector,cacheEntries[oldUsed].cache)) return NULL; + if ( !_FAT_disc_readSectors( cache->disc, sector, next_page - sector, cacheEntries[oldUsed].cache ) ) return NULL; - cacheEntries[oldUsed].sector = sector; - cacheEntries[oldUsed].count = next_page-sector; - cacheEntries[oldUsed].last_access = accessTime(); + cacheEntries[oldUsed].sector = sector; + cacheEntries[oldUsed].count = next_page - sector; + cacheEntries[oldUsed].last_access = accessTime(); - return &(cacheEntries[oldUsed]); + return &( cacheEntries[oldUsed] ); } -bool _FAT_cache_readSectors(CACHE *cache,sec_t sector,sec_t numSectors,void *buffer) +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; + sec_t sec; + sec_t secs_to_read; + CACHE_ENTRY *entry; + uint8_t *dest = buffer; - while(numSectors>0) { - entry = _FAT_cache_getPage(cache,sector); - if(entry==NULL) return false; + while ( numSectors > 0 ) + { + entry = _FAT_cache_getPage( cache, sector ); + if ( entry == NULL ) return false; - sec = sector - entry->sector; - secs_to_read = entry->count - sec; - if(secs_to_read>numSectors) secs_to_read = numSectors; + sec = sector - entry->sector; + secs_to_read = entry->count - sec; + if ( secs_to_read > numSectors ) secs_to_read = numSectors; - memcpy(dest,entry->cache + (sec*BYTES_PER_READ),(secs_to_read*BYTES_PER_READ)); + memcpy( dest, entry->cache + ( sec*BYTES_PER_READ ), ( secs_to_read*BYTES_PER_READ ) ); - dest += (secs_to_read*BYTES_PER_READ); - sector += secs_to_read; - numSectors -= secs_to_read; - } + dest += ( secs_to_read * BYTES_PER_READ ); + sector += secs_to_read; + numSectors -= secs_to_read; + } - return true; + return true; } /* Reads some data from a cache page, determined by the sector number */ -bool _FAT_cache_readPartialSector (CACHE* cache, void* buffer, sec_t sector, unsigned int offset, size_t size) +bool _FAT_cache_readPartialSector ( CACHE* cache, void* buffer, sec_t sector, unsigned int offset, size_t size ) { - sec_t sec; - CACHE_ENTRY *entry; + sec_t sec; + CACHE_ENTRY *entry; - if (offset + size > BYTES_PER_READ) return false; + if ( offset + size > BYTES_PER_READ ) return false; - entry = _FAT_cache_getPage(cache,sector); - if(entry==NULL) return false; + entry = _FAT_cache_getPage( cache, sector ); + if ( entry == NULL ) return false; - sec = sector - entry->sector; - memcpy(buffer,entry->cache + ((sec*BYTES_PER_READ) + offset),size); + sec = sector - entry->sector; + memcpy( buffer, entry->cache + ( ( sec*BYTES_PER_READ ) + offset ), size ); - return true; + return true; } -bool _FAT_cache_readLittleEndianValue (CACHE* cache, uint32_t *value, sec_t sector, unsigned int offset, int num_bytes) { - uint8_t buf[4]; - if (!_FAT_cache_readPartialSector(cache, buf, sector, offset, num_bytes)) return false; +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; - switch(num_bytes) { - case 1: *value = buf[0]; break; - case 2: *value = u8array_to_u16(buf,0); break; - case 4: *value = u8array_to_u32(buf,0); break; - default: return false; - } - return true; + switch ( num_bytes ) + { + case 1: *value = buf[0]; break; + case 2: *value = u8array_to_u16( buf, 0 ); break; + case 4: *value = u8array_to_u32( buf, 0 ); break; + default: return false; + } + return true; } /* Writes some data to a cache page, making sure it is loaded into memory first. */ -bool _FAT_cache_writePartialSector (CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size) +bool _FAT_cache_writePartialSector ( CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size ) { - sec_t sec; - CACHE_ENTRY *entry; + sec_t sec; + CACHE_ENTRY *entry; - if (offset + size > BYTES_PER_READ) return false; + if ( offset + size > BYTES_PER_READ ) return false; - entry = _FAT_cache_getPage(cache,sector); - if(entry==NULL) return false; + entry = _FAT_cache_getPage( cache, sector ); + if ( entry == NULL ) return false; - sec = sector - entry->sector; - memcpy(entry->cache + ((sec*BYTES_PER_READ) + offset),buffer,size); + sec = sector - entry->sector; + memcpy( entry->cache + ( ( sec*BYTES_PER_READ ) + offset ), buffer, size ); - entry->dirty = true; - return true; + entry->dirty = true; + return true; } -bool _FAT_cache_writeLittleEndianValue (CACHE* cache, const uint32_t value, sec_t sector, unsigned int offset, int size) { - uint8_t buf[4] = {0, 0, 0, 0}; +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}; - switch(size) { - case 1: buf[0] = value; break; - case 2: u16_to_u8array(buf, 0, value); break; - case 4: u32_to_u8array(buf, 0, value); break; - default: return false; - } + switch ( size ) + { + case 1: buf[0] = value; break; + case 2: u16_to_u8array( buf, 0, value ); break; + case 4: u32_to_u8array( buf, 0, value ); break; + default: return false; + } - return _FAT_cache_writePartialSector(cache, buf, sector, offset, size); + return _FAT_cache_writePartialSector( cache, buf, sector, offset, size ); } /* Writes some data to a cache page, zeroing out the page first */ -bool _FAT_cache_eraseWritePartialSector (CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size) +bool _FAT_cache_eraseWritePartialSector ( CACHE* cache, const void* buffer, sec_t sector, unsigned int offset, size_t size ) { - sec_t sec; - CACHE_ENTRY *entry; + sec_t sec; + CACHE_ENTRY *entry; - if (offset + size > BYTES_PER_READ) return false; + if ( offset + size > BYTES_PER_READ ) return false; - entry = _FAT_cache_getPage(cache,sector); - if(entry==NULL) return false; + entry = _FAT_cache_getPage( cache, sector ); + if ( entry == NULL ) return false; - sec = sector - entry->sector; - memset(entry->cache + (sec*BYTES_PER_READ),0,BYTES_PER_READ); - memcpy(entry->cache + ((sec*BYTES_PER_READ) + offset),buffer,size); + sec = sector - entry->sector; + memset( entry->cache + ( sec*BYTES_PER_READ ), 0, BYTES_PER_READ ); + memcpy( entry->cache + ( ( sec*BYTES_PER_READ ) + offset ), buffer, size ); - entry->dirty = true; - return true; + entry->dirty = true; + return true; } -static CACHE_ENTRY* _FAT_cache_findPage(CACHE *cache, sec_t sector, sec_t count) { +static CACHE_ENTRY* _FAT_cache_findPage( CACHE *cache, sec_t sector, sec_t count ) +{ - unsigned int i; - CACHE_ENTRY* cacheEntries = cache->cacheEntries; - unsigned int numberOfPages = cache->numberOfPages; - CACHE_ENTRY *entry = NULL; - sec_t lowest = UINT_MAX; + unsigned int i; + CACHE_ENTRY* cacheEntries = cache->cacheEntries; + unsigned int numberOfPages = cache->numberOfPages; + CACHE_ENTRY *entry = NULL; + sec_t lowest = UINT_MAX; - for(i=0;i cacheEntries[i].sector) { - intersect = sector - cacheEntries[i].sector < cacheEntries[i].count; - } else { - intersect = cacheEntries[i].sector - sector < count; - } + for ( i = 0; i < 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]; - } - } - } + if ( intersect && ( cacheEntries[i].sector < lowest ) ) + { + lowest = cacheEntries[i].sector; + entry = &cacheEntries[i]; + } + } + } - return entry; + return entry; } -bool _FAT_cache_writeSectors (CACHE* cache, sec_t sector, sec_t numSectors, const void* buffer) +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; + sec_t sec; + sec_t secs_to_write; + CACHE_ENTRY* entry; + const uint8_t *src = buffer; - while(numSectors>0) - { - entry = _FAT_cache_findPage(cache,sector,numSectors); + while ( numSectors > 0 ) + { + entry = _FAT_cache_findPage( cache, sector, numSectors ); - if(entry!=NULL) { + if ( entry != NULL ) + { - if ( entry->sector > sector) { + if ( entry->sector > sector ) + { - secs_to_write = entry->sector - sector; + secs_to_write = entry->sector - sector; - _FAT_disc_writeSectors(cache->disc,sector,secs_to_write,src); - src += (secs_to_write*BYTES_PER_READ); - sector += secs_to_write; - numSectors -= secs_to_write; - } + _FAT_disc_writeSectors( cache->disc, sector, secs_to_write, src ); + src += ( secs_to_write * BYTES_PER_READ ); + sector += secs_to_write; + numSectors -= secs_to_write; + } - sec = sector - entry->sector; - secs_to_write = entry->count - sec; + sec = sector - entry->sector; + secs_to_write = entry->count - sec; - if(secs_to_write>numSectors) secs_to_write = numSectors; + if ( secs_to_write > numSectors ) secs_to_write = numSectors; - memcpy(entry->cache + (sec*BYTES_PER_READ),src,(secs_to_write*BYTES_PER_READ)); + memcpy( entry->cache + ( sec*BYTES_PER_READ ), src, ( secs_to_write*BYTES_PER_READ ) ); - src += (secs_to_write*BYTES_PER_READ); - sector += secs_to_write; - numSectors -= secs_to_write; + src += ( secs_to_write * BYTES_PER_READ ); + sector += secs_to_write; + numSectors -= secs_to_write; - entry->dirty = true; + entry->dirty = true; - } else { - _FAT_disc_writeSectors(cache->disc,sector,numSectors,src); - numSectors=0; - } - } - return true; + } + else + { + _FAT_disc_writeSectors( cache->disc, sector, numSectors, src ); + numSectors = 0; + } + } + return true; } /* Flushes all dirty pages to disc, clearing the dirty flag. */ -bool _FAT_cache_flush (CACHE* cache) { - unsigned int i; +bool _FAT_cache_flush ( CACHE* cache ) +{ + unsigned int i; - for (i = 0; i < cache->numberOfPages; i++) { - if (cache->cacheEntries[i].dirty) { - if (!_FAT_disc_writeSectors (cache->disc, cache->cacheEntries[i].sector, cache->cacheEntries[i].count, cache->cacheEntries[i].cache)) { - return false; - } - } - cache->cacheEntries[i].dirty = false; - } + for ( i = 0; i < cache->numberOfPages; i++ ) + { + if ( cache->cacheEntries[i].dirty ) + { + if ( !_FAT_disc_writeSectors ( cache->disc, cache->cacheEntries[i].sector, cache->cacheEntries[i].count, cache->cacheEntries[i].cache ) ) + { + return false; + } + } + cache->cacheEntries[i].dirty = false; + } - return true; + return true; } -void _FAT_cache_invalidate (CACHE* cache) { - unsigned int i; - _FAT_cache_flush(cache); - for (i = 0; i < cache->numberOfPages; i++) { - cache->cacheEntries[i].sector = CACHE_FREE; - cache->cacheEntries[i].last_access = 0; - cache->cacheEntries[i].count = 0; - cache->cacheEntries[i].dirty = false; - } +void _FAT_cache_invalidate ( CACHE* cache ) +{ + unsigned int i; + _FAT_cache_flush( cache ); + for ( i = 0; i < cache->numberOfPages; i++ ) + { + cache->cacheEntries[i].sector = CACHE_FREE; + cache->cacheEntries[i].last_access = 0; + cache->cacheEntries[i].count = 0; + cache->cacheEntries[i].dirty = false; + } } diff --git a/source/libfat/fat_cache.h b/source/libfat/fat_cache.h index ce754c6d..5733b98c 100644 --- a/source/libfat/fat_cache.h +++ b/source/libfat/fat_cache.h @@ -42,20 +42,22 @@ #define PAGE_SECTORS 64 #define CACHE_PAGE_SIZE (BYTES_PER_READ * PAGE_SECTORS) -typedef struct { - sec_t sector; - unsigned int count; - unsigned int last_access; - bool dirty; - uint8_t* cache; +typedef struct +{ + 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; +typedef struct +{ + const DISC_INTERFACE* disc; + sec_t endOfPartition; + unsigned int numberOfPages; + unsigned int sectorsPerPage; + CACHE_ENTRY* cacheEntries; } CACHE; /* @@ -65,9 +67,9 @@ 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_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 @@ -77,9 +79,9 @@ 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_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 @@ -89,42 +91,44 @@ 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); +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); +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) { - return _FAT_cache_readPartialSector (cache, buffer, sector, 0, BYTES_PER_READ); +static inline bool _FAT_cache_readSector ( CACHE* cache, void* buffer, sec_t sector ) +{ + return _FAT_cache_readPartialSector ( cache, buffer, sector, 0, BYTES_PER_READ ); } /* Write a full sector to the cache */ -static inline bool _FAT_cache_writeSector (CACHE* cache, const void* buffer, sec_t sector) { - return _FAT_cache_writePartialSector (cache, buffer, sector, 0, BYTES_PER_READ); +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 ); } -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); +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); +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 5a555e38..dfb5e4ce 100644 --- a/source/libfat/fatdir.c +++ b/source/libfat/fatdir.c @@ -1,11 +1,11 @@ /* fatdir.c - - Functions used by the newlib disc stubs to interface with + + Functions used by the newlib disc stubs to interface with this library Copyright (c) 2006 Michael "Chishm" Chisholm - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -45,566 +45,639 @@ #include "lock.h" -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) { - r->_errno = ENODEV; - return -1; - } - - // Move the path pointer to the start of the actual path - if (strchr (path, ':') != NULL) { - path = strchr (path, ':') + 1; - } - if (strchr (path, ':') != NULL) { - r->_errno = EINVAL; - return -1; - } - - _FAT_lock(&partition->lock); - - // Search for the file on the disc - if (!_FAT_directory_entryFromPath (partition, &dirEntry, path, NULL)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOENT; - return -1; - } - - // Fill in the stat struct - _FAT_directory_entryStat (partition, &dirEntry, st); - - _FAT_unlock(&partition->lock); - return 0; -} - -int _FAT_link_r (struct _reent *r, const char *existing, const char *newLink) { - r->_errno = ENOTSUP; - return -1; -} - -int _FAT_unlink_r (struct _reent *r, const char *path) { - PARTITION* partition = NULL; - DIR_ENTRY dirEntry; - DIR_ENTRY dirContents; - uint32_t cluster; - bool nextEntry; - bool errorOccured = false; - - // Get the partition this directory is on - partition = _FAT_partition_getPartitionFromPath (path); - if (partition == NULL) { - r->_errno = ENODEV; - return -1; - } - - // Make sure we aren't trying to write to a read-only disc - if (partition->readOnly) { - r->_errno = EROFS; - return -1; - } - - // Move the path pointer to the start of the actual path - if (strchr (path, ':') != NULL) { - path = strchr (path, ':') + 1; - } - if (strchr (path, ':') != NULL) { - r->_errno = EINVAL; - return -1; - } - - _FAT_lock(&partition->lock); - - // Search for the file on the disc - if (!_FAT_directory_entryFromPath (partition, &dirEntry, path, NULL)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOENT; - return -1; - } - - cluster = _FAT_directory_entryGetCluster (partition, dirEntry.entryData); - - - // If this is a directory, make sure it is empty - if (_FAT_directory_isDirectory (&dirEntry)) { - nextEntry = _FAT_directory_getFirstEntry (partition, &dirContents, cluster); - - while (nextEntry) { - if (!_FAT_directory_isDot (&dirContents)) { - // The directory had something in it that isn't a reference to itself or it's parent - _FAT_unlock(&partition->lock); - r->_errno = EPERM; - return -1; - } - nextEntry = _FAT_directory_getNextEntry (partition, &dirContents); - } - } - - if (_FAT_fat_isValidCluster(partition, cluster)) { - // Remove the cluster chain for this file - if (!_FAT_fat_clearLinks (partition, cluster)) { - r->_errno = EIO; - errorOccured = true; - } - } - - // Remove the directory entry for this file - if (!_FAT_directory_removeEntry (partition, &dirEntry)) { - r->_errno = EIO; - errorOccured = true; - } - - // Flush any sectors in the disc cache - if (!_FAT_cache_flush(partition->cache)) { - r->_errno = EIO; - errorOccured = true; - } - - _FAT_unlock(&partition->lock); - if (errorOccured) { - return -1; - } else { - return 0; - } -} - -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) { - r->_errno = ENODEV; - return -1; - } - - // Move the path pointer to the start of the actual path - if (strchr (path, ':') != NULL) { - path = strchr (path, ':') + 1; - } - if (strchr (path, ':') != NULL) { - r->_errno = EINVAL; - return -1; - } - - _FAT_lock(&partition->lock); - - // Try changing directory - if (_FAT_directory_chdir (partition, path)) { - // Successful - _FAT_unlock(&partition->lock); - return 0; - } else { - // Failed - _FAT_unlock(&partition->lock); - r->_errno = ENOTDIR; - return -1; - } -} - -int _FAT_rename_r (struct _reent *r, const char *oldName, const char *newName) { - PARTITION* partition = NULL; - DIR_ENTRY oldDirEntry; - DIR_ENTRY newDirEntry; - const char *pathEnd; - uint32_t dirCluster; - - // Get the partition this directory is on - partition = _FAT_partition_getPartitionFromPath (oldName); - if (partition == NULL) { - r->_errno = ENODEV; - return -1; - } - - _FAT_lock(&partition->lock); - - // Make sure the same partition is used for the old and new names - if (partition != _FAT_partition_getPartitionFromPath (newName)) { - _FAT_unlock(&partition->lock); - r->_errno = EXDEV; - return -1; - } - - // Make sure we aren't trying to write to a read-only disc - if (partition->readOnly) { - _FAT_unlock(&partition->lock); - r->_errno = EROFS; - return -1; - } - - // Move the path pointer to the start of the actual path - if (strchr (oldName, ':') != NULL) { - oldName = strchr (oldName, ':') + 1; - } - if (strchr (oldName, ':') != NULL) { - _FAT_unlock(&partition->lock); - r->_errno = EINVAL; - return -1; - } - if (strchr (newName, ':') != NULL) { - newName = strchr (newName, ':') + 1; - } - if (strchr (newName, ':') != NULL) { - _FAT_unlock(&partition->lock); - r->_errno = EINVAL; - return -1; - } - - // Search for the file on the disc - if (!_FAT_directory_entryFromPath (partition, &oldDirEntry, oldName, NULL)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOENT; - return -1; - } - - // Make sure there is no existing file / directory with the new name - if (_FAT_directory_entryFromPath (partition, &newDirEntry, newName, NULL)) { - _FAT_unlock(&partition->lock); - r->_errno = EEXIST; - return -1; - } - - // Create the new file entry - // Get the directory it has to go in - pathEnd = strrchr (newName, DIR_SEPARATOR); - if (pathEnd == NULL) { - // No path was specified - dirCluster = partition->cwdCluster; - pathEnd = newName; - } else { - // Path was specified -- get the right dirCluster - // Recycling newDirEntry, since it needs to be recreated anyway - if (!_FAT_directory_entryFromPath (partition, &newDirEntry, newName, pathEnd) || - !_FAT_directory_isDirectory(&newDirEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOTDIR; - return -1; - } - dirCluster = _FAT_directory_entryGetCluster (partition, newDirEntry.entryData); - // Move the pathEnd past the last DIR_SEPARATOR - pathEnd += 1; - } - - // Copy the entry data - memcpy (&newDirEntry, &oldDirEntry, sizeof(DIR_ENTRY)); - - // Set the new name - strncpy (newDirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1); - - // Write the new entry - if (!_FAT_directory_addEntry (partition, &newDirEntry, dirCluster)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOSPC; - return -1; - } - - // Remove the old entry - if (!_FAT_directory_removeEntry (partition, &oldDirEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = EIO; - return -1; - } - - // Flush any sectors in the disc cache - if (!_FAT_cache_flush (partition->cache)) { - _FAT_unlock(&partition->lock); - r->_errno = EIO; - return -1; - } - - _FAT_unlock(&partition->lock); - return 0; -} - -int _FAT_mkdir_r (struct _reent *r, const char *path, int mode) { - PARTITION* partition = NULL; - bool fileExists; - DIR_ENTRY dirEntry; - const char* pathEnd; - uint32_t parentCluster, dirCluster; - uint8_t newEntryData[DIR_ENTRY_DATA_SIZE]; - - partition = _FAT_partition_getPartitionFromPath (path); - if (partition == NULL) { - r->_errno = ENODEV; - return -1; - } - - // Move the path pointer to the start of the actual path - if (strchr (path, ':') != NULL) { - path = strchr (path, ':') + 1; - } - if (strchr (path, ':') != NULL) { - r->_errno = EINVAL; - return -1; - } - - _FAT_lock(&partition->lock); - - // Search for the file/directory on the disc - fileExists = _FAT_directory_entryFromPath (partition, &dirEntry, path, NULL); - - // Make sure it doesn't exist - if (fileExists) { - _FAT_unlock(&partition->lock); - r->_errno = EEXIST; - return -1; - } - - if (partition->readOnly) { - // We can't write to a read-only partition - _FAT_unlock(&partition->lock); - r->_errno = EROFS; - return -1; - } - - // Get the directory it has to go in - pathEnd = strrchr (path, DIR_SEPARATOR); - if (pathEnd == NULL) { - // No path was specified - parentCluster = partition->cwdCluster; - pathEnd = path; - } else { - // Path was specified -- get the right parentCluster - // Recycling dirEntry, since it needs to be recreated anyway - if (!_FAT_directory_entryFromPath (partition, &dirEntry, path, pathEnd) || - !_FAT_directory_isDirectory(&dirEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOTDIR; - return -1; - } - parentCluster = _FAT_directory_entryGetCluster (partition, dirEntry.entryData); - // Move the pathEnd past the last DIR_SEPARATOR - pathEnd += 1; - } - // Create the entry data - strncpy (dirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1); - memset (dirEntry.entryData, 0, DIR_ENTRY_DATA_SIZE); - - // Set the creation time and date - dirEntry.entryData[DIR_ENTRY_cTime_ms] = 0; - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cTime, _FAT_filetime_getTimeFromRTC()); - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cDate, _FAT_filetime_getDateFromRTC()); - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_mTime, _FAT_filetime_getTimeFromRTC()); - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_mDate, _FAT_filetime_getDateFromRTC()); - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_aDate, _FAT_filetime_getDateFromRTC()); - - // Set the directory attribute - dirEntry.entryData[DIR_ENTRY_attributes] = ATTRIB_DIR; - - // Get a cluster for the new directory - dirCluster = _FAT_fat_linkFreeClusterCleared (partition, CLUSTER_FREE); - if (!_FAT_fat_isValidCluster(partition, dirCluster)) { - // No space left on disc for the cluster - _FAT_unlock(&partition->lock); - r->_errno = ENOSPC; - return -1; - } - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cluster, dirCluster); - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_clusterHigh, dirCluster >> 16); - - // Write the new directory's entry to it's parent - if (!_FAT_directory_addEntry (partition, &dirEntry, parentCluster)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOSPC; - return -1; - } - - // Create the dot entry within the directory - memset (newEntryData, 0, DIR_ENTRY_DATA_SIZE); - memset (newEntryData, ' ', 11); - newEntryData[DIR_ENTRY_name] = '.'; - newEntryData[DIR_ENTRY_attributes] = ATTRIB_DIR; - u16_to_u8array (newEntryData, DIR_ENTRY_cluster, dirCluster); - u16_to_u8array (newEntryData, DIR_ENTRY_clusterHigh, dirCluster >> 16); - - // Write it to the directory, erasing that sector in the process - _FAT_cache_eraseWritePartialSector ( partition->cache, newEntryData, - _FAT_fat_clusterToSector (partition, dirCluster), 0, DIR_ENTRY_DATA_SIZE); - - - // Create the double dot entry within the directory - - // if ParentDir == Rootdir then ".."" always link to Cluster 0 - if(parentCluster == partition->rootDirCluster) - parentCluster = FAT16_ROOT_DIR_CLUSTER; - - newEntryData[DIR_ENTRY_name + 1] = '.'; - u16_to_u8array (newEntryData, DIR_ENTRY_cluster, parentCluster); - u16_to_u8array (newEntryData, DIR_ENTRY_clusterHigh, parentCluster >> 16); - - // Write it to the directory - _FAT_cache_writePartialSector ( partition->cache, newEntryData, - _FAT_fat_clusterToSector (partition, dirCluster), DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); - - // Flush any sectors in the disc cache - if (!_FAT_cache_flush(partition->cache)) { - _FAT_unlock(&partition->lock); - r->_errno = EIO; - return -1; - } - - _FAT_unlock(&partition->lock); - return 0; -} - -int _FAT_statvfs_r (struct _reent *r, const char *path, struct statvfs *buf) +int _FAT_stat_r ( struct _reent *r, const char *path, struct stat *st ) { - PARTITION* partition = NULL; - unsigned int freeClusterCount; + PARTITION* partition = NULL; + DIR_ENTRY dirEntry; - // Get the partition of the requested path - partition = _FAT_partition_getPartitionFromPath (path); - if (partition == NULL) { - r->_errno = ENODEV; - return -1; - } + // Get the partition this file is on + partition = _FAT_partition_getPartitionFromPath ( path ); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } - _FAT_lock(&partition->lock); + // Move the path pointer to the start of the actual path + if ( strchr ( path, ':' ) != NULL ) + { + path = strchr ( path, ':' ) + 1; + } + if ( strchr ( path, ':' ) != NULL ) + { + r->_errno = EINVAL; + return -1; + } - freeClusterCount = _FAT_fat_freeClusterCount (partition); - - // FAT clusters = POSIX blocks - buf->f_bsize = partition->bytesPerCluster; // File system block size. - buf->f_frsize = partition->bytesPerCluster; // Fundamental file system block size. - - buf->f_blocks = partition->fat.lastCluster - CLUSTER_FIRST + 1; // Total number of blocks on file system in units of f_frsize. - buf->f_bfree = freeClusterCount; // Total number of free blocks. - buf->f_bavail = freeClusterCount; // Number of free blocks available to non-privileged process. + _FAT_lock( &partition->lock ); - // Treat requests for info on inodes as clusters - buf->f_files = partition->fat.lastCluster - CLUSTER_FIRST + 1; // Total number of file serial numbers. - buf->f_ffree = freeClusterCount; // Total number of free file serial numbers. - buf->f_favail = freeClusterCount; // Number of file serial numbers available to non-privileged process. - - // File system ID. 32bit ioType value - buf->f_fsid = _FAT_disc_hostType(partition->disc); - - // Bit mask of f_flag values. - buf->f_flag = ST_NOSUID /* No support for ST_ISUID and ST_ISGID file mode bits */ - | (partition->readOnly ? ST_RDONLY /* Read only file system */ : 0 ) ; - // Maximum filename length. - buf->f_namemax = MAX_FILENAME_LENGTH; + // Search for the file on the disc + if ( !_FAT_directory_entryFromPath ( partition, &dirEntry, path, NULL ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = ENOENT; + return -1; + } - _FAT_unlock(&partition->lock); - return 0; + // Fill in the stat struct + _FAT_directory_entryStat ( partition, &dirEntry, st ); + + _FAT_unlock( &partition->lock ); + return 0; } -DIR_ITER* _FAT_diropen_r(struct _reent *r, DIR_ITER *dirState, const char *path) { - DIR_ENTRY dirEntry; - DIR_STATE_STRUCT* state = (DIR_STATE_STRUCT*) (dirState->dirStruct); - bool fileExists; - - state->partition = _FAT_partition_getPartitionFromPath (path); - if (state->partition == NULL) { - r->_errno = ENODEV; - return NULL; - } - - // Move the path pointer to the start of the actual path - if (strchr (path, ':') != NULL) { - path = strchr (path, ':') + 1; - } - if (strchr (path, ':') != NULL) { - r->_errno = EINVAL; - return NULL; - } - - _FAT_lock(&state->partition->lock); - - // Get the start cluster of the directory - fileExists = _FAT_directory_entryFromPath (state->partition, &dirEntry, path, NULL); - - if (!fileExists) { - _FAT_unlock(&state->partition->lock); - r->_errno = ENOENT; - return NULL; - } - - // Make sure it is a directory - if (! _FAT_directory_isDirectory (&dirEntry)) { - _FAT_unlock(&state->partition->lock); - r->_errno = ENOTDIR; - return NULL; - } - - // Save the start cluster for use when resetting the directory data - state->startCluster = _FAT_directory_entryGetCluster (state->partition, dirEntry.entryData); - - // Get the first entry for use with a call to dirnext - state->validEntry = - _FAT_directory_getFirstEntry (state->partition, &(state->currentEntry), state->startCluster); - - // We are now using this entry - state->inUse = true; - _FAT_unlock(&state->partition->lock); - return (DIR_ITER*) state; +int _FAT_link_r ( struct _reent *r, const char *existing, const char *newLink ) +{ + r->_errno = ENOTSUP; + return -1; } -int _FAT_dirreset_r (struct _reent *r, DIR_ITER *dirState) { - DIR_STATE_STRUCT* state = (DIR_STATE_STRUCT*) (dirState->dirStruct); +int _FAT_unlink_r ( struct _reent *r, const char *path ) +{ + PARTITION* partition = NULL; + DIR_ENTRY dirEntry; + DIR_ENTRY dirContents; + uint32_t cluster; + bool nextEntry; + bool errorOccured = false; - _FAT_lock(&state->partition->lock); - - // Make sure we are still using this entry - if (!state->inUse) { - _FAT_unlock(&state->partition->lock); - r->_errno = EBADF; - return -1; - } + // Get the partition this directory is on + partition = _FAT_partition_getPartitionFromPath ( path ); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } - // Get the first entry for use with a call to dirnext - state->validEntry = - _FAT_directory_getFirstEntry (state->partition, &(state->currentEntry), state->startCluster); + // Make sure we aren't trying to write to a read-only disc + if ( partition->readOnly ) + { + r->_errno = EROFS; + return -1; + } - _FAT_unlock(&state->partition->lock); - return 0; + // Move the path pointer to the start of the actual path + if ( strchr ( path, ':' ) != NULL ) + { + path = strchr ( path, ':' ) + 1; + } + if ( strchr ( path, ':' ) != NULL ) + { + r->_errno = EINVAL; + return -1; + } + + _FAT_lock( &partition->lock ); + + // Search for the file on the disc + if ( !_FAT_directory_entryFromPath ( partition, &dirEntry, path, NULL ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = ENOENT; + return -1; + } + + cluster = _FAT_directory_entryGetCluster ( partition, dirEntry.entryData ); + + + // If this is a directory, make sure it is empty + if ( _FAT_directory_isDirectory ( &dirEntry ) ) + { + nextEntry = _FAT_directory_getFirstEntry ( partition, &dirContents, cluster ); + + while ( nextEntry ) + { + if ( !_FAT_directory_isDot ( &dirContents ) ) + { + // The directory had something in it that isn't a reference to itself or it's parent + _FAT_unlock( &partition->lock ); + r->_errno = EPERM; + return -1; + } + nextEntry = _FAT_directory_getNextEntry ( partition, &dirContents ); + } + } + + if ( _FAT_fat_isValidCluster( partition, cluster ) ) + { + // Remove the cluster chain for this file + if ( !_FAT_fat_clearLinks ( partition, cluster ) ) + { + r->_errno = EIO; + errorOccured = true; + } + } + + // Remove the directory entry for this file + if ( !_FAT_directory_removeEntry ( partition, &dirEntry ) ) + { + r->_errno = EIO; + errorOccured = true; + } + + // Flush any sectors in the disc cache + if ( !_FAT_cache_flush( partition->cache ) ) + { + r->_errno = EIO; + errorOccured = true; + } + + _FAT_unlock( &partition->lock ); + if ( errorOccured ) + { + return -1; + } + else + { + return 0; + } } -int _FAT_dirnext_r (struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *filestat) { - DIR_STATE_STRUCT* state = (DIR_STATE_STRUCT*) (dirState->dirStruct); +int _FAT_chdir_r ( struct _reent *r, const char *path ) +{ + PARTITION* partition = NULL; - _FAT_lock(&state->partition->lock); - - // Make sure we are still using this entry - if (!state->inUse) { - _FAT_unlock(&state->partition->lock); - r->_errno = EBADF; - return -1; - } - - // Make sure there is another file to report on - if (! state->validEntry) { - _FAT_unlock(&state->partition->lock); - r->_errno = ENOENT; - return -1; - } + // Get the partition this directory is on + partition = _FAT_partition_getPartitionFromPath ( path ); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } - // Get the filename - strncpy (filename, state->currentEntry.filename, MAX_FILENAME_LENGTH); - // Get the stats, if requested - if (filestat != NULL) { - _FAT_directory_entryStat (state->partition, &(state->currentEntry), filestat); - } - - // Look for the next entry for use next time - state->validEntry = - _FAT_directory_getNextEntry (state->partition, &(state->currentEntry)); + // Move the path pointer to the start of the actual path + if ( strchr ( path, ':' ) != NULL ) + { + path = strchr ( path, ':' ) + 1; + } + if ( strchr ( path, ':' ) != NULL ) + { + r->_errno = EINVAL; + return -1; + } - _FAT_unlock(&state->partition->lock); - return 0; + _FAT_lock( &partition->lock ); + + // Try changing directory + if ( _FAT_directory_chdir ( partition, path ) ) + { + // Successful + _FAT_unlock( &partition->lock ); + return 0; + } + else + { + // Failed + _FAT_unlock( &partition->lock ); + r->_errno = ENOTDIR; + return -1; + } } -int _FAT_dirclose_r (struct _reent *r, DIR_ITER *dirState) { - DIR_STATE_STRUCT* state = (DIR_STATE_STRUCT*) (dirState->dirStruct); - - // We are no longer using this entry - _FAT_lock(&state->partition->lock); - state->inUse = false; - _FAT_unlock(&state->partition->lock); +int _FAT_rename_r ( struct _reent *r, const char *oldName, const char *newName ) +{ + PARTITION* partition = NULL; + DIR_ENTRY oldDirEntry; + DIR_ENTRY newDirEntry; + const char *pathEnd; + uint32_t dirCluster; - return 0; + // Get the partition this directory is on + partition = _FAT_partition_getPartitionFromPath ( oldName ); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } + + _FAT_lock( &partition->lock ); + + // Make sure the same partition is used for the old and new names + if ( partition != _FAT_partition_getPartitionFromPath ( newName ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EXDEV; + return -1; + } + + // Make sure we aren't trying to write to a read-only disc + if ( partition->readOnly ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EROFS; + return -1; + } + + // Move the path pointer to the start of the actual path + if ( strchr ( oldName, ':' ) != NULL ) + { + oldName = strchr ( oldName, ':' ) + 1; + } + if ( strchr ( oldName, ':' ) != NULL ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EINVAL; + return -1; + } + if ( strchr ( newName, ':' ) != NULL ) + { + newName = strchr ( newName, ':' ) + 1; + } + if ( strchr ( newName, ':' ) != NULL ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EINVAL; + return -1; + } + + // Search for the file on the disc + if ( !_FAT_directory_entryFromPath ( partition, &oldDirEntry, oldName, NULL ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = ENOENT; + return -1; + } + + // Make sure there is no existing file / directory with the new name + if ( _FAT_directory_entryFromPath ( partition, &newDirEntry, newName, NULL ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EEXIST; + return -1; + } + + // Create the new file entry + // Get the directory it has to go in + pathEnd = strrchr ( newName, DIR_SEPARATOR ); + if ( pathEnd == NULL ) + { + // No path was specified + dirCluster = partition->cwdCluster; + pathEnd = newName; + } + else + { + // Path was specified -- get the right dirCluster + // Recycling newDirEntry, since it needs to be recreated anyway + if ( !_FAT_directory_entryFromPath ( partition, &newDirEntry, newName, pathEnd ) || + !_FAT_directory_isDirectory( &newDirEntry ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = ENOTDIR; + return -1; + } + dirCluster = _FAT_directory_entryGetCluster ( partition, newDirEntry.entryData ); + // Move the pathEnd past the last DIR_SEPARATOR + pathEnd += 1; + } + + // Copy the entry data + memcpy ( &newDirEntry, &oldDirEntry, sizeof( DIR_ENTRY ) ); + + // Set the new name + strncpy ( newDirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1 ); + + // Write the new entry + if ( !_FAT_directory_addEntry ( partition, &newDirEntry, dirCluster ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = ENOSPC; + return -1; + } + + // Remove the old entry + if ( !_FAT_directory_removeEntry ( partition, &oldDirEntry ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EIO; + return -1; + } + + // Flush any sectors in the disc cache + if ( !_FAT_cache_flush ( partition->cache ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EIO; + return -1; + } + + _FAT_unlock( &partition->lock ); + return 0; +} + +int _FAT_mkdir_r ( struct _reent *r, const char *path, int mode ) +{ + PARTITION* partition = NULL; + bool fileExists; + DIR_ENTRY dirEntry; + const char* pathEnd; + uint32_t parentCluster, dirCluster; + uint8_t newEntryData[DIR_ENTRY_DATA_SIZE]; + + partition = _FAT_partition_getPartitionFromPath ( path ); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } + + // Move the path pointer to the start of the actual path + if ( strchr ( path, ':' ) != NULL ) + { + path = strchr ( path, ':' ) + 1; + } + if ( strchr ( path, ':' ) != NULL ) + { + r->_errno = EINVAL; + return -1; + } + + _FAT_lock( &partition->lock ); + + // Search for the file/directory on the disc + fileExists = _FAT_directory_entryFromPath ( partition, &dirEntry, path, NULL ); + + // Make sure it doesn't exist + if ( fileExists ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EEXIST; + return -1; + } + + if ( partition->readOnly ) + { + // We can't write to a read-only partition + _FAT_unlock( &partition->lock ); + r->_errno = EROFS; + return -1; + } + + // Get the directory it has to go in + pathEnd = strrchr ( path, DIR_SEPARATOR ); + if ( pathEnd == NULL ) + { + // No path was specified + parentCluster = partition->cwdCluster; + pathEnd = path; + } + else + { + // Path was specified -- get the right parentCluster + // Recycling dirEntry, since it needs to be recreated anyway + if ( !_FAT_directory_entryFromPath ( partition, &dirEntry, path, pathEnd ) || + !_FAT_directory_isDirectory( &dirEntry ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = ENOTDIR; + return -1; + } + parentCluster = _FAT_directory_entryGetCluster ( partition, dirEntry.entryData ); + // Move the pathEnd past the last DIR_SEPARATOR + pathEnd += 1; + } + // Create the entry data + strncpy ( dirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1 ); + memset ( dirEntry.entryData, 0, DIR_ENTRY_DATA_SIZE ); + + // Set the creation time and date + dirEntry.entryData[DIR_ENTRY_cTime_ms] = 0; + u16_to_u8array ( dirEntry.entryData, DIR_ENTRY_cTime, _FAT_filetime_getTimeFromRTC() ); + u16_to_u8array ( dirEntry.entryData, DIR_ENTRY_cDate, _FAT_filetime_getDateFromRTC() ); + u16_to_u8array ( dirEntry.entryData, DIR_ENTRY_mTime, _FAT_filetime_getTimeFromRTC() ); + u16_to_u8array ( dirEntry.entryData, DIR_ENTRY_mDate, _FAT_filetime_getDateFromRTC() ); + u16_to_u8array ( dirEntry.entryData, DIR_ENTRY_aDate, _FAT_filetime_getDateFromRTC() ); + + // Set the directory attribute + dirEntry.entryData[DIR_ENTRY_attributes] = ATTRIB_DIR; + + // Get a cluster for the new directory + dirCluster = _FAT_fat_linkFreeClusterCleared ( partition, CLUSTER_FREE ); + if ( !_FAT_fat_isValidCluster( partition, dirCluster ) ) + { + // No space left on disc for the cluster + _FAT_unlock( &partition->lock ); + r->_errno = ENOSPC; + return -1; + } + u16_to_u8array ( dirEntry.entryData, DIR_ENTRY_cluster, dirCluster ); + u16_to_u8array ( dirEntry.entryData, DIR_ENTRY_clusterHigh, dirCluster >> 16 ); + + // Write the new directory's entry to it's parent + if ( !_FAT_directory_addEntry ( partition, &dirEntry, parentCluster ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = ENOSPC; + return -1; + } + + // Create the dot entry within the directory + memset ( newEntryData, 0, DIR_ENTRY_DATA_SIZE ); + memset ( newEntryData, ' ', 11 ); + newEntryData[DIR_ENTRY_name] = '.'; + newEntryData[DIR_ENTRY_attributes] = ATTRIB_DIR; + u16_to_u8array ( newEntryData, DIR_ENTRY_cluster, dirCluster ); + u16_to_u8array ( newEntryData, DIR_ENTRY_clusterHigh, dirCluster >> 16 ); + + // Write it to the directory, erasing that sector in the process + _FAT_cache_eraseWritePartialSector ( partition->cache, newEntryData, + _FAT_fat_clusterToSector ( partition, dirCluster ), 0, DIR_ENTRY_DATA_SIZE ); + + + // Create the double dot entry within the directory + + // if ParentDir == Rootdir then ".."" always link to Cluster 0 + if ( parentCluster == partition->rootDirCluster ) + parentCluster = FAT16_ROOT_DIR_CLUSTER; + + newEntryData[DIR_ENTRY_name + 1] = '.'; + u16_to_u8array ( newEntryData, DIR_ENTRY_cluster, parentCluster ); + u16_to_u8array ( newEntryData, DIR_ENTRY_clusterHigh, parentCluster >> 16 ); + + // Write it to the directory + _FAT_cache_writePartialSector ( partition->cache, newEntryData, + _FAT_fat_clusterToSector ( partition, dirCluster ), DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE ); + + // Flush any sectors in the disc cache + if ( !_FAT_cache_flush( partition->cache ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EIO; + return -1; + } + + _FAT_unlock( &partition->lock ); + return 0; +} + +int _FAT_statvfs_r ( struct _reent *r, const char *path, struct statvfs *buf ) +{ + PARTITION* partition = NULL; + unsigned int freeClusterCount; + + // Get the partition of the requested path + partition = _FAT_partition_getPartitionFromPath ( path ); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } + + _FAT_lock( &partition->lock ); + + freeClusterCount = _FAT_fat_freeClusterCount ( partition ); + + // FAT clusters = POSIX blocks + buf->f_bsize = partition->bytesPerCluster; // File system block size. + buf->f_frsize = partition->bytesPerCluster; // Fundamental file system block size. + + buf->f_blocks = partition->fat.lastCluster - CLUSTER_FIRST + 1; // Total number of blocks on file system in units of f_frsize. + buf->f_bfree = freeClusterCount; // Total number of free blocks. + buf->f_bavail = freeClusterCount; // Number of free blocks available to non-privileged process. + + // Treat requests for info on inodes as clusters + buf->f_files = partition->fat.lastCluster - CLUSTER_FIRST + 1; // Total number of file serial numbers. + buf->f_ffree = freeClusterCount; // Total number of free file serial numbers. + buf->f_favail = freeClusterCount; // Number of file serial numbers available to non-privileged process. + + // File system ID. 32bit ioType value + buf->f_fsid = _FAT_disc_hostType( partition->disc ); + + // Bit mask of f_flag values. + buf->f_flag = ST_NOSUID /* No support for ST_ISUID and ST_ISGID file mode bits */ + | ( partition->readOnly ? ST_RDONLY /* Read only file system */ : 0 ) ; + // Maximum filename length. + buf->f_namemax = MAX_FILENAME_LENGTH; + + _FAT_unlock( &partition->lock ); + return 0; +} + +DIR_ITER* _FAT_diropen_r( struct _reent *r, DIR_ITER *dirState, const char *path ) +{ + DIR_ENTRY dirEntry; + DIR_STATE_STRUCT* state = ( DIR_STATE_STRUCT* ) ( dirState->dirStruct ); + bool fileExists; + + state->partition = _FAT_partition_getPartitionFromPath ( path ); + if ( state->partition == NULL ) + { + r->_errno = ENODEV; + return NULL; + } + + // Move the path pointer to the start of the actual path + if ( strchr ( path, ':' ) != NULL ) + { + path = strchr ( path, ':' ) + 1; + } + if ( strchr ( path, ':' ) != NULL ) + { + r->_errno = EINVAL; + return NULL; + } + + _FAT_lock( &state->partition->lock ); + + // Get the start cluster of the directory + fileExists = _FAT_directory_entryFromPath ( state->partition, &dirEntry, path, NULL ); + + if ( !fileExists ) + { + _FAT_unlock( &state->partition->lock ); + r->_errno = ENOENT; + return NULL; + } + + // Make sure it is a directory + if ( ! _FAT_directory_isDirectory ( &dirEntry ) ) + { + _FAT_unlock( &state->partition->lock ); + r->_errno = ENOTDIR; + return NULL; + } + + // Save the start cluster for use when resetting the directory data + state->startCluster = _FAT_directory_entryGetCluster ( state->partition, dirEntry.entryData ); + + // Get the first entry for use with a call to dirnext + state->validEntry = + _FAT_directory_getFirstEntry ( state->partition, &( state->currentEntry ), state->startCluster ); + + // We are now using this entry + state->inUse = true; + _FAT_unlock( &state->partition->lock ); + return ( DIR_ITER* ) state; +} + +int _FAT_dirreset_r ( struct _reent *r, DIR_ITER *dirState ) +{ + DIR_STATE_STRUCT* state = ( DIR_STATE_STRUCT* ) ( dirState->dirStruct ); + + _FAT_lock( &state->partition->lock ); + + // Make sure we are still using this entry + if ( !state->inUse ) + { + _FAT_unlock( &state->partition->lock ); + r->_errno = EBADF; + return -1; + } + + // Get the first entry for use with a call to dirnext + state->validEntry = + _FAT_directory_getFirstEntry ( state->partition, &( state->currentEntry ), state->startCluster ); + + _FAT_unlock( &state->partition->lock ); + return 0; +} + +int _FAT_dirnext_r ( struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *filestat ) +{ + DIR_STATE_STRUCT* state = ( DIR_STATE_STRUCT* ) ( dirState->dirStruct ); + + _FAT_lock( &state->partition->lock ); + + // Make sure we are still using this entry + if ( !state->inUse ) + { + _FAT_unlock( &state->partition->lock ); + r->_errno = EBADF; + return -1; + } + + // Make sure there is another file to report on + if ( ! state->validEntry ) + { + _FAT_unlock( &state->partition->lock ); + r->_errno = ENOENT; + return -1; + } + + // Get the filename + strncpy ( filename, state->currentEntry.filename, MAX_FILENAME_LENGTH ); + // Get the stats, if requested + if ( filestat != NULL ) + { + _FAT_directory_entryStat ( state->partition, &( state->currentEntry ), filestat ); + } + + // Look for the next entry for use next time + state->validEntry = + _FAT_directory_getNextEntry ( state->partition, &( state->currentEntry ) ); + + _FAT_unlock( &state->partition->lock ); + return 0; +} + +int _FAT_dirclose_r ( struct _reent *r, DIR_ITER *dirState ) +{ + DIR_STATE_STRUCT* state = ( DIR_STATE_STRUCT* ) ( dirState->dirStruct ); + + // We are no longer using this entry + _FAT_lock( &state->partition->lock ); + state->inUse = false; + _FAT_unlock( &state->partition->lock ); + + return 0; } diff --git a/source/libfat/fatdir.h b/source/libfat/fatdir.h index 1b47a914..7f0b7eb1 100644 --- a/source/libfat/fatdir.h +++ b/source/libfat/fatdir.h @@ -39,35 +39,36 @@ #include "common.h" #include "directory.h" -typedef struct { - PARTITION* partition; - DIR_ENTRY currentEntry; - uint32_t startCluster; - bool inUse; - bool validEntry; +typedef struct +{ + 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); +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 ba8dddb5..718a2700 100644 --- a/source/libfat/fatfile.c +++ b/source/libfat/fatfile.c @@ -45,208 +45,241 @@ #include "filetime.h" #include "lock.h" -int _FAT_open_r (struct _reent *r, void *fileStruct, const char *path, int flags, int mode) { - PARTITION* partition = NULL; - bool fileExists; - DIR_ENTRY dirEntry; - const char* pathEnd; - uint32_t dirCluster; - FILE_STRUCT* file = (FILE_STRUCT*) fileStruct; - partition = _FAT_partition_getPartitionFromPath (path); +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 ); - if (partition == NULL) { - r->_errno = ENODEV; - return -1; - } + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } - // Move the path pointer to the start of the actual path - if (strchr (path, ':') != NULL) { - path = strchr (path, ':') + 1; - } - if (strchr (path, ':') != NULL) { - r->_errno = EINVAL; - return -1; - } + // Move the path pointer to the start of the actual path + if ( strchr ( path, ':' ) != NULL ) + { + path = strchr ( path, ':' ) + 1; + } + if ( strchr ( path, ':' ) != NULL ) + { + r->_errno = EINVAL; + return -1; + } - // Determine which mode the file is openned for - if ((flags & 0x03) == O_RDONLY) { - // Open the file for read-only access - file->read = true; - file->write = false; - file->append = false; - } else if ((flags & 0x03) == O_WRONLY) { - // Open file for write only access - file->read = false; - file->write = true; - file->append = false; - } else if ((flags & 0x03) == O_RDWR) { - // Open file for read/write access - file->read = true; - file->write = true; - file->append = false; - } else { - r->_errno = EACCES; - return -1; - } + // Determine which mode the file is openned for + if ( ( flags & 0x03 ) == O_RDONLY ) + { + // Open the file for read-only access + file->read = true; + file->write = false; + file->append = false; + } + else if ( ( flags & 0x03 ) == O_WRONLY ) + { + // Open file for write only access + file->read = false; + file->write = true; + file->append = false; + } + else if ( ( flags & 0x03 ) == O_RDWR ) + { + // Open file for read/write access + file->read = true; + file->write = true; + file->append = false; + } + else + { + r->_errno = EACCES; + return -1; + } - // Make sure we aren't trying to write to a read-only disc - if (file->write && partition->readOnly) { - r->_errno = EROFS; - return -1; - } + // Make sure we aren't trying to write to a read-only disc + if ( file->write && partition->readOnly ) + { + r->_errno = EROFS; + return -1; + } - // Search for the file on the disc - _FAT_lock(&partition->lock); - fileExists = _FAT_directory_entryFromPath (partition, &dirEntry, path, NULL); + // Search for the file on the disc + _FAT_lock( &partition->lock ); + fileExists = _FAT_directory_entryFromPath ( partition, &dirEntry, path, NULL ); - // The file shouldn't exist if we are trying to create it - if ((flags & O_CREAT) && (flags & O_EXCL) && fileExists) { - _FAT_unlock(&partition->lock); - r->_errno = EEXIST; - return -1; - } + // The file shouldn't exist if we are trying to create it + if ( ( flags & O_CREAT ) && ( flags & O_EXCL ) && fileExists ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EEXIST; + return -1; + } - // It should not be a directory if we're openning a file, - if (fileExists && _FAT_directory_isDirectory(&dirEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = EISDIR; - return -1; - } + // It should not be a directory if we're openning a file, + if ( fileExists && _FAT_directory_isDirectory( &dirEntry ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EISDIR; + return -1; + } - // We haven't modified the file yet - file->modified = false; + // We haven't modified the file yet + file->modified = false; - // If the file doesn't exist, create it if we're allowed to - if (!fileExists) { - if (flags & O_CREAT) { - if (partition->readOnly) { - // We can't write to a read-only partition - _FAT_unlock(&partition->lock); - r->_errno = EROFS; - return -1; - } - // Create the file - // Get the directory it has to go in - pathEnd = strrchr (path, DIR_SEPARATOR); - if (pathEnd == NULL) { - // No path was specified - dirCluster = partition->cwdCluster; - pathEnd = path; - } else { - // Path was specified -- get the right dirCluster - // Recycling dirEntry, since it needs to be recreated anyway - if (!_FAT_directory_entryFromPath (partition, &dirEntry, path, pathEnd) || - !_FAT_directory_isDirectory(&dirEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOTDIR; - return -1; - } - dirCluster = _FAT_directory_entryGetCluster (partition, dirEntry.entryData); - // Move the pathEnd past the last DIR_SEPARATOR - pathEnd += 1; - } - // Create the entry data - strncpy (dirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1); - memset (dirEntry.entryData, 0, DIR_ENTRY_DATA_SIZE); + // If the file doesn't exist, create it if we're allowed to + if ( !fileExists ) + { + if ( flags & O_CREAT ) + { + if ( partition->readOnly ) + { + // We can't write to a read-only partition + _FAT_unlock( &partition->lock ); + r->_errno = EROFS; + return -1; + } + // Create the file + // Get the directory it has to go in + pathEnd = strrchr ( path, DIR_SEPARATOR ); + if ( pathEnd == NULL ) + { + // No path was specified + dirCluster = partition->cwdCluster; + pathEnd = path; + } + else + { + // Path was specified -- get the right dirCluster + // Recycling dirEntry, since it needs to be recreated anyway + if ( !_FAT_directory_entryFromPath ( partition, &dirEntry, path, pathEnd ) || + !_FAT_directory_isDirectory( &dirEntry ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = ENOTDIR; + return -1; + } + dirCluster = _FAT_directory_entryGetCluster ( partition, dirEntry.entryData ); + // Move the pathEnd past the last DIR_SEPARATOR + pathEnd += 1; + } + // Create the entry data + strncpy ( dirEntry.filename, pathEnd, MAX_FILENAME_LENGTH - 1 ); + memset ( dirEntry.entryData, 0, DIR_ENTRY_DATA_SIZE ); - // Set the creation time and date - dirEntry.entryData[DIR_ENTRY_cTime_ms] = 0; - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cTime, _FAT_filetime_getTimeFromRTC()); - u16_to_u8array (dirEntry.entryData, DIR_ENTRY_cDate, _FAT_filetime_getDateFromRTC()); + // Set the creation time and date + dirEntry.entryData[DIR_ENTRY_cTime_ms] = 0; + u16_to_u8array ( dirEntry.entryData, DIR_ENTRY_cTime, _FAT_filetime_getTimeFromRTC() ); + u16_to_u8array ( dirEntry.entryData, DIR_ENTRY_cDate, _FAT_filetime_getDateFromRTC() ); - if (!_FAT_directory_addEntry (partition, &dirEntry, dirCluster)) { - _FAT_unlock(&partition->lock); - r->_errno = ENOSPC; - return -1; - } + if ( !_FAT_directory_addEntry ( partition, &dirEntry, dirCluster ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = ENOSPC; + return -1; + } - // File entry is modified - file->modified = true; - } else { - // file doesn't exist, and we aren't creating it - _FAT_unlock(&partition->lock); - r->_errno = ENOENT; - return -1; - } - } + // File entry is modified + file->modified = true; + } + else + { + // file doesn't exist, and we aren't creating it + _FAT_unlock( &partition->lock ); + r->_errno = ENOENT; + return -1; + } + } - file->filesize = u8array_to_u32 (dirEntry.entryData, DIR_ENTRY_fileSize); + file->filesize = u8array_to_u32 ( dirEntry.entryData, DIR_ENTRY_fileSize ); - /* Allow LARGEFILEs with undefined results - // Make sure that the file size can fit in the available space - if (!(flags & O_LARGEFILE) && (file->filesize >= (1<<31))) { - r->_errno = EFBIG; - return -1; - } - */ + /* Allow LARGEFILEs with undefined results + // Make sure that the file size can fit in the available space + if (!(flags & O_LARGEFILE) && (file->filesize >= (1<<31))) { + r->_errno = EFBIG; + return -1; + } + */ - // Make sure we aren't trying to write to a read-only file - if (file->write && !_FAT_directory_isWritable(&dirEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = EROFS; - return -1; - } + // Make sure we aren't trying to write to a read-only file + if ( file->write && !_FAT_directory_isWritable( &dirEntry ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EROFS; + return -1; + } - // Associate this file with a particular partition - file->partition = partition; + // Associate this file with a particular partition + file->partition = partition; - file->startCluster = _FAT_directory_entryGetCluster (partition, dirEntry.entryData); + file->startCluster = _FAT_directory_entryGetCluster ( partition, dirEntry.entryData ); - // Truncate the file if requested - if ((flags & O_TRUNC) && file->write && (file->startCluster != 0)) { - _FAT_fat_clearLinks (partition, file->startCluster); - file->startCluster = CLUSTER_FREE; - file->filesize = 0; - // File is modified since we just cut it all off - file->modified = true; - } + // Truncate the file if requested + if ( ( flags & O_TRUNC ) && file->write && ( file->startCluster != 0 ) ) + { + _FAT_fat_clearLinks ( partition, file->startCluster ); + file->startCluster = CLUSTER_FREE; + file->filesize = 0; + // File is modified since we just cut it all off + file->modified = true; + } - // Remember the position of this file's directory entry - file->dirEntryStart = dirEntry.dataStart; // Points to the start of the LFN entries of a file, or the alias for no LFN - file->dirEntryEnd = dirEntry.dataEnd; + // Remember the position of this file's directory entry + file->dirEntryStart = dirEntry.dataStart; // Points to the start of the LFN entries of a file, or the alias for no LFN + file->dirEntryEnd = dirEntry.dataEnd; - // Reset read/write pointer - file->currentPosition = 0; - file->rwPosition.cluster = file->startCluster; - file->rwPosition.sector = 0; - file->rwPosition.byte = 0; + // Reset read/write pointer + file->currentPosition = 0; + file->rwPosition.cluster = file->startCluster; + file->rwPosition.sector = 0; + file->rwPosition.byte = 0; - if (flags & O_APPEND) { - file->append = true; + if ( flags & O_APPEND ) + { + file->append = true; - // Set append pointer to the end of the file - file->appendPosition.cluster = _FAT_fat_lastCluster (partition, file->startCluster); - file->appendPosition.sector = (file->filesize % partition->bytesPerCluster) / BYTES_PER_READ; - file->appendPosition.byte = file->filesize % BYTES_PER_READ; + // Set append pointer to the end of the file + file->appendPosition.cluster = _FAT_fat_lastCluster ( partition, file->startCluster ); + file->appendPosition.sector = ( file->filesize % partition->bytesPerCluster ) / BYTES_PER_READ; + file->appendPosition.byte = file->filesize % BYTES_PER_READ; - // Check if the end of the file is on the end of a cluster - if ( (file->filesize > 0) && ((file->filesize % partition->bytesPerCluster)==0) ){ - // Set flag to allocate a new cluster - file->appendPosition.sector = partition->sectorsPerCluster; - file->appendPosition.byte = 0; - } - } else { - file->append = false; - // Use something sane for the append pointer, so the whole file struct contains known values - file->appendPosition = file->rwPosition; - } + // Check if the end of the file is on the end of a cluster + if ( ( file->filesize > 0 ) && ( ( file->filesize % partition->bytesPerCluster ) == 0 ) ) + { + // Set flag to allocate a new cluster + file->appendPosition.sector = partition->sectorsPerCluster; + file->appendPosition.byte = 0; + } + } + else + { + file->append = false; + // Use something sane for the append pointer, so the whole file struct contains known values + file->appendPosition = file->rwPosition; + } - file->inUse = true; + file->inUse = true; - // Insert this file into the double-linked list of open files - partition->openFileCount += 1; - if (partition->firstOpenFile) { - file->nextOpenFile = partition->firstOpenFile; - partition->firstOpenFile->prevOpenFile = file; - } else { - file->nextOpenFile = NULL; - } - file->prevOpenFile = NULL; - partition->firstOpenFile = file; + // Insert this file into the double-linked list of open files + partition->openFileCount += 1; + if ( partition->firstOpenFile ) + { + file->nextOpenFile = partition->firstOpenFile; + partition->firstOpenFile->prevOpenFile = file; + } + else + { + file->nextOpenFile = NULL; + } + file->prevOpenFile = NULL; + partition->firstOpenFile = file; - _FAT_unlock(&partition->lock); + _FAT_unlock( &partition->lock ); - return (int) file; + return ( int ) file; } /* @@ -254,929 +287,1068 @@ 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]; +int _FAT_syncToDisc ( FILE_STRUCT* file ) +{ + uint8_t dirEntryData[DIR_ENTRY_DATA_SIZE]; - if (!file || !file->inUse) { - return EBADF; - } + if ( !file || !file->inUse ) + { + return EBADF; + } - if (file->write && file->modified) { - // Load the old entry - _FAT_cache_readPartialSector (file->partition->cache, dirEntryData, - _FAT_fat_clusterToSector(file->partition, file->dirEntryEnd.cluster) + file->dirEntryEnd.sector, - file->dirEntryEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); + if ( file->write && file->modified ) + { + // Load the old entry + _FAT_cache_readPartialSector ( file->partition->cache, dirEntryData, + _FAT_fat_clusterToSector( file->partition, file->dirEntryEnd.cluster ) + file->dirEntryEnd.sector, + file->dirEntryEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE ); - // Write new data to the directory entry - // File size - u32_to_u8array (dirEntryData, DIR_ENTRY_fileSize, file->filesize); + // Write new data to the directory entry + // File size + u32_to_u8array ( dirEntryData, DIR_ENTRY_fileSize, file->filesize ); - // Start cluster - u16_to_u8array (dirEntryData, DIR_ENTRY_cluster, file->startCluster); - u16_to_u8array (dirEntryData, DIR_ENTRY_clusterHigh, file->startCluster >> 16); + // Start cluster + u16_to_u8array ( dirEntryData, DIR_ENTRY_cluster, file->startCluster ); + u16_to_u8array ( dirEntryData, DIR_ENTRY_clusterHigh, file->startCluster >> 16 ); - // Modification time and date - u16_to_u8array (dirEntryData, DIR_ENTRY_mTime, _FAT_filetime_getTimeFromRTC()); - u16_to_u8array (dirEntryData, DIR_ENTRY_mDate, _FAT_filetime_getDateFromRTC()); + // Modification time and date + u16_to_u8array ( dirEntryData, DIR_ENTRY_mTime, _FAT_filetime_getTimeFromRTC() ); + u16_to_u8array ( dirEntryData, DIR_ENTRY_mDate, _FAT_filetime_getDateFromRTC() ); - // Access date - u16_to_u8array (dirEntryData, DIR_ENTRY_aDate, _FAT_filetime_getDateFromRTC()); + // Access date + u16_to_u8array ( dirEntryData, DIR_ENTRY_aDate, _FAT_filetime_getDateFromRTC() ); - // Set archive attribute - dirEntryData[DIR_ENTRY_attributes] |= ATTRIB_ARCH; + // Set archive attribute + dirEntryData[DIR_ENTRY_attributes] |= ATTRIB_ARCH; - // Write the new entry - _FAT_cache_writePartialSector (file->partition->cache, dirEntryData, - _FAT_fat_clusterToSector(file->partition, file->dirEntryEnd.cluster) + file->dirEntryEnd.sector, - file->dirEntryEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE); + // Write the new entry + _FAT_cache_writePartialSector ( file->partition->cache, dirEntryData, + _FAT_fat_clusterToSector( file->partition, file->dirEntryEnd.cluster ) + file->dirEntryEnd.sector, + file->dirEntryEnd.offset * DIR_ENTRY_DATA_SIZE, DIR_ENTRY_DATA_SIZE ); - // Flush any sectors in the disc cache - if (!_FAT_cache_flush(file->partition->cache)) { - return EIO; - } - } + // Flush any sectors in the disc cache + if ( !_FAT_cache_flush( file->partition->cache ) ) + { + return EIO; + } + } - file->modified = false; + file->modified = false; - return 0; + return 0; } -int _FAT_close_r (struct _reent *r, int fd) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - int ret = 0; +int _FAT_close_r ( struct _reent *r, int fd ) +{ + FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + int ret = 0; - if (!file->inUse) { - r->_errno = EBADF; - return -1; - } + if ( !file->inUse ) + { + r->_errno = EBADF; + return -1; + } - _FAT_lock(&file->partition->lock); + _FAT_lock( &file->partition->lock ); - if (file->write) { - ret = _FAT_syncToDisc (file); - if (ret != 0) { - r->_errno = ret; - ret = -1; - } - } + if ( file->write ) + { + ret = _FAT_syncToDisc ( file ); + if ( ret != 0 ) + { + r->_errno = ret; + ret = -1; + } + } - file->inUse = false; + file->inUse = false; - // Remove this file from the double-linked list of open files - file->partition->openFileCount -= 1; - if (file->nextOpenFile) { - file->nextOpenFile->prevOpenFile = file->prevOpenFile; - } - if (file->prevOpenFile) { - file->prevOpenFile->nextOpenFile = file->nextOpenFile; - } else { - file->partition->firstOpenFile = file->nextOpenFile; - } + // Remove this file from the double-linked list of open files + file->partition->openFileCount -= 1; + if ( file->nextOpenFile ) + { + file->nextOpenFile->prevOpenFile = file->prevOpenFile; + } + if ( file->prevOpenFile ) + { + file->prevOpenFile->nextOpenFile = file->nextOpenFile; + } + else + { + file->partition->firstOpenFile = file->nextOpenFile; + } - _FAT_unlock(&file->partition->lock); + _FAT_unlock( &file->partition->lock ); - return ret; + return ret; } -ssize_t _FAT_read_r (struct _reent *r, int fd, char *ptr, size_t len) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - PARTITION* partition; - CACHE* cache; - FILE_POSITION position; - uint32_t tempNextCluster; - unsigned int tempVar; - size_t remain; - bool flagNoError = true; +ssize_t _FAT_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) +{ + FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + PARTITION* partition; + CACHE* cache; + FILE_POSITION position; + uint32_t tempNextCluster; + unsigned int tempVar; + size_t remain; + bool flagNoError = true; - // Short circuit cases where len is 0 (or less) - if (len <= 0) { - return 0; - } + // Short circuit cases where len is 0 (or less) + if ( len <= 0 ) + { + return 0; + } - // Make sure we can actually read from the file - if ((file == NULL) || !file->inUse || !file->read) { - r->_errno = EBADF; - return -1; - } + // Make sure we can actually read from the file + if ( ( file == NULL ) || !file->inUse || !file->read ) + { + r->_errno = EBADF; + return -1; + } - partition = file->partition; - _FAT_lock(&partition->lock); + partition = file->partition; + _FAT_lock( &partition->lock ); - // Don't try to read if the read pointer is past the end of file - if (file->currentPosition >= file->filesize || file->startCluster == CLUSTER_FREE) { - r->_errno = EOVERFLOW; - _FAT_unlock(&partition->lock); - return 0; - } + // Don't try to read if the read pointer is past the end of file + if ( file->currentPosition >= file->filesize || file->startCluster == CLUSTER_FREE ) + { + r->_errno = EOVERFLOW; + _FAT_unlock( &partition->lock ); + return 0; + } - // Don't read past end of file - if (len + file->currentPosition > file->filesize) { - r->_errno = EOVERFLOW; - len = file->filesize - file->currentPosition; - } + // Don't read past end of file + if ( len + file->currentPosition > file->filesize ) + { + r->_errno = EOVERFLOW; + len = file->filesize - file->currentPosition; + } - remain = len; - position = file->rwPosition; - cache = file->partition->cache; + remain = len; + position = file->rwPosition; + cache = file->partition->cache; - // Align to sector - tempVar = BYTES_PER_READ - position.byte; - if (tempVar > remain) { - tempVar = remain; - } + // Align to sector + tempVar = BYTES_PER_READ - position.byte; + if ( tempVar > remain ) + { + tempVar = remain; + } - if ((tempVar < BYTES_PER_READ) && flagNoError) - { - _FAT_cache_readPartialSector ( cache, ptr, _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, - position.byte, tempVar); + if ( ( tempVar < BYTES_PER_READ ) && flagNoError ) + { + _FAT_cache_readPartialSector ( cache, ptr, _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, + position.byte, tempVar ); - remain -= tempVar; - ptr += tempVar; + remain -= tempVar; + ptr += tempVar; - position.byte += tempVar; - if (position.byte >= BYTES_PER_READ) { - position.byte = 0; - position.sector++; - } - } + position.byte += tempVar; + if ( position.byte >= BYTES_PER_READ ) + { + position.byte = 0; + position.sector++; + } + } - // align to cluster - // tempVar is number of sectors to read - if (remain > (partition->sectorsPerCluster - position.sector) * BYTES_PER_READ) { - tempVar = partition->sectorsPerCluster - position.sector; - } else { - tempVar = remain / BYTES_PER_READ; - } + // align to cluster + // tempVar is number of sectors to read + if ( remain > ( partition->sectorsPerCluster - position.sector ) * BYTES_PER_READ ) + { + tempVar = partition->sectorsPerCluster - position.sector; + } + else + { + tempVar = remain / BYTES_PER_READ; + } - if ((tempVar > 0) && flagNoError) { - if (! _FAT_cache_readSectors (cache, _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, - tempVar, ptr)) - { - flagNoError = false; - r->_errno = EIO; - } else { - ptr += tempVar * BYTES_PER_READ; - remain -= tempVar * BYTES_PER_READ; - position.sector += tempVar; - } - } + if ( ( tempVar > 0 ) && flagNoError ) + { + if ( ! _FAT_cache_readSectors ( cache, _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, + tempVar, ptr ) ) + { + flagNoError = false; + r->_errno = EIO; + } + else + { + ptr += tempVar * BYTES_PER_READ; + remain -= tempVar * BYTES_PER_READ; + position.sector += tempVar; + } + } - // Move onto next cluster - // It should get to here without reading anything if a cluster is due to be allocated - if ((position.sector >= partition->sectorsPerCluster) && flagNoError) { - tempNextCluster = _FAT_fat_nextCluster(partition, position.cluster); - if ((remain == 0) && (tempNextCluster == CLUSTER_EOF)) { - position.sector = partition->sectorsPerCluster; - } else if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { - r->_errno = EIO; - flagNoError = false; - } else { - position.sector = 0; - position.cluster = tempNextCluster; - } - } + // Move onto next cluster + // It should get to here without reading anything if a cluster is due to be allocated + if ( ( position.sector >= partition->sectorsPerCluster ) && flagNoError ) + { + tempNextCluster = _FAT_fat_nextCluster( partition, position.cluster ); + if ( ( remain == 0 ) && ( tempNextCluster == CLUSTER_EOF ) ) + { + position.sector = partition->sectorsPerCluster; + } + else if ( !_FAT_fat_isValidCluster( partition, tempNextCluster ) ) + { + r->_errno = EIO; + flagNoError = false; + } + else + { + position.sector = 0; + position.cluster = tempNextCluster; + } + } - // Read in whole clusters, contiguous blocks at a time - while ((remain >= partition->bytesPerCluster) && flagNoError) { - uint32_t chunkEnd; - uint32_t nextChunkStart = position.cluster; - size_t chunkSize = 0; + // Read in whole clusters, contiguous blocks at a time + while ( ( remain >= partition->bytesPerCluster ) && flagNoError ) + { + uint32_t chunkEnd; + uint32_t nextChunkStart = position.cluster; + size_t chunkSize = 0; - do { - chunkEnd = nextChunkStart; - nextChunkStart = _FAT_fat_nextCluster (partition, chunkEnd); - chunkSize += partition->bytesPerCluster; - } while ((nextChunkStart == chunkEnd + 1) && + do + { + chunkEnd = nextChunkStart; + nextChunkStart = _FAT_fat_nextCluster ( partition, chunkEnd ); + chunkSize += partition->bytesPerCluster; + } + while ( ( nextChunkStart == chunkEnd + 1 ) && #ifdef LIMIT_SECTORS - (chunkSize + partition->bytesPerCluster <= LIMIT_SECTORS * BYTES_PER_READ) && + ( chunkSize + partition->bytesPerCluster <= LIMIT_SECTORS * BYTES_PER_READ ) && #endif - (chunkSize + partition->bytesPerCluster <= remain)); + ( chunkSize + partition->bytesPerCluster <= remain ) ); - if (!_FAT_cache_readSectors (cache, _FAT_fat_clusterToSector (partition, position.cluster), - chunkSize / BYTES_PER_READ, ptr)) - { - flagNoError = false; - r->_errno = EIO; - break; - } - ptr += chunkSize; - remain -= chunkSize; + if ( !_FAT_cache_readSectors ( cache, _FAT_fat_clusterToSector ( partition, position.cluster ), + chunkSize / BYTES_PER_READ, ptr ) ) + { + flagNoError = false; + r->_errno = EIO; + break; + } + ptr += chunkSize; + remain -= chunkSize; - // Advance to next cluster - if ((remain == 0) && (nextChunkStart == CLUSTER_EOF)) { - position.sector = partition->sectorsPerCluster; - position.cluster = chunkEnd; - } else if (!_FAT_fat_isValidCluster(partition, nextChunkStart)) { - r->_errno = EIO; - flagNoError = false; - } else { - position.sector = 0; - position.cluster = nextChunkStart; - } - } + // Advance to next cluster + if ( ( remain == 0 ) && ( nextChunkStart == CLUSTER_EOF ) ) + { + position.sector = partition->sectorsPerCluster; + position.cluster = chunkEnd; + } + else if ( !_FAT_fat_isValidCluster( partition, nextChunkStart ) ) + { + r->_errno = EIO; + flagNoError = false; + } + else + { + position.sector = 0; + position.cluster = nextChunkStart; + } + } - // Read remaining sectors - tempVar = remain / BYTES_PER_READ; // Number of sectors left - if ((tempVar > 0) && flagNoError) { - if (!_FAT_cache_readSectors (cache, _FAT_fat_clusterToSector (partition, position.cluster), - tempVar, ptr)) - { - flagNoError = false; - r->_errno = EIO; - } else { - ptr += tempVar * BYTES_PER_READ; - remain -= tempVar * BYTES_PER_READ; - position.sector += tempVar; - } - } + // Read remaining sectors + tempVar = remain / BYTES_PER_READ; // Number of sectors left + if ( ( tempVar > 0 ) && flagNoError ) + { + if ( !_FAT_cache_readSectors ( cache, _FAT_fat_clusterToSector ( partition, position.cluster ), + tempVar, ptr ) ) + { + flagNoError = false; + r->_errno = EIO; + } + else + { + ptr += tempVar * BYTES_PER_READ; + remain -= tempVar * BYTES_PER_READ; + position.sector += tempVar; + } + } - // Last remaining sector - // Check if anything is left - if ((remain > 0) && flagNoError) { - _FAT_cache_readPartialSector ( cache, ptr, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, 0, remain); - position.byte += remain; - remain = 0; - } + // Last remaining sector + // Check if anything is left + if ( ( remain > 0 ) && flagNoError ) + { + _FAT_cache_readPartialSector ( cache, ptr, + _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, 0, remain ); + position.byte += remain; + remain = 0; + } - // Length read is the wanted length minus the stuff not read - len = len - remain; + // Length read is the wanted length minus the stuff not read + len = len - remain; - // Update file information - file->rwPosition = position; - file->currentPosition += len; + // Update file information + file->rwPosition = position; + file->currentPosition += len; - _FAT_unlock(&partition->lock); - return len; + _FAT_unlock( &partition->lock ); + return len; } // if current position is on the cluster border and more data has to be written // 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)) { - // invalid arguments - internal error - r->_errno = EINVAL; - goto err; - } - if (position->sector == partition->sectorsPerCluster) { - // need to advance to next cluster - tempNextCluster = _FAT_fat_nextCluster(partition, position->cluster); - if ((tempNextCluster == CLUSTER_EOF) || (tempNextCluster == CLUSTER_FREE)) { - // Ran out of clusters so get a new one - tempNextCluster = _FAT_fat_linkFreeCluster(partition, position->cluster); - } - if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { - // Couldn't get a cluster, so abort - r->_errno = ENOSPC; - goto err; - } - position->sector = 0; - position->cluster = tempNextCluster; - } - return true; + uint32_t tempNextCluster; + // do nothing if no more data to write + if ( remain == 0 ) return true; + if ( flagNoError && *flagNoError == false ) return false; + if ( ( remain < 0 ) || ( position->sector > partition->sectorsPerCluster ) ) + { + // invalid arguments - internal error + r->_errno = EINVAL; + goto err; + } + if ( position->sector == partition->sectorsPerCluster ) + { + // need to advance to next cluster + tempNextCluster = _FAT_fat_nextCluster( partition, position->cluster ); + if ( ( tempNextCluster == CLUSTER_EOF ) || ( tempNextCluster == CLUSTER_FREE ) ) + { + // Ran out of clusters so get a new one + tempNextCluster = _FAT_fat_linkFreeCluster( partition, position->cluster ); + } + if ( !_FAT_fat_isValidCluster( partition, tempNextCluster ) ) + { + // Couldn't get a cluster, so abort + r->_errno = ENOSPC; + goto err; + } + position->sector = 0; + position->cluster = tempNextCluster; + } + return true; err: - if (flagNoError) *flagNoError = false; - return false; + if ( flagNoError ) *flagNoError = false; + return false; } /* Extend a file so that the size is the same as the rwPosition */ -static bool _FAT_file_extend_r (struct _reent *r, FILE_STRUCT* file) { - PARTITION* partition = file->partition; - CACHE* cache = file->partition->cache; - FILE_POSITION position; - uint8_t zeroBuffer [BYTES_PER_READ] = {0}; - uint32_t remain; - uint32_t tempNextCluster; - unsigned int sector; - - position.byte = file->filesize % BYTES_PER_READ; - position.sector = (file->filesize % partition->bytesPerCluster) / BYTES_PER_READ; - // It is assumed that there is always a startCluster - // This will be true when _FAT_file_extend_r is called from _FAT_write_r - position.cluster = _FAT_fat_lastCluster (partition, file->startCluster); - - remain = file->currentPosition - file->filesize; - - if ((remain > 0) && (file->filesize > 0) && (position.sector == 0) && (position.byte == 0)) { - // Get a new cluster on the edge of a cluster boundary - tempNextCluster = _FAT_fat_linkFreeCluster(partition, position.cluster); - if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { - // Couldn't get a cluster, so abort - r->_errno = ENOSPC; - return false; - } - position.cluster = tempNextCluster; - position.sector = 0; - } - - if (remain + position.byte < BYTES_PER_READ) { - // Only need to clear to the end of the sector - _FAT_cache_writePartialSector (cache, zeroBuffer, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, position.byte, remain); - position.byte += remain; - } else { - if (position.byte > 0) { - _FAT_cache_writePartialSector (cache, zeroBuffer, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, position.byte, - BYTES_PER_READ - position.byte); - remain -= (BYTES_PER_READ - position.byte); - position.byte = 0; - position.sector ++; - } - - while (remain >= BYTES_PER_READ) { - if (position.sector >= partition->sectorsPerCluster) { - position.sector = 0; - // Ran out of clusters so get a new one - tempNextCluster = _FAT_fat_linkFreeCluster(partition, position.cluster); - if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { - // Couldn't get a cluster, so abort - r->_errno = ENOSPC; - return false; - } - position.cluster = tempNextCluster; - } - - sector = _FAT_fat_clusterToSector (partition, position.cluster) + position.sector; - _FAT_cache_writeSectors (cache, sector, 1, zeroBuffer); - - remain -= BYTES_PER_READ; - position.sector ++; - } - - if (!_FAT_check_position_for_next_cluster(r, &position, partition, remain, NULL)) { - // error already marked - return false; - } - - if (remain > 0) { - _FAT_cache_writePartialSector (cache, zeroBuffer, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, 0, remain); - position.byte = remain; - } - } - - file->rwPosition = position; - file->filesize = file->currentPosition; - return true; -} - -ssize_t _FAT_write_r (struct _reent *r, int fd, const char *ptr, size_t len) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - PARTITION* partition; - CACHE* cache; - FILE_POSITION position; - uint32_t tempNextCluster; - unsigned int tempVar; - size_t remain; - bool flagNoError = true; - bool flagAppending = false; - - // Make sure we can actually write to the file - if ((file == NULL) || !file->inUse || !file->write) { - r->_errno = EBADF; - return -1; - } - - partition = file->partition; - cache = file->partition->cache; - _FAT_lock(&partition->lock); - - // Only write up to the maximum file size, taking into account wrap-around of ints - if (remain + file->filesize > FILE_MAX_SIZE || len + file->filesize < file->filesize) { - len = FILE_MAX_SIZE - file->filesize; - } - remain = len; - - // Short circuit cases where len is 0 (or less) - if (len <= 0) { - _FAT_unlock(&partition->lock); - return 0; - } - - // Get a new cluster for the start of the file if required - if (file->startCluster == CLUSTER_FREE) { - tempNextCluster = _FAT_fat_linkFreeCluster (partition, CLUSTER_FREE); - if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { - // Couldn't get a cluster, so abort immediately - _FAT_unlock(&partition->lock); - r->_errno = ENOSPC; - return -1; - } - file->startCluster = tempNextCluster; - - // Appending starts at the begining for a 0 byte file - file->appendPosition.cluster = file->startCluster; - file->appendPosition.sector = 0; - file->appendPosition.byte = 0; - - file->rwPosition.cluster = file->startCluster; - file->rwPosition.sector = 0; - file->rwPosition.byte = 0; - } - - if (file->append) { - position = file->appendPosition; - flagAppending = true; - } else { - // If the write pointer is past the end of the file, extend the file to that size - if (file->currentPosition > file->filesize) { - if (!_FAT_file_extend_r (r, file)) { - _FAT_unlock(&partition->lock); - return -1; - } - } - - // Write at current read pointer - position = file->rwPosition; - - // If it is writing past the current end of file, set appending flag - if (len + file->currentPosition > file->filesize) { - flagAppending = true; - } - } - - // Move onto next cluster if needed - _FAT_check_position_for_next_cluster(r, &position, partition, remain, &flagNoError); - - // Align to sector - tempVar = BYTES_PER_READ - position.byte; - if (tempVar > remain) { - tempVar = remain; - } - - if ((tempVar < BYTES_PER_READ) && flagNoError) { - // Write partial sector to disk - _FAT_cache_writePartialSector (cache, ptr, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, position.byte, tempVar); - - remain -= tempVar; - ptr += tempVar; - position.byte += tempVar; - - - // Move onto next sector - if (position.byte >= BYTES_PER_READ) { - position.byte = 0; - position.sector ++; - } - } - - // Align to cluster - // tempVar is number of sectors to write - if (remain > (partition->sectorsPerCluster - position.sector) * BYTES_PER_READ) { - tempVar = partition->sectorsPerCluster - position.sector; - } else { - tempVar = remain / BYTES_PER_READ; - } - - if ((tempVar > 0 && tempVar < partition->sectorsPerCluster) && flagNoError) { - if (!_FAT_cache_writeSectors (cache, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, tempVar, ptr)) - { - flagNoError = false; - r->_errno = EIO; - } else { - ptr += tempVar * BYTES_PER_READ; - remain -= tempVar * BYTES_PER_READ; - position.sector += tempVar; - } - } - - // Write whole clusters - while ((remain >= partition->bytesPerCluster) && flagNoError) { - // allocate next cluster - _FAT_check_position_for_next_cluster(r, &position, partition, remain, &flagNoError); - if (!flagNoError) break; - // set indexes to the current position - uint32_t chunkEnd = position.cluster; - uint32_t nextChunkStart = position.cluster; - size_t chunkSize = partition->bytesPerCluster; - FILE_POSITION next_position = position; - - // group consecutive clusters - while (flagNoError && -#ifdef LIMIT_SECTORS - (chunkSize + partition->bytesPerCluster <= LIMIT_SECTORS * BYTES_PER_READ) && -#endif - (chunkSize + partition->bytesPerCluster < remain)) - { - // pretend to use up all sectors in next_position - next_position.sector = partition->sectorsPerCluster; - // get or allocate next cluster - _FAT_check_position_for_next_cluster(r, &next_position, partition, - remain - chunkSize, &flagNoError); - if (!flagNoError) break; // exit loop on error - nextChunkStart = next_position.cluster; - if (nextChunkStart != chunkEnd + 1) break; // exit loop if not consecutive - chunkEnd = nextChunkStart; - chunkSize += partition->bytesPerCluster; - } - - if ( !_FAT_cache_writeSectors (cache, - _FAT_fat_clusterToSector(partition, position.cluster), chunkSize / BYTES_PER_READ, ptr)) - { - flagNoError = false; - r->_errno = EIO; - break; - } - ptr += chunkSize; - remain -= chunkSize; - - if ((chunkEnd != nextChunkStart) && _FAT_fat_isValidCluster(partition, nextChunkStart)) { - // new cluster is already allocated (because it was not consecutive) - position.cluster = nextChunkStart; - position.sector = 0; - } else { - // Allocate a new cluster when next writing the file - position.cluster = chunkEnd; - position.sector = partition->sectorsPerCluster; - } - } - - // allocate next cluster if needed - _FAT_check_position_for_next_cluster(r, &position, partition, remain, &flagNoError); - - // Write remaining sectors - tempVar = remain / BYTES_PER_READ; // Number of sectors left - if ((tempVar > 0) && flagNoError) { - if (!_FAT_cache_writeSectors (cache, _FAT_fat_clusterToSector (partition, position.cluster), tempVar, ptr)) - { - flagNoError = false; - r->_errno = EIO; - } else { - ptr += tempVar * BYTES_PER_READ; - remain -= tempVar * BYTES_PER_READ; - position.sector += tempVar; - } - } - - // Last remaining sector - if ((remain > 0) && flagNoError) { - if (flagAppending) { - _FAT_cache_eraseWritePartialSector ( cache, ptr, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, 0, remain); - } else { - _FAT_cache_writePartialSector ( cache, ptr, - _FAT_fat_clusterToSector (partition, position.cluster) + position.sector, 0, remain); - } - position.byte += remain; - remain = 0; - } - - - // Amount written is the originally requested amount minus stuff remaining - len = len - remain; - - // Update file information - file->modified = true; - if (file->append) { - // Appending doesn't affect the read pointer - file->appendPosition = position; - file->filesize += len; - } else { - // Writing also shifts the read pointer - file->rwPosition = position; - file->currentPosition += len; - if (file->filesize < file->currentPosition) { - file->filesize = file->currentPosition; - } - } - _FAT_unlock(&partition->lock); - - return len; -} - - -off_t _FAT_seek_r (struct _reent *r, int fd, off_t pos, int dir) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - PARTITION* partition; - uint32_t cluster, nextCluster; - int clusCount; - off_t newPosition; - uint32_t position; - - if ((file == NULL) || (file->inUse == false)) { - // invalid file - r->_errno = EBADF; - return -1; - } - - partition = file->partition; - _FAT_lock(&partition->lock); - - switch (dir) { - case SEEK_SET: - newPosition = pos; - break; - case SEEK_CUR: - newPosition = (off_t)file->currentPosition + pos; - break; - case SEEK_END: - newPosition = (off_t)file->filesize + pos; - break; - default: - _FAT_unlock(&partition->lock); - r->_errno = EINVAL; - return -1; - } - - if ((pos > 0) && (newPosition < 0)) { - _FAT_unlock(&partition->lock); - r->_errno = EOVERFLOW; - return -1; - } - - // newPosition can only be larger than the FILE_MAX_SIZE on platforms where - // off_t is larger than 32 bits. - if (newPosition < 0 || ((sizeof(newPosition) > 4) && newPosition > (off_t)FILE_MAX_SIZE)) { - _FAT_unlock(&partition->lock); - r->_errno = EINVAL; - return -1; - } - - position = (uint32_t)newPosition; - - // Only change the read/write position if it is within the bounds of the current filesize, - // or at the very edge of the file - if (position <= file->filesize && file->startCluster != CLUSTER_FREE) { - // Calculate where the correct cluster is - // how many clusters from start of file - clusCount = position / partition->bytesPerCluster; - cluster = file->startCluster; - if (position >= file->currentPosition) { - // start from current cluster - int currentCount = file->currentPosition / partition->bytesPerCluster; - if (file->rwPosition.sector == partition->sectorsPerCluster) { - currentCount--; - } - clusCount -= currentCount; - cluster = file->rwPosition.cluster; - } - // Calculate the sector and byte of the current position, - // and store them - file->rwPosition.sector = (position % partition->bytesPerCluster) / BYTES_PER_READ; - file->rwPosition.byte = position % BYTES_PER_READ; - - nextCluster = _FAT_fat_nextCluster (partition, cluster); - while ((clusCount > 0) && (nextCluster != CLUSTER_FREE) && (nextCluster != CLUSTER_EOF)) { - clusCount--; - cluster = nextCluster; - nextCluster = _FAT_fat_nextCluster (partition, cluster); - } - - // Check if ran out of clusters and it needs to allocate a new one - if (clusCount > 0) { - if ((clusCount == 1) && (file->filesize == position) && (file->rwPosition.sector == 0)) { - // Set flag to allocate a new cluster - file->rwPosition.sector = partition->sectorsPerCluster; - file->rwPosition.byte = 0; - } else { - _FAT_unlock(&partition->lock); - r->_errno = EINVAL; - return -1; - } - } - - file->rwPosition.cluster = cluster; - } - - // Save position - file->currentPosition = position; - - _FAT_unlock(&partition->lock); - return position; -} - - - -int _FAT_fstat_r (struct _reent *r, int fd, struct stat *st) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - PARTITION* partition; - DIR_ENTRY fileEntry; - - if ((file == NULL) || (file->inUse == false)) { - // invalid file - r->_errno = EBADF; - return -1; - } - - partition = file->partition; - _FAT_lock(&partition->lock); - - // Get the file's entry data - fileEntry.dataStart = file->dirEntryStart; - fileEntry.dataEnd = file->dirEntryEnd; - - if (!_FAT_directory_entryFromPosition (partition, &fileEntry)) { - _FAT_unlock(&partition->lock); - r->_errno = EIO; - return -1; - } - - // Fill in the stat struct - _FAT_directory_entryStat (partition, &fileEntry, st); - - // Fix stats that have changed since the file was openned - st->st_ino = (ino_t)(file->startCluster); // The file serial number is the start cluster - st->st_size = file->filesize; // File size - - _FAT_unlock(&partition->lock); - return 0; -} - -int _FAT_ftruncate_r (struct _reent *r, int fd, off_t len) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - PARTITION* partition; - int ret=0; - uint32_t newSize = (uint32_t)len; - - if (len < 0) { - // Trying to truncate to a negative size - r->_errno = EINVAL; - return -1; - } - - if ((sizeof(len) > 4) && len > (off_t)FILE_MAX_SIZE) { - // Trying to extend the file beyond what FAT supports - r->_errno = EFBIG; - return -1; - } - - if (!file || !file->inUse) { - // invalid file - r->_errno = EBADF; - return -1; - } - - if (!file->write) { - // Read-only file - r->_errno = EINVAL; - return -1; - } - - partition = file->partition; - _FAT_lock(&partition->lock); - - if (newSize > file->filesize) { - // Expanding the file - FILE_POSITION savedPosition; - uint32_t savedOffset; - // Get a new cluster for the start of the file if required - if (file->startCluster == CLUSTER_FREE) { - uint32_t tempNextCluster = _FAT_fat_linkFreeCluster (partition, CLUSTER_FREE); - if (!_FAT_fat_isValidCluster(partition, tempNextCluster)) { - // Couldn't get a cluster, so abort immediately - _FAT_unlock(&partition->lock); - r->_errno = ENOSPC; - return -1; - } - file->startCluster = tempNextCluster; - - file->rwPosition.cluster = file->startCluster; - file->rwPosition.sector = 0; - file->rwPosition.byte = 0; - } - // Save the read/write pointer - savedPosition = file->rwPosition; - savedOffset = file->currentPosition; - // Set the position to the new size - file->currentPosition = newSize; - // Extend the file to the new position - if (!_FAT_file_extend_r (r, file)) { - ret = -1; - } - // Set the append position to the new rwPointer - if (file->append) { - file->appendPosition = file->rwPosition; - } - // Restore the old rwPointer; - file->rwPosition = savedPosition; - file->currentPosition = savedOffset; - } else if (newSize < file->filesize){ - // Shrinking the file - if (len == 0) { - // Cutting the file down to nothing, clear all clusters used - _FAT_fat_clearLinks (partition, file->startCluster); - file->startCluster = CLUSTER_FREE; - - file->appendPosition.cluster = CLUSTER_FREE; - file->appendPosition.sector = 0; - file->appendPosition.byte = 0; - } else { - // Trimming the file down to the required size - unsigned int chainLength; - uint32_t lastCluster; - - // Drop the unneeded end of the cluster chain. - // If the end falls on a cluster boundary, drop that cluster too, - // then set a flag to allocate a cluster as needed - chainLength = ((newSize-1) / partition->bytesPerCluster) + 1; - lastCluster = _FAT_fat_trimChain (partition, file->startCluster, chainLength); - - if (file->append) { - file->appendPosition.byte = newSize % BYTES_PER_READ; - // Does the end of the file fall on the edge of a cluster? - if (newSize % partition->bytesPerCluster == 0) { - // Set a flag to allocate a new cluster - file->appendPosition.sector = partition->sectorsPerCluster; - } else { - file->appendPosition.sector = (newSize % partition->bytesPerCluster) / BYTES_PER_READ; - } - file->appendPosition.cluster = lastCluster; - } - } - } else { - // Truncating to same length, so don't do anything - } - - file->filesize = newSize; - file->modified = true; - - _FAT_unlock(&partition->lock); - return ret; -} - -int _FAT_fsync_r (struct _reent *r, int fd) { - FILE_STRUCT* file = (FILE_STRUCT*) fd; - int ret = 0; - - if (!file->inUse) { - r->_errno = EBADF; - return -1; - } - - _FAT_lock(&file->partition->lock); - - ret = _FAT_syncToDisc (file); - if (ret != 0) { - r->_errno = ret; - ret = -1; - } - - _FAT_unlock(&file->partition->lock); - - return ret; -} - -typedef int (*_frag_append_t)(void *ff, u32 offset, u32 sector, u32 count); - -int _FAT_get_fragments (const char *path, _frag_append_t append_fragment, void *callback_data) +static bool _FAT_file_extend_r ( struct _reent *r, FILE_STRUCT* file ) { - struct _reent r; - FILE_STRUCT file; - PARTITION* partition; - u32 cluster; - u32 sector; - u32 offset; // in sectors - u32 size; // in sectors - int ret = -1; - int fd; + PARTITION* partition = file->partition; + CACHE* cache = file->partition->cache; + FILE_POSITION position; + uint8_t zeroBuffer [BYTES_PER_READ] = {0}; + uint32_t remain; + uint32_t tempNextCluster; + unsigned int sector; - fd = _FAT_open_r (&r, &file, path, O_RDONLY, 0); - if (fd == -1) return -1; - if (fd != (int)&file) return -1; + position.byte = file->filesize % BYTES_PER_READ; + position.sector = ( file->filesize % partition->bytesPerCluster ) / BYTES_PER_READ; + // It is assumed that there is always a startCluster + // This will be true when _FAT_file_extend_r is called from _FAT_write_r + position.cluster = _FAT_fat_lastCluster ( partition, file->startCluster ); - partition = file.partition; - _FAT_lock(&partition->lock); + remain = file->currentPosition - file->filesize; - size = file.filesize / BYTES_PER_READ; - cluster = file.startCluster; - offset = 0; + if ( ( remain > 0 ) && ( file->filesize > 0 ) && ( position.sector == 0 ) && ( position.byte == 0 ) ) + { + // Get a new cluster on the edge of a cluster boundary + tempNextCluster = _FAT_fat_linkFreeCluster( partition, position.cluster ); + if ( !_FAT_fat_isValidCluster( partition, tempNextCluster ) ) + { + // Couldn't get a cluster, so abort + r->_errno = ENOSPC; + return false; + } + position.cluster = tempNextCluster; + position.sector = 0; + } - do { - if (!_FAT_fat_isValidCluster(partition, cluster)) { - // invalid cluster - goto out; - } - // add cluster to fileinfo - sector = _FAT_fat_clusterToSector(partition, cluster); - if (append_fragment(callback_data, offset, sector, partition->sectorsPerCluster)) { - // too many fragments - goto out; - } - offset += partition->sectorsPerCluster; - cluster = _FAT_fat_nextCluster (partition, cluster); - } while (offset < size); + if ( remain + position.byte < BYTES_PER_READ ) + { + // Only need to clear to the end of the sector + _FAT_cache_writePartialSector ( cache, zeroBuffer, + _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, position.byte, remain ); + position.byte += remain; + } + else + { + if ( position.byte > 0 ) + { + _FAT_cache_writePartialSector ( cache, zeroBuffer, + _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, position.byte, + BYTES_PER_READ - position.byte ); + remain -= ( BYTES_PER_READ - position.byte ); + position.byte = 0; + position.sector ++; + } - // set size - append_fragment(callback_data, size, 0, 0); - // success - ret = 0; + while ( remain >= BYTES_PER_READ ) + { + if ( position.sector >= partition->sectorsPerCluster ) + { + position.sector = 0; + // Ran out of clusters so get a new one + tempNextCluster = _FAT_fat_linkFreeCluster( partition, position.cluster ); + if ( !_FAT_fat_isValidCluster( partition, tempNextCluster ) ) + { + // Couldn't get a cluster, so abort + r->_errno = ENOSPC; + return false; + } + position.cluster = tempNextCluster; + } - out: - _FAT_unlock(&partition->lock); - _FAT_close_r(&r, fd); - return ret; + sector = _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector; + _FAT_cache_writeSectors ( cache, sector, 1, zeroBuffer ); + + remain -= BYTES_PER_READ; + position.sector ++; + } + + if ( !_FAT_check_position_for_next_cluster( r, &position, partition, remain, NULL ) ) + { + // error already marked + return false; + } + + if ( remain > 0 ) + { + _FAT_cache_writePartialSector ( cache, zeroBuffer, + _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, 0, remain ); + position.byte = remain; + } + } + + file->rwPosition = position; + file->filesize = file->currentPosition; + return true; +} + +ssize_t _FAT_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) +{ + FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + PARTITION* partition; + CACHE* cache; + FILE_POSITION position; + uint32_t tempNextCluster; + unsigned int tempVar; + size_t remain; + bool flagNoError = true; + bool flagAppending = false; + + // Make sure we can actually write to the file + if ( ( file == NULL ) || !file->inUse || !file->write ) + { + r->_errno = EBADF; + return -1; + } + + partition = file->partition; + cache = file->partition->cache; + _FAT_lock( &partition->lock ); + + // Only write up to the maximum file size, taking into account wrap-around of ints + if ( remain + file->filesize > FILE_MAX_SIZE || len + file->filesize < file->filesize ) + { + len = FILE_MAX_SIZE - file->filesize; + } + remain = len; + + // Short circuit cases where len is 0 (or less) + if ( len <= 0 ) + { + _FAT_unlock( &partition->lock ); + return 0; + } + + // Get a new cluster for the start of the file if required + if ( file->startCluster == CLUSTER_FREE ) + { + tempNextCluster = _FAT_fat_linkFreeCluster ( partition, CLUSTER_FREE ); + if ( !_FAT_fat_isValidCluster( partition, tempNextCluster ) ) + { + // Couldn't get a cluster, so abort immediately + _FAT_unlock( &partition->lock ); + r->_errno = ENOSPC; + return -1; + } + file->startCluster = tempNextCluster; + + // Appending starts at the begining for a 0 byte file + file->appendPosition.cluster = file->startCluster; + file->appendPosition.sector = 0; + file->appendPosition.byte = 0; + + file->rwPosition.cluster = file->startCluster; + file->rwPosition.sector = 0; + file->rwPosition.byte = 0; + } + + if ( file->append ) + { + position = file->appendPosition; + flagAppending = true; + } + else + { + // If the write pointer is past the end of the file, extend the file to that size + if ( file->currentPosition > file->filesize ) + { + if ( !_FAT_file_extend_r ( r, file ) ) + { + _FAT_unlock( &partition->lock ); + return -1; + } + } + + // Write at current read pointer + position = file->rwPosition; + + // If it is writing past the current end of file, set appending flag + if ( len + file->currentPosition > file->filesize ) + { + flagAppending = true; + } + } + + // Move onto next cluster if needed + _FAT_check_position_for_next_cluster( r, &position, partition, remain, &flagNoError ); + + // Align to sector + tempVar = BYTES_PER_READ - position.byte; + if ( tempVar > remain ) + { + tempVar = remain; + } + + if ( ( tempVar < BYTES_PER_READ ) && flagNoError ) + { + // Write partial sector to disk + _FAT_cache_writePartialSector ( cache, ptr, + _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, position.byte, tempVar ); + + remain -= tempVar; + ptr += tempVar; + position.byte += tempVar; + + + // Move onto next sector + if ( position.byte >= BYTES_PER_READ ) + { + position.byte = 0; + position.sector ++; + } + } + + // Align to cluster + // tempVar is number of sectors to write + if ( remain > ( partition->sectorsPerCluster - position.sector ) * BYTES_PER_READ ) + { + tempVar = partition->sectorsPerCluster - position.sector; + } + else + { + tempVar = remain / BYTES_PER_READ; + } + + if ( ( tempVar > 0 && tempVar < partition->sectorsPerCluster ) && flagNoError ) + { + if ( !_FAT_cache_writeSectors ( cache, + _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, tempVar, ptr ) ) + { + flagNoError = false; + r->_errno = EIO; + } + else + { + ptr += tempVar * BYTES_PER_READ; + remain -= tempVar * BYTES_PER_READ; + position.sector += tempVar; + } + } + + // Write whole clusters + while ( ( remain >= partition->bytesPerCluster ) && flagNoError ) + { + // allocate next cluster + _FAT_check_position_for_next_cluster( r, &position, partition, remain, &flagNoError ); + if ( !flagNoError ) break; + // set indexes to the current position + uint32_t chunkEnd = position.cluster; + uint32_t nextChunkStart = position.cluster; + size_t chunkSize = partition->bytesPerCluster; + FILE_POSITION next_position = position; + + // group consecutive clusters + while ( flagNoError && +#ifdef LIMIT_SECTORS + ( chunkSize + partition->bytesPerCluster <= LIMIT_SECTORS * BYTES_PER_READ ) && +#endif + ( chunkSize + partition->bytesPerCluster < remain ) ) + { + // pretend to use up all sectors in next_position + next_position.sector = partition->sectorsPerCluster; + // get or allocate next cluster + _FAT_check_position_for_next_cluster( r, &next_position, partition, + remain - chunkSize, &flagNoError ); + if ( !flagNoError ) break; // exit loop on error + nextChunkStart = next_position.cluster; + if ( nextChunkStart != chunkEnd + 1 ) break; // exit loop if not consecutive + chunkEnd = nextChunkStart; + chunkSize += partition->bytesPerCluster; + } + + if ( !_FAT_cache_writeSectors ( cache, + _FAT_fat_clusterToSector( partition, position.cluster ), chunkSize / BYTES_PER_READ, ptr ) ) + { + flagNoError = false; + r->_errno = EIO; + break; + } + ptr += chunkSize; + remain -= chunkSize; + + if ( ( chunkEnd != nextChunkStart ) && _FAT_fat_isValidCluster( partition, nextChunkStart ) ) + { + // new cluster is already allocated (because it was not consecutive) + position.cluster = nextChunkStart; + position.sector = 0; + } + else + { + // Allocate a new cluster when next writing the file + position.cluster = chunkEnd; + position.sector = partition->sectorsPerCluster; + } + } + + // allocate next cluster if needed + _FAT_check_position_for_next_cluster( r, &position, partition, remain, &flagNoError ); + + // Write remaining sectors + tempVar = remain / BYTES_PER_READ; // Number of sectors left + if ( ( tempVar > 0 ) && flagNoError ) + { + if ( !_FAT_cache_writeSectors ( cache, _FAT_fat_clusterToSector ( partition, position.cluster ), tempVar, ptr ) ) + { + flagNoError = false; + r->_errno = EIO; + } + else + { + ptr += tempVar * BYTES_PER_READ; + remain -= tempVar * BYTES_PER_READ; + position.sector += tempVar; + } + } + + // Last remaining sector + if ( ( remain > 0 ) && flagNoError ) + { + if ( flagAppending ) + { + _FAT_cache_eraseWritePartialSector ( cache, ptr, + _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, 0, remain ); + } + else + { + _FAT_cache_writePartialSector ( cache, ptr, + _FAT_fat_clusterToSector ( partition, position.cluster ) + position.sector, 0, remain ); + } + position.byte += remain; + remain = 0; + } + + + // Amount written is the originally requested amount minus stuff remaining + len = len - remain; + + // Update file information + file->modified = true; + if ( file->append ) + { + // Appending doesn't affect the read pointer + file->appendPosition = position; + file->filesize += len; + } + else + { + // Writing also shifts the read pointer + file->rwPosition = position; + file->currentPosition += len; + if ( file->filesize < file->currentPosition ) + { + file->filesize = file->currentPosition; + } + } + _FAT_unlock( &partition->lock ); + + return len; +} + + +off_t _FAT_seek_r ( struct _reent *r, int fd, off_t pos, int dir ) +{ + FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + PARTITION* partition; + uint32_t cluster, nextCluster; + int clusCount; + off_t newPosition; + uint32_t position; + + if ( ( file == NULL ) || ( file->inUse == false ) ) + { + // invalid file + r->_errno = EBADF; + return -1; + } + + partition = file->partition; + _FAT_lock( &partition->lock ); + + switch ( dir ) + { + case SEEK_SET: + newPosition = pos; + break; + case SEEK_CUR: + newPosition = ( off_t )file->currentPosition + pos; + break; + case SEEK_END: + newPosition = ( off_t )file->filesize + pos; + break; + default: + _FAT_unlock( &partition->lock ); + r->_errno = EINVAL; + return -1; + } + + if ( ( pos > 0 ) && ( newPosition < 0 ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EOVERFLOW; + return -1; + } + + // newPosition can only be larger than the FILE_MAX_SIZE on platforms where + // off_t is larger than 32 bits. + if ( newPosition < 0 || ( ( sizeof( newPosition ) > 4 ) && newPosition > ( off_t )FILE_MAX_SIZE ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EINVAL; + return -1; + } + + position = ( uint32_t )newPosition; + + // Only change the read/write position if it is within the bounds of the current filesize, + // or at the very edge of the file + if ( position <= file->filesize && file->startCluster != CLUSTER_FREE ) + { + // Calculate where the correct cluster is + // how many clusters from start of file + clusCount = position / partition->bytesPerCluster; + cluster = file->startCluster; + if ( position >= file->currentPosition ) + { + // start from current cluster + int currentCount = file->currentPosition / partition->bytesPerCluster; + if ( file->rwPosition.sector == partition->sectorsPerCluster ) + { + currentCount--; + } + clusCount -= currentCount; + cluster = file->rwPosition.cluster; + } + // Calculate the sector and byte of the current position, + // and store them + file->rwPosition.sector = ( position % partition->bytesPerCluster ) / BYTES_PER_READ; + file->rwPosition.byte = position % BYTES_PER_READ; + + nextCluster = _FAT_fat_nextCluster ( partition, cluster ); + while ( ( clusCount > 0 ) && ( nextCluster != CLUSTER_FREE ) && ( nextCluster != CLUSTER_EOF ) ) + { + clusCount--; + cluster = nextCluster; + nextCluster = _FAT_fat_nextCluster ( partition, cluster ); + } + + // Check if ran out of clusters and it needs to allocate a new one + if ( clusCount > 0 ) + { + if ( ( clusCount == 1 ) && ( file->filesize == position ) && ( file->rwPosition.sector == 0 ) ) + { + // Set flag to allocate a new cluster + file->rwPosition.sector = partition->sectorsPerCluster; + file->rwPosition.byte = 0; + } + else + { + _FAT_unlock( &partition->lock ); + r->_errno = EINVAL; + return -1; + } + } + + file->rwPosition.cluster = cluster; + } + + // Save position + file->currentPosition = position; + + _FAT_unlock( &partition->lock ); + return position; +} + + + +int _FAT_fstat_r ( struct _reent *r, int fd, struct stat *st ) +{ + FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + PARTITION* partition; + DIR_ENTRY fileEntry; + + if ( ( file == NULL ) || ( file->inUse == false ) ) + { + // invalid file + r->_errno = EBADF; + return -1; + } + + partition = file->partition; + _FAT_lock( &partition->lock ); + + // Get the file's entry data + fileEntry.dataStart = file->dirEntryStart; + fileEntry.dataEnd = file->dirEntryEnd; + + if ( !_FAT_directory_entryFromPosition ( partition, &fileEntry ) ) + { + _FAT_unlock( &partition->lock ); + r->_errno = EIO; + return -1; + } + + // Fill in the stat struct + _FAT_directory_entryStat ( partition, &fileEntry, st ); + + // Fix stats that have changed since the file was openned + st->st_ino = ( ino_t )( file->startCluster ); // The file serial number is the start cluster + st->st_size = file->filesize; // File size + + _FAT_unlock( &partition->lock ); + return 0; +} + +int _FAT_ftruncate_r ( struct _reent *r, int fd, off_t len ) +{ + FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + PARTITION* partition; + int ret = 0; + uint32_t newSize = ( uint32_t )len; + + if ( len < 0 ) + { + // Trying to truncate to a negative size + r->_errno = EINVAL; + return -1; + } + + if ( ( sizeof( len ) > 4 ) && len > ( off_t )FILE_MAX_SIZE ) + { + // Trying to extend the file beyond what FAT supports + r->_errno = EFBIG; + return -1; + } + + if ( !file || !file->inUse ) + { + // invalid file + r->_errno = EBADF; + return -1; + } + + if ( !file->write ) + { + // Read-only file + r->_errno = EINVAL; + return -1; + } + + partition = file->partition; + _FAT_lock( &partition->lock ); + + if ( newSize > file->filesize ) + { + // Expanding the file + FILE_POSITION savedPosition; + uint32_t savedOffset; + // Get a new cluster for the start of the file if required + if ( file->startCluster == CLUSTER_FREE ) + { + uint32_t tempNextCluster = _FAT_fat_linkFreeCluster ( partition, CLUSTER_FREE ); + if ( !_FAT_fat_isValidCluster( partition, tempNextCluster ) ) + { + // Couldn't get a cluster, so abort immediately + _FAT_unlock( &partition->lock ); + r->_errno = ENOSPC; + return -1; + } + file->startCluster = tempNextCluster; + + file->rwPosition.cluster = file->startCluster; + file->rwPosition.sector = 0; + file->rwPosition.byte = 0; + } + // Save the read/write pointer + savedPosition = file->rwPosition; + savedOffset = file->currentPosition; + // Set the position to the new size + file->currentPosition = newSize; + // Extend the file to the new position + if ( !_FAT_file_extend_r ( r, file ) ) + { + ret = -1; + } + // Set the append position to the new rwPointer + if ( file->append ) + { + file->appendPosition = file->rwPosition; + } + // Restore the old rwPointer; + file->rwPosition = savedPosition; + file->currentPosition = savedOffset; + } + else if ( newSize < file->filesize ) + { + // Shrinking the file + if ( len == 0 ) + { + // Cutting the file down to nothing, clear all clusters used + _FAT_fat_clearLinks ( partition, file->startCluster ); + file->startCluster = CLUSTER_FREE; + + file->appendPosition.cluster = CLUSTER_FREE; + file->appendPosition.sector = 0; + file->appendPosition.byte = 0; + } + else + { + // Trimming the file down to the required size + unsigned int chainLength; + uint32_t lastCluster; + + // Drop the unneeded end of the cluster chain. + // If the end falls on a cluster boundary, drop that cluster too, + // then set a flag to allocate a cluster as needed + chainLength = ( ( newSize - 1 ) / partition->bytesPerCluster ) + 1; + lastCluster = _FAT_fat_trimChain ( partition, file->startCluster, chainLength ); + + if ( file->append ) + { + file->appendPosition.byte = newSize % BYTES_PER_READ; + // Does the end of the file fall on the edge of a cluster? + if ( newSize % partition->bytesPerCluster == 0 ) + { + // Set a flag to allocate a new cluster + file->appendPosition.sector = partition->sectorsPerCluster; + } + else + { + file->appendPosition.sector = ( newSize % partition->bytesPerCluster ) / BYTES_PER_READ; + } + file->appendPosition.cluster = lastCluster; + } + } + } + else + { + // Truncating to same length, so don't do anything + } + + file->filesize = newSize; + file->modified = true; + + _FAT_unlock( &partition->lock ); + return ret; +} + +int _FAT_fsync_r ( struct _reent *r, int fd ) +{ + FILE_STRUCT* file = ( FILE_STRUCT* ) fd; + int ret = 0; + + if ( !file->inUse ) + { + r->_errno = EBADF; + return -1; + } + + _FAT_lock( &file->partition->lock ); + + ret = _FAT_syncToDisc ( file ); + if ( ret != 0 ) + { + r->_errno = ret; + ret = -1; + } + + _FAT_unlock( &file->partition->lock ); + + return ret; +} + +typedef int ( *_frag_append_t )( void *ff, u32 offset, u32 sector, u32 count ); + +int _FAT_get_fragments ( const char *path, _frag_append_t append_fragment, void *callback_data ) +{ + struct _reent r; + FILE_STRUCT file; + PARTITION* partition; + u32 cluster; + u32 sector; + u32 offset; // in sectors + u32 size; // in sectors + int ret = -1; + int fd; + + 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 ); + + size = file.filesize / BYTES_PER_READ; + cluster = file.startCluster; + offset = 0; + + do + { + if ( !_FAT_fat_isValidCluster( partition, cluster ) ) + { + // invalid cluster + goto out; + } + // add cluster to fileinfo + sector = _FAT_fat_clusterToSector( partition, cluster ); + if ( append_fragment( callback_data, offset, sector, partition->sectorsPerCluster ) ) + { + // too many fragments + goto out; + } + offset += partition->sectorsPerCluster; + cluster = _FAT_fat_nextCluster ( partition, cluster ); + } + while ( offset < size ); + + // set size + append_fragment( callback_data, size, 0, 0 ); + // success + ret = 0; + +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 448a5ee3..537c665b 100644 --- a/source/libfat/fatfile.h +++ b/source/libfat/fatfile.h @@ -1,11 +1,11 @@ /* fatfile.h - - Functions used by the newlib disc stubs to interface with + + Functions used by the newlib disc stubs to interface with this library Copyright (c) 2006 Michael "Chishm" Chisholm - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -39,67 +39,69 @@ #include "partition.h" #include "directory.h" -#define FILE_MAX_SIZE ((uint32_t)0xFFFFFFFF) // 4GiB - 1B +#define FILE_MAX_SIZE ((uint32_t)0xFFFFFFFF) // 4GiB - 1B -typedef struct { - u32 cluster; - sec_t sector; - s32 byte; +typedef struct +{ + 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; +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; }; 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); +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 639a6374..d2fa769d 100644 --- a/source/libfat/file_allocation_table.c +++ b/source/libfat/file_allocation_table.c @@ -35,166 +35,179 @@ /* Gets the cluster linked from input cluster */ -uint32_t _FAT_fat_nextCluster(PARTITION* partition, uint32_t cluster) +uint32_t _FAT_fat_nextCluster( PARTITION* partition, uint32_t cluster ) { - uint32_t nextCluster = CLUSTER_FREE; - sec_t sector; - int offset; + uint32_t nextCluster = CLUSTER_FREE; + sec_t sector; + int offset; - if (cluster == CLUSTER_FREE) { - return CLUSTER_FREE; - } + if ( cluster == CLUSTER_FREE ) + { + return CLUSTER_FREE; + } - switch (partition->filesysType) - { - case FS_UNKNOWN: - return CLUSTER_ERROR; - break; + switch ( partition->filesysType ) + { + case FS_UNKNOWN: + return CLUSTER_ERROR; + break; - case FS_FAT12: - { - u32 nextCluster_h; - sector = partition->fat.fatStart + (((cluster * 3) / 2) / BYTES_PER_READ); - offset = ((cluster * 3) / 2) % BYTES_PER_READ; + case FS_FAT12: + { + u32 nextCluster_h; + sector = partition->fat.fatStart + ( ( ( cluster * 3 ) / 2 ) / BYTES_PER_READ ); + offset = ( ( cluster * 3 ) / 2 ) % BYTES_PER_READ; - _FAT_cache_readLittleEndianValue (partition->cache, &nextCluster, sector, offset, sizeof(u8)); + _FAT_cache_readLittleEndianValue ( partition->cache, &nextCluster, sector, offset, sizeof( u8 ) ); - offset++; + offset++; - if (offset >= BYTES_PER_READ) { - offset = 0; - sector++; - } - nextCluster_h = 0; + if ( offset >= BYTES_PER_READ ) + { + offset = 0; + sector++; + } + nextCluster_h = 0; - _FAT_cache_readLittleEndianValue (partition->cache, &nextCluster_h, sector, offset, sizeof(u8)); - nextCluster |= (nextCluster_h << 8); + _FAT_cache_readLittleEndianValue ( partition->cache, &nextCluster_h, sector, offset, sizeof( u8 ) ); + nextCluster |= ( nextCluster_h << 8 ); - if (cluster & 0x01) { - nextCluster = nextCluster >> 4; - } else { - nextCluster &= 0x0FFF; - } + if ( cluster & 0x01 ) + { + nextCluster = nextCluster >> 4; + } + else + { + nextCluster &= 0x0FFF; + } - if (nextCluster >= 0x0FF7) - { - nextCluster = CLUSTER_EOF; - } + if ( nextCluster >= 0x0FF7 ) + { + nextCluster = CLUSTER_EOF; + } - break; - } - case FS_FAT16: - sector = partition->fat.fatStart + ((cluster << 1) / BYTES_PER_READ); - offset = (cluster % (BYTES_PER_READ >> 1)) << 1; + break; + } + case FS_FAT16: + sector = partition->fat.fatStart + ( ( cluster << 1 ) / BYTES_PER_READ ); + offset = ( cluster % ( BYTES_PER_READ >> 1 ) ) << 1; - _FAT_cache_readLittleEndianValue (partition->cache, &nextCluster, sector, offset, sizeof(u16)); + _FAT_cache_readLittleEndianValue ( partition->cache, &nextCluster, sector, offset, sizeof( u16 ) ); - if (nextCluster >= 0xFFF7) { - nextCluster = CLUSTER_EOF; - } - break; + if ( nextCluster >= 0xFFF7 ) + { + nextCluster = CLUSTER_EOF; + } + break; - case FS_FAT32: - sector = partition->fat.fatStart + ((cluster << 2) / BYTES_PER_READ); - offset = (cluster % (BYTES_PER_READ >> 2)) << 2; + case FS_FAT32: + sector = partition->fat.fatStart + ( ( cluster << 2 ) / BYTES_PER_READ ); + offset = ( cluster % ( BYTES_PER_READ >> 2 ) ) << 2; - _FAT_cache_readLittleEndianValue (partition->cache, &nextCluster, sector, offset, sizeof(u32)); + _FAT_cache_readLittleEndianValue ( partition->cache, &nextCluster, sector, offset, sizeof( u32 ) ); - if (nextCluster >= 0x0FFFFFF7) { - nextCluster = CLUSTER_EOF; - } - break; + if ( nextCluster >= 0x0FFFFFF7 ) + { + nextCluster = CLUSTER_EOF; + } + break; - default: - return CLUSTER_ERROR; - break; - } + default: + return CLUSTER_ERROR; + break; + } - return nextCluster; + return nextCluster; } /* 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; +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 */)) - { - return false; - } + if ( ( cluster < CLUSTER_FIRST ) || ( cluster > partition->fat.lastCluster /* This will catch CLUSTER_ERROR */ ) ) + { + return false; + } - switch (partition->filesysType) - { - case FS_UNKNOWN: - return false; - break; + switch ( partition->filesysType ) + { + case FS_UNKNOWN: + return false; + break; - case FS_FAT12: - sector = partition->fat.fatStart + (((cluster * 3) / 2) / BYTES_PER_READ); - offset = ((cluster * 3) / 2) % BYTES_PER_READ; + case FS_FAT12: + sector = partition->fat.fatStart + ( ( ( cluster * 3 ) / 2 ) / BYTES_PER_READ ); + offset = ( ( cluster * 3 ) / 2 ) % BYTES_PER_READ; - if (cluster & 0x01) { + if ( cluster & 0x01 ) + { - _FAT_cache_readLittleEndianValue (partition->cache, &oldValue, sector, offset, sizeof(u8)); + _FAT_cache_readLittleEndianValue ( partition->cache, &oldValue, sector, offset, sizeof( u8 ) ); - value = (value << 4) | (oldValue & 0x0F); + value = ( value << 4 ) | ( oldValue & 0x0F ); - _FAT_cache_writeLittleEndianValue (partition->cache, value & 0xFF, sector, offset, sizeof(u8)); + _FAT_cache_writeLittleEndianValue ( partition->cache, value & 0xFF, sector, offset, sizeof( u8 ) ); - offset++; - if (offset >= BYTES_PER_READ) { - offset = 0; - sector++; - } + offset++; + if ( offset >= BYTES_PER_READ ) + { + offset = 0; + sector++; + } - _FAT_cache_writeLittleEndianValue (partition->cache, (value >> 8) & 0xFF, sector, offset, sizeof(u8)); + _FAT_cache_writeLittleEndianValue ( partition->cache, ( value >> 8 ) & 0xFF, sector, offset, sizeof( u8 ) ); - } else { + } + else + { - _FAT_cache_writeLittleEndianValue (partition->cache, value, sector, offset, sizeof(u8)); + _FAT_cache_writeLittleEndianValue ( partition->cache, value, sector, offset, sizeof( u8 ) ); - offset++; - if (offset >= BYTES_PER_READ) { - offset = 0; - sector++; - } + offset++; + if ( offset >= BYTES_PER_READ ) + { + offset = 0; + sector++; + } - _FAT_cache_readLittleEndianValue (partition->cache, &oldValue, sector, offset, sizeof(u8)); + _FAT_cache_readLittleEndianValue ( partition->cache, &oldValue, sector, offset, sizeof( u8 ) ); - value = ((value >> 8) & 0x0F) | (oldValue & 0xF0); + value = ( ( value >> 8 ) & 0x0F ) | ( oldValue & 0xF0 ); - _FAT_cache_writeLittleEndianValue (partition->cache, value, sector, offset, sizeof(u8)); - } + _FAT_cache_writeLittleEndianValue ( partition->cache, value, sector, offset, sizeof( u8 ) ); + } - break; + break; - case FS_FAT16: - sector = partition->fat.fatStart + ((cluster << 1) / BYTES_PER_READ); - offset = (cluster % (BYTES_PER_READ >> 1)) << 1; + case FS_FAT16: + sector = partition->fat.fatStart + ( ( cluster << 1 ) / BYTES_PER_READ ); + offset = ( cluster % ( BYTES_PER_READ >> 1 ) ) << 1; - _FAT_cache_writeLittleEndianValue (partition->cache, value, sector, offset, sizeof(u16)); + _FAT_cache_writeLittleEndianValue ( partition->cache, value, sector, offset, sizeof( u16 ) ); - break; + break; - case FS_FAT32: - sector = partition->fat.fatStart + ((cluster << 2) / BYTES_PER_READ); - offset = (cluster % (BYTES_PER_READ >> 2)) << 2; + case FS_FAT32: + sector = partition->fat.fatStart + ( ( cluster << 2 ) / BYTES_PER_READ ); + offset = ( cluster % ( BYTES_PER_READ >> 2 ) ) << 2; - _FAT_cache_writeLittleEndianValue (partition->cache, value, sector, offset, sizeof(u32)); + _FAT_cache_writeLittleEndianValue ( partition->cache, value, sector, offset, sizeof( u32 ) ); - break; + break; - default: - return false; - break; - } + default: + return false; + break; + } - return true; + return true; } /*----------------------------------------------------------------- @@ -203,58 +216,67 @@ 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; +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) { - return CLUSTER_ERROR; - } + if ( cluster > lastCluster ) + { + return CLUSTER_ERROR; + } - // Check if the cluster already has a link, and return it if so - curLink = _FAT_fat_nextCluster(partition, cluster); - if ((curLink >= CLUSTER_FIRST) && (curLink <= lastCluster)) { - return curLink; // Return the current link - don't allocate a new one - } + // Check if the cluster already has a link, and return it if so + curLink = _FAT_fat_nextCluster( partition, cluster ); + if ( ( curLink >= CLUSTER_FIRST ) && ( curLink <= lastCluster ) ) + { + return curLink; // Return the current link - don't allocate a new one + } - // Get a free cluster - firstFree = partition->fat.firstFree; - // Start at first valid cluster - if (firstFree < CLUSTER_FIRST) { - firstFree = CLUSTER_FIRST; - } + // Get a free cluster + firstFree = partition->fat.firstFree; + // Start at first valid cluster + if ( firstFree < CLUSTER_FIRST ) + { + firstFree = CLUSTER_FIRST; + } - // Search until a free cluster is found - while (_FAT_fat_nextCluster(partition, firstFree) != CLUSTER_FREE) { - firstFree++; - if (firstFree > lastCluster) { - if (loopedAroundFAT) { - // If couldn't get a free cluster then return an error - partition->fat.firstFree = firstFree; - return CLUSTER_ERROR; - } else { - // Try looping back to the beginning of the FAT - // This was suggested by loopy - firstFree = CLUSTER_FIRST; - loopedAroundFAT = true; - } - } - } - partition->fat.firstFree = firstFree; + // Search until a free cluster is found + while ( _FAT_fat_nextCluster( partition, firstFree ) != CLUSTER_FREE ) + { + firstFree++; + if ( firstFree > lastCluster ) + { + if ( loopedAroundFAT ) + { + // If couldn't get a free cluster then return an error + partition->fat.firstFree = firstFree; + return CLUSTER_ERROR; + } + else + { + // Try looping back to the beginning of the FAT + // This was suggested by loopy + firstFree = CLUSTER_FIRST; + loopedAroundFAT = true; + } + } + } + partition->fat.firstFree = firstFree; - if ((cluster >= CLUSTER_FIRST) && (cluster < lastCluster)) - { - // Update the linked from FAT entry - _FAT_fat_writeFatEntry (partition, cluster, firstFree); - } - // Create the linked to FAT entry - _FAT_fat_writeFatEntry (partition, firstFree, CLUSTER_EOF); + if ( ( cluster >= CLUSTER_FIRST ) && ( cluster < lastCluster ) ) + { + // Update the linked from FAT entry + _FAT_fat_writeFatEntry ( partition, cluster, firstFree ); + } + // Create the linked to FAT entry + _FAT_fat_writeFatEntry ( partition, firstFree, CLUSTER_EOF ); - return firstFree; + return firstFree; } /*----------------------------------------------------------------- @@ -263,27 +285,30 @@ 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]; +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); + // Link the cluster + newCluster = _FAT_fat_linkFreeCluster( partition, cluster ); - if (newCluster == CLUSTER_FREE || newCluster == CLUSTER_ERROR) { - return CLUSTER_ERROR; - } + if ( newCluster == CLUSTER_FREE || newCluster == CLUSTER_ERROR ) + { + return CLUSTER_ERROR; + } - // Clear all the sectors within the cluster - memset (emptySector, 0, BYTES_PER_READ); - for (i = 0; i < partition->sectorsPerCluster; i++) { - _FAT_cache_writeSectors (partition->cache, - _FAT_fat_clusterToSector (partition, newCluster) + i, - 1, emptySector); - } + // Clear all the sectors within the cluster + memset ( emptySector, 0, BYTES_PER_READ ); + for ( i = 0; i < partition->sectorsPerCluster; i++ ) + { + _FAT_cache_writeSectors ( partition->cache, + _FAT_fat_clusterToSector ( partition, newCluster ) + i, + 1, emptySector ); + } - return newCluster; + return newCluster; } @@ -291,29 +316,32 @@ uint32_t _FAT_fat_linkFreeClusterCleared (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; +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) { - partition->fat.firstFree = cluster; - } + // If this clears up more space in the FAT before the current free pointer, move it backwards + if ( cluster < partition->fat.firstFree ) + { + partition->fat.firstFree = cluster; + } - while ((cluster != CLUSTER_EOF) && (cluster != CLUSTER_FREE) && (cluster != CLUSTER_ERROR)) { - // Store next cluster before erasing the link - nextCluster = _FAT_fat_nextCluster (partition, cluster); + while ( ( cluster != CLUSTER_EOF ) && ( cluster != CLUSTER_FREE ) && ( cluster != CLUSTER_ERROR ) ) + { + // Store next cluster before erasing the link + nextCluster = _FAT_fat_nextCluster ( partition, cluster ); - // Erase the link - _FAT_fat_writeFatEntry (partition, cluster, CLUSTER_FREE); + // Erase the link + _FAT_fat_writeFatEntry ( partition, cluster, CLUSTER_FREE ); - // Move onto next cluster - cluster = nextCluster; - } + // Move onto next cluster + cluster = nextCluster; + } - return true; + return true; } /*----------------------------------------------------------------- @@ -324,60 +352,71 @@ 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; +uint32_t _FAT_fat_trimChain ( PARTITION* partition, uint32_t startCluster, unsigned int chainLength ) +{ + uint32_t nextCluster; - if (chainLength == 0) { - // Drop the entire chain - _FAT_fat_clearLinks (partition, startCluster); - return CLUSTER_FREE; - } else { - // Find the last cluster in the chain, and the one after it - chainLength--; - nextCluster = _FAT_fat_nextCluster (partition, startCluster); - while ((chainLength > 0) && (nextCluster != CLUSTER_FREE) && (nextCluster != CLUSTER_EOF)) { - chainLength--; - startCluster = nextCluster; - nextCluster = _FAT_fat_nextCluster (partition, startCluster); - } + if ( chainLength == 0 ) + { + // Drop the entire chain + _FAT_fat_clearLinks ( partition, startCluster ); + return CLUSTER_FREE; + } + else + { + // Find the last cluster in the chain, and the one after it + chainLength--; + nextCluster = _FAT_fat_nextCluster ( partition, startCluster ); + while ( ( chainLength > 0 ) && ( nextCluster != CLUSTER_FREE ) && ( nextCluster != CLUSTER_EOF ) ) + { + chainLength--; + startCluster = nextCluster; + nextCluster = _FAT_fat_nextCluster ( partition, startCluster ); + } - // Drop all clusters after the last in the chain - if (nextCluster != CLUSTER_FREE && nextCluster != CLUSTER_EOF) { - _FAT_fat_clearLinks (partition, nextCluster); - } + // Drop all clusters after the last in the chain + if ( nextCluster != CLUSTER_FREE && nextCluster != CLUSTER_EOF ) + { + _FAT_fat_clearLinks ( partition, nextCluster ); + } - // Mark the last cluster in the chain as the end of the file - _FAT_fat_writeFatEntry (partition, startCluster, CLUSTER_EOF); + // Mark the last cluster in the chain as the end of the file + _FAT_fat_writeFatEntry ( partition, startCluster, CLUSTER_EOF ); - return startCluster; - } + return startCluster; + } } /*----------------------------------------------------------------- _FAT_fat_lastCluster Trace the cluster links until the last one is found -----------------------------------------------------------------*/ -uint32_t _FAT_fat_lastCluster (PARTITION* partition, uint32_t cluster) { - while ((_FAT_fat_nextCluster(partition, cluster) != CLUSTER_FREE) && (_FAT_fat_nextCluster(partition, cluster) != CLUSTER_EOF)) { - cluster = _FAT_fat_nextCluster(partition, cluster); - } - return cluster; +uint32_t _FAT_fat_lastCluster ( PARTITION* partition, uint32_t cluster ) +{ + while ( ( _FAT_fat_nextCluster( partition, cluster ) != CLUSTER_FREE ) && ( _FAT_fat_nextCluster( partition, cluster ) != CLUSTER_EOF ) ) + { + cluster = _FAT_fat_nextCluster( partition, cluster ); + } + return cluster; } /*----------------------------------------------------------------- _FAT_fat_freeClusterCount Return the number of free clusters available -----------------------------------------------------------------*/ -unsigned int _FAT_fat_freeClusterCount (PARTITION* partition) { - unsigned int count = 0; - uint32_t curCluster; +unsigned int _FAT_fat_freeClusterCount ( PARTITION* partition ) +{ + unsigned int count = 0; + uint32_t curCluster; - for (curCluster = CLUSTER_FIRST; curCluster <= partition->fat.lastCluster; curCluster++) { - if (_FAT_fat_nextCluster(partition, curCluster) == CLUSTER_FREE) { - count++; - } - } + for ( curCluster = CLUSTER_FIRST; curCluster <= partition->fat.lastCluster; curCluster++ ) + { + if ( _FAT_fat_nextCluster( partition, curCluster ) == CLUSTER_FREE ) + { + count++; + } + } - return count; + return count; } diff --git a/source/libfat/file_allocation_table.h b/source/libfat/file_allocation_table.h index de500496..336df819 100644 --- a/source/libfat/file_allocation_table.h +++ b/source/libfat/file_allocation_table.h @@ -33,38 +33,40 @@ #include "common.h" #include "partition.h" -#define CLUSTER_EOF_16 0xFFFF -#define CLUSTER_EOF 0x0FFFFFFF -#define CLUSTER_FREE 0x00000000 -#define CLUSTER_ROOT 0x00000000 -#define CLUSTER_FIRST 0x00000002 -#define CLUSTER_ERROR 0xFFFFFFFF +#define CLUSTER_EOF_16 0xFFFF +#define CLUSTER_EOF 0x0FFFFFFF +#define CLUSTER_FREE 0x00000000 +#define CLUSTER_ROOT 0x00000000 +#define CLUSTER_FIRST 0x00000002 +#define CLUSTER_ERROR 0xFFFFFFFF #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) { - return (cluster >= CLUSTER_FIRST) ? - ((cluster - CLUSTER_FIRST) * (sec_t)partition->sectorsPerCluster) + partition->dataStart : - partition->rootDirStart; +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; } -static inline bool _FAT_fat_isValidCluster (PARTITION* partition, uint32_t cluster) { - return (cluster >= CLUSTER_FIRST) && (cluster <= partition->fat.lastCluster /* This will catch CLUSTER_ERROR */); +static inline bool _FAT_fat_isValidCluster ( PARTITION* partition, uint32_t cluster ) +{ + 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 d297bf64..8568c4f1 100644 --- a/source/libfat/filetime.c +++ b/source/libfat/filetime.c @@ -3,7 +3,7 @@ Conversion of file time and date values to various other types Copyright (c) 2006 Michael "Chishm" Chisholm - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -40,68 +40,73 @@ #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) { - return 0; - } - localtime_r(&epochTime, &timeParts); + struct tm timeParts; + time_t epochTime; - // Check that the values are all in range. - // If they are not, return 0 (no timestamp) - if ((timeParts.tm_hour < 0) || (timeParts.tm_hour > MAX_HOUR)) return 0; - if ((timeParts.tm_min < 0) || (timeParts.tm_min > MAX_MINUTE)) return 0; - if ((timeParts.tm_sec < 0) || (timeParts.tm_sec > MAX_SECOND)) return 0; - - return ( - ((timeParts.tm_hour & 0x1F) << 11) | - ((timeParts.tm_min & 0x3F) << 5) | - ((timeParts.tm_sec >> 1) & 0x1F) - ); + if ( time( &epochTime ) == ( time_t ) - 1 ) + { + return 0; + } + localtime_r( &epochTime, &timeParts ); + + // Check that the values are all in range. + // If they are not, return 0 (no timestamp) + if ( ( timeParts.tm_hour < 0 ) || ( timeParts.tm_hour > MAX_HOUR ) ) return 0; + if ( ( timeParts.tm_min < 0 ) || ( timeParts.tm_min > MAX_MINUTE ) ) return 0; + if ( ( timeParts.tm_sec < 0 ) || ( timeParts.tm_sec > MAX_SECOND ) ) return 0; + + return ( + ( ( timeParts.tm_hour & 0x1F ) << 11 ) | + ( ( timeParts.tm_min & 0x3F ) << 5 ) | + ( ( timeParts.tm_sec >> 1 ) & 0x1F ) + ); #else - return 0; + 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) { - return 0; - } - localtime_r(&epochTime, &timeParts); + struct tm timeParts; + time_t epochTime; - if ((timeParts.tm_mon < MIN_MONTH) || (timeParts.tm_mon > MAX_MONTH)) return 0; - if ((timeParts.tm_mday < MIN_DAY) || (timeParts.tm_mday > MAX_DAY)) return 0; - - return ( - (((timeParts.tm_year - 80) & 0x7F) <<9) | // Adjust for MS-FAT base year (1980 vs 1900 for tm_year) - (((timeParts.tm_mon + 1) & 0xF) << 5) | - (timeParts.tm_mday & 0x1F) - ); + if ( time( &epochTime ) == ( time_t ) - 1 ) + { + return 0; + } + localtime_r( &epochTime, &timeParts ); + + if ( ( timeParts.tm_mon < MIN_MONTH ) || ( timeParts.tm_mon > MAX_MONTH ) ) return 0; + if ( ( timeParts.tm_mday < MIN_DAY ) || ( timeParts.tm_mday > MAX_DAY ) ) return 0; + + return ( + ( ( ( timeParts.tm_year - 80 ) & 0x7F ) << 9 ) | // Adjust for MS-FAT base year (1980 vs 1900 for tm_year) + ( ( ( timeParts.tm_mon + 1 ) & 0xF ) << 5 ) | + ( timeParts.tm_mday & 0x1F ) + ); #else - return 0; + return 0; #endif } -time_t _FAT_filetime_to_time_t (uint16_t t, uint16_t d) { - struct tm timeParts; +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_mday = d & 0x1F; - timeParts.tm_mon = ((d >> 5) & 0x0F) - 1; - timeParts.tm_year = (d >> 9) + 80; - - timeParts.tm_isdst = 0; - - return mktime(&timeParts); + timeParts.tm_hour = t >> 11; + timeParts.tm_min = ( t >> 5 ) & 0x3F; + timeParts.tm_sec = ( t & 0x1F ) << 1; + + timeParts.tm_mday = d & 0x1F; + timeParts.tm_mon = ( ( d >> 5 ) & 0x0F ) - 1; + timeParts.tm_year = ( d >> 9 ) + 80; + + timeParts.tm_isdst = 0; + + return mktime( &timeParts ); } diff --git a/source/libfat/filetime.h b/source/libfat/filetime.h index 8ffd539a..a15d75cb 100644 --- a/source/libfat/filetime.h +++ b/source/libfat/filetime.h @@ -32,10 +32,10 @@ #include "common.h" #include -uint16_t _FAT_filetime_getTimeFromRTC (void); -uint16_t _FAT_filetime_getDateFromRTC (void); +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); +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 0b3cbd06..cd508d24 100644 --- a/source/libfat/libfat.c +++ b/source/libfat/libfat.c @@ -1,6 +1,6 @@ /* - 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 @@ -38,160 +38,178 @@ #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) { - PARTITION* partition; - devoptab_t* devops; - char* nameCopy; +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()) { - interface->shutdown(); - return false; - } + if ( !interface->isInserted() ) + { + interface->shutdown(); + return false; + } - devops = _FAT_mem_allocate (sizeof(devoptab_t) + strlen(name) + 1); - if (!devops) { - interface->shutdown(); - return false; - } - // Use the space allocated at the end of the devoptab struct for storing the name - nameCopy = (char*)(devops+1); + devops = _FAT_mem_allocate ( sizeof( devoptab_t ) + strlen( name ) + 1 ); + if ( !devops ) + { + interface->shutdown(); + return false; + } + // Use the space allocated at the end of the devoptab struct for storing the name + nameCopy = ( char* )( devops + 1 ); - // Initialize the file system - partition = _FAT_partition_constructor (interface, cacheSize, SectorsPerPage, startSector); - if (!partition) { - _FAT_mem_free (devops); - interface->shutdown(); - return false; - } + // Initialize the file system + partition = _FAT_partition_constructor ( interface, cacheSize, SectorsPerPage, startSector ); + if ( !partition ) + { + _FAT_mem_free ( devops ); + interface->shutdown(); + return false; + } - // Add an entry for this device to the devoptab table - memcpy (devops, &dotab_fat, sizeof(dotab_fat)); - strcpy (nameCopy, name); - devops->name = nameCopy; - devops->deviceData = partition; + // Add an entry for this device to the devoptab table + memcpy ( devops, &dotab_fat, sizeof( dotab_fat ) ); + strcpy ( nameCopy, name ); + devops->name = nameCopy; + devops->deviceData = partition; - AddDevice (devops); + AddDevice ( devops ); - return true; + return true; } -bool fatMountSimple (const char* name, const DISC_INTERFACE* interface) { - return fatMount (name, interface, 0, DEFAULT_CACHE_PAGES, DEFAULT_SECTORS_PAGE); +bool fatMountSimple ( const char* name, const DISC_INTERFACE* interface ) +{ + return fatMount ( name, interface, 0, DEFAULT_CACHE_PAGES, DEFAULT_SECTORS_PAGE ); } -void fatUnmount (const char* name) { - devoptab_t *devops; - PARTITION* partition; - const DISC_INTERFACE *disc; +void fatUnmount ( const char* name ) +{ + devoptab_t *devops; + PARTITION* partition; + const DISC_INTERFACE *disc; - devops = (devoptab_t*)GetDeviceOpTab (name); - if (!devops) { - return; - } + devops = ( devoptab_t* )GetDeviceOpTab ( name ); + if ( !devops ) + { + return; + } - // Perform a quick check to make sure we're dealing with a libfat controlled device - if (devops->open_r != dotab_fat.open_r) { - return; - } + // Perform a quick check to make sure we're dealing with a libfat controlled device + if ( devops->open_r != dotab_fat.open_r ) + { + return; + } - if (RemoveDevice (name) == -1) { - return; - } + if ( RemoveDevice ( name ) == -1 ) + { + return; + } - partition = (PARTITION*)devops->deviceData; - disc = partition->disc; - _FAT_partition_destructor (partition); - _FAT_mem_free (devops); - disc->shutdown(); + partition = ( PARTITION* )devops->deviceData; + disc = partition->disc; + _FAT_partition_destructor ( partition ); + _FAT_mem_free ( devops ); + disc->shutdown(); } -bool fatInit (uint32_t cacheSize, bool setAsDefaultDevice) { - int i; - int defaultDevice = -1; - const DISC_INTERFACE *disc; +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++) - { - disc = _FAT_disc_interfaces[i].getInterface(); - if (fatMount (_FAT_disc_interfaces[i].name, disc, 0, cacheSize, DEFAULT_SECTORS_PAGE)) { - // The first device to successfully mount is set as the default - if (defaultDevice < 0) { - defaultDevice = i; - } - } - } + for ( i = 0; + _FAT_disc_interfaces[i].name != NULL && _FAT_disc_interfaces[i].getInterface != NULL; + i++ ) + { + disc = _FAT_disc_interfaces[i].getInterface(); + if ( fatMount ( _FAT_disc_interfaces[i].name, disc, 0, cacheSize, DEFAULT_SECTORS_PAGE ) ) + { + // The first device to successfully mount is set as the default + if ( defaultDevice < 0 ) + { + defaultDevice = i; + } + } + } - if (defaultDevice < 0) { - // None of our devices mounted - return false; - } + if ( defaultDevice < 0 ) + { + // None of our devices mounted + return false; + } - if (setAsDefaultDevice) { - char filePath[MAXPATHLEN * 2]; - strcpy (filePath, _FAT_disc_interfaces[defaultDevice].name); - strcat (filePath, ":/"); + if ( setAsDefaultDevice ) + { + char filePath[MAXPATHLEN * 2]; + strcpy ( filePath, _FAT_disc_interfaces[defaultDevice].name ); + strcat ( filePath, ":/" ); #ifdef ARGV_MAGIC - if ( __system_argv->argvMagic == ARGV_MAGIC && __system_argv->argc >= 1 && strrchr( __system_argv->argv[0], '/' )!=NULL ) { - // Check the app's path against each of our mounted devices, to see - // if we can support it. If so, change to that path. - for (i = 0; - _FAT_disc_interfaces[i].name != NULL && _FAT_disc_interfaces[i].getInterface != NULL; - i++) - { - if ( !strncasecmp( __system_argv->argv[0], _FAT_disc_interfaces[i].name, - strlen(_FAT_disc_interfaces[i].name))) - { - char *lastSlash; - strcpy(filePath, __system_argv->argv[0]); - lastSlash = strrchr( filePath, '/' ); + if ( __system_argv->argvMagic == ARGV_MAGIC && __system_argv->argc >= 1 && strrchr( __system_argv->argv[0], '/' ) != NULL ) + { + // Check the app's path against each of our mounted devices, to see + // if we can support it. If so, change to that path. + for ( i = 0; + _FAT_disc_interfaces[i].name != NULL && _FAT_disc_interfaces[i].getInterface != NULL; + i++ ) + { + if ( !strncasecmp( __system_argv->argv[0], _FAT_disc_interfaces[i].name, + strlen( _FAT_disc_interfaces[i].name ) ) ) + { + char *lastSlash; + strcpy( filePath, __system_argv->argv[0] ); + lastSlash = strrchr( filePath, '/' ); - if ( NULL != lastSlash) { - if ( *(lastSlash - 1) == ':') lastSlash++; - *lastSlash = 0; - } - } - } - } + if ( NULL != lastSlash ) + { + if ( *( lastSlash - 1 ) == ':' ) lastSlash++; + *lastSlash = 0; + } + } + } + } #endif - chdir (filePath); - } + chdir ( filePath ); + } - return true; + return true; } -bool fatInitDefault (void) { - return fatInit (DEFAULT_CACHE_PAGES, true); +bool fatInitDefault ( void ) +{ + return fatInit ( DEFAULT_CACHE_PAGES, true ); } diff --git a/source/libfat/libfatversion.h b/source/libfat/libfatversion.h index 40c50463..fb524e73 100644 --- a/source/libfat/libfatversion.h +++ b/source/libfat/libfatversion.h @@ -1,9 +1,9 @@ #ifndef __LIBFATVERSION_H__ #define __LIBFATVERSION_H__ -#define _LIBFAT_MAJOR_ 1 -#define _LIBFAT_MINOR_ 0 -#define _LIBFAT_PATCH_ 7 +#define _LIBFAT_MAJOR_ 1 +#define _LIBFAT_MINOR_ 0 +#define _LIBFAT_PATCH_ 7 #define _LIBFAT_STRING "libFAT Release 1.0.7" diff --git a/source/libfat/lock.h b/source/libfat/lock.h index 73b8902b..4fc4efdd 100644 --- a/source/libfat/lock.h +++ b/source/libfat/lock.h @@ -33,24 +33,24 @@ #ifdef USE_LWP_LOCK -static inline void _FAT_lock_init(mutex_t *mutex) +static inline void _FAT_lock_init( mutex_t *mutex ) { - LWP_MutexInit(mutex, false); + LWP_MutexInit( mutex, false ); } -static inline void _FAT_lock_deinit(mutex_t *mutex) +static inline void _FAT_lock_deinit( mutex_t *mutex ) { - LWP_MutexDestroy(*mutex); + LWP_MutexDestroy( *mutex ); } -static inline void _FAT_lock(mutex_t *mutex) +static inline void _FAT_lock( mutex_t *mutex ) { - LWP_MutexLock(*mutex); + LWP_MutexLock( *mutex ); } -static inline void _FAT_unlock(mutex_t *mutex) +static inline void _FAT_unlock( mutex_t *mutex ) { - LWP_MutexUnlock(*mutex); + LWP_MutexUnlock( *mutex ); } #else @@ -60,24 +60,24 @@ 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; + return; } -static inline void _FAT_lock_deinit(mutex_t *mutex) +static inline void _FAT_lock_deinit( mutex_t *mutex ) { - return; + return; } -static inline void _FAT_lock(mutex_t *mutex) +static inline void _FAT_lock( mutex_t *mutex ) { - return; + return; } -static inline void _FAT_unlock(mutex_t *mutex) +static inline void _FAT_unlock( mutex_t *mutex ) { - return; + return; } #endif // USE_LWP_LOCK diff --git a/source/libfat/mem_allocate.h b/source/libfat/mem_allocate.h index 2d38f9ce..a69e13b1 100644 --- a/source/libfat/mem_allocate.h +++ b/source/libfat/mem_allocate.h @@ -33,17 +33,20 @@ #include -static inline void* _FAT_mem_allocate (size_t size) { - return malloc (size); +static inline void* _FAT_mem_allocate ( size_t 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) { - free (mem); +static inline void _FAT_mem_free ( void* mem ) +{ + free ( mem ); } #endif // _MEM_ALLOCATE_H diff --git a/source/libfat/partition.c b/source/libfat/partition.c index 955468de..f29e9cdd 100644 --- a/source/libfat/partition.c +++ b/source/libfat/partition.c @@ -50,263 +50,298 @@ Data offsets */ // BIOS Parameter Block offsets -enum BPB { - BPB_jmpBoot = 0x00, - BPB_OEMName = 0x03, - // BIOS Parameter Block - BPB_bytesPerSector = 0x0B, - BPB_sectorsPerCluster = 0x0D, - BPB_reservedSectors = 0x0E, - BPB_numFATs = 0x10, - BPB_rootEntries = 0x11, - BPB_numSectorsSmall = 0x13, - BPB_mediaDesc = 0x15, - BPB_sectorsPerFAT = 0x16, - BPB_sectorsPerTrk = 0x18, - BPB_numHeads = 0x1A, - BPB_numHiddenSectors = 0x1C, - BPB_numSectors = 0x20, - // Ext BIOS Parameter Block for FAT16 - BPB_FAT16_driveNumber = 0x24, - BPB_FAT16_reserved1 = 0x25, - BPB_FAT16_extBootSig = 0x26, - BPB_FAT16_volumeID = 0x27, - BPB_FAT16_volumeLabel = 0x2B, - BPB_FAT16_fileSysType = 0x36, - // Bootcode - BPB_FAT16_bootCode = 0x3E, - // FAT32 extended block - BPB_FAT32_sectorsPerFAT32 = 0x24, - BPB_FAT32_extFlags = 0x28, - BPB_FAT32_fsVer = 0x2A, - BPB_FAT32_rootClus = 0x2C, - BPB_FAT32_fsInfo = 0x30, - BPB_FAT32_bkBootSec = 0x32, - // Ext BIOS Parameter Block for FAT32 - BPB_FAT32_driveNumber = 0x40, - BPB_FAT32_reserved1 = 0x41, - BPB_FAT32_extBootSig = 0x42, - BPB_FAT32_volumeID = 0x43, - BPB_FAT32_volumeLabel = 0x47, - BPB_FAT32_fileSysType = 0x52, - // Bootcode - BPB_FAT32_bootCode = 0x5A, - BPB_bootSig_55 = 0x1FE, - BPB_bootSig_AA = 0x1FF +enum BPB +{ + BPB_jmpBoot = 0x00, + BPB_OEMName = 0x03, + // BIOS Parameter Block + BPB_bytesPerSector = 0x0B, + BPB_sectorsPerCluster = 0x0D, + BPB_reservedSectors = 0x0E, + BPB_numFATs = 0x10, + BPB_rootEntries = 0x11, + BPB_numSectorsSmall = 0x13, + BPB_mediaDesc = 0x15, + BPB_sectorsPerFAT = 0x16, + BPB_sectorsPerTrk = 0x18, + BPB_numHeads = 0x1A, + BPB_numHiddenSectors = 0x1C, + BPB_numSectors = 0x20, + // Ext BIOS Parameter Block for FAT16 + BPB_FAT16_driveNumber = 0x24, + BPB_FAT16_reserved1 = 0x25, + BPB_FAT16_extBootSig = 0x26, + BPB_FAT16_volumeID = 0x27, + BPB_FAT16_volumeLabel = 0x2B, + BPB_FAT16_fileSysType = 0x36, + // Bootcode + BPB_FAT16_bootCode = 0x3E, + // FAT32 extended block + BPB_FAT32_sectorsPerFAT32 = 0x24, + BPB_FAT32_extFlags = 0x28, + BPB_FAT32_fsVer = 0x2A, + BPB_FAT32_rootClus = 0x2C, + BPB_FAT32_fsInfo = 0x30, + BPB_FAT32_bkBootSec = 0x32, + // Ext BIOS Parameter Block for FAT32 + BPB_FAT32_driveNumber = 0x40, + BPB_FAT32_reserved1 = 0x41, + BPB_FAT32_extBootSig = 0x42, + BPB_FAT32_volumeID = 0x43, + BPB_FAT32_volumeLabel = 0x47, + BPB_FAT32_fileSysType = 0x52, + // Bootcode + BPB_FAT32_bootCode = 0x5A, + BPB_bootSig_55 = 0x1FE, + BPB_bootSig_AA = 0x1FF }; 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 *ptr; - int i; + uint8_t part_table[16*4]; + uint8_t *ptr; + int i; - uint8_t sectorBuffer[BYTES_PER_READ] = {0}; + uint8_t sectorBuffer[BYTES_PER_READ] = {0}; - // Read first sector of disc - if (!_FAT_disc_readSectors (disc, 0, 1, sectorBuffer)) { - return 0; - } + // Read first sector of disc + if ( !_FAT_disc_readSectors ( disc, 0, 1, sectorBuffer ) ) + { + return 0; + } - memcpy(part_table,sectorBuffer+0x1BE,16*4); - ptr = part_table; + memcpy( part_table, sectorBuffer + 0x1BE, 16*4 ); + ptr = part_table; - for(i=0;i<4;i++,ptr+=16) { - sec_t part_lba = u8array_to_u32(ptr, 0x8); + for ( i = 0; i < 4; i++, ptr += 16 ) + { + sec_t part_lba = u8array_to_u32( ptr, 0x8 ); - if (!memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG)) || - !memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { - return part_lba; - } + if ( !memcmp( sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof( FAT_SIG ) ) || + !memcmp( sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof( FAT_SIG ) ) ) + { + return part_lba; + } - if(ptr[4]==0) continue; + if ( ptr[4] == 0 ) continue; - if(ptr[4]==0x0F) { - sec_t part_lba2=part_lba; - sec_t next_lba2=0; - int n; + if ( ptr[4] == 0x0F ) + { + sec_t part_lba2 = part_lba; + sec_t next_lba2 = 0; + int n; - for(n=0;n<8;n++) // max 8 logic partitions - { - if(!_FAT_disc_readSectors (disc, part_lba+next_lba2, 1, sectorBuffer)) return 0; + for ( n = 0; n < 8; n++ ) // max 8 logic partitions + { + if ( !_FAT_disc_readSectors ( disc, part_lba + next_lba2, 1, sectorBuffer ) ) return 0; - part_lba2 = part_lba + next_lba2 + u8array_to_u32(sectorBuffer, 0x1C6) ; - next_lba2 = u8array_to_u32(sectorBuffer, 0x1D6); + part_lba2 = part_lba + next_lba2 + u8array_to_u32( sectorBuffer, 0x1C6 ) ; + next_lba2 = u8array_to_u32( sectorBuffer, 0x1D6 ); - if(!_FAT_disc_readSectors (disc, part_lba2, 1, sectorBuffer)) return 0; + if ( !_FAT_disc_readSectors ( disc, part_lba2, 1, sectorBuffer ) ) return 0; - if (!memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG)) || - !memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) - { - return part_lba2; - } + if ( !memcmp( sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof( FAT_SIG ) ) || + !memcmp( sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof( FAT_SIG ) ) ) + { + return part_lba2; + } - if(next_lba2==0) break; - } - } else { - if(!_FAT_disc_readSectors (disc, part_lba, 1, sectorBuffer)) return 0; - if (!memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG)) || - !memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { - return part_lba; - } - } - } - return 0; + if ( next_lba2 == 0 ) break; + } + } + else + { + if ( !_FAT_disc_readSectors ( disc, part_lba, 1, sectorBuffer ) ) return 0; + if ( !memcmp( sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof( FAT_SIG ) ) || + !memcmp( sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof( FAT_SIG ) ) ) + { + return part_lba; + } + } + } + return 0; } -PARTITION* _FAT_partition_constructor (const DISC_INTERFACE* disc, uint32_t cacheSize, uint32_t sectorsPerPage, sec_t startSector) { - PARTITION* partition; - uint8_t sectorBuffer[BYTES_PER_READ] = {0}; +PARTITION* _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}; - // Read first sector of disc - if (!_FAT_disc_readSectors (disc, startSector, 1, sectorBuffer)) { - return NULL; - } + // Read first sector of disc + if ( !_FAT_disc_readSectors ( disc, startSector, 1, sectorBuffer ) ) + { + return NULL; + } - // Make sure it is a valid MBR or boot sector - if ( (sectorBuffer[BPB_bootSig_55] != 0x55) || (sectorBuffer[BPB_bootSig_AA] != 0xAA)) { - return NULL; - } + // Make sure it is a valid MBR or boot sector + if ( ( sectorBuffer[BPB_bootSig_55] != 0x55 ) || ( sectorBuffer[BPB_bootSig_AA] != 0xAA ) ) + { + return NULL; + } - if (startSector != 0) { - // We're told where to start the partition, so just accept it - } else if (!memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { - // Check if there is a FAT string, which indicates this is a boot sector - startSector = 0; - } else if (!memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) { - // Check for FAT32 - startSector = 0; - } else { - startSector = FindFirstValidPartition(disc); - if (!_FAT_disc_readSectors (disc, startSector, 1, sectorBuffer)) { - return NULL; - } - } + if ( startSector != 0 ) + { + // We're told where to start the partition, so just accept it + } + else if ( !memcmp( sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof( FAT_SIG ) ) ) + { + // Check if there is a FAT string, which indicates this is a boot sector + startSector = 0; + } + else if ( !memcmp( sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof( FAT_SIG ) ) ) + { + // Check for FAT32 + startSector = 0; + } + else + { + startSector = FindFirstValidPartition( disc ); + if ( !_FAT_disc_readSectors ( disc, startSector, 1, sectorBuffer ) ) + { + return NULL; + } + } - // Now verify that this is indeed a FAT partition - if (memcmp(sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof(FAT_SIG)) && - memcmp(sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof(FAT_SIG))) - { - return NULL; - } + // Now verify that this is indeed a FAT partition + if ( memcmp( sectorBuffer + BPB_FAT16_fileSysType, FAT_SIG, sizeof( FAT_SIG ) ) && + memcmp( sectorBuffer + BPB_FAT32_fileSysType, FAT_SIG, sizeof( FAT_SIG ) ) ) + { + return NULL; + } - // check again for the last two cases to make sure that we really have a FAT filesystem here - // and won't corrupt any data - if(memcmp(sectorBuffer + BPB_FAT16_fileSysType, "FAT", 3) != 0 && memcmp(sectorBuffer + BPB_FAT32_fileSysType, "FAT32", 5) != 0) - { - return NULL; - } + // check again for the last two cases to make sure that we really have a FAT filesystem here + // and won't corrupt any data + if ( memcmp( sectorBuffer + BPB_FAT16_fileSysType, "FAT", 3 ) != 0 && memcmp( sectorBuffer + BPB_FAT32_fileSysType, "FAT32", 5 ) != 0 ) + { + return NULL; + } - partition = (PARTITION*) _FAT_mem_allocate (sizeof(PARTITION)); - if (partition == NULL) { - return NULL; - } + partition = ( PARTITION* ) _FAT_mem_allocate ( sizeof( PARTITION ) ); + if ( partition == NULL ) + { + return NULL; + } - _FAT_startSector = startSector; + _FAT_startSector = startSector; - // Init the partition lock - _FAT_lock_init(&partition->lock); + // Init the partition lock + _FAT_lock_init( &partition->lock ); - // Set partition's disc interface - partition->disc = disc; + // Set partition's disc interface + partition->disc = disc; - // Store required information about the file system - partition->fat.sectorsPerFat = u8array_to_u16(sectorBuffer, BPB_sectorsPerFAT); - if (partition->fat.sectorsPerFat == 0) { - partition->fat.sectorsPerFat = u8array_to_u32( sectorBuffer, BPB_FAT32_sectorsPerFAT32); - } + // Store required information about the file system + partition->fat.sectorsPerFat = u8array_to_u16( sectorBuffer, BPB_sectorsPerFAT ); + if ( partition->fat.sectorsPerFat == 0 ) + { + partition->fat.sectorsPerFat = u8array_to_u32( sectorBuffer, BPB_FAT32_sectorsPerFAT32 ); + } - partition->numberOfSectors = u8array_to_u16( sectorBuffer, BPB_numSectorsSmall); - if (partition->numberOfSectors == 0) { - partition->numberOfSectors = u8array_to_u32( sectorBuffer, BPB_numSectors); - } + partition->numberOfSectors = u8array_to_u16( sectorBuffer, BPB_numSectorsSmall ); + if ( partition->numberOfSectors == 0 ) + { + partition->numberOfSectors = u8array_to_u32( sectorBuffer, BPB_numSectors ); + } - partition->bytesPerSector = BYTES_PER_READ; // Sector size is redefined to be 512 bytes - partition->sectorsPerCluster = sectorBuffer[BPB_sectorsPerCluster] * u8array_to_u16(sectorBuffer, BPB_bytesPerSector) / BYTES_PER_READ; - partition->bytesPerCluster = partition->bytesPerSector * partition->sectorsPerCluster; - partition->fat.fatStart = startSector + u8array_to_u16(sectorBuffer, BPB_reservedSectors); + partition->bytesPerSector = BYTES_PER_READ; // Sector size is redefined to be 512 bytes + partition->sectorsPerCluster = sectorBuffer[BPB_sectorsPerCluster] * u8array_to_u16( sectorBuffer, BPB_bytesPerSector ) / BYTES_PER_READ; + partition->bytesPerCluster = partition->bytesPerSector * partition->sectorsPerCluster; + partition->fat.fatStart = startSector + u8array_to_u16( sectorBuffer, BPB_reservedSectors ); - partition->rootDirStart = partition->fat.fatStart + (sectorBuffer[BPB_numFATs] * partition->fat.sectorsPerFat); - partition->dataStart = partition->rootDirStart + - (( u8array_to_u16(sectorBuffer, BPB_rootEntries) * DIR_ENTRY_DATA_SIZE) / partition->bytesPerSector); + partition->rootDirStart = partition->fat.fatStart + ( sectorBuffer[BPB_numFATs] * partition->fat.sectorsPerFat ); + partition->dataStart = partition->rootDirStart + + ( ( u8array_to_u16( sectorBuffer, BPB_rootEntries ) * DIR_ENTRY_DATA_SIZE ) / partition->bytesPerSector ); - partition->totalSize = ((uint64_t)partition->numberOfSectors - (partition->dataStart - startSector)) * (uint64_t)partition->bytesPerSector; + partition->totalSize = ( ( uint64_t )partition->numberOfSectors - ( partition->dataStart - startSector ) ) * ( uint64_t )partition->bytesPerSector; - // Store info about FAT - uint32_t clusterCount = (partition->numberOfSectors - (uint32_t)(partition->dataStart - startSector)) / partition->sectorsPerCluster; - partition->fat.lastCluster = clusterCount + CLUSTER_FIRST - 1; - partition->fat.firstFree = CLUSTER_FIRST; + // Store info about FAT + uint32_t clusterCount = ( partition->numberOfSectors - ( uint32_t )( partition->dataStart - startSector ) ) / partition->sectorsPerCluster; + partition->fat.lastCluster = clusterCount + CLUSTER_FIRST - 1; + partition->fat.firstFree = CLUSTER_FIRST; - if (clusterCount < CLUSTERS_PER_FAT12) { - partition->filesysType = FS_FAT12; // FAT12 volume - } else if (clusterCount < CLUSTERS_PER_FAT16) { - partition->filesysType = FS_FAT16; // FAT16 volume - } else { - partition->filesysType = FS_FAT32; // FAT32 volume - } + if ( clusterCount < CLUSTERS_PER_FAT12 ) + { + partition->filesysType = FS_FAT12; // FAT12 volume + } + else if ( clusterCount < CLUSTERS_PER_FAT16 ) + { + partition->filesysType = FS_FAT16; // FAT16 volume + } + else + { + partition->filesysType = FS_FAT32; // FAT32 volume + } - if (partition->filesysType != FS_FAT32) { - partition->rootDirCluster = FAT16_ROOT_DIR_CLUSTER; - } else { - // Set up for the FAT32 way - partition->rootDirCluster = u8array_to_u32(sectorBuffer, BPB_FAT32_rootClus); - // Check if FAT mirroring is enabled - if (!(sectorBuffer[BPB_FAT32_extFlags] & 0x80)) { - // Use the active FAT - partition->fat.fatStart = partition->fat.fatStart + ( partition->fat.sectorsPerFat * (sectorBuffer[BPB_FAT32_extFlags] & 0x0F)); - } - } + if ( partition->filesysType != FS_FAT32 ) + { + partition->rootDirCluster = FAT16_ROOT_DIR_CLUSTER; + } + else + { + // Set up for the FAT32 way + partition->rootDirCluster = u8array_to_u32( sectorBuffer, BPB_FAT32_rootClus ); + // Check if FAT mirroring is enabled + if ( !( sectorBuffer[BPB_FAT32_extFlags] & 0x80 ) ) + { + // Use the active FAT + partition->fat.fatStart = partition->fat.fatStart + ( partition->fat.sectorsPerFat * ( sectorBuffer[BPB_FAT32_extFlags] & 0x0F ) ); + } + } - // Create a cache to use - partition->cache = _FAT_cache_constructor (cacheSize, sectorsPerPage, partition->disc, startSector+partition->numberOfSectors); + // Create a cache to use + partition->cache = _FAT_cache_constructor ( cacheSize, sectorsPerPage, partition->disc, startSector + partition->numberOfSectors ); - // Set current directory to the root - partition->cwdCluster = partition->rootDirCluster; + // Set current directory to the root + partition->cwdCluster = partition->rootDirCluster; - // Check if this disc is writable, and set the readOnly property appropriately - partition->readOnly = !(_FAT_disc_features(disc) & FEATURE_MEDIUM_CANWRITE); + // Check if this disc is writable, and set the readOnly property appropriately + partition->readOnly = !( _FAT_disc_features( disc ) & FEATURE_MEDIUM_CANWRITE ); - // There are currently no open files on this partition - partition->openFileCount = 0; - partition->firstOpenFile = NULL; + // There are currently no open files on this partition + partition->openFileCount = 0; + partition->firstOpenFile = NULL; - return partition; + return partition; } -void _FAT_partition_destructor (PARTITION* partition) { - FILE_STRUCT* nextFile; +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) { - _FAT_syncToDisc (nextFile); - nextFile = nextFile->nextOpenFile; - } + // Synchronize open files + nextFile = partition->firstOpenFile; + while ( nextFile ) + { + _FAT_syncToDisc ( nextFile ); + nextFile = nextFile->nextOpenFile; + } - // Free memory used by the cache, writing it to disc at the same time - _FAT_cache_destructor (partition->cache); + // Free memory used by the cache, writing it to disc at the same time + _FAT_cache_destructor ( partition->cache ); - // Unlock the partition and destroy the lock - _FAT_unlock(&partition->lock); - _FAT_lock_deinit(&partition->lock); + // Unlock the partition and destroy the lock + _FAT_unlock( &partition->lock ); + _FAT_lock_deinit( &partition->lock ); - // Free memory used by the partition - _FAT_mem_free (partition); + // Free memory used by the partition + _FAT_mem_free ( partition ); } -PARTITION* _FAT_partition_getPartitionFromPath (const char* path) { - const devoptab_t *devops; +PARTITION* _FAT_partition_getPartitionFromPath ( const char* path ) +{ + const devoptab_t *devops; - devops = GetDeviceOpTab (path); + devops = GetDeviceOpTab ( path ); - if (!devops) { - return NULL; - } + if ( !devops ) + { + return NULL; + } - return (PARTITION*)devops->deviceData; + return ( PARTITION* )devops->deviceData; } diff --git a/source/libfat/partition.h b/source/libfat/partition.h index 5c9595e0..4417dc0e 100644 --- a/source/libfat/partition.h +++ b/source/libfat/partition.h @@ -40,49 +40,51 @@ extern const char* DEVICE_NAME; // Filesystem 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; +typedef struct +{ + 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 +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 } 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); +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); +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); +PARTITION* _FAT_partition_getPartitionFromPath ( const char* path ); #endif // _PARTITION_H diff --git a/source/libntfs/acls.c b/source/libntfs/acls.c index 76cc6ce5..eaf47ee7 100644 --- a/source/libntfs/acls.c +++ b/source/libntfs/acls.c @@ -1,8 +1,8 @@ /** * acls.c - General function to process NTFS ACLs * - * This module is part of ntfs-3g library, but may also be - * integrated in tools running over Linux or Windows + * This module is part of ntfs-3g library, but may also be + * integrated in tools running over Linux or Windows * * Copyright (c) 2007-2009 Jean-Pierre Andre * @@ -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 @@ -109,3313 +109,3594 @@ #endif /* HAVE_CONFIG_H */ /* - * A few useful constants + * A few useful constants */ /* - * null SID (S-1-0-0) + * 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 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 */ -} ; - -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 nullsidbytes[] = +{ + 1, /* revision */ + 1, /* auth count */ + 0, 0, 0, 0, 0, 0, /* base */ + 0, 0, 0, 0 /* 1st level */ }; -const SID *adminsid = (const SID*)adminsidbytes; +static const SID *nullsid = ( const SID* )nullsidbytes; /* - * SID for system + * SID for world (S-1-1-0) */ -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; - -/* - * 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 worldsidbytes[] = +{ + 1, /* revision */ + 1, /* auth count */ + 0, 0, 0, 0, 0, 1, /* base */ + 0, 0, 0, 0 /* 1st level */ } ; -static const SID *ownersid = (const SID*)ownersidbytes; +const SID *worldsid = ( const SID* )worldsidbytes; /* - * SID for generic creator-group - * S-1-3-1 + * SID for administrator */ -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 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; + +/* + * 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 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 SID *groupsid = (const SID*)groupsidbytes; +static const SID *ownersid = ( const SID* )ownersidbytes; /* - * Determine the size of a SID + * SID for generic creator-group + * S-1-3-1 */ -int ntfs_sid_size(const SID * sid) +static const char groupsidbytes[] = { - return (sid->sub_authority_count * 4 + 8); + 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; + +/* + * Determine the size of a SID + */ + +int ntfs_sid_size( const SID * sid ) +{ + return ( sid->sub_authority_count * 4 + 8 ); } /* - * Test whether two SID are equal + * Test whether two SID are equal */ -BOOL ntfs_same_sid(const SID *first, const SID *second) +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 ) ); } /* - * Test whether a SID means "world user" - * Local users group also recognized as world + * Test whether a SID means "world user" + * Local users group also recognized as world */ -static int is_world_sid(const SID * usid) +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 ) ) ) + ); } /* - * Test whether a SID means "some user (or group)" - * Currently we only check for S-1-5-21... but we should - * probably test for other configurations + * Test whether a SID means "some user (or group)" + * Currently we only check for S-1-5-21... but we should + * probably test for other configurations */ -BOOL ntfs_is_user_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 ) ) ); } /* - * Determine the size of a security attribute - * whatever the order of fields + * Determine the size of a security attribute + * whatever the order of fields */ -unsigned int ntfs_attr_size(const char *attr) +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 ); } /* - * Do sanity checks on a SID read from storage - * (just check revision and number of authorities) + * Do sanity checks on a SID read from storage + * (just check revision and number of authorities) */ -BOOL ntfs_valid_sid(const SID *sid) +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 ) ); } /* - * Check whether a SID is acceptable for an implicit - * mapping pattern. - * It should have been already checked it is a valid user SID. + * Check whether a SID is acceptable for an implicit + * mapping pattern. + * It should have been already checked it is a valid user SID. * - * The last authority reference has to be >= 1000 (Windows usage) - * and <= 0x7fffffff, so that 30 bits from a uid and 30 more bits + * The last authority reference has to be >= 1000 (Windows usage) + * and <= 0x7fffffff, so that 30 bits from a uid and 30 more bits * from a gid an be inserted with no overflow. */ -BOOL ntfs_valid_pattern(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 ) ); } /* - * Compute the uid or gid associated to a SID - * through an implicit mapping + * Compute the uid or gid associated to a SID + * through an implicit mapping * - * Returns 0 (root) if it does not match pattern + * Returns 0 (root) if it does not match pattern */ -static u32 findimplicit(const SID *xsid, const SID *pattern, int parity) +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 ); } /* - * Find usid mapped to a Linux user - * Returns NULL if not found + * Find usid mapped to a Linux user + * 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 ); } /* - * Find Linux group mapped to a gsid - * Returns 0 (root) if not found + * Find Linux group mapped to a gsid + * 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 ); } /* - * Find Linux owner mapped to a usid - * Returns 0 (root) if not found + * Find Linux owner mapped to a usid + * Returns 0 (root) if not found */ -uid_t ntfs_find_user(const struct MAPPING* usermapping, const SID *usid) +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 ); } /* - * Find Linux group mapped to a gsid - * Returns 0 (root) if not found + * Find Linux group mapped to a gsid + * Returns 0 (root) if not found */ -gid_t ntfs_find_group(const struct MAPPING* groupmapping, const SID * gsid) +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 ); } /* - * Check the validity of the ACEs in a DACL or SACL + * Check the validity of the ACEs in a DACL or SACL */ -static BOOL valid_acl(const ACL *pacl, unsigned int end) +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 ); } /* - * Do sanity checks on security descriptors read from storage - * basically, we make sure that every field holds within - * allocated storage - * Should not be called with a NULL argument - * returns TRUE if considered safe - * if not, error should be logged by caller + * Do sanity checks on security descriptors read from storage + * basically, we make sure that every field holds within + * allocated storage + * Should not be called with a NULL argument + * returns TRUE if considered safe + * if not, error should be logged by caller */ -BOOL ntfs_valid_descr(const char *securattr, unsigned int attrsz) +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 ); } /* - * Copy the inheritable parts of an ACL + * Copy the inheritable parts of an ACL * - * Returns the size of the new ACL - * or zero if nothing is inheritable + * Returns the size of the new ACL + * 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 /* - * Do sanity checks on a Posix descriptor - * Should not be called with a NULL argument - * returns TRUE if considered safe - * if not, error should be logged by caller + * Do sanity checks on a Posix descriptor + * Should not be called with a NULL argument + * returns TRUE if considered safe + * if not, error should be logged by caller */ -BOOL ntfs_valid_posix(const struct POSIX_SECURITY *pxdesc) +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; i < pxdesc->acccnt + 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 ); } /* - * Set standard header data into a Posix ACL - * The mode argument should provide the 3 upper bits of target mode + * Set standard header data into a Posix ACL + * The mode argument should provide the 3 upper bits of target mode */ -static mode_t posix_header(struct POSIX_SECURITY *pxdesc, mode_t basemode) +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; i < pxdesc->acccnt; 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 ); } /* - * Sort ACEs in a Posix ACL - * This is useful for always getting reusable converted ACLs, - * it also helps in merging ACEs. - * Repeated tag+id are allowed and not merged here. + * Sort ACEs in a Posix ACL + * This is useful for always getting reusable converted ACLs, + * it also helps in merging ACEs. + * Repeated tag+id are allowed and not merged here. * - * Tags should be in ascending sequence and for a repeatable tag - * ids should be in ascending sequence. + * Tags should be in ascending sequence and for a repeatable tag + * ids should be in ascending sequence. */ -void ntfs_sort_posix(struct POSIX_SECURITY *pxdesc) +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; i < pxdesc->acccnt; 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; i < offs + pxdesc->defcnt; 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 ); } /* - * Merge a new mode into a Posix descriptor - * The Posix descriptor is not reallocated, its size is unchanged + * Merge a new mode into a Posix descriptor + * The Posix descriptor is not reallocated, its size is unchanged * - * returns 0 if ok + * returns 0 if ok */ -int ntfs_merge_mode_posix(struct POSIX_SECURITY *pxdesc, mode_t mode) +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 ); } /* - * Replace an access or default Posix ACL - * The resulting ACL is checked for validity + * Replace an access or default Posix ACL + * The resulting ACL is checked for validity * - * Returns a new ACL or NULL if there is a problem + * Returns a new ACL or NULL if there is a problem */ -struct POSIX_SECURITY *ntfs_replace_acl(const struct POSIX_SECURITY *oldpxdesc, - const struct POSIX_ACL *newacl, int count, BOOL deflt) +struct POSIX_SECURITY *ntfs_replace_acl( const struct POSIX_SECURITY *oldpxdesc, + const struct POSIX_ACL *newacl, int count, BOOL deflt ) { - struct POSIX_SECURITY *newpxdesc; - size_t newsize; - int offset; - int oldoffset; - int i; + 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; i < newpxdesc->acccnt; i++ ) + newpxdesc->acl.ace[i] = oldpxdesc->acl.ace[i]; + /* copy default ACEs */ + for ( i = 0; i < count; i++ ) + newpxdesc->acl.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; i < count; i++ ) + newpxdesc->acl.ace[i] = newacl->ace[i]; + /* copy default ACEs */ + oldoffset = oldpxdesc->firstdef; + for ( i = 0; i < newpxdesc->defcnt; 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 ); } /* - * Build an inherited Posix descriptor from parent - * descriptor (if any) restricted to creation mode + * Build an inherited Posix descriptor from parent + * descriptor (if any) restricted to creation mode * - * Returns the inherited descriptor or NULL if there is a problem + * Returns the inherited descriptor or NULL if there is a problem */ 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) +static int merge_lists_posix( struct POSIX_ACE *targetace, + const struct POSIX_ACE *firstace, + const struct POSIX_ACE *secondace, + int firstcnt, int secondcnt ) { - int k; + 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 ); } /* - * Merge two Posix ACLs - * The input ACLs have to be adequately sorted + * Merge two Posix ACLs + * The input ACLs have to be adequately sorted * - * Returns the merged ACL, which is allocated and has to be freed by caller, - * or NULL if failed + * Returns the merged ACL, which is allocated and has to be freed by caller, + * or NULL if failed */ -struct POSIX_SECURITY *ntfs_merge_descr_posix(const struct POSIX_SECURITY *first, - const struct POSIX_SECURITY *second) +struct POSIX_SECURITY *ntfs_merge_descr_posix( const struct POSIX_SECURITY *first, + const struct POSIX_SECURITY *second ) { - struct POSIX_SECURITY *pxdesc; - struct POSIX_ACE *targetace; - const struct POSIX_ACE *firstace; - const struct POSIX_ACE *secondace; - size_t size; - int k; + 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) +static BOOL build_user_denials( ACL *pacl, + const SID *usid, struct MAPPING* const mapping[], + ACE_FLAGS flags, const struct POSIX_ACE *pxace, + struct BUILD_CONTEXT *pset ) { - BIGSID defsid; - ACCESS_ALLOWED_ACE *pdace; - const SID *sid; - int sidsz; - int pos; - int acecnt; - le32 grants; - le32 denials; - u16 perms; - u16 mixperms; - u16 tag; - BOOL rejected; - BOOL rootuser; - BOOL avoidmask; + 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) +static BOOL build_user_grants( ACL *pacl, + const SID *usid, struct MAPPING* const mapping[], + ACE_FLAGS flags, const struct POSIX_ACE *pxace, + struct BUILD_CONTEXT *pset ) { - BIGSID defsid; - ACCESS_ALLOWED_ACE *pgace; - const SID *sid; - int sidsz; - int pos; - int acecnt; - le32 grants; - u16 perms; - u16 tag; - BOOL rejected; - BOOL rootuser; + 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) +static BOOL build_group_denials_grant( ACL *pacl, + const SID *gsid, struct MAPPING* const mapping[], + ACE_FLAGS flags, const struct POSIX_ACE *pxace, + struct BUILD_CONTEXT *pset ) { - BIGSID defsid; - ACCESS_ALLOWED_ACE *pdace; - ACCESS_ALLOWED_ACE *pgace; - const SID *sid; - int sidsz; - int pos; - int acecnt; - le32 grants; - le32 denials; - u16 perms; - u16 mixperms; - u16 tag; - BOOL avoidmask; - BOOL rootgroup; - BOOL rejected; + 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 + * Build an ACL composed of several ACE's + * returns size of ACL or zero if failed * - * Three schemes are defined : + * Three schemes are defined : * - * 1) if root is neither owner nor group up to 7 ACE's are set up : - * - denials to owner (preventing grants to world or group to apply) + * 1) if root is neither owner nor group up to 7 ACE's are set up : + * - denials to owner (preventing grants to world or group to apply) * + mask denials to designated user (unless mask allows all) * + denials to designated user - * - grants to owner (always present - first grant) + * - 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) - * - grants to group (unless group has no more than world rights) + * - 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 * + denials to designated group - * - grants to world (unless none) - * - full privileges to administrator, always present - * - full privileges to system, always present + * - grants to world (unless none) + * - full privileges to administrator, always present + * - full privileges to system, always present * - * The same scheme is applied for Posix ACLs, with the mask represented - * as denials prepended to grants for designated users and groups + * The same scheme is applied for Posix ACLs, with the mask represented + * as denials prepended to grants for designated users and groups * - * This is inspired by an Internet Draft from Marius Aamodt Eriksen - * for mapping NFSv4 ACLs to Posix ACLs (draft-ietf-nfsv4-acl-mapping-00.txt) - * More recent versions of the draft (draft-ietf-nfsv4-acl-mapping-05.txt) - * are not followed, as they ignore the Posix mask and lead to - * loss of compatibility with Linux implementations on other fs. + * This is inspired by an Internet Draft from Marius Aamodt Eriksen + * for mapping NFSv4 ACLs to Posix ACLs (draft-ietf-nfsv4-acl-mapping-00.txt) + * More recent versions of the draft (draft-ietf-nfsv4-acl-mapping-05.txt) + * are not followed, as they ignore the Posix mask and lead to + * loss of compatibility with Linux implementations on other fs. * - * Note that denials to group are located after grants to owner. - * This only occurs in the unfrequent situation where world - * has more rights than group and cannot be avoided if owner and other - * have some common right which is denied to group (eg for mode 745 - * executing has to be denied to group, but not to owner or world). - * This rare situation is processed by Windows correctly, but - * Windows utilities may want to change the order, with a - * consequence of applying the group denials to the Windows owner. - * The interpretation on Linux is not affected by the order change. + * Note that denials to group are located after grants to owner. + * This only occurs in the unfrequent situation where world + * has more rights than group and cannot be avoided if owner and other + * have some common right which is denied to group (eg for mode 745 + * executing has to be denied to group, but not to owner or world). + * This rare situation is processed by Windows correctly, but + * Windows utilities may want to change the order, with a + * consequence of applying the group denials to the Windows owner. + * The interpretation on Linux is not affected by the order change. * - * 2) if root is either owner or group, two problems arise : - * - granting full rights to administrator (as needed to transpose - * to Windows rights bypassing granting to root) would imply - * Linux permissions to always be seen as rwx, no matter the chmod - * - there is no different SID to separate an administrator owner - * from an administrator group. Hence Linux permissions for owner - * would always be similar to permissions to group. + * 2) if root is either owner or group, two problems arise : + * - granting full rights to administrator (as needed to transpose + * to Windows rights bypassing granting to root) would imply + * Linux permissions to always be seen as rwx, no matter the chmod + * - there is no different SID to separate an administrator owner + * from an administrator group. Hence Linux permissions for owner + * would always be similar to permissions to group. * - * as a work-around, up to 5 ACE's are set up if owner or group : - * - grants to owner, always present at first position - * - grants to group, always present - * - grants to world, unless none - * - full privileges to administrator, always present - * - full privileges to system, always present + * as a work-around, up to 5 ACE's are set up if owner or group : + * - grants to owner, always present at first position + * - grants to group, always present + * - grants to world, unless none + * - full privileges to administrator, always present + * - full privileges to system, always present * - * On Windows, these ACE's are processed normally, though they - * are redundant (owner, group and administrator are the same, - * as a consequence any denials would damage administrator rights) - * but on Linux, privileges to administrator are ignored (they - * are not needed as root has always full privileges), and - * neither grants to group are applied to owner, nor grants to - * world are applied to owner or group. + * On Windows, these ACE's are processed normally, though they + * are redundant (owner, group and administrator are the same, + * as a consequence any denials would damage administrator rights) + * but on Linux, privileges to administrator are ignored (they + * are not needed as root has always full privileges), and + * neither grants to group are applied to owner, nor grants to + * world are applied to owner or group. * - * 3) finally a similar situation arises when group is owner (they - * have the same SID), but is not root. - * In this situation up to 6 ACE's are set up : + * 3) finally a similar situation arises when group is owner (they + * have the same SID), but is not root. + * In this situation up to 6 ACE's are set up : * - * - denials to owner (preventing grants to world to apply) - * - grants to owner (always present) - * - grants to group (unless groups has same rights as world) - * - grants to world (unless none) - * - full privileges to administrator, always present - * - full privileges to system, always present + * - denials to owner (preventing grants to world to apply) + * - grants to owner (always present) + * - grants to group (unless groups has same rights as world) + * - grants to world (unless none) + * - full privileges to administrator, always present + * - full privileges to system, always present * - * On Windows, these ACE's are processed normally, though they - * are redundant (as owner and group are the same), but this has - * no impact on administrator rights + * On Windows, these ACE's are processed normally, though they + * are redundant (as owner and group are the same), but this has + * no impact on administrator rights * - * Special flags (S_ISVTX, S_ISGID, S_ISUID) : - * an extra null ACE is inserted to hold these flags, using - * the same conventions as cygwin. + * Special flags (S_ISVTX, S_ISGID, S_ISUID) : + * an extra null ACE is inserted to hold these flags, using + * the same conventions as cygwin. * */ -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) +static int buildacls_posix( struct MAPPING* const mapping[], + char *secattr, int offs, const struct POSIX_SECURITY *pxdesc, + int isdir, const SID *usid, const SID *gsid ) { - struct BUILD_CONTEXT aceset[2], *pset; - BOOL adminowns; - BOOL groupowns; - ACL *pacl; - ACCESS_ALLOWED_ACE *pgace; - ACCESS_ALLOWED_ACE *pdace; - const struct POSIX_ACE *pxace; - BOOL ok; - mode_t mode; - u16 tag; - u16 perms; - ACE_FLAGS flags; - int pos; - int i; - int k; - BIGSID defsid; - const SID *sid; - int acecnt; - int usidsz; - int gsidsz; - int wsidsz; - int asidsz; - int ssidsz; - int nsidsz; - le32 grants; + 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 /* - * Build a full security descriptor from a Posix ACL - * returns descriptor in allocated memory, must free() after use + * Build a full security descriptor from a Posix ACL + * returns descriptor in allocated memory, must free() after use */ -char *ntfs_build_descr_posix(struct MAPPING* const mapping[], - struct POSIX_SECURITY *pxdesc, - int isdir, const SID *usid, const SID *gsid) +char *ntfs_build_descr_posix( struct MAPPING* const mapping[], + struct POSIX_SECURITY *pxdesc, + int isdir, const SID *usid, const SID *gsid ) { - int newattrsz; - SECURITY_DESCRIPTOR_RELATIVE *pnhead; - char *newattr; - int aclsz; - int usidsz; - int gsidsz; - int wsidsz; - int asidsz; - int ssidsz; - int k; + 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; k < pxdesc->acccnt; 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 */ /* - * Build a full security descriptor - * returns descriptor in allocated memory, must free() after use + * Build a full security descriptor + * 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 ); } /* - * Create a mode_t permission set - * from owner, group and world grants as represented in ACEs + * Create a mode_t permission set + * 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 /* - * Normalize a Posix ACL either from a sorted raw set of - * access ACEs or default ACEs - * (standard case : different owner, group and administrator) + * Normalize a Posix ACL either from a sorted raw set of + * access ACEs or default ACEs + * (standard case : different owner, group and administrator) */ -static int norm_std_permissions_posix(struct POSIX_SECURITY *posix_desc, - BOOL groupowns, int start, int count, int target) +static int norm_std_permissions_posix( struct POSIX_SECURITY *posix_desc, + BOOL groupowns, int start, int count, int target ) { - int j,k; - s32 id; - u16 tag; - u16 tagsset; - struct POSIX_ACE *pxace; - mode_t grantgrps; - mode_t grantwrld; - mode_t denywrld; - mode_t allow; - mode_t deny; - mode_t perms; - mode_t mode; + 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 */ /* - * Interpret an ACL and extract meaningful grants - * (standard case : different owner, group and administrator) + * Interpret an ACL and extract meaningful grants + * (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 ) ); } /* - * Interpret an ACL and extract meaningful grants - * (special case : owner and group are the same, - * and not administrator) + * Interpret an ACL and extract meaningful grants + * (special case : owner and group are the same, + * 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 /* - * Normalize a Posix ACL either from a sorted raw set of - * access ACEs or default ACEs - * (special case : owner or/and group is administrator) + * Normalize a Posix ACL either from a sorted raw set of + * access ACEs or default ACEs + * (special case : owner or/and group is administrator) */ -static int norm_ownadmin_permissions_posix(struct POSIX_SECURITY *posix_desc, - int start, int count, int target) +static int norm_ownadmin_permissions_posix( struct POSIX_SECURITY *posix_desc, + int start, int count, int target ) { - int j,k; - s32 id; - u16 tag; - u16 tagsset; - struct POSIX_ACE *pxace; - int acccnt; - mode_t denywrld; - mode_t allow; - mode_t deny; - mode_t perms; - mode_t mode; + int 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 */ /* - * Interpret an ACL and extract meaningful grants - * (special case : owner or/and group is administrator) + * Interpret an ACL and extract meaningful grants + * (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 /* - * Define the owner of a file as the first user allowed - * to change the owner, instead of the user defined as owner. + * Define the owner of a file as the first user allowed + * to change the owner, instead of the user defined as owner. * - * This produces better approximations for files written by a - * Windows user in an inheritable directory owned by another user, - * as the access rights are inheritable but the ownership is not. + * This produces better approximations for files written by a + * Windows user in an inheritable directory owned by another user, + * as the access rights are inheritable but the ownership is not. * - * An important case is the directories "Documents and Settings/user" - * which the users must have access to, though Windows considers them - * as owned by administrator. + * An important case is the directories "Documents and Settings/user" + * which the users must have access to, though Windows considers them + * as owned by administrator. */ -const SID *ntfs_acl_owner(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 /* - * Special case for files owned by administrator with full - * access granted to a mapped user : consider this user as the tenant - * of the file. + * Special case for files owned by administrator with full + * access granted to a mapped user : consider this user as the tenant + * of the file. * - * This situation cannot be represented with Linux concepts and can - * only be found for files or directories created by Windows. - * Typical situation : directory "Documents and Settings/user" which - * is on the path to user's files and must be given access to user - * only. + * This situation cannot be represented with Linux concepts and can + * only be found for files or directories created by Windows. + * Typical situation : directory "Documents and Settings/user" which + * is on the path to user's files and must be given access to user + * only. * - * Check file is owned by administrator and no user has rights before - * calling. - * Returns the uid of tenant or zero if none + * Check file is owned by administrator and no user has rights before + * calling. + * 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 */ @@ -3423,871 +3704,991 @@ static uid_t find_tenant(struct MAPPING *const mapping[], #if POSIXACLS /* - * Build Posix permissions from an ACL - * returns a pointer to the requested permissions - * or a null pointer (with errno set) if there is a problem + * Build Posix permissions from an ACL + * returns a pointer to the requested permissions + * or a null pointer (with errno set) if there is a problem * - * If the NTFS ACL was created according to our rules, the retrieved - * Posix ACL should be the exact ACL which was set. However if - * the NTFS ACL was built by a different tool, the result could - * be a a poor approximation of what was expected + * If the NTFS ACL was created according to our rules, the retrieved + * Posix ACL should be the exact ACL which was set. However if + * the NTFS ACL was built by a different tool, the result could + * be a a poor approximation of what was expected */ 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; j < acecnt; j++ ) + { + pace = ( const ACCESS_ALLOWED_ACE* ) & securattr[offace]; + if ( pace->flags & 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 */ /* - * Build unix-style (mode_t) permissions from an ACL - * returns the requested permissions - * or a negative result (with errno set) if there is a problem + * Build unix-style (mode_t) permissions from an ACL + * returns the requested permissions + * 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 ); } /* - * The following must be in some library... + * The following must be in some library... */ -static unsigned long atoul(const char *p) -{ /* must be somewhere ! */ - unsigned long v; +static unsigned long atoul( const char *p ) +{ /* must be somewhere ! */ + unsigned long v; - v = 0; - while ((*p >= '0') && (*p <= '9')) - v = v * 10 + (*p++) - '0'; - return (v); + v = 0; + while ( ( *p >= '0' ) && ( *p <= '9' ) ) + v = v * 10 + ( *p++ ) - '0'; + return ( v ); } /* - * Build an internal representation of a SID - * Returns a copy in allocated memory if it succeeds - * The SID is checked to be a valid user one. + * Build an internal representation of a SID + * Returns a copy in allocated memory if it succeeds + * The SID is checked to be a valid user one. */ -static SID *encodesid(const char *sidstr) +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 ); } /* - * Early logging before the logs are redirected + * Early logging before the logs are redirected * - * (not quite satisfactory : this appears before the ntfs-g banner, - * and with a different pid) + * (not quite satisfactory : this appears before the ntfs-g banner, + * and with a different pid) */ -static void log_early_error(const char *format, ...) - __attribute__((format(printf, 1, 2))); +static void log_early_error( const char *format, ... ) +__attribute__( ( format( printf, 1, 2 ) ) ); -static void log_early_error(const char *format, ...) +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 + * Get a single mapping item from buffer * - * Always reads a full line, truncating long lines - * Refills buffer when exhausted - * Returns pointer to item, or NULL when there is no more + * Always reads a full line, truncating long lines + * Refills buffer when exhausted + * 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 ); } /* - * Read user mapping file and split into their attribute. - * Parameters are kept as text in a chained list until logins - * are converted to uid. - * Returns the head of list, if any + * Read user mapping file and split into their attribute. + * Parameters are kept as text in a chained list until logins + * are converted to uid. + * Returns the head of list, if any * - * If an absolute path is provided, the mapping file is assumed - * to be located in another mounted file system, and plain read() - * are used to get its contents. - * If a relative path is provided, the mapping file is assumed - * to be located on the current file system, and internal IO - * have to be used since we are still mounting and we have not - * entered the fuse loop yet. + * If an absolute path is provided, the mapping file is assumed + * to be located in another mounted file system, and plain read() + * are used to get its contents. + * If a relative path is provided, the mapping file is assumed + * to be located on the current file system, and internal IO + * have to be used since we are still mounting and we have not + * entered the fuse loop yet. */ -struct MAPLIST *ntfs_read_mapping(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 ); } /* - * Free memory used to store the user mapping - * The only purpose is to facilitate the detection of memory leaks + * Free memory used to store the user mapping + * The only purpose is to facilitate the detection of memory leaks */ -void ntfs_free_mapping(struct MAPPING *mapping[]) +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 + * Build the user mapping list + * user identification may be given in symbolic or numeric format * - * ! Note ! : does getpwnam() read /etc/passwd or some other file ? - * if so there is a possible recursion into fuse if this - * file is on NTFS, and fuse is not recursion safe. + * ! Note ! : does getpwnam() read /etc/passwd or some other file ? + * if so there is a possible recursion into fuse if this + * file is on NTFS, and fuse is not recursion safe. */ -struct MAPPING *ntfs_do_user_mapping(struct MAPLIST *firstitem) +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 ); } /* - * Build the group mapping list - * group identification may be given in symbolic or numeric format + * Build the group mapping list + * group identification may be given in symbolic or numeric format * - * gid not associated to a uid are processed first in order - * to favour real groups + * gid not associated to a uid are processed first in order + * to favour real groups * - * ! Note ! : does getgrnam() read /etc/group or some other file ? - * if so there is a possible recursion into fuse if this - * file is on NTFS, and fuse is not recursion safe. + * ! Note ! : does getgrnam() read /etc/group or some other file ? + * if so there is a possible recursion into fuse if this + * file is on NTFS, and fuse is not recursion safe. */ -struct MAPPING *ntfs_do_group_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..50a6ae6e 100644 --- a/source/libntfs/acls.h +++ b/source/libntfs/acls.h @@ -25,30 +25,30 @@ #define ACLS_H /* - * JPA configuration modes for security.c / acls.c - * should be moved to some config file + * JPA configuration modes for security.c / acls.c + * should be moved to some config file */ -#define BUFSZ 1024 /* buffer size to read mapping file */ +#define BUFSZ 1024 /* buffer size to read mapping file */ #define MAPPINGFILE ".NTFS-3G/UserMapping" /* default mapping file */ #define LINESZ 120 /* maximum useful size of a mapping line */ #define CACHE_PERMISSIONS_BITS 6 /* log2 of unitary allocation of permissions */ #define CACHE_PERMISSIONS_SIZE 262144 /* max cacheable permissions */ /* - * JPA The following must be in some library... - * but did not found out where + * JPA The following must be in some library... + * but did not found out where */ #define endian_rev16(x) (((x >> 8) & 255) | ((x & 255) << 8)) #define endian_rev32(x) (((x >> 24) & 255) | ((x >> 8) & 0xff00) \ - | ((x & 0xff00) << 8) | ((x & 255) << 24)) + | ((x & 0xff00) << 8) | ((x & 255) << 24)) #define cpu_to_be16(x) endian_rev16(cpu_to_le16(x)) #define cpu_to_be32(x) endian_rev32(cpu_to_le32(x)) /* - * Macro definitions needed to share code with secaudit + * Macro definitions needed to share code with secaudit */ #define NTFS_FIND_USID(map,uid,buf) ntfs_find_usid(map,uid,buf) @@ -58,25 +58,25 @@ /* - * Matching of ntfs permissions to Linux permissions - * these constants are adapted to endianness - * when setting, set them all - * when checking, check one is present + * Matching of ntfs permissions to Linux permissions + * these constants are adapted to endianness + * when setting, set them all + * 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 \ - | READ_CONTROL | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA) + | READ_CONTROL | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA) #define FILE_EXEC (FILE_EXECUTE) #define DIR_READ FILE_LIST_DIRECTORY #define DIR_WRITE (FILE_ADD_FILE | FILE_ADD_SUBDIRECTORY | FILE_DELETE_CHILD \ - | READ_CONTROL | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA) + | 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,115 +85,116 @@ #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) + | 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) + | 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) /* - * To identify NTFS ACL meaning Posix ACL granted to root - * we use rights always granted to anybody, so they have no impact - * either on Windows or on Linux. + * To identify NTFS ACL meaning Posix ACL granted to root + * we use rights always granted to anybody, so they have no impact + * either on Windows or on Linux. */ -#define ROOT_OWNER_UNMARK SYNCHRONIZE /* ACL granted to root as owner */ -#define ROOT_GROUP_UNMARK FILE_READ_EA /* ACL granted to root as group */ +#define ROOT_OWNER_UNMARK SYNCHRONIZE /* ACL granted to root as owner */ +#define ROOT_GROUP_UNMARK FILE_READ_EA /* ACL granted to root as group */ /* - * A type large enough to hold any SID + * A type large enough to hold any SID */ typedef char BIGSID[40]; /* - * Struct to hold the input mapping file - * (private to this module) + * Struct to hold the input mapping file + * (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); +typedef int ( *FILEREADER )( void *fileid, char *buf, size_t size, off_t pos ); /* - * Constants defined in acls.c + * Constants defined in acls.c */ extern const SID *adminsid; extern const SID *worldsid; /* - * Functions defined in acls.c + * Functions defined in acls.c */ -BOOL ntfs_valid_descr(const char *securattr, unsigned int attrsz); -BOOL ntfs_valid_pattern(const SID *sid); -BOOL ntfs_valid_sid(const SID *sid); -BOOL ntfs_same_sid(const SID *first, const SID *second); +BOOL ntfs_valid_descr( const char *securattr, unsigned int attrsz ); +BOOL ntfs_valid_pattern( const SID *sid ); +BOOL ntfs_valid_sid( const SID *sid ); +BOOL ntfs_same_sid( const SID *first, const SID *second ); -BOOL ntfs_is_user_sid(const SID *usid); +BOOL ntfs_is_user_sid( const SID *usid ); -int ntfs_sid_size(const SID * sid); -unsigned int ntfs_attr_size(const char *attr); +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); -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); +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 ); #if POSIXACLS -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); +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); -struct POSIX_SECURITY *ntfs_replace_acl(const struct POSIX_SECURITY *oldpxdesc, - const struct POSIX_ACL *newacl, int count, BOOL deflt); + 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 ); struct POSIX_SECURITY *ntfs_build_permissions_posix( - 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); -char *ntfs_build_descr_posix(struct MAPPING* const mapping[], - struct POSIX_SECURITY *pxdesc, - int isdir, const SID *usid, const SID *gsid); + 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 ); +char *ntfs_build_descr_posix( struct MAPPING* const mapping[], + 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); -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); -void ntfs_free_mapping(struct MAPPING *mapping[]); +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 ); +void ntfs_free_mapping( struct MAPPING *mapping[] ); #endif /* ACLS_H */ diff --git a/source/libntfs/attrib.c b/source/libntfs/attrib.c index 123c9a91..40c70299 100644 --- a/source/libntfs/attrib.c +++ b/source/libntfs/attrib.c @@ -65,54 +65,56 @@ #include "misc.h" #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 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 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) +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) +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) +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) \ -int NAttr##func_name(ntfs_attr *na) { return NAttrFlag (na, flag); } \ -void NAttrSet##func_name(ntfs_attr *na) { NAttrSetFlag (na, flag); } \ +#define GenNAttrIno(func_name, flag) \ +int NAttr##func_name(ntfs_attr *na) { return NAttrFlag (na, flag); } \ +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( Compressed, FILE_ATTR_COMPRESSED ) +GenNAttrIno( Encrypted, FILE_ATTR_ENCRYPTED ) +GenNAttrIno( Sparse, FILE_ATTR_SPARSE_FILE ) /** * ntfs_get_attribute_value_length - Find the length of an attribute @@ -122,213 +124,231 @@ GenNAttrIno(Sparse, FILE_ATTR_SPARSE_FILE) * * Returns: */ -s64 ntfs_get_attribute_value_length(const ATTR_RECORD *a) +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 ); } /** * ntfs_get_attribute_value - Get a copy of an attribute - * @vol: - * @a: - * @b: + * @vol: + * @a: + * @b: * * Description... * * Returns: */ -s64 ntfs_get_attribute_value(const ntfs_volume *vol, - const ATTR_RECORD *a, u8 *b) +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:... */ /** * __ntfs_attr_init - primary initialization of an ntfs attribute structure - * @na: ntfs attribute to initialize - * @ni: ntfs inode with which to initialize the ntfs attribute - * @type: attribute type - * @name: attribute name in little endian Unicode or NULL - * @name_len: length of attribute @name in Unicode characters (if @name given) + * @na: ntfs attribute to initialize + * @ni: ntfs inode with which to initialize the ntfs attribute + * @type: attribute type + * @name: attribute name in little endian Unicode or NULL + * @name_len: length of attribute @name in Unicode characters (if @name given) * * 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,46 +366,48 @@ 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 ); + } } /** * ntfs_attr_open - open an ntfs attribute for access - * @ni: open ntfs inode in which the ntfs attribute resides - * @type: attribute type - * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL - * @name_len: length of attribute @name in Unicode characters (if @name given) + * @ni: open ntfs inode in which the ntfs attribute resides + * @type: attribute type + * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL + * @name_len: length of attribute @name in Unicode characters (if @name given) * * Allocate a new ntfs attribute structure, initialize it with @ni, @type, * @name, and @name_len, then return it. Return NULL on error with @@ -395,202 +417,216 @@ 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); + if ( !name ) + { + if ( a->name_length ) + { + name = ntfs_ucsndup( ( ntfschar* )( ( u8* )a + le16_to_cpu( + a->name_offset ) ), a->name_length ); + if ( !name ) + goto put_err_out; + newname = name; + name_len = a->name_length; + } + else + { + name = AT_UNNAMED; + name_len = 0; + } + } + + __ntfs_attr_init( na, ni, type, name, name_len ); + + /* + * Wipe the flags in case they are not zero for an attribute list + * attribute. Windows does not complain about invalid flags and chkdsk + * does not detect or fix them so we need to cope with it, too. + */ + if ( type == AT_ATTRIBUTE_LIST ) + a->flags = 0; + + if ( ( type == AT_DATA ) && !a->initialized_size ) + { + /* + * Define/redefine the compression state if stream is + * empty, based on the compression mark on parent + * directory (for unnamed data streams) or on current + * inode (for named data streams). The compression mark + * may change any time, the compression state can only + * change when stream is wiped out. + * + * 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; + ntfs_log_leave( "\n" ); + return na; put_err_out: - ntfs_attr_put_search_ctx(ctx); + ntfs_attr_put_search_ctx( ctx ); err_out: - free(newname); - free(na); - na = NULL; - goto out; + free( newname ); + free( na ); + na = NULL; + goto out; } /** * ntfs_attr_close - free an ntfs attribute structure - * @na: ntfs attribute structure to free + * @na: ntfs attribute structure to free * * Release all memory associated with the ntfs attribute @na and then release * @na itself. */ -void ntfs_attr_close(ntfs_attr *na) +void ntfs_attr_close( ntfs_attr *na ) { - if (!na) - return; - if (NAttrNonResident(na) && na->rl) - free(na->rl); - /* Don't release if using an internal constant. */ - if (na->name != AT_UNNAMED && na->name != NTFS_INDEX_I30 - && na->name != STREAM_SDS) - free(na->name); - free(na); + 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 ); } /** * ntfs_attr_map_runlist - map (a part of) a runlist of an ntfs attribute - * @na: ntfs attribute for which to map (part of) a runlist - * @vcn: map runlist part containing this vcn + * @na: ntfs attribute for which to map (part of) a runlist + * @vcn: map runlist part containing this vcn * * Map the part of a runlist containing the @vcn of the ntfs attribute @na. * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn) +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; } /** * ntfs_attr_map_whole_runlist - map the whole runlist of an ntfs attribute - * @na: ntfs attribute for which to map the runlist + * @na: ntfs attribute for which to map the runlist * * Map the whole runlist of the ntfs attribute @na. For an attribute made up * of only one attribute extent this is the same as calling @@ -600,110 +636,120 @@ int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn) * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_map_whole_runlist(ntfs_attr *na) +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); + /* 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; + ntfs_log_leave( "\n" ); + return ret; } /** * ntfs_attr_vcn_to_lcn - convert a vcn into a lcn given an ntfs attribute - * @na: ntfs attribute whose runlist to use for conversion - * @vcn: vcn to convert + * @na: ntfs attribute whose runlist to use for conversion + * @vcn: vcn to convert * * Convert the virtual cluster number @vcn of an attribute into a logical * cluster number (lcn) of a device using the runlist @na->rl to map vcns to @@ -714,47 +760,48 @@ out: * * Since lcns must be >= 0, we use negative return values with special meaning: * - * Return value Meaning / Description + * Return value Meaning / Description * ========================================== - * -1 = LCN_HOLE Hole / not allocated on disk. - * -3 = LCN_ENOENT There is no such vcn in the attribute. - * -4 = LCN_EINVAL Input parameter error. - * -5 = LCN_EIO Corrupt fs, disk i/o error, or not enough memory. + * -1 = LCN_HOLE Hole / not allocated on disk. + * -3 = LCN_ENOENT There is no such vcn in the attribute. + * -4 = LCN_EINVAL Input parameter error. + * -5 = LCN_EIO Corrupt fs, disk i/o error, or not enough memory. */ -LCN ntfs_attr_vcn_to_lcn(ntfs_attr *na, const VCN vcn) +LCN 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); + ntfs_log_trace( "Entering for inode 0x%llx, attr 0x%x.\n", ( unsigned long + long )na->ni->mft_no, na->type ); retry: - /* Convert vcn to lcn. If that fails map the runlist and retry once. */ - lcn = ntfs_rl_vcn_to_lcn(na->rl, vcn); - if (lcn >= 0) - return lcn; - if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) { - is_retry = TRUE; - goto retry; - } - /* - * If the attempt to map the runlist failed, or we are getting - * LCN_RL_NOT_MAPPED despite having mapped the attribute extent - * successfully, something is really badly wrong... - */ - if (!is_retry || lcn == (LCN)LCN_RL_NOT_MAPPED) - return (LCN)LCN_EIO; - /* lcn contains the appropriate error code. */ - return lcn; + /* Convert vcn to lcn. If that fails map the runlist and retry once. */ + lcn = ntfs_rl_vcn_to_lcn( na->rl, vcn ); + if ( lcn >= 0 ) + return lcn; + if ( !is_retry && !ntfs_attr_map_runlist( na, vcn ) ) + { + is_retry = TRUE; + goto retry; + } + /* + * If the attempt to map the runlist failed, or we are getting + * LCN_RL_NOT_MAPPED despite having mapped the attribute extent + * successfully, something is really badly wrong... + */ + if ( !is_retry || lcn == ( LCN )LCN_RL_NOT_MAPPED ) + return ( LCN )LCN_EIO; + /* lcn contains the appropriate error code. */ + return lcn; } /** * ntfs_attr_find_vcn - find a vcn in the runlist of an ntfs attribute - * @na: ntfs attribute whose runlist to search - * @vcn: vcn to find + * @na: ntfs attribute whose runlist to search + * @vcn: vcn to find * * Find the virtual cluster number @vcn in the runlist of the ntfs attribute * @na and return the the address of the runlist element containing the @vcn. @@ -766,288 +813,321 @@ retry: * * If there is an error return NULL with errno set to the error code. The * following error codes are defined: - * EINVAL Input parameter error. - * ENOENT There is no such vcn in the runlist. - * ENOMEM Not enough memory. - * EIO I/O error or corrupt metadata. + * EINVAL Input parameter error. + * ENOENT There is no such vcn in the runlist. + * ENOMEM Not enough memory. + * EIO I/O error or corrupt metadata. */ -runlist_element *ntfs_attr_find_vcn(ntfs_attr *na, const VCN vcn) +runlist_element *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); + ntfs_log_trace( "Entering for inode 0x%llx, attr 0x%x, vcn %llx\n", + ( unsigned long long )na->ni->mft_no, na->type, + ( long long )vcn ); retry: - rl = na->rl; - if (!rl) - goto map_rl; - if (vcn < rl[0].vcn) - goto map_rl; - while (rl->length) { - if (vcn < rl[1].vcn) { - if (rl->lcn >= (LCN)LCN_HOLE) - return rl; - break; - } - rl++; - } - switch (rl->lcn) { - case (LCN)LCN_RL_NOT_MAPPED: - goto map_rl; - case (LCN)LCN_ENOENT: - errno = ENOENT; - break; - case (LCN)LCN_EINVAL: - errno = EINVAL; - break; - default: - errno = EIO; - break; - } - return NULL; + rl = na->rl; + if ( !rl ) + goto map_rl; + if ( vcn < rl[0].vcn ) + goto map_rl; + while ( rl->length ) + { + if ( vcn < rl[1].vcn ) + { + if ( rl->lcn >= ( LCN )LCN_HOLE ) + return rl; + break; + } + rl++; + } + switch ( rl->lcn ) + { + case ( LCN )LCN_RL_NOT_MAPPED: + goto map_rl; + case ( LCN )LCN_ENOENT: + errno = ENOENT; + break; + case ( LCN )LCN_EINVAL: + errno = EINVAL; + break; + default: + errno = EIO; + break; + } + return NULL; map_rl: - /* The @vcn is in an unmapped region, map the runlist and retry. */ - if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) { - is_retry = TRUE; - goto retry; - } - /* - * If we already retried or the mapping attempt failed something has - * gone badly wrong. EINVAL and ENOENT coming from a failed mapping - * attempt are equivalent to errors for us as they should not happen - * in our code paths. - */ - if (is_retry || errno == EINVAL || errno == ENOENT) - errno = EIO; - return NULL; + /* The @vcn is in an unmapped region, map the runlist and retry. */ + if ( !is_retry && !ntfs_attr_map_runlist( na, vcn ) ) + { + is_retry = TRUE; + goto retry; + } + /* + * If we already retried or the mapping attempt failed something has + * gone badly wrong. EINVAL and ENOENT coming from a failed mapping + * attempt are equivalent to errors for us as they should not happen + * in our code paths. + */ + if ( is_retry || errno == EINVAL || errno == ENOENT ) + errno = EIO; + return NULL; } /** * ntfs_attr_pread_i - see description at ntfs_attr_pread() - */ -static s64 ntfs_attr_pread_i(ntfs_attr *na, const s64 pos, s64 count, void *b) + */ +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)) { + 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); + ntfs_attr_put_search_ctx( ctx ); + return -1; + } + val = ( char* )ctx->attr + le16_to_cpu( ctx->attr->value_offset ); + if ( val < ( char* )ctx->attr || val + + le32_to_cpu( ctx->attr->value_length ) > + ( char* )ctx->mrec + vol->mft_record_size ) + { + errno = EIO; + ntfs_log_perror( "%s: Sanity check failed", __FUNCTION__ ); + goto res_err_out; + } + memcpy( b, val + pos, count ); + ntfs_attr_put_search_ctx( ctx ); + return count; + } + total = total2 = 0; + /* Zero out reads beyond initialized size. */ + if ( pos + count > max_init ) + { + if ( pos >= max_init ) + { + memset( b, 0, count ); + return count; + } + total2 = pos + count - max_init; + count -= total2; + memset( ( u8* )b + count, 0, total2 ); + } + /* + * for encrypted non-resident attributes with efs_raw set + * the last two bytes aren't read from disk but contain + * the number of padding bytes so original size can be + * restored + */ + if ( na->ni->vol->efs_raw && + ( na->data_flags & ATTR_IS_ENCRYPTED ) && + ( ( pos + count ) > max_init - 2 ) ) + { + efs_padding_length = 511 - ( ( na->data_size - 1 ) & 511 ); + if ( pos + count == max_init ) + { + if ( count == 1 ) + { + *( ( u8* )b + count - 1 ) = ( u8 )( efs_padding_length >> 8 ); + count--; + total2++; + } + else + { + *( u16* )( ( u8* )b + count - 2 ) = cpu_to_le16( efs_padding_length ); + count -= 2; + total2 += 2; + } + } + else + { + *( ( u8* )b + count - 1 ) = ( u8 )( efs_padding_length & 0xff ); + count--; + total2++; + } + } + + /* Find the runlist element containing the vcn. */ + rl = ntfs_attr_find_vcn( na, pos >> vol->cluster_size_bits ); + if ( !rl ) + { + /* + * If the vcn is not present it is an out of bounds read. + * However, we already truncated the read to the data_size, + * so getting this here is an error. + */ + if ( errno == ENOENT ) + { + errno = EIO; + ntfs_log_perror( "%s: Failed to find VCN #1", __FUNCTION__ ); + } + return -1; + } + /* + * Gather the requested data into the linear destination buffer. Note, + * a partial final vcn is taken care of by the @count capping of read + * length. + */ + ofs = pos - ( rl->vcn << vol->cluster_size_bits ); + for ( ; count; rl++, ofs = 0 ) + { + if ( rl->lcn == LCN_RL_NOT_MAPPED ) + { + rl = ntfs_attr_find_vcn( na, rl->vcn ); + if ( !rl ) + { + if ( errno == ENOENT ) + { + errno = EIO; + ntfs_log_perror( "%s: Failed to find VCN #2", + __FUNCTION__ ); + } + goto rl_err_out; + } + /* Needed for case when runs merged. */ + ofs = pos + total - ( rl->vcn << vol->cluster_size_bits ); + } + if ( !rl->length ) + { + errno = EIO; + ntfs_log_perror( "%s: Zero run length", __FUNCTION__ ); + goto rl_err_out; + } + if ( rl->lcn < ( LCN )0 ) + { + if ( rl->lcn != ( LCN )LCN_HOLE ) + { + ntfs_log_perror( "%s: Bad run (%lld)", + __FUNCTION__, + ( long long )rl->lcn ); + goto rl_err_out; + } + /* It is a hole, just zero the matching @b range. */ + to_read = min( count, ( rl->length << + vol->cluster_size_bits ) - ofs ); + memset( b, 0, to_read ); + /* Update progress counters. */ + total += to_read; + count -= to_read; + b = ( u8* )b + to_read; + continue; + } + /* It is a real lcn, read it into @dst. */ + to_read = min( count, ( rl->length << vol->cluster_size_bits ) - + ofs ); retry: - ntfs_log_trace("Reading %lld bytes from vcn %lld, lcn %lld, ofs" - " %lld.\n", (long long)to_read, (long long)rl->vcn, - (long long )rl->lcn, (long long)ofs); - br = ntfs_pread(vol->dev, (rl->lcn << vol->cluster_size_bits) + - ofs, to_read, b); - /* If everything ok, update progress counters and continue. */ - if (br > 0) { - total += br; - count -= br; - b = (u8*)b + br; - } - if (br == to_read) - continue; - /* If the syscall was interrupted, try again. */ - if (br == (s64)-1 && errno == EINTR) - goto retry; - if (total) - return total; - if (!br) - errno = EIO; - ntfs_log_perror("%s: ntfs_pread failed", __FUNCTION__); - return -1; - } - /* Finally, return the number of bytes read. */ - return total + total2; + ntfs_log_trace( "Reading %lld bytes from vcn %lld, lcn %lld, ofs" + " %lld.\n", ( long long )to_read, ( long long )rl->vcn, + ( long long )rl->lcn, ( long long )ofs ); + br = ntfs_pread( vol->dev, ( rl->lcn << vol->cluster_size_bits ) + + ofs, to_read, b ); + /* If everything ok, update progress counters and continue. */ + if ( br > 0 ) + { + total += br; + count -= br; + b = ( u8* )b + br; + } + if ( br == to_read ) + continue; + /* If the syscall was interrupted, try again. */ + if ( br == ( s64 ) - 1 && errno == EINTR ) + goto retry; + if ( total ) + return total; + if ( !br ) + errno = EIO; + ntfs_log_perror( "%s: ntfs_pread failed", __FUNCTION__ ); + return -1; + } + /* Finally, return the number of bytes read. */ + return total + total2; rl_err_out: - if (total) - return total; - errno = EIO; - return -1; + if ( total ) + return total; + errno = EIO; + return -1; } /** * ntfs_attr_pread - read from an attribute specified by an ntfs_attr structure - * @na: ntfs attribute to read from - * @pos: byte position in the attribute to begin reading from - * @count: number of bytes to read - * @b: output data buffer + * @na: ntfs attribute to read from + * @pos: byte position in the attribute to begin reading from + * @count: number of bytes to read + * @b: output data buffer * * This function will read @count bytes starting at offset @pos from the ntfs * attribute @na into the data buffer @b. @@ -1061,563 +1141,634 @@ rl_err_out: * to the return code of ntfs_pread(), or to EINVAL in case of invalid * arguments. */ -s64 ntfs_attr_pread(ntfs_attr *na, const s64 pos, s64 count, void *b) +s64 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) +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); + ntfs_log_trace( "pos %lld, count %lld\n", ( long long )pos, + ( long long )count ); + + if ( !na || pos < 0 || count < 0 ) + { + errno = EINVAL; + goto err_out; + } + + buf = ntfs_calloc( NTFS_BUF_SIZE ); + if ( !buf ) + goto err_out; + + rli = na->rl; + ofsi = 0; + vol = na->ni->vol; + while ( pos < end ) + { + while ( rli->length && ( ofsi + ( rli->length << + vol->cluster_size_bits ) <= pos ) ) + { + ofsi += ( rli->length << vol->cluster_size_bits ); + rli++; + } + size = min( end - pos, NTFS_BUF_SIZE ); + written = ntfs_rl_pwrite( vol, rli, ofsi, pos, size, buf ); + if ( written <= 0 ) + { + ntfs_log_perror( "Failed to zero space" ); + goto err_free; + } + pos += written; + } + + ret = 0; +err_free: + free( buf ); err_out: - return ret; + return ret; } -static int ntfs_attr_fill_hole(ntfs_attr *na, s64 count, s64 *ofs, - runlist_element **rl, VCN *update_from) +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; + 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; + return ret; } -static int stuff_hole(ntfs_attr *na, const s64 pos); +static int stuff_hole( ntfs_attr *na, const s64 pos ); /* - * Split an existing hole for overwriting with data - * The hole may have to be split into two or three parts, so - * that the overwritten part fits within a single compression block + * Split an existing hole for overwriting with data + * The hole may have to be split into two or three parts, so + * that the overwritten part fits within a single compression block * - * No cluster allocation is needed, this will be done later in - * standard hole filling, hence no need to reserve runs for - * future needs. + * No cluster allocation is needed, this will be done later in + * standard hole filling, hence no need to reserve runs for + * future needs. * - * Returns the number of clusters with existing compressed data - * in the compression block to be written to - * (or the full block, if it was a full hole) - * -1 if there were an error + * Returns the number of clusters with existing compressed data + * in the compression block to be written to + * (or the full block, if it was a full hole) + * -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 */ + /* + * 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; + 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 ); } /* - * Borrow space from adjacent hole for appending data - * The hole may have to be split so that the end of hole is not - * affected by cluster allocation and overwriting - * Cluster allocation is needed for the overwritten compression block + * Borrow space from adjacent hole for appending data + * The hole may have to be split so that the end of hole is not + * affected by cluster allocation and overwriting + * Cluster allocation is needed for the overwritten compression block * - * Must always leave two unused entries in the runlist + * Must always leave two unused entries in the runlist * - * Returns the number of clusters with existing compressed data - * in the compression block to be written to - * -1 if there were an error + * Returns the number of clusters with existing compressed data + * in the compression block to be written to + * -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 ); } /** * ntfs_attr_pwrite - positioned write to an ntfs attribute - * @na: ntfs attribute to write to - * @pos: position in the attribute to write to - * @count: number of bytes to write - * @b: data buffer to write to disk + * @na: ntfs attribute to write to + * @pos: position in the attribute to write to + * @count: number of bytes to write + * @b: data buffer to write to disk * * This function will write @count bytes from data buffer @b to ntfs attribute * @na at position @pos. @@ -1631,706 +1782,780 @@ static int borrow_from_hole(ntfs_attr *na, runlist_element **prl, * appropriately to the return code of ntfs_pwrite(), or to EINVAL in case of * invalid arguments. */ -s64 ntfs_attr_pwrite(ntfs_attr *na, const s64 pos, s64 count, const void *b) +s64 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); + /* 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; + 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; + 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; + total = -1; + goto out; } -int ntfs_attr_pclose(ntfs_attr *na) +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 ); + + 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); + 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); + } + 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. - */ + /* + * 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; + 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; + ok = FALSE; + goto out; } /** * ntfs_attr_mst_pread - multi sector transfer protected ntfs attribute read - * @na: multi sector transfer protected ntfs attribute to read from - * @pos: byte position in the attribute to begin reading from - * @bk_cnt: number of mst protected blocks to read - * @bk_size: size of each mst protected block in bytes - * @dst: output data buffer + * @na: multi sector transfer protected ntfs attribute to read from + * @pos: byte position in the attribute to begin reading from + * @bk_cnt: number of mst protected blocks to read + * @bk_size: size of each mst protected block in bytes + * @dst: output data buffer * * This function will read @bk_cnt blocks of size @bk_size bytes each starting * at offset @pos from the ntfs attribute @na into the data buffer @b. @@ -2353,38 +2578,39 @@ 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; } /** * ntfs_attr_mst_pwrite - multi sector transfer protected ntfs attribute write - * @na: multi sector transfer protected ntfs attribute to write to - * @pos: position in the attribute to write to - * @bk_cnt: number of mst protected blocks to write - * @bk_size: size of each mst protected block in bytes - * @src: data buffer to write to disk + * @na: multi sector transfer protected ntfs attribute to write to + * @pos: position in the attribute to write to + * @bk_cnt: number of mst protected blocks to write + * @bk_size: size of each mst protected block in bytes + * @src: data buffer to write to disk * * This function will write @bk_cnt blocks of size @bk_size bytes each from * data buffer @b to multi sector transfer (mst) protected ntfs attribute @na @@ -2408,60 +2634,64 @@ 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; } /** * ntfs_attr_find - find (next) attribute in mft record - * @type: attribute type to find - * @name: attribute name to find (optional, i.e. NULL means don't care) - * @name_len: attribute name length (only needed if @name present) - * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present) - * @val: attribute value to find (optional, resident attributes only) - * @val_len: attribute value length - * @ctx: search context with mft record and attribute to search from + * @type: attribute type to find + * @name: attribute name to find (optional, i.e. NULL means don't care) + * @name_len: attribute name length (only needed if @name present) + * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present) + * @val: attribute value to find (optional, resident attributes only) + * @val_len: attribute value length + * @ctx: search context with mft record and attribute to search from * * You shouldn't need to call this function directly. Use lookup_attr() instead. * @@ -2521,165 +2751,187 @@ s64 ntfs_attr_mst_pwrite(ntfs_attr *na, const s64 pos, s64 bk_cnt, * rely on being able to find the first extent in the base mft record. * * Warning: Never use @val when looking for attribute types which can be - * non-resident as this most likely will result in a crash! + * 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) +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 *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; } /** * ntfs_external_attr_find - find an attribute in the attribute list of an inode - * @type: attribute type to find - * @name: attribute name to find (optional, i.e. NULL means don't care) - * @name_len: attribute name length (only needed if @name present) - * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present) - * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only) - * @val: attribute value to find (optional, resident attributes only) - * @val_len: attribute value length - * @ctx: search context with mft record and attribute to search from + * @type: attribute type to find + * @name: attribute name to find (optional, i.e. NULL means don't care) + * @name_len: attribute name length (only needed if @name present) + * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present) + * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only) + * @val: attribute value to find (optional, resident attributes only) + * @val_len: attribute value length + * @ctx: search context with mft record and attribute to search from * * You shouldn't need to call this function directly. Use ntfs_attr_lookup() * instead. @@ -2735,345 +2987,370 @@ char *ntfs_attr_name_get(const ntfschar *uname, const int uname_len) * @ctx->al_entry is set to NULL also (see above). * * The following error codes are defined: - * ENOENT Attribute not found, not an error as such. - * EINVAL Invalid arguments. - * EIO I/O error or corrupt data structures found. - * ENOMEM Not enough memory to allocate necessary buffers. + * ENOENT Attribute not found, not an error as such. + * EINVAL Invalid arguments. + * 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; + 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; + /* + * 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. - */ + if ( MREF_LE( al_entry->mft_reference ) == ni->mft_no ) + { + if ( MSEQNO_LE( al_entry->mft_reference ) != + le16_to_cpu( + ni->mrec->sequence_number ) ) + { + ntfs_log_error( "Found stale mft reference in " + "attribute list!\n" ); + break; + } + } + else /* Mft references do not match. */ + { + /* Do we want the base record back? */ + if ( MREF_LE( al_entry->mft_reference ) == + base_ni->mft_no ) + { + ni = ctx->ntfs_ino = base_ni; + ctx->mrec = ctx->base_mrec; + } + else + { + /* We want an extent record. */ + ni = ntfs_extent_inode_open( base_ni, + al_entry->mft_reference ); + if ( !ni ) + break; + ctx->ntfs_ino = ni; + ctx->mrec = ni->mrec; + } + } + a = ctx->attr = ( ATTR_RECORD* )( ( char* )ctx->mrec + + le16_to_cpu( ctx->mrec->attrs_offset ) ); + /* + * ctx->ntfs_ino, ctx->mrec, and ctx->attr now point to the + * mft record containing the attribute represented by the + * current al_entry. + * + * We could call into ntfs_attr_find() to find the right + * attribute in this mft record but this would be less + * efficient and not quite accurate as ntfs_attr_find() ignores + * the attribute instance numbers for example which become + * important when one plays with attribute lists. Also, because + * a proper match has been found in the attribute list entry + * above, the comparison can now be optimized. So it is worth + * re-implementing a simplified ntfs_attr_find() here. + * + * Use a manual loop so we can still use break and continue + * with the same meanings as above. + */ do_next_attr_loop: - if ((char*)a < (char*)ctx->mrec || (char*)a > (char*)ctx->mrec + - le32_to_cpu(ctx->mrec->bytes_allocated)) - break; - if (a->type == AT_END) - continue; - if (!a->length) - break; - if (al_entry->instance != a->instance) - goto do_next_attr; - /* - * If the type and/or the name are/is mismatched between the - * attribute list entry and the attribute record, there is - * corruption so we break and return error EIO. - */ - if (al_entry->type != a->type) - break; - if (!ntfs_names_are_equal((ntfschar*)((char*)a + - le16_to_cpu(a->name_offset)), - a->name_length, al_name, - al_name_len, CASE_SENSITIVE, - vol->upcase, vol->upcase_len)) - break; - ctx->attr = a; - /* - * If no @val specified or @val specified and it matches, we - * have found it! Also, if !@type, it is an enumeration, so we - * want the current attribute. - */ - if ((type == AT_UNUSED) || !val || (!a->non_resident && - le32_to_cpu(a->value_length) == val_len && - !memcmp((char*)a + le16_to_cpu(a->value_offset), - val, val_len))) { - return 0; - } + if ( ( char* )a < ( char* )ctx->mrec || ( char* )a > ( char* )ctx->mrec + + le32_to_cpu( ctx->mrec->bytes_allocated ) ) + break; + if ( a->type == AT_END ) + continue; + if ( !a->length ) + break; + if ( al_entry->instance != a->instance ) + goto do_next_attr; + /* + * If the type and/or the name are/is mismatched between the + * attribute list entry and the attribute record, there is + * corruption so we break and return error EIO. + */ + if ( al_entry->type != a->type ) + break; + if ( !ntfs_names_are_equal( ( ntfschar* )( ( char* )a + + le16_to_cpu( a->name_offset ) ), + a->name_length, al_name, + al_name_len, CASE_SENSITIVE, + vol->upcase, vol->upcase_len ) ) + break; + ctx->attr = a; + /* + * If no @val specified or @val specified and it matches, we + * have found it! Also, if !@type, it is an enumeration, so we + * want the current attribute. + */ + if ( ( type == AT_UNUSED ) || !val || ( !a->non_resident && + le32_to_cpu( a->value_length ) == val_len && + !memcmp( ( char* )a + le16_to_cpu( a->value_offset ), + val, val_len ) ) ) + { + return 0; + } do_next_attr: - /* Proceed to the next attribute in the current mft record. */ - a = (ATTR_RECORD*)((char*)a + le32_to_cpu(a->length)); - goto do_next_attr_loop; - } - if (ni != base_ni) { - ctx->ntfs_ino = base_ni; - ctx->mrec = ctx->base_mrec; - ctx->attr = ctx->base_attr; - } - errno = EIO; - ntfs_log_perror("Inode is corrupt (%lld)", (long long)base_ni->mft_no); - return -1; + /* Proceed to the next attribute in the current mft record. */ + a = ( ATTR_RECORD* )( ( char* )a + le32_to_cpu( a->length ) ); + goto do_next_attr_loop; + } + if ( ni != base_ni ) + { + ctx->ntfs_ino = base_ni; + ctx->mrec = ctx->base_mrec; + ctx->attr = ctx->base_attr; + } + errno = EIO; + ntfs_log_perror( "Inode is corrupt (%lld)", ( long long )base_ni->mft_no ); + return -1; not_found: - /* - * If we were looking for AT_END or we were enumerating and reached the - * end, we reset the search context @ctx and use ntfs_attr_find() to - * seek to the end of the base mft record. - */ - if (type == AT_UNUSED || type == AT_END) { - ntfs_attr_reinit_search_ctx(ctx); - return ntfs_attr_find(AT_END, name, name_len, ic, val, val_len, - ctx); - } - /* - * The attribute wasn't found. Before we return, we want to ensure - * @ctx->mrec and @ctx->attr indicate the position at which the - * attribute should be inserted in the base mft record. Since we also - * want to preserve @ctx->al_entry we cannot reinitialize the search - * context using ntfs_attr_reinit_search_ctx() as this would set - * @ctx->al_entry to NULL. Thus we do the necessary bits manually (see - * ntfs_attr_init_search_ctx() below). Note, we _only_ preserve - * @ctx->al_entry as the remaining fields (base_*) are identical to - * their non base_ counterparts and we cannot set @ctx->base_attr - * correctly yet as we do not know what @ctx->attr will be set to by - * the call to ntfs_attr_find() below. - */ - ctx->mrec = ctx->base_mrec; - ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + - le16_to_cpu(ctx->mrec->attrs_offset)); - ctx->is_first = TRUE; - ctx->ntfs_ino = ctx->base_ntfs_ino; - ctx->base_ntfs_ino = NULL; - ctx->base_mrec = NULL; - ctx->base_attr = NULL; - /* - * In case there are multiple matches in the base mft record, need to - * keep enumerating until we get an attribute not found response (or - * another error), otherwise we would keep returning the same attribute - * over and over again and all programs using us for enumeration would - * lock up in a tight loop. - */ - { - int ret; + /* + * If we were looking for AT_END or we were enumerating and reached the + * end, we reset the search context @ctx and use ntfs_attr_find() to + * seek to the end of the base mft record. + */ + if ( type == AT_UNUSED || type == AT_END ) + { + ntfs_attr_reinit_search_ctx( ctx ); + return ntfs_attr_find( AT_END, name, name_len, ic, val, val_len, + ctx ); + } + /* + * The attribute wasn't found. Before we return, we want to ensure + * @ctx->mrec and @ctx->attr indicate the position at which the + * attribute should be inserted in the base mft record. Since we also + * want to preserve @ctx->al_entry we cannot reinitialize the search + * context using ntfs_attr_reinit_search_ctx() as this would set + * @ctx->al_entry to NULL. Thus we do the necessary bits manually (see + * ntfs_attr_init_search_ctx() below). Note, we _only_ preserve + * @ctx->al_entry as the remaining fields (base_*) are identical to + * their non base_ counterparts and we cannot set @ctx->base_attr + * correctly yet as we do not know what @ctx->attr will be set to by + * the call to ntfs_attr_find() below. + */ + ctx->mrec = ctx->base_mrec; + ctx->attr = ( ATTR_RECORD* )( ( u8* )ctx->mrec + + le16_to_cpu( ctx->mrec->attrs_offset ) ); + ctx->is_first = TRUE; + ctx->ntfs_ino = ctx->base_ntfs_ino; + ctx->base_ntfs_ino = NULL; + ctx->base_mrec = NULL; + ctx->base_attr = NULL; + /* + * In case there are multiple matches in the base mft record, need to + * keep enumerating until we get an attribute not found response (or + * another error), otherwise we would keep returning the same attribute + * over and over again and all programs using us for enumeration would + * lock up in a tight loop. + */ + { + int ret; - do { - ret = ntfs_attr_find(type, name, name_len, ic, val, - val_len, ctx); - } while (!ret); - return ret; - } + do + { + ret = ntfs_attr_find( type, name, name_len, ic, val, + val_len, ctx ); + } + while ( !ret ); + return ret; + } } /** * ntfs_attr_lookup - find an attribute in an ntfs inode - * @type: attribute type to find - * @name: attribute name to find (optional, i.e. NULL means don't care) - * @name_len: attribute name length (only needed if @name present) - * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present) - * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only) - * @val: attribute value to find (optional, resident attributes only) - * @val_len: attribute value length - * @ctx: search context with mft record and attribute to search from + * @type: attribute type to find + * @name: attribute name to find (optional, i.e. NULL means don't care) + * @name_len: attribute name length (only needed if @name present) + * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present) + * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only) + * @val: attribute value to find (optional, resident attributes only) + * @val_len: attribute value length + * @ctx: search context with mft record and attribute to search from * * Find an attribute in an ntfs inode. On first search @ctx->ntfs_ino must * be the base mft record and @ctx must have been obtained from a call to @@ -3126,48 +3403,49 @@ not_found: * * * The following error codes are defined: - * ENOENT Attribute not found, not an error as such. - * EINVAL Invalid arguments. - * EIO I/O error or corrupt data structures found. - * ENOMEM Not enough memory to allocate necessary buffers. + * ENOENT Attribute not found, not an error as such. + * EINVAL Invalid arguments. + * 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); + ntfs_log_enter( "Entering for attribute type 0x%x\n", type ); + + if ( !ctx || !ctx->mrec || !ctx->attr || ( name && name != AT_UNNAMED && + ( !ctx->ntfs_ino || !( vol = ctx->ntfs_ino->vol ) || + !vol->upcase || !vol->upcase_len ) ) ) + { + errno = EINVAL; + ntfs_log_perror( "%s", __FUNCTION__ ); + goto out; + } + + if ( ctx->base_ntfs_ino ) + base_ni = ctx->base_ntfs_ino; + else + base_ni = ctx->ntfs_ino; + if ( !base_ni || !NInoAttrList( base_ni ) || type == AT_ATTRIBUTE_LIST ) + ret = ntfs_attr_find( type, name, name_len, ic, val, val_len, ctx ); + else + ret = ntfs_external_attr_find( type, name, name_len, ic, + lowest_vcn, val, val_len, ctx ); out: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave( "\n" ); + return ret; } /** * ntfs_attr_position - find given or next attribute type in an ntfs inode - * @type: attribute type to start lookup - * @ctx: search context with mft record and attribute to search from + * @type: attribute type to start lookup + * @ctx: search context with mft record and attribute to search from * * Find an attribute type in an ntfs inode or the next attribute which is not * the AT_END attribute. Please see more details at ntfs_attr_lookup. @@ -3176,80 +3454,83 @@ out: * error code. * * The following error codes are defined: - * EINVAL Invalid arguments. - * EIO I/O error or corrupt data structures found. - * ENOMEM Not enough memory to allocate necessary buffers. - * ENOSPC No attribute was found after 'type', only AT_END. + * EINVAL Invalid arguments. + * EIO I/O error or corrupt data structures found. + * ENOMEM Not enough memory to allocate necessary buffers. + * ENOSPC No attribute was found after 'type', only AT_END. */ -int ntfs_attr_position(const ATTR_TYPES type, ntfs_attr_search_ctx *ctx) +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; } /** * ntfs_attr_init_search_ctx - initialize an attribute search context - * @ctx: attribute search context to initialize - * @ni: ntfs inode with which to initialize the search context - * @mrec: mft record with which to initialize the search context + * @ctx: attribute search context to initialize + * @ni: ntfs inode with which to initialize the search context + * @mrec: mft record with which to initialize the search context * * 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; } /** * ntfs_attr_reinit_search_ctx - reinitialize an attribute search context - * @ctx: attribute search context to reinitialize + * @ctx: attribute search context to reinitialize * * Reinitialize the attribute search context @ctx. * * This is used when a search for a new attribute is being started to reset * the search context to the beginning. */ -void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx) +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; } /** * ntfs_attr_get_search_ctx - allocate/initialize a new attribute search context - * @ni: ntfs inode with which to initialize the search context - * @mrec: mft record with which to initialize the search context + * @ni: ntfs inode with which to initialize the search context + * @mrec: mft record with which to initialize the search context * * Allocate a new attribute search context, initialize it with @ni and @mrec, * and return it. Return NULL on error with errno set. @@ -3260,37 +3541,38 @@ void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx) * be NULL and @mrec to be set. Do NOT do this unless you understand the * implications!!! For example it is no longer safe to call ntfs_attr_lookup(). */ -ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec) +ntfs_attr_search_ctx *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; } /** * ntfs_attr_put_search_ctx - release an attribute search context - * @ctx: attribute search context to free + * @ctx: attribute search context to free * * Release the attribute search context @ctx. */ -void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx) +void ntfs_attr_put_search_ctx( ntfs_attr_search_ctx *ctx ) { - // NOTE: save errno if it could change and function stays void! - free(ctx); + // NOTE: save errno if it could change and function stays void! + free( ctx ); } /** * ntfs_attr_find_in_attrdef - find an attribute in the $AttrDef system file - * @vol: ntfs volume to which the attribute belongs - * @type: attribute type which to find + * @vol: ntfs volume to which the attribute belongs + * @type: attribute type which to find * * Search for the attribute definition record corresponding to the attribute * @type in the $AttrDef system file. @@ -3298,97 +3580,102 @@ void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx) * Return the attribute type definition record if found and NULL if not found * or an error occurred. On error the error code is stored in errno. The * following error codes are defined: - * ENOENT - The attribute @type is not specified in $AttrDef. - * EINVAL - Invalid parameters (e.g. @vol is not valid). + * 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; } /** * ntfs_attr_size_bounds_check - check a size of an attribute type for validity - * @vol: ntfs volume to which the attribute belongs - * @type: attribute type which to check - * @size: size which to check + * @vol: ntfs volume to which the attribute belongs + * @type: attribute type which to check + * @size: size which to check * * Check whether the @size in bytes is valid for an attribute of @type on the * ntfs volume @vol. This information is obtained from $AttrDef system file. * * Return 0 if valid and -1 if not valid or an error occurred. On error the * error code is stored in errno. The following error codes are defined: - * ERANGE - @size is not valid for the attribute @type. - * ENOENT - The attribute @type is not specified in $AttrDef. - * EINVAL - Invalid parameters (e.g. @size is < 0 or @vol is not valid). + * ERANGE - @size is not valid for the attribute @type. + * 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; } /** * ntfs_attr_can_be_non_resident - check if an attribute can be non-resident - * @vol: ntfs volume to which the attribute belongs - * @type: attribute type to check - * @name: attribute name to check - * @name_len: attribute name length + * @vol: ntfs volume to which the attribute belongs + * @type: attribute type to check + * @name: attribute name to check + * @name_len: attribute name length * * Check whether the attribute of @type and @name with name length @name_len on * the ntfs volume @vol is allowed to be non-resident. This information is @@ -3398,49 +3685,51 @@ int ntfs_attr_size_bounds_check(const ntfs_volume *vol, const ATTR_TYPES type, * Return 0 if the attribute is allowed to be non-resident and -1 if not or an * error occurred. On error the error code is stored in errno. The following * error codes are defined: - * EPERM - The attribute is not allowed to be non-resident. - * ENOENT - The attribute @type is not specified in $AttrDef. - * EINVAL - Invalid parameters (e.g. @vol is not valid). + * EPERM - The attribute is not allowed to be non-resident. + * 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; } /** * ntfs_attr_can_be_resident - check if an attribute can be resident - * @vol: ntfs volume to which the attribute belongs - * @type: attribute type which to check + * @vol: ntfs volume to which the attribute belongs + * @type: attribute type which to check * * Check whether the attribute of @type on the ntfs volume @vol is allowed to * be resident. This information is derived from our ntfs knowledge and may @@ -3451,496 +3740,530 @@ static int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPE * Return 0 if the attribute is allowed to be resident and -1 if not or an * error occurred. On error the error code is stored in errno. The following * error codes are defined: - * EPERM - The attribute is not allowed to be resident. - * EINVAL - Invalid parameters (e.g. @vol is not valid). + * EPERM - The attribute is not allowed to be resident. + * EINVAL - Invalid parameters (e.g. @vol is not valid). * * Warning: In the system file $MFT the attribute $Bitmap must be non-resident - * otherwise windows will not boot (blue screen of death)! We cannot - * check for this here as we don't know which inode's $Bitmap is being - * asked about so the caller needs to special case this. + * otherwise windows will not boot (blue screen of death)! We cannot + * check for this here as we don't know which inode's $Bitmap is being + * asked about so the caller needs to special case this. */ -int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPES type) +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; } /** * ntfs_make_room_for_attr - make room for an attribute inside an mft record - * @m: mft record - * @pos: position at which to make space - * @size: byte size to make available at this position + * @m: mft record + * @pos: position at which to make space + * @size: byte size to make available at this position * * @pos points to the attribute in front of which we want to make space. * * Return 0 on success or -1 on error. On error the error code is stored in * errno. Possible error codes are: - * ENOSPC - There is not enough space available to complete operation. The - * caller has to make space before calling this. - * EINVAL - Input parameters were faulty. + * ENOSPC - There is not enough space available to complete operation. The + * caller has to make space before calling this. + * EINVAL - Input parameters were faulty. */ -int ntfs_make_room_for_attr(MFT_RECORD *m, u8 *pos, u32 size) +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; } /** * ntfs_resident_attr_record_add - add resident attribute to inode - * @ni: opened ntfs inode to which MFT record add attribute - * @type: type of the new attribute - * @name: name of the new attribute - * @name_len: name length of the new attribute - * @val: value of the new attribute - * @size: size of new attribute (length of @val, if @val != NULL) - * @flags: flags of the new attribute + * @ni: opened ntfs inode to which MFT record add attribute + * @type: type of the new attribute + * @name: name of the new attribute + * @name_len: name length of the new attribute + * @val: value of the new attribute + * @size: size of new attribute (length of @val, if @val != NULL) + * @flags: flags of the new attribute * * Return offset to attribute from the beginning of the mft record on success * and -1 on error. On error the error code is stored in errno. * Possible error codes are: - * EINVAL - Invalid arguments passed to function. - * EEXIST - Attribute of such type and with same name already exists. - * EIO - I/O error occurred or damaged filesystem. + * EINVAL - Invalid arguments passed to function. + * 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; + /* 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; + ntfs_attr_put_search_ctx( ctx ); + errno = err; + return -1; } /** * ntfs_non_resident_attr_record_add - add extent of non-resident attribute - * @ni: opened ntfs inode to which MFT record add attribute - * @type: type of the new attribute extent - * @name: name of the new attribute extent - * @name_len: name length of the new attribute extent - * @lowest_vcn: lowest vcn of the new attribute extent - * @dataruns_size: dataruns size of the new attribute extent - * @flags: flags of the new attribute extent + * @ni: opened ntfs inode to which MFT record add attribute + * @type: type of the new attribute extent + * @name: name of the new attribute extent + * @name_len: name length of the new attribute extent + * @lowest_vcn: lowest vcn of the new attribute extent + * @dataruns_size: dataruns size of the new attribute extent + * @flags: flags of the new attribute extent * * Return offset to attribute from the beginning of the mft record on success * and -1 on error. On error the error code is stored in errno. * Possible error codes are: - * EINVAL - Invalid arguments passed to function. - * EEXIST - Attribute of such type, with same lowest vcn and with same - * name already exists. - * EIO - I/O error occurred or damaged filesystem. + * EINVAL - Invalid arguments passed to function. + * EEXIST - Attribute of such type, with same lowest vcn and with same + * 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; + } + offset = ( u8* )ctx->attr - ( u8* )ctx->mrec; + ntfs_attr_put_search_ctx( ctx ); + return offset; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx( ctx ); + errno = err; + return -1; } /** * ntfs_attr_record_rm - remove attribute extent - * @ctx: search context describing the attribute which should be removed + * @ctx: search context describing the attribute which should be removed * * If this function succeed, user should reinit search context if he/she wants * use it anymore. * * Return 0 on success and -1 on error. On error the error code is stored in * errno. Possible error codes are: - * EINVAL - Invalid arguments passed to function. - * EIO - I/O error occurred or damaged filesystem. + * EINVAL - Invalid arguments passed to function. + * EIO - I/O error occurred or damaged filesystem. */ -int ntfs_attr_record_rm(ntfs_attr_search_ctx *ctx) +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; } /** * ntfs_attr_add - add attribute to inode - * @ni: opened ntfs inode to which add attribute - * @type: type of the new attribute - * @name: name in unicode of the new attribute - * @name_len: name length in unicode characters of the new attribute - * @val: value of new attribute - * @size: size of the new attribute / length of @val (if specified) + * @ni: opened ntfs inode to which add attribute + * @type: type of the new attribute + * @name: name in unicode of the new attribute + * @name_len: name length in unicode characters of the new attribute + * @val: value of new attribute + * @size: size of the new attribute / length of @val (if specified) * * @val should always be specified for always resident attributes (eg. FILE_NAME * attribute), for attributes that can become non-resident @val can be NULL @@ -3959,484 +4282,522 @@ 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; - } + 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 attribute. */ + offset = ntfs_non_resident_attr_record_add( attr_ni, type, name, + name_len, 0, 8, data_flags ); + if ( offset < 0 ) + { + err = errno; + ntfs_log_perror( "Failed to add non resident attribute" ); + goto free_err_out; + } - /* If @size == 0, we are done. */ - if (!size) - return 0; + /* If @size == 0, we are done. */ + if ( !size ) + return 0; - /* Open new attribute and resize it. */ - na = ntfs_attr_open(ni, type, name, name_len); - if (!na) { - err = errno; - ntfs_log_perror("Failed to open just added attribute"); - goto rm_attr_err_out; - } - /* Resize and set attribute value. */ - if (ntfs_attr_truncate(na, size) || - (val && (ntfs_attr_pwrite(na, 0, size, val) != size))) { - err = errno; - ntfs_log_perror("Failed to initialize just added attribute"); - if (ntfs_attr_rm(na)) - ntfs_log_perror("Failed to remove just added attribute"); - ntfs_attr_close(na); - goto err_out; - } - ntfs_attr_close(na); - return 0; + /* Open new attribute and resize it. */ + na = ntfs_attr_open( ni, type, name, name_len ); + if ( !na ) + { + err = errno; + ntfs_log_perror( "Failed to open just added attribute" ); + goto rm_attr_err_out; + } + /* Resize and set attribute value. */ + if ( ntfs_attr_truncate( na, size ) || + ( val && ( ntfs_attr_pwrite( na, 0, size, val ) != size ) ) ) + { + err = errno; + ntfs_log_perror( "Failed to initialize just added attribute" ); + if ( ntfs_attr_rm( na ) ) + ntfs_log_perror( "Failed to remove just added attribute" ); + ntfs_attr_close( na ); + goto err_out; + } + ntfs_attr_close( na ); + return 0; rm_attr_err_out: - /* Remove just added attribute. */ - if (ntfs_attr_record_resize(attr_ni->mrec, - (ATTR_RECORD*)((u8*)attr_ni->mrec + offset), 0)) - ntfs_log_perror("Failed to remove just added attribute #2"); + /* Remove just added attribute. */ + if ( ntfs_attr_record_resize( attr_ni->mrec, + ( ATTR_RECORD* )( ( u8* )attr_ni->mrec + offset ), 0 ) ) + ntfs_log_perror( "Failed to remove just added attribute #2" ); free_err_out: - /* Free MFT record, if it doesn't contain attributes. */ - if (le32_to_cpu(attr_ni->mrec->bytes_in_use) - - le16_to_cpu(attr_ni->mrec->attrs_offset) == 8) - if (ntfs_mft_record_free(attr_ni->vol, attr_ni)) - ntfs_log_perror("Failed to free MFT record"); + /* Free MFT record, if it doesn't contain attributes. */ + if ( le32_to_cpu( attr_ni->mrec->bytes_in_use ) - + le16_to_cpu( attr_ni->mrec->attrs_offset ) == 8 ) + if ( ntfs_mft_record_free( attr_ni->vol, attr_ni ) ) + ntfs_log_perror( "Failed to free MFT record" ); err_out: - errno = err; - return -1; + errno = err; + return -1; } /* - * Change an attribute flag + * 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 + * @na: opened ntfs attribute to delete * * Remove attribute and all it's extents from ntfs inode. If attribute was non * resident also free all clusters allocated by attribute. * * Return 0 on success or -1 on error with errno set to the error code. */ -int ntfs_attr_rm(ntfs_attr *na) +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; } /** * ntfs_attr_record_resize - resize an attribute record - * @m: mft record containing attribute record - * @a: attribute record to resize - * @new_size: new size in bytes to which to resize the attribute record @a + * @m: mft record containing attribute record + * @a: attribute record to resize + * @new_size: new size in bytes to which to resize the attribute record @a * * Resize the attribute record @a, i.e. the resident part of the attribute, in * the mft record @m to @new_size bytes. * * Return 0 on success and -1 on error with errno set to the error code. * The following error codes are defined: - * ENOSPC - Not enough space in the mft record @m to perform the resize. + * ENOSPC - Not enough space in the mft record @m to perform the resize. * Note that on error no modifications have been performed whatsoever. * * Warning: If you make a record smaller without having copied all the data you - * are interested in the data may be overwritten! + * are interested in the data may be overwritten! */ -int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size) +int ntfs_attr_record_resize( MFT_RECORD *m, ATTR_RECORD *a, u32 new_size ) { - u32 old_size, alloc_size, attr_size; - - old_size = le32_to_cpu(m->bytes_in_use); - alloc_size = le32_to_cpu(m->bytes_allocated); - attr_size = le32_to_cpu(a->length); - - ntfs_log_trace("Sizes: old=%u alloc=%u attr=%u new=%u\n", - (unsigned)old_size, (unsigned)alloc_size, - (unsigned)attr_size, (unsigned)new_size); + 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; } /** * ntfs_resident_attr_value_resize - resize the value of a resident attribute - * @m: mft record containing attribute record - * @a: attribute record whose value to resize - * @new_size: new size in bytes to which to resize the attribute value of @a + * @m: mft record containing attribute record + * @a: attribute record whose value to resize + * @new_size: new size in bytes to which to resize the attribute value of @a * * Resize the value of the attribute @a in the mft record @m to @new_size bytes. * If the value is made bigger, the newly "allocated" space is cleared. * * Return 0 on success and -1 on error with errno set to the error code. * The following error codes are defined: - * ENOSPC - Not enough space in the mft record @m to perform the resize. + * 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; } /** * ntfs_attr_record_move_to - move attribute record to target inode - * @ctx: attribute search context describing the attribute record - * @ni: opened ntfs inode to which move attribute record + * @ctx: attribute search context describing the attribute record + * @ni: opened ntfs inode to which move attribute record * * If this function succeed, user should reinit search context if he/she wants * use it anymore. * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_record_move_to(ntfs_attr_search_ctx *ctx, ntfs_inode *ni) +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; + ntfs_attr_put_search_ctx( nctx ); + return 0; put_err_out: - ntfs_attr_put_search_ctx(nctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx( nctx ); + errno = err; + return -1; } /** * ntfs_attr_record_move_away - move away attribute record from it's mft record - * @ctx: attribute search context describing the attribute record - * @extra: minimum amount of free space in the new holder of record + * @ctx: attribute search context describing the attribute record + * @extra: minimum amount of free space in the new holder of record * * New attribute record holder must have free @extra bytes after moving * attribute record to it. @@ -4446,863 +4807,925 @@ put_err_out: * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_record_move_away(ntfs_attr_search_ctx *ctx, int extra) +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; } /** * ntfs_attr_make_non_resident - convert a resident to a non-resident attribute - * @na: open ntfs attribute to make non-resident - * @ctx: ntfs search context describing the attribute + * @na: open ntfs attribute to make non-resident + * @ctx: ntfs search context describing the attribute * * Convert a resident ntfs attribute to a non-resident one. * * Return 0 on success and -1 on error with errno set to the error code. The * following error codes are defined: - * EPERM - The attribute is not allowed to be non-resident. - * TODO: others... + * EPERM - The attribute is not allowed to be non-resident. + * TODO: others... * * NOTE to self: No changes in the attribute list are required to move from - * a resident to a non-resident attribute. + * a resident to a non-resident attribute. * * Warning: We do not set the inode dirty and we do not write out anything! - * 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. + * 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; + 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); +static int ntfs_resident_attr_resize( ntfs_attr *na, const s64 newsize ); /** * ntfs_resident_attr_resize - resize a resident, open ntfs attribute - * @na: resident ntfs attribute to resize - * @newsize: new size (in bytes) to which to resize the attribute + * @na: resident ntfs attribute to resize + * @newsize: new size (in bytes) to which to resize the attribute * * Change the size of a resident, open ntfs attribute @na to @newsize bytes. * Can also be used to force an attribute non-resident. In this case, the * size cannot be changed. * - * On success return 0 + * On success return 0 * On error return values are: - * STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT - * STATUS_ERROR - otherwise + * STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT + * STATUS_ERROR - otherwise * The following error codes are defined: - * ENOMEM - Not enough memory to complete operation. - * ERANGE - @newsize is not valid for the attribute type of @na. - * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST. + * ENOMEM - Not enough memory to complete operation. + * 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; + + 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; + /* + * Set the inode (and its base inode if it exists) dirty so it is + * written out later. + */ + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + ntfs_attr_put_search_ctx( ctx ); + return 0; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return ret; + ntfs_attr_put_search_ctx( ctx ); + errno = err; + return ret; } -static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize) +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; } /* - * Force an attribute to be made non-resident without - * changing its size. + * Force an attribute to be made non-resident without + * changing its size. * - * This is particularly needed when the attribute has no data, - * as the non-resident variant requires more space in the MFT - * record, and may imply expelling some other attribute. + * This is particularly needed when the attribute has no data, + * as the non-resident variant requires more space in the MFT + * record, and may imply expelling some other attribute. * - * As a consequence the existing ntfs_attr_search_ctx's have to - * be closed or reinitialized. + * As a consequence the existing ntfs_attr_search_ctx's have to + * be closed or reinitialized. * - * returns 0 if successful, - * < 0 if failed, with errno telling why + * returns 0 if successful, + * < 0 if failed, with errno telling why */ -int ntfs_attr_force_non_resident(ntfs_attr *na) +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 ); } /** * ntfs_attr_make_resident - convert a non-resident to a resident attribute - * @na: open ntfs attribute to make resident - * @ctx: ntfs search context describing the attribute + * @na: open ntfs attribute to make resident + * @ctx: ntfs search context describing the attribute * * Convert a non-resident ntfs attribute to a resident one. * * Return 0 on success and -1 on error with errno set to the error code. The * following error codes are defined: - * EINVAL - Invalid arguments passed. - * EPERM - The attribute is not allowed to be resident. - * EIO - I/O error, damaged inode or bug. - * ENOSPC - There is no enough space to perform conversion. - * EOPNOTSUPP - Requested conversion is not supported yet. + * EINVAL - Invalid arguments passed. + * EPERM - The attribute is not allowed to be resident. + * EIO - I/O error, damaged inode or bug. + * ENOSPC - There is no enough space to perform conversion. + * EOPNOTSUPP - Requested conversion is not supported yet. * * Warning: We do not set the inode dirty and we do not write out anything! - * 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. + * We expect the caller to do this as this is a fairly low level + * function and it is likely there will be further changes made. */ -static int ntfs_attr_make_resident(ntfs_attr *na, ntfs_attr_search_ctx *ctx) +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); - } + 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; + return ret; +leave: ret = -1; goto out; /* return -1 */ +retry: ret = -2; goto out; error: ret = -3; goto out; } @@ -5310,337 +5733,369 @@ error: ret = -3; goto out; /** * ntfs_attr_update_mapping_pairs_i - see ntfs_attr_update_mapping_pairs */ -static int ntfs_attr_update_mapping_pairs_i(ntfs_attr *na, VCN from_vcn) +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; - } + 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; - } + err = ntfs_mapping_pairs_build( na->ni->vol, ( u8* )a + + le16_to_cpu( a->mapping_pairs_offset ), mp_size, na->rl, + stop_vcn, &stop_rl ); + if ( stop_rl ) + stop_vcn = stop_rl->vcn; + else + stop_vcn = 0; + if ( err < 0 && errno != ENOSPC ) + { + err = errno; + ntfs_log_perror( "Failed to build MP" ); + if ( ntfs_mft_record_free( na->ni->vol, ni ) ) + ntfs_log_perror( "Couldn't free MFT record" ); + errno = err; + goto put_err_out; + } + a->highest_vcn = cpu_to_sle64( stop_vcn - 1 ); + ntfs_inode_mark_dirty( ni ); + /* All mapping pairs has been written. */ + if ( !err ) + break; + } ok: - ret = 0; + ret = 0; out: - return ret; + return ret; put_err_out: - if (ctx) - ntfs_attr_put_search_ctx(ctx); - goto out; + if ( ctx ) + ntfs_attr_put_search_ctx( ctx ); + goto out; } #undef NTFS_VCN_DELETE_MARK /** * ntfs_attr_update_mapping_pairs - update mapping pairs for ntfs attribute - * @na: non-resident ntfs open attribute for which we need update - * @from_vcn: update runlist starting this VCN + * @na: non-resident ntfs open attribute for which we need update + * @from_vcn: update runlist starting this VCN * * Build mapping pairs from @na->rl and write them to the disk. Also, this * function updates sparse bit, allocated and compressed size (allocates/frees @@ -5657,403 +6112,446 @@ put_err_out: * * On success return 0 and on error return -1 with errno set to the error code. * The following error codes are defined: - * EINVAL - Invalid arguments passed. - * ENOMEM - Not enough memory to complete operation. - * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST - * or there is no free MFT records left to allocate. + * EINVAL - Invalid arguments passed. + * ENOMEM - Not enough memory to complete operation. + * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST + * or there is no free MFT records left to allocate. */ -int ntfs_attr_update_mapping_pairs(ntfs_attr *na, VCN from_vcn) +int 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; } /** * ntfs_non_resident_attr_shrink - shrink a non-resident, open ntfs attribute - * @na: non-resident ntfs attribute to shrink - * @newsize: new size (in bytes) to which to shrink the attribute + * @na: non-resident ntfs attribute to shrink + * @newsize: new size (in bytes) to which to shrink the attribute * * Reduce the size of a non-resident, open ntfs attribute @na to @newsize bytes. * * On success return 0 and on error return -1 with errno set to the error code. * The following error codes are defined: - * ENOMEM - Not enough memory to complete operation. - * ERANGE - @newsize is not valid for the attribute type of @na. + * ENOMEM - Not enough memory to complete operation. + * ERANGE - @newsize is not valid for the attribute type of @na. */ -static int ntfs_non_resident_attr_shrink(ntfs_attr *na, const s64 newsize) +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; + /* Set the inode dirty so it is written out later. */ + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + /* Done! */ + ntfs_attr_put_search_ctx( ctx ); + return 0; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx( ctx ); + errno = err; + return -1; } /** * ntfs_non_resident_attr_expand - expand a non-resident, open ntfs attribute - * @na: non-resident ntfs attribute to expand - * @newsize: new size (in bytes) to which to expand the attribute + * @na: non-resident ntfs attribute to expand + * @newsize: new size (in bytes) to which to expand the attribute * * Expand the size of a non-resident, open ntfs attribute @na to @newsize bytes, * by allocating new clusters. * * On success return 0 and on error return -1 with errno set to the error code. * The following error codes are defined: - * ENOMEM - Not enough memory to complete operation. - * ERANGE - @newsize is not valid for the attribute type of @na. - * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST. + * ENOMEM - Not enough memory to complete operation. + * ERANGE - @newsize is not valid for the attribute type of @na. + * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST. */ -static int ntfs_non_resident_attr_expand_i(ntfs_attr *na, const s64 newsize) +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; + 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; + /* 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; + ntfs_attr_put_search_ctx( ctx ); + errno = err; + return -1; } -static int ntfs_non_resident_attr_expand(ntfs_attr *na, const s64 newsize) +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; } /** * ntfs_attr_truncate - resize an ntfs attribute - * @na: open ntfs attribute to resize - * @newsize: new size (in bytes) to which to resize the attribute + * @na: open ntfs attribute to resize + * @newsize: new size (in bytes) to which to resize the attribute * * Change the size of an open ntfs attribute @na to @newsize bytes. If the * attribute is made bigger and the attribute is resident the newly @@ -6063,339 +6561,361 @@ static int ntfs_non_resident_attr_expand(ntfs_attr *na, const s64 newsize) * * On success return 0. * On error return values are: - * STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT - * STATUS_ERROR - otherwise + * STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT + * STATUS_ERROR - otherwise * The following error codes are defined: - * EINVAL - Invalid arguments were passed to the function. - * EOPNOTSUPP - The desired resize is not implemented yet. - * EACCES - Encrypted attribute. + * EINVAL - Invalid arguments were passed to the function. + * EOPNOTSUPP - The desired resize is not implemented yet. + * EACCES - Encrypted attribute. */ -int ntfs_attr_truncate(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 + * Stuff a hole in a compressed file * - * An unallocated hole must be aligned on compression block size. - * If needed current block and target block are stuffed with zeroes. + * An unallocated hole must be aligned on compression block size. + * If needed current block and target block are stuffed with zeroes. * - * Returns 0 if succeeded, - * -1 if it failed (as explained in errno) + * Returns 0 if succeeded, + * -1 if it failed (as explained in errno) */ -static int stuff_hole(ntfs_attr *na, const s64 pos) +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 ); } /** * ntfs_attr_readall - read the entire data from an ntfs attribute - * @ni: open ntfs inode in which the ntfs attribute resides - * @type: attribute type - * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL - * @name_len: length of attribute @name in Unicode characters (if @name given) - * @data_size: if non-NULL then store here the data size + * @ni: open ntfs inode in which the ntfs attribute resides + * @type: attribute type + * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL + * @name_len: length of attribute @name in Unicode characters (if @name given) + * @data_size: if non-NULL then store here the data size * * This function will read the entire content of an ntfs attribute. * If @name is AT_UNNAMED then look specifically for an unnamed attribute. - * If @name is NULL then the attribute could be either named or not. + * If @name is NULL then the attribute could be either named or not. * In both those cases @name_len is not used at all. * - * On success a buffer is allocated with the content of the attribute + * On success a buffer is allocated with the content of the attribute * and which needs to be freed when it's not needed anymore. If the * @data_size parameter is non-NULL then the data size is set there. * * On error NULL is returned with errno set to the error code. */ -void *ntfs_attr_readall(ntfs_inode *ni, const ATTR_TYPES type, - ntfschar *name, u32 name_len, s64 *data_size) +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; + ntfs_attr *na; + void *data, *ret = NULL; + s64 size; + + ntfs_log_enter( "Entering\n" ); + + na = ntfs_attr_open( ni, type, name, name_len ); + if ( !na ) + { + ntfs_log_perror( "ntfs_attr_open failed" ); + goto err_exit; + } + data = ntfs_malloc( na->data_size ); + if ( !data ) + goto out; + + size = ntfs_attr_pread( na, 0, na->data_size, data ); + if ( size != na->data_size ) + { + ntfs_log_perror( "ntfs_attr_pread failed" ); + free( data ); + goto out; + } + ret = data; + if ( data_size ) + *data_size = size; out: - ntfs_attr_close(na); + ntfs_attr_close( na ); err_exit: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave( "\n" ); + return ret; } -int ntfs_attr_exist(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, - u32 name_len) +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. */ #define BCX(x) ((x) - (((x) >> 1) & 0x77777777) - \ - (((x) >> 2) & 0x33333333) - \ - (((x) >> 3) & 0x11111111)) + (((x) >> 2) & 0x33333333) - \ + (((x) >> 3) & 0x11111111)) #define BITCOUNT(x) (((BCX(x) + (BCX(x) >> 4)) & 0x0F0F0F0F) % 255) -static u8 *ntfs_init_lut256(void) +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) +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); + 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; + 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..bc9205c0 100644 --- a/source/libntfs/attrib.h +++ b/source/libntfs/attrib.h @@ -49,19 +49,20 @@ 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; /** * struct ntfs_attr_search_ctx - search context used in attribute search functions - * @mrec: buffer containing mft record to search - * @attr: attribute record in @mrec where to begin/continue search - * @is_first: if true lookup_attr() begins search with @attr, else after @attr + * @mrec: buffer containing mft record to search + * @attr: attribute record in @mrec where to begin/continue search + * @is_first: if true lookup_attr() begins search with @attr, else after @attr * * Structure must be initialized to zero before the first call to one of the * attribute search functions. Initialize @mrec to point to the mft record to @@ -75,35 +76,36 @@ 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 void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx); +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 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 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 - * @ctx: initialised attribute search context + * @ctx: initialised attribute search context * * Syntactic sugar for walking attributes in an inode. * @@ -111,42 +113,42 @@ extern ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol, * ntfs_attr_lookup(). * * Example: When you want to enumerate all attributes in an open ntfs inode - * @ni, you can simply do: + * @ni, you can simply do: * - * int err; - * ntfs_attr_search_ctx *ctx = ntfs_attr_get_search_ctx(ni, NULL); - * if (!ctx) - * // Error code is in errno. Handle this case. - * while (!(err = ntfs_attrs_walk(ctx))) { - * ATTR_RECORD *attr = ctx->attr; - * // attr now contains the next attribute. Do whatever you want - * // with it and then just continue with the while loop. - * } - * if (err && errno != ENOENT) - * // Ooops. An error occurred! You should handle this case. - * // Now finished with all attributes in the inode. + * int err; + * ntfs_attr_search_ctx *ctx = ntfs_attr_get_search_ctx(ni, NULL); + * if (!ctx) + * // Error code is in errno. Handle this case. + * while (!(err = ntfs_attrs_walk(ctx))) { + * ATTR_RECORD *attr = ctx->attr; + * // attr now contains the next attribute. Do whatever you want + * // with it and then just continue with the while loop. + * } + * if (err && errno != ENOENT) + * // Ooops. An error occurred! You should handle this case. + * // Now finished with all attributes in the inode. */ -static __inline__ int ntfs_attrs_walk(ntfs_attr_search_ctx *ctx) +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 ); } /** * struct ntfs_attr - ntfs in memory non-resident attribute structure - * @rl: if not NULL, the decompressed runlist - * @ni: base ntfs inode to which this attribute belongs - * @type: attribute type - * @name: Unicode name of the attribute - * @name_len: length of @name in Unicode characters - * @state: NTFS attribute specific flags describing this attribute - * @allocated_size: copy from the attribute record - * @data_size: copy from the attribute record - * @initialized_size: copy from the attribute record - * @compressed_size: copy from the attribute record - * @compression_block_size: size of a compression block (cb) - * @compression_block_size_bits: log2 of the size of a cb - * @compression_block_clusters: number of clusters per cb + * @rl: if not NULL, the decompressed runlist + * @ni: base ntfs inode to which this attribute belongs + * @type: attribute type + * @name: Unicode name of the attribute + * @name_len: length of @name in Unicode characters + * @state: NTFS attribute specific flags describing this attribute + * @allocated_size: copy from the attribute record + * @data_size: copy from the attribute record + * @initialized_size: copy from the attribute record + * @compressed_size: copy from the attribute record + * @compression_block_size: size of a compression block (cb) + * @compression_block_size_bits: log2 of the size of a cb + * @compression_block_clusters: number of clusters per cb * * This structure exists purely to provide a mechanism of caching the runlist * of an attribute. If you want to operate on a particular attribute extent, @@ -174,68 +176,70 @@ 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) -#define set_nattr_flag(na, flag) set_bit(NA_##flag, (na)->state) -#define clear_nattr_flag(na, flag) clear_bit(NA_##flag, (na)->state) +#define test_nattr_flag(na, flag) test_bit(NA_##flag, (na)->state) +#define set_nattr_flag(na, flag) set_bit(NA_##flag, (na)->state) +#define clear_nattr_flag(na, flag) clear_bit(NA_##flag, (na)->state) -#define NAttrInitialized(na) test_nattr_flag(na, Initialized) -#define NAttrSetInitialized(na) set_nattr_flag(na, Initialized) -#define NAttrClearInitialized(na) clear_nattr_flag(na, Initialized) +#define NAttrInitialized(na) test_nattr_flag(na, Initialized) +#define NAttrSetInitialized(na) set_nattr_flag(na, Initialized) +#define NAttrClearInitialized(na) clear_nattr_flag(na, Initialized) -#define NAttrNonResident(na) test_nattr_flag(na, NonResident) -#define NAttrSetNonResident(na) set_nattr_flag(na, NonResident) -#define NAttrClearNonResident(na) clear_nattr_flag(na, NonResident) +#define NAttrNonResident(na) test_nattr_flag(na, NonResident) +#define NAttrSetNonResident(na) set_nattr_flag(na, NonResident) +#define NAttrClearNonResident(na) clear_nattr_flag(na, NonResident) -#define NAttrBeingNonResident(na) test_nattr_flag(na, BeingNonResident) -#define NAttrSetBeingNonResident(na) set_nattr_flag(na, BeingNonResident) -#define NAttrClearBeingNonResident(na) clear_nattr_flag(na, BeingNonResident) +#define NAttrBeingNonResident(na) test_nattr_flag(na, BeingNonResident) +#define NAttrSetBeingNonResident(na) set_nattr_flag(na, BeingNonResident) +#define NAttrClearBeingNonResident(na) clear_nattr_flag(na, BeingNonResident) -#define NAttrFullyMapped(na) test_nattr_flag(na, FullyMapped) -#define NAttrSetFullyMapped(na) set_nattr_flag(na, FullyMapped) -#define NAttrClearFullyMapped(na) clear_nattr_flag(na, FullyMapped) +#define NAttrFullyMapped(na) test_nattr_flag(na, FullyMapped) +#define NAttrSetFullyMapped(na) set_nattr_flag(na, FullyMapped) +#define NAttrClearFullyMapped(na) clear_nattr_flag(na, FullyMapped) -#define NAttrComprClosing(na) test_nattr_flag(na, ComprClosing) -#define NAttrSetComprClosing(na) set_nattr_flag(na, ComprClosing) -#define NAttrClearComprClosing(na) clear_nattr_flag(na, ComprClosing) +#define NAttrComprClosing(na) test_nattr_flag(na, ComprClosing) +#define NAttrSetComprClosing(na) set_nattr_flag(na, ComprClosing) +#define NAttrClearComprClosing(na) clear_nattr_flag(na, ComprClosing) -#define GenNAttrIno(func_name, flag) \ -extern int NAttr##func_name(ntfs_attr *na); \ -extern void NAttrSet##func_name(ntfs_attr *na); \ +#define GenNAttrIno(func_name, flag) \ +extern int NAttr##func_name(ntfs_attr *na); \ +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( Compressed, FILE_ATTR_COMPRESSED ) +GenNAttrIno( Encrypted, FILE_ATTR_ENCRYPTED ) +GenNAttrIno( Sparse, FILE_ATTR_SPARSE_FILE ) #undef GenNAttrIno /** @@ -243,99 +247,100 @@ 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); -extern void ntfs_attr_close(ntfs_attr *na); +/* 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 int ntfs_attr_pclose(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 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); +extern int ntfs_attr_map_runlist( ntfs_attr *na, VCN vcn ); +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 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); -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_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_attr_record_rm(ntfs_attr_search_ctx *ctx); +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_rm(ntfs_attr *na); +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_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); +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 ); -extern int ntfs_attr_update_mapping_pairs(ntfs_attr *na, VCN from_vcn); +extern int ntfs_attr_update_mapping_pairs( ntfs_attr *na, VCN from_vcn ); -extern int ntfs_attr_truncate(ntfs_attr *na, const s64 newsize); +extern int ntfs_attr_truncate( ntfs_attr *na, const s64 newsize ); /** * get_attribute_value_length - return the length of the value of an attribute - * @a: pointer to a buffer containing the attribute record + * @a: pointer to a buffer containing the attribute record * * Return the byte size of the attribute value of the attribute @a (as it * would be after eventual decompression and filling in of holes if sparse). @@ -344,13 +349,13 @@ extern int ntfs_attr_truncate(ntfs_attr *na, const s64 newsize); * * FIXME: Describe possible errnos. */ -extern s64 ntfs_get_attribute_value_length(const ATTR_RECORD *a); +extern s64 ntfs_get_attribute_value_length( const ATTR_RECORD *a ); /** * get_attribute_value - return the attribute value of an attribute - * @vol: volume on which the attribute is present - * @a: attribute to get the value of - * @b: destination buffer for the attribute value + * @vol: volume on which the attribute is present + * @a: attribute to get the value of + * @b: destination buffer for the attribute value * * Make a copy of the attribute value of the attribute @a into the destination * buffer @b. Note, that the size of @b has to be at least equal to the value @@ -360,16 +365,16 @@ extern s64 ntfs_get_attribute_value_length(const ATTR_RECORD *a); * then nothing was read due to a zero-length attribute value, otherwise * errno describes the error. */ -extern s64 ntfs_get_attribute_value(const ntfs_volume *vol, - const ATTR_RECORD *a, u8 *b); +extern s64 ntfs_get_attribute_value( const ntfs_volume *vol, + const ATTR_RECORD *a, u8 *b ); -extern void ntfs_attr_name_free(char **name); -extern char *ntfs_attr_name_get(const ntfschar *uname, const int uname_len); -extern int ntfs_attr_exist(ntfs_inode *ni, const ATTR_TYPES type, - ntfschar *name, u32 name_len); -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 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 ); #endif /* defined _NTFS_ATTRIB_H */ diff --git a/source/libntfs/attrib_frag.c b/source/libntfs/attrib_frag.c index 5c3c4a1d..155315ee 100644 --- a/source/libntfs/attrib_frag.c +++ b/source/libntfs/attrib_frag.c @@ -65,43 +65,44 @@ #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) +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) +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) +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) \ -int NAttr##func_name(ntfs_attr *na) { return NAttrFlag (na, flag); } \ -void NAttrSet##func_name(ntfs_attr *na) { NAttrSetFlag (na, flag); } \ +#define GenNAttrIno(func_name, flag) \ +int NAttr##func_name(ntfs_attr *na) { return NAttrFlag (na, flag); } \ +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( Compressed, FILE_ATTR_COMPRESSED ) +GenNAttrIno( Encrypted, FILE_ATTR_ENCRYPTED ) +GenNAttrIno( Sparse, FILE_ATTR_SPARSE_FILE ) /** * ntfs_get_attribute_value_length - Find the length of an attribute @@ -111,213 +112,231 @@ GenNAttrIno(Sparse, FILE_ATTR_SPARSE_FILE) * * Returns: */ -s64 ntfs_get_attribute_value_length(const ATTR_RECORD *a) +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 ); } /** * ntfs_get_attribute_value - Get a copy of an attribute - * @vol: - * @a: - * @b: + * @vol: + * @a: + * @b: * * Description... * * Returns: */ -s64 ntfs_get_attribute_value(const ntfs_volume *vol, - const ATTR_RECORD *a, u8 *b) +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:... */ /** * __ntfs_attr_init - primary initialization of an ntfs attribute structure - * @na: ntfs attribute to initialize - * @ni: ntfs inode with which to initialize the ntfs attribute - * @type: attribute type - * @name: attribute name in little endian Unicode or NULL - * @name_len: length of attribute @name in Unicode characters (if @name given) + * @na: ntfs attribute to initialize + * @ni: ntfs inode with which to initialize the ntfs attribute + * @type: attribute type + * @name: attribute name in little endian Unicode or NULL + * @name_len: length of attribute @name in Unicode characters (if @name given) * * 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; } /** @@ -335,46 +354,48 @@ 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 ); + } } /** * ntfs_attr_open - open an ntfs attribute for access - * @ni: open ntfs inode in which the ntfs attribute resides - * @type: attribute type - * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL - * @name_len: length of attribute @name in Unicode characters (if @name given) + * @ni: open ntfs inode in which the ntfs attribute resides + * @type: attribute type + * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL + * @name_len: length of attribute @name in Unicode characters (if @name given) * * Allocate a new ntfs attribute structure, initialize it with @ni, @type, * @name, and @name_len, then return it. Return NULL on error with @@ -384,196 +405,210 @@ 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. - */ - a->flags &= ~ATTR_COMPRESSION_MASK; - if (na->ni->flags & FILE_ATTR_COMPRESSED) - a->flags |= ATTR_IS_COMPRESSED; - } - - cs = a->flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE); - - if (na->type == AT_DATA && na->name == AT_UNNAMED && - ((!(a->flags & ATTR_IS_SPARSE) != !NAttrSparse(na)) || - (!(a->flags & ATTR_IS_ENCRYPTED) != !NAttrEncrypted(na)))) { - errno = EIO; - ntfs_log_perror("Inode %lld has corrupt attribute flags " - "(0x%x <> 0x%x)",(unsigned long long)ni->mft_no, - a->flags, na->ni->flags); - goto put_err_out; - } + 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); + if ( !name ) + { + if ( a->name_length ) + { + name = ntfs_ucsndup( ( ntfschar* )( ( u8* )a + le16_to_cpu( + a->name_offset ) ), a->name_length ); + if ( !name ) + goto put_err_out; + newname = name; + name_len = a->name_length; + } + else + { + name = AT_UNNAMED; + name_len = 0; + } + } + + __ntfs_attr_init( na, ni, type, name, name_len ); + + /* + * Wipe the flags in case they are not zero for an attribute list + * attribute. Windows does not complain about invalid flags and chkdsk + * does not detect or fix them so we need to cope with it, too. + */ + if ( type == AT_ATTRIBUTE_LIST ) + a->flags = 0; + + if ( ( type == AT_DATA ) && !a->initialized_size ) + { + /* + * Define/redefine the compression state if stream is + * empty, based on the compression mark on parent + * directory (for unnamed data streams) or on current + * inode (for named data streams). The compression mark + * may change any time, the compression state can only + * change when stream is wiped out. + */ + a->flags &= ~ATTR_COMPRESSION_MASK; + if ( na->ni->flags & FILE_ATTR_COMPRESSED ) + a->flags |= ATTR_IS_COMPRESSED; + } + + cs = a->flags & ( ATTR_IS_COMPRESSED | ATTR_IS_SPARSE ); + + if ( na->type == AT_DATA && na->name == AT_UNNAMED && + ( ( !( a->flags & ATTR_IS_SPARSE ) != !NAttrSparse( na ) ) || + ( !( a->flags & ATTR_IS_ENCRYPTED ) != !NAttrEncrypted( na ) ) ) ) + { + errno = EIO; + ntfs_log_perror( "Inode %lld has corrupt attribute flags " + "(0x%x <> 0x%x)", ( unsigned long long )ni->mft_no, + a->flags, na->ni->flags ); + goto put_err_out; + } + + if ( a->non_resident ) + { + if ( ( a->flags & ATTR_COMPRESSION_MASK ) + && !a->compression_unit ) + { + errno = EIO; + ntfs_log_perror( "Compressed inode %lld attr 0x%x has " + "no compression unit", + ( unsigned long long )ni->mft_no, type ); + goto put_err_out; + } + ntfs_attr_init( na, TRUE, a->flags, + a->flags & ATTR_IS_ENCRYPTED, + a->flags & ATTR_IS_SPARSE, + sle64_to_cpu( a->allocated_size ), + sle64_to_cpu( a->data_size ), + sle64_to_cpu( a->initialized_size ), + cs ? sle64_to_cpu( a->compressed_size ) : 0, + cs ? a->compression_unit : 0 ); + } + else + { + s64 l = le32_to_cpu( a->value_length ); + ntfs_attr_init( na, FALSE, a->flags, + a->flags & ATTR_IS_ENCRYPTED, + a->flags & ATTR_IS_SPARSE, ( l + 7 ) & ~7, l, l, + cs ? ( l + 7 ) & ~7 : 0, 0 ); + } + ntfs_attr_put_search_ctx( ctx ); out: - ntfs_log_leave("\n"); - return na; + ntfs_log_leave( "\n" ); + return na; put_err_out: - ntfs_attr_put_search_ctx(ctx); + ntfs_attr_put_search_ctx( ctx ); err_out: - free(newname); - free(na); - na = NULL; - goto out; + free( newname ); + free( na ); + na = NULL; + goto out; } /** * ntfs_attr_close - free an ntfs attribute structure - * @na: ntfs attribute structure to free + * @na: ntfs attribute structure to free * * Release all memory associated with the ntfs attribute @na and then release * @na itself. */ -void ntfs_attr_close(ntfs_attr *na) +void ntfs_attr_close( ntfs_attr *na ) { - if (!na) - return; - if (NAttrNonResident(na) && na->rl) - free(na->rl); - /* Don't release if using an internal constant. */ - if (na->name != AT_UNNAMED && na->name != NTFS_INDEX_I30 - && na->name != STREAM_SDS) - free(na->name); - free(na); + 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 ); } /** * ntfs_attr_map_runlist - map (a part of) a runlist of an ntfs attribute - * @na: ntfs attribute for which to map (part of) a runlist - * @vcn: map runlist part containing this vcn + * @na: ntfs attribute for which to map (part of) a runlist + * @vcn: map runlist part containing this vcn * * Map the part of a runlist containing the @vcn of the ntfs attribute @na. * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn) +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; } /** * ntfs_attr_map_whole_runlist - map the whole runlist of an ntfs attribute - * @na: ntfs attribute for which to map the runlist + * @na: ntfs attribute for which to map the runlist * * Map the whole runlist of the ntfs attribute @na. For an attribute made up * of only one attribute extent this is the same as calling @@ -583,103 +618,111 @@ int ntfs_attr_map_runlist(ntfs_attr *na, VCN vcn) * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_map_whole_runlist(ntfs_attr *na) +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 ); - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - goto out; + ctx = ntfs_attr_get_search_ctx( na->ni, NULL ); + if ( !ctx ) + goto out; - /* Map all attribute extents one by one. */ - next_vcn = last_vcn = highest_vcn = 0; - a = NULL; - while (1) { - runlist_element *rl; + /* Map all attribute extents one by one. */ + next_vcn = last_vcn = highest_vcn = 0; + a = NULL; + while ( 1 ) + { + runlist_element *rl; - int not_mapped = 0; - if (ntfs_rl_vcn_to_lcn(na->rl, next_vcn) == LCN_RL_NOT_MAPPED) - not_mapped = 1; + int not_mapped = 0; + if ( ntfs_rl_vcn_to_lcn( na->rl, next_vcn ) == LCN_RL_NOT_MAPPED ) + not_mapped = 1; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, - CASE_SENSITIVE, next_vcn, NULL, 0, ctx)) - break; + if ( ntfs_attr_lookup( na->type, na->name, na->name_len, + CASE_SENSITIVE, next_vcn, NULL, 0, ctx ) ) + break; - a = ctx->attr; + a = ctx->attr; - if (not_mapped) { - /* Decode the runlist. */ - rl = ntfs_mapping_pairs_decompress(na->ni->vol, - a, na->rl); - if (!rl) - goto err_out; - na->rl = rl; - } + if ( not_mapped ) + { + /* Decode the runlist. */ + rl = ntfs_mapping_pairs_decompress( na->ni->vol, + a, na->rl ); + if ( !rl ) + goto err_out; + na->rl = rl; + } - /* Are we in the first extent? */ - if (!next_vcn) { - if (a->lowest_vcn) { - errno = EIO; - ntfs_log_perror("First extent of inode %llu " - "attribute has non-zero lowest_vcn", - (unsigned long long)na->ni->mft_no); - goto err_out; - } - /* Get the last vcn in the attribute. */ - last_vcn = sle64_to_cpu(a->allocated_size) >> - vol->cluster_size_bits; - } + /* Are we in the first extent? */ + if ( !next_vcn ) + { + if ( a->lowest_vcn ) + { + errno = EIO; + ntfs_log_perror( "First extent of inode %llu " + "attribute has non-zero lowest_vcn", + ( unsigned long long )na->ni->mft_no ); + goto err_out; + } + /* Get the last vcn in the attribute. */ + last_vcn = sle64_to_cpu( a->allocated_size ) >> + vol->cluster_size_bits; + } - /* Get the lowest vcn for the next extent. */ - highest_vcn = sle64_to_cpu(a->highest_vcn); - next_vcn = highest_vcn + 1; + /* Get the lowest vcn for the next extent. */ + highest_vcn = sle64_to_cpu( a->highest_vcn ); + next_vcn = highest_vcn + 1; - /* Only one extent or error, which we catch below. */ - if (next_vcn <= 0) { - errno = ENOENT; - break; - } + /* Only one extent or error, which we catch below. */ + if ( next_vcn <= 0 ) + { + errno = ENOENT; + break; + } - /* Avoid endless loops due to corruption. */ - if (next_vcn < sle64_to_cpu(a->lowest_vcn)) { - errno = EIO; - ntfs_log_perror("Inode %llu has corrupt attribute list", - (unsigned long long)na->ni->mft_no); - goto err_out; - } - } - if (!a) { - ntfs_log_perror("Couldn't find attribute for runlist mapping"); - goto err_out; - } - if (highest_vcn && highest_vcn != last_vcn - 1) { - errno = EIO; - ntfs_log_perror("Failed to load full runlist: inode: %llu " - "highest_vcn: 0x%llx last_vcn: 0x%llx", - (unsigned long long)na->ni->mft_no, - (long long)highest_vcn, (long long)last_vcn); - goto err_out; - } - if (errno == ENOENT) - ret = 0; -err_out: - ntfs_attr_put_search_ctx(ctx); + /* Avoid endless loops due to corruption. */ + if ( next_vcn < sle64_to_cpu( a->lowest_vcn ) ) + { + errno = EIO; + ntfs_log_perror( "Inode %llu has corrupt attribute list", + ( unsigned long long )na->ni->mft_no ); + goto err_out; + } + } + if ( !a ) + { + ntfs_log_perror( "Couldn't find attribute for runlist mapping" ); + goto err_out; + } + if ( highest_vcn && highest_vcn != last_vcn - 1 ) + { + errno = EIO; + ntfs_log_perror( "Failed to load full runlist: inode: %llu " + "highest_vcn: 0x%llx last_vcn: 0x%llx", + ( unsigned long long )na->ni->mft_no, + ( long long )highest_vcn, ( long long )last_vcn ); + goto err_out; + } + if ( errno == ENOENT ) + ret = 0; +err_out: + ntfs_attr_put_search_ctx( ctx ); out: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave( "\n" ); + return ret; } /** * ntfs_attr_vcn_to_lcn - convert a vcn into a lcn given an ntfs attribute - * @na: ntfs attribute whose runlist to use for conversion - * @vcn: vcn to convert + * @na: ntfs attribute whose runlist to use for conversion + * @vcn: vcn to convert * * Convert the virtual cluster number @vcn of an attribute into a logical * cluster number (lcn) of a device using the runlist @na->rl to map vcns to @@ -690,47 +733,48 @@ out: * * Since lcns must be >= 0, we use negative return values with special meaning: * - * Return value Meaning / Description + * Return value Meaning / Description * ========================================== - * -1 = LCN_HOLE Hole / not allocated on disk. - * -3 = LCN_ENOENT There is no such vcn in the attribute. - * -4 = LCN_EINVAL Input parameter error. - * -5 = LCN_EIO Corrupt fs, disk i/o error, or not enough memory. + * -1 = LCN_HOLE Hole / not allocated on disk. + * -3 = LCN_ENOENT There is no such vcn in the attribute. + * -4 = LCN_EINVAL Input parameter error. + * -5 = LCN_EIO Corrupt fs, disk i/o error, or not enough memory. */ -LCN ntfs_attr_vcn_to_lcn(ntfs_attr *na, const VCN vcn) +LCN 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); + ntfs_log_trace( "Entering for inode 0x%llx, attr 0x%x.\n", ( unsigned long + long )na->ni->mft_no, na->type ); retry: - /* Convert vcn to lcn. If that fails map the runlist and retry once. */ - lcn = ntfs_rl_vcn_to_lcn(na->rl, vcn); - if (lcn >= 0) - return lcn; - if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) { - is_retry = TRUE; - goto retry; - } - /* - * If the attempt to map the runlist failed, or we are getting - * LCN_RL_NOT_MAPPED despite having mapped the attribute extent - * successfully, something is really badly wrong... - */ - if (!is_retry || lcn == (LCN)LCN_RL_NOT_MAPPED) - return (LCN)LCN_EIO; - /* lcn contains the appropriate error code. */ - return lcn; + /* Convert vcn to lcn. If that fails map the runlist and retry once. */ + lcn = ntfs_rl_vcn_to_lcn( na->rl, vcn ); + if ( lcn >= 0 ) + return lcn; + if ( !is_retry && !ntfs_attr_map_runlist( na, vcn ) ) + { + is_retry = TRUE; + goto retry; + } + /* + * If the attempt to map the runlist failed, or we are getting + * LCN_RL_NOT_MAPPED despite having mapped the attribute extent + * successfully, something is really badly wrong... + */ + if ( !is_retry || lcn == ( LCN )LCN_RL_NOT_MAPPED ) + return ( LCN )LCN_EIO; + /* lcn contains the appropriate error code. */ + return lcn; } /** * ntfs_attr_find_vcn - find a vcn in the runlist of an ntfs attribute - * @na: ntfs attribute whose runlist to search - * @vcn: vcn to find + * @na: ntfs attribute whose runlist to search + * @vcn: vcn to find * * Find the virtual cluster number @vcn in the runlist of the ntfs attribute * @na and return the the address of the runlist element containing the @vcn. @@ -742,67 +786,72 @@ retry: * * If there is an error return NULL with errno set to the error code. The * following error codes are defined: - * EINVAL Input parameter error. - * ENOENT There is no such vcn in the runlist. - * ENOMEM Not enough memory. - * EIO I/O error or corrupt metadata. + * EINVAL Input parameter error. + * ENOENT There is no such vcn in the runlist. + * ENOMEM Not enough memory. + * EIO I/O error or corrupt metadata. */ -runlist_element *ntfs_attr_find_vcn(ntfs_attr *na, const VCN vcn) +runlist_element *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); + ntfs_log_trace( "Entering for inode 0x%llx, attr 0x%x, vcn %llx\n", + ( unsigned long long )na->ni->mft_no, na->type, + ( long long )vcn ); retry: - rl = na->rl; - if (!rl) - goto map_rl; - if (vcn < rl[0].vcn) - goto map_rl; - while (rl->length) { - if (vcn < rl[1].vcn) { - if (rl->lcn >= (LCN)LCN_HOLE) - return rl; - break; - } - rl++; - } - switch (rl->lcn) { - case (LCN)LCN_RL_NOT_MAPPED: - goto map_rl; - case (LCN)LCN_ENOENT: - errno = ENOENT; - break; - case (LCN)LCN_EINVAL: - errno = EINVAL; - break; - default: - errno = EIO; - break; - } - return NULL; + rl = na->rl; + if ( !rl ) + goto map_rl; + if ( vcn < rl[0].vcn ) + goto map_rl; + while ( rl->length ) + { + if ( vcn < rl[1].vcn ) + { + if ( rl->lcn >= ( LCN )LCN_HOLE ) + return rl; + break; + } + rl++; + } + switch ( rl->lcn ) + { + case ( LCN )LCN_RL_NOT_MAPPED: + goto map_rl; + case ( LCN )LCN_ENOENT: + errno = ENOENT; + break; + case ( LCN )LCN_EINVAL: + errno = EINVAL; + break; + default: + errno = EIO; + break; + } + return NULL; map_rl: - /* The @vcn is in an unmapped region, map the runlist and retry. */ - if (!is_retry && !ntfs_attr_map_runlist(na, vcn)) { - is_retry = TRUE; - goto retry; - } - /* - * If we already retried or the mapping attempt failed something has - * gone badly wrong. EINVAL and ENOENT coming from a failed mapping - * attempt are equivalent to errors for us as they should not happen - * in our code paths. - */ - if (is_retry || errno == EINVAL || errno == ENOENT) - errno = EIO; - return NULL; + /* The @vcn is in an unmapped region, map the runlist and retry. */ + if ( !is_retry && !ntfs_attr_map_runlist( na, vcn ) ) + { + is_retry = TRUE; + goto retry; + } + /* + * If we already retried or the mapping attempt failed something has + * gone badly wrong. EINVAL and ENOENT coming from a failed mapping + * attempt are equivalent to errors for us as they should not happen + * in our code paths. + */ + if ( is_retry || errno == EINVAL || errno == ENOENT ) + errno = EIO; + return NULL; } @@ -810,257 +859,274 @@ map_rl: /** * ntfs_attr_pread_i - see description at ntfs_attr_pread() - */ -static s64 ntfs_attr_getfragments_i(ntfs_attr *na, const s64 pos, s64 count, u64 offset, - _ntfs_frag_append_t append_fragment, void *callback_data) + */ +static s64 ntfs_attr_getfragments_i( ntfs_attr *na, const s64 pos, s64 count, u64 offset, + _ntfs_frag_append_t append_fragment, void *callback_data ) { - u64 b = offset; - s64 br, to_read, ofs, total, total2, max_read, max_init; - ntfs_volume *vol; - runlist_element *rl; - //u16 efs_padding_length; + u64 b = offset; + s64 br, to_read, ofs, total, total2, max_read, max_init; + ntfs_volume *vol; + runlist_element *rl; + //u16 efs_padding_length; - /* Sanity checking arguments is done in ntfs_attr_pread(). */ - - if ((na->data_flags & ATTR_COMPRESSION_MASK) && NAttrNonResident(na)) - { - //return -1; // no compressed files - return -31; - /* - if ((na->data_flags & ATTR_COMPRESSION_MASK) - == ATTR_IS_COMPRESSED) - return ntfs_compressed_attr_pread(na, pos, count, b); - else { - // compression mode not supported - errno = EOPNOTSUPP; - return -1; - } - */ - } - /* - * Encrypted non-resident attributes are not supported. We return - * access denied, which is what Windows NT4 does, too. - * However, allow if mounted with efs_raw option - */ - vol = na->ni->vol; - if (!vol->efs_raw && NAttrEncrypted(na) && NAttrNonResident(na)) { - errno = EACCES; - //return -1; - return -32; - } - - if (!count) - return 0; - /* - * Truncate reads beyond end of attribute, - * but round to next 512 byte boundary for encrypted - * attributes with efs_raw mount option - */ - max_read = na->data_size; - max_init = na->initialized_size; - if (na->ni->vol->efs_raw - && (na->data_flags & ATTR_IS_ENCRYPTED) - && NAttrNonResident(na)) { - if (na->data_size != na->initialized_size) { - ntfs_log_error("uninitialized encrypted file not supported\n"); - errno = EINVAL; - //return -1; - return -33; - } - max_init = max_read = ((na->data_size + 511) & ~511) + 2; - } - if (pos + count > max_read) { - if (pos >= max_read) - return 0; - count = max_read - pos; - } - /* If it is a resident attribute, get the value from the mft record. */ - if (!NAttrNonResident(na)) - { - return -34; // No resident files - /* - ntfs_attr_search_ctx *ctx; - char *val; + /* 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)) - { - return -35; //No encrypted files - /* - efs_padding_length = 511 - ((na->data_size - 1) & 511); - if (pos+count == max_init) { - if (count == 1) { - *((u8*)b+count-1) = (u8)(efs_padding_length >> 8); - count--; - total2++; - } else { - *(u16*)((u8*)b+count-2) = cpu_to_le16(efs_padding_length); - count -= 2; - total2 +=2; - } - } else { - *((u8*)b+count-1) = (u8)(efs_padding_length & 0xff); - count--; - total2++; - } - */ - } - - /* Find the runlist element containing the vcn. */ - rl = ntfs_attr_find_vcn(na, pos >> vol->cluster_size_bits); - if (!rl) { - /* - * If the vcn is not present it is an out of bounds read. - * However, we already truncated the read to the data_size, - * so getting this here is an error. - */ - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN #1", __FUNCTION__); - } - //return -1; - return -36; - } - /* - * Gather the requested data into the linear destination buffer. Note, - * a partial final vcn is taken care of by the @count capping of read - * length. - */ - ofs = pos - (rl->vcn << vol->cluster_size_bits); - for (; count; rl++, ofs = 0) { - if (rl->lcn == LCN_RL_NOT_MAPPED) { - rl = ntfs_attr_find_vcn(na, rl->vcn); - if (!rl) { - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN #2", - __FUNCTION__); - } - goto rl_err_out; - } - /* Needed for case when runs merged. */ - ofs = pos + total - (rl->vcn << vol->cluster_size_bits); - } - if (!rl->length) { - errno = EIO; - ntfs_log_perror("%s: Zero run length", __FUNCTION__); - goto rl_err_out; - } - if (rl->lcn < (LCN)0) { - if (rl->lcn != (LCN)LCN_HOLE) { - ntfs_log_perror("%s: Bad run (%lld)", - __FUNCTION__, - (long long)rl->lcn); - goto rl_err_out; - } - /* It is a hole, just zero the matching @b range. */ - to_read = min(count, (rl->length << - vol->cluster_size_bits) - ofs); - //memset(b, 0, to_read); - /* Update progress counters. */ - total += to_read; - count -= to_read; - b = b + to_read; - continue; - } - /* It is a real lcn, read it into @dst. */ - to_read = min(count, (rl->length << vol->cluster_size_bits) - - ofs); + if ( ( na->data_flags & ATTR_COMPRESSION_MASK ) && NAttrNonResident( na ) ) + { + //return -1; // no compressed files + return -31; + /* + if ((na->data_flags & ATTR_COMPRESSION_MASK) + == ATTR_IS_COMPRESSED) + return ntfs_compressed_attr_pread(na, pos, count, b); + else { + // compression mode not supported + errno = EOPNOTSUPP; + return -1; + } + */ + } + /* + * Encrypted non-resident attributes are not supported. We return + * access denied, which is what Windows NT4 does, too. + * However, allow if mounted with efs_raw option + */ + vol = na->ni->vol; + if ( !vol->efs_raw && NAttrEncrypted( na ) && NAttrNonResident( na ) ) + { + errno = EACCES; + //return -1; + return -32; + } + + if ( !count ) + return 0; + /* + * Truncate reads beyond end of attribute, + * but round to next 512 byte boundary for encrypted + * attributes with efs_raw mount option + */ + max_read = na->data_size; + max_init = na->initialized_size; + if ( na->ni->vol->efs_raw + && ( na->data_flags & ATTR_IS_ENCRYPTED ) + && NAttrNonResident( na ) ) + { + if ( na->data_size != na->initialized_size ) + { + ntfs_log_error( "uninitialized encrypted file not supported\n" ); + errno = EINVAL; + //return -1; + return -33; + } + max_init = max_read = ( ( na->data_size + 511 ) & ~511 ) + 2; + } + if ( pos + count > max_read ) + { + if ( pos >= max_read ) + return 0; + count = max_read - pos; + } + /* If it is a resident attribute, get the value from the mft record. */ + if ( !NAttrNonResident( na ) ) + { + return -34; // No resident files + /* + ntfs_attr_search_ctx *ctx; + char *val; + + ctx = ntfs_attr_get_search_ctx(na->ni, NULL); + if (!ctx) + return -1; + if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, + 0, NULL, 0, ctx)) { + res_err_out: + ntfs_attr_put_search_ctx(ctx); + return -1; + } + val = (char*)ctx->attr + le16_to_cpu(ctx->attr->value_offset); + if (val < (char*)ctx->attr || val + + le32_to_cpu(ctx->attr->value_length) > + (char*)ctx->mrec + vol->mft_record_size) { + errno = EIO; + ntfs_log_perror("%s: Sanity check failed", __FUNCTION__); + goto res_err_out; + } + memcpy(b, val + pos, count); + ntfs_attr_put_search_ctx(ctx); + return count; + */ + } + total = total2 = 0; + /* Zero out reads beyond initialized size. */ + if ( pos + count > max_init ) + { + if ( pos >= max_init ) + { + //memset(b, 0, count); + return count; + } + total2 = pos + count - max_init; + count -= total2; + //memset((u8*)b + count, 0, total2); + } + /* + * for encrypted non-resident attributes with efs_raw set + * the last two bytes aren't read from disk but contain + * the number of padding bytes so original size can be + * restored + */ + if ( na->ni->vol->efs_raw && + ( na->data_flags & ATTR_IS_ENCRYPTED ) && + ( ( pos + count ) > max_init - 2 ) ) + { + return -35; //No encrypted files + /* + efs_padding_length = 511 - ((na->data_size - 1) & 511); + if (pos+count == max_init) { + if (count == 1) { + *((u8*)b+count-1) = (u8)(efs_padding_length >> 8); + count--; + total2++; + } else { + *(u16*)((u8*)b+count-2) = cpu_to_le16(efs_padding_length); + count -= 2; + total2 +=2; + } + } else { + *((u8*)b+count-1) = (u8)(efs_padding_length & 0xff); + count--; + total2++; + } + */ + } + + /* Find the runlist element containing the vcn. */ + rl = ntfs_attr_find_vcn( na, pos >> vol->cluster_size_bits ); + if ( !rl ) + { + /* + * If the vcn is not present it is an out of bounds read. + * However, we already truncated the read to the data_size, + * so getting this here is an error. + */ + if ( errno == ENOENT ) + { + errno = EIO; + ntfs_log_perror( "%s: Failed to find VCN #1", __FUNCTION__ ); + } + //return -1; + return -36; + } + /* + * Gather the requested data into the linear destination buffer. Note, + * a partial final vcn is taken care of by the @count capping of read + * length. + */ + ofs = pos - ( rl->vcn << vol->cluster_size_bits ); + for ( ; count; rl++, ofs = 0 ) + { + if ( rl->lcn == LCN_RL_NOT_MAPPED ) + { + rl = ntfs_attr_find_vcn( na, rl->vcn ); + if ( !rl ) + { + if ( errno == ENOENT ) + { + errno = EIO; + ntfs_log_perror( "%s: Failed to find VCN #2", + __FUNCTION__ ); + } + goto rl_err_out; + } + /* Needed for case when runs merged. */ + ofs = pos + total - ( rl->vcn << vol->cluster_size_bits ); + } + if ( !rl->length ) + { + errno = EIO; + ntfs_log_perror( "%s: Zero run length", __FUNCTION__ ); + goto rl_err_out; + } + if ( rl->lcn < ( LCN )0 ) + { + if ( rl->lcn != ( LCN )LCN_HOLE ) + { + ntfs_log_perror( "%s: Bad run (%lld)", + __FUNCTION__, + ( long long )rl->lcn ); + goto rl_err_out; + } + /* It is a hole, just zero the matching @b range. */ + to_read = min( count, ( rl->length << + vol->cluster_size_bits ) - ofs ); + //memset(b, 0, to_read); + /* Update progress counters. */ + total += to_read; + count -= to_read; + b = b + to_read; + continue; + } + /* It is a real lcn, read it into @dst. */ + to_read = min( count, ( rl->length << vol->cluster_size_bits ) - + ofs ); retry: - ntfs_log_trace("Reading %lld bytes from vcn %lld, lcn %lld, ofs" - " %lld.\n", (long long)to_read, (long long)rl->vcn, - (long long )rl->lcn, (long long)ofs); - /* - br = ntfs_pread(vol->dev, (rl->lcn << vol->cluster_size_bits) + - ofs, to_read, b); - */ - br = to_read; - // convert to sectors unit - u32 off_sec = b >> 9; - u32 sector = ((rl->lcn << vol->cluster_size_bits) + ofs) >> 9; - u32 count_sec = to_read >> 9; - int ret; - ret = append_fragment(callback_data, off_sec, sector, count_sec); - if (ret) { - if (ret < 0) return ret; - return -50; - } - /* If everything ok, update progress counters and continue. */ - if (br > 0) { - total += br; - count -= br; - b = b + br; - } - if (br == to_read) - continue; - /* If the syscall was interrupted, try again. */ - if (br == (s64)-1 && errno == EINTR) - goto retry; - if (total) - return total; - if (!br) - errno = EIO; - ntfs_log_perror("%s: ntfs_pread failed", __FUNCTION__); - //return -1; - return -38; - } - /* Finally, return the number of bytes read. */ - return total + total2; + ntfs_log_trace( "Reading %lld bytes from vcn %lld, lcn %lld, ofs" + " %lld.\n", ( long long )to_read, ( long long )rl->vcn, + ( long long )rl->lcn, ( long long )ofs ); + /* + br = ntfs_pread(vol->dev, (rl->lcn << vol->cluster_size_bits) + + ofs, to_read, b); + */ + br = to_read; + // convert to sectors unit + u32 off_sec = b >> 9; + u32 sector = ( ( rl->lcn << vol->cluster_size_bits ) + ofs ) >> 9; + u32 count_sec = to_read >> 9; + int ret; + ret = append_fragment( callback_data, off_sec, sector, count_sec ); + if ( ret ) + { + if ( ret < 0 ) return ret; + return -50; + } + /* If everything ok, update progress counters and continue. */ + if ( br > 0 ) + { + total += br; + count -= br; + b = b + br; + } + if ( br == to_read ) + continue; + /* If the syscall was interrupted, try again. */ + if ( br == ( s64 ) - 1 && errno == EINTR ) + goto retry; + if ( total ) + return total; + if ( !br ) + errno = EIO; + ntfs_log_perror( "%s: ntfs_pread failed", __FUNCTION__ ); + //return -1; + return -38; + } + /* Finally, return the number of bytes read. */ + return total + total2; rl_err_out: - if (total) - return total; - errno = EIO; - //return -1; - return -39; + if ( total ) + return total; + errno = EIO; + //return -1; + return -39; } /** * ntfs_attr_pread - read from an attribute specified by an ntfs_attr structure - * @na: ntfs attribute to read from - * @pos: byte position in the attribute to begin reading from - * @count: number of bytes to read - * @b: output data buffer + * @na: ntfs attribute to read from + * @pos: byte position in the attribute to begin reading from + * @count: number of bytes to read + * @b: output data buffer * * This function will read @count bytes starting at offset @pos from the ntfs * attribute @na into the data buffer @b. @@ -1074,236 +1140,256 @@ 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; + s64 ret; - if (!na || !na->ni || !na->ni->vol || !callback_data || pos < 0 || count < 0) { - errno = EINVAL; - ntfs_log_perror("%s: na=%p b=%p pos=%lld count=%lld", - __FUNCTION__, na, callback_data, (long long)pos, - (long long)count); - //return -1; - return -21; - } + if ( !na || !na->ni || !na->ni->vol || !callback_data || pos < 0 || count < 0 ) + { + errno = EINVAL; + ntfs_log_perror( "%s: na=%p b=%p pos=%lld count=%lld", + __FUNCTION__, na, callback_data, ( long long )pos, + ( long long )count ); + //return -1; + return -21; + } - /* - ntfs_log_enter("Entering for inode %lld attr 0x%x pos %lld count " - "%lld\n", (unsigned long long)na->ni->mft_no, - na->type, (long long)pos, (long long)count); - */ + /* + ntfs_log_enter("Entering for inode %lld attr 0x%x pos %lld count " + "%lld\n", (unsigned long long)na->ni->mft_no, + na->type, (long long)pos, (long long)count); + */ - ret = ntfs_attr_getfragments_i(na, pos, count, offset, - append_fragment, callback_data); + ret = ntfs_attr_getfragments_i( na, pos, count, offset, + append_fragment, callback_data ); - //ntfs_log_leave("\n"); - return ret; + //ntfs_log_leave("\n"); + return ret; } #if 0 -static int ntfs_attr_fill_zero(ntfs_attr *na, s64 pos, s64 count) +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); + ntfs_log_trace( "pos %lld, count %lld\n", ( long long )pos, + ( long long )count ); + + if ( !na || pos < 0 || count < 0 ) + { + errno = EINVAL; + goto err_out; + } + + buf = ntfs_calloc( NTFS_BUF_SIZE ); + if ( !buf ) + goto err_out; + + rli = na->rl; + ofsi = 0; + vol = na->ni->vol; + while ( pos < end ) + { + while ( rli->length && ( ofsi + ( rli->length << + vol->cluster_size_bits ) <= pos ) ) + { + ofsi += ( rli->length << vol->cluster_size_bits ); + rli++; + } + size = min( end - pos, NTFS_BUF_SIZE ); + written = ntfs_rl_pwrite( vol, rli, ofsi, pos, size, buf ); + if ( written <= 0 ) + { + ntfs_log_perror( "Failed to zero space" ); + goto err_free; + } + pos += written; + } + + ret = 0; +err_free: + free( buf ); err_out: - return ret; + return ret; } -static int ntfs_attr_fill_hole(ntfs_attr *na, s64 count, s64 *ofs, - runlist_element **rl, VCN *update_from) +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 hole. - * We may need space to decompress existing compressed data. - */ - rlc = ntfs_cluster_alloc(vol, (*rl)->vcn, (*rl)->length, - lcn_seek_from, DATA_ZONE); - } else - rlc = ntfs_cluster_alloc(vol, from_vcn, need, - lcn_seek_from, DATA_ZONE); - if (!rlc) - goto err_out; - - *rl = ntfs_runlists_merge(na->rl, rlc); - /* - * For a compressed attribute, we must be sure there is an - * available entry, so reserve it before it gets too late. - */ - if (*rl && (na->data_flags & ATTR_COMPRESSION_MASK)) - *rl = ntfs_rl_extend(*rl,1); - if (!*rl) { - eo = errno; - ntfs_log_perror("Failed to merge runlists"); - if (ntfs_cluster_free_from_rl(vol, rlc)) { - ntfs_log_perror("Failed to free hot clusters. " - "Please run chkdsk /f"); - } - errno = eo; - goto err_out; - } - na->rl = *rl; - if (*update_from == -1) - *update_from = from_vcn; - *rl = ntfs_attr_find_vcn(na, cur_vcn); - if (!*rl) { - /* - * It's definitely a BUG, if we failed to find @cur_vcn, because - * we missed it during instantiating of the hole. - */ - ntfs_log_error("Failed to find run after hole instantiation. " - "Please report to %s.\n", NTFS_DEV_LIST); - errno = EIO; - goto err_out; - } - /* If leaved part of the hole go to the next run. */ - if ((*rl)->lcn < 0) - (*rl)++; - /* Now LCN shoudn't be less than 0. */ - if ((*rl)->lcn < 0) { - ntfs_log_error("BUG! LCN is lesser than 0. " - "Please report to the %s.\n", NTFS_DEV_LIST); - errno = EIO; - goto err_out; - } - if (*ofs) { - /* Clear non-sparse region from @cur_vcn to @*ofs. */ - if (ntfs_attr_fill_zero(na, cur_vcn << vol->cluster_size_bits, - *ofs)) - goto err_out; - } - if ((*rl)->vcn < cur_vcn) { - /* - * Clusters that replaced hole are merged with - * previous run, so we need to update offset. - */ - *ofs += (cur_vcn - (*rl)->vcn) << vol->cluster_size_bits; - } - if ((*rl)->vcn > cur_vcn) { - /* - * We left part of the hole, so we need to update offset - */ - *ofs -= ((*rl)->vcn - cur_vcn) << vol->cluster_size_bits; - } - - ret = 0; + to_write = min( count, ( ( *rl )->length << vol->cluster_size_bits ) - *ofs ); + + cur_vcn = ( *rl )->vcn; + from_vcn = ( *rl )->vcn + ( *ofs >> vol->cluster_size_bits ); + + ntfs_log_trace( "count: %lld, cur_vcn: %lld, from: %lld, to: %lld, ofs: " + "%lld\n", ( long long )count, ( long long )cur_vcn, + ( long long )from_vcn, ( long long )to_write, ( long long )*ofs ); + + /* Map whole runlist to be able update mapping pairs later. */ + if ( ntfs_attr_map_whole_runlist( na ) ) + goto err_out; + + /* Restore @*rl, it probably get lost during runlist mapping. */ + *rl = ntfs_attr_find_vcn( na, cur_vcn ); + if ( !*rl ) + { + ntfs_log_error( "Failed to find run after mapping runlist. " + "Please report to %s.\n", NTFS_DEV_LIST ); + errno = EIO; + goto err_out; + } + + /* Search backwards to find the best lcn to start seek from. */ + rlc = *rl; + while ( rlc->vcn ) + { + rlc--; + if ( rlc->lcn >= 0 ) + { + /* + * avoid fragmenting a compressed file + * Windows does not do that, and that may + * not be desirable for files which can + * be updated + */ + if ( na->data_flags & ATTR_COMPRESSION_MASK ) + lcn_seek_from = rlc->lcn + rlc->length; + else + lcn_seek_from = rlc->lcn + ( from_vcn - rlc->vcn ); + break; + } + } + if ( lcn_seek_from == -1 ) + { + /* Backwards search failed, search forwards. */ + rlc = *rl; + while ( rlc->length ) + { + rlc++; + if ( rlc->lcn >= 0 ) + { + lcn_seek_from = rlc->lcn - ( rlc->vcn - from_vcn ); + if ( lcn_seek_from < -1 ) + lcn_seek_from = -1; + break; + } + } + } + + need = ( ( *ofs + to_write - 1 ) >> vol->cluster_size_bits ) + + 1 + ( *rl )->vcn - from_vcn; + if ( ( na->data_flags & ATTR_COMPRESSION_MASK ) + && ( need < na->compression_block_clusters ) ) + { + /* + * for a compressed file, be sure to allocate the full hole. + * We may need space to decompress existing compressed data. + */ + rlc = ntfs_cluster_alloc( vol, ( *rl )->vcn, ( *rl )->length, + lcn_seek_from, DATA_ZONE ); + } + else + rlc = ntfs_cluster_alloc( vol, from_vcn, need, + lcn_seek_from, DATA_ZONE ); + if ( !rlc ) + goto err_out; + + *rl = ntfs_runlists_merge( na->rl, rlc ); + /* + * For a compressed attribute, we must be sure there is an + * available entry, so reserve it before it gets too late. + */ + if ( *rl && ( na->data_flags & ATTR_COMPRESSION_MASK ) ) + *rl = ntfs_rl_extend( *rl, 1 ); + if ( !*rl ) + { + eo = errno; + ntfs_log_perror( "Failed to merge runlists" ); + if ( ntfs_cluster_free_from_rl( vol, rlc ) ) + { + ntfs_log_perror( "Failed to free hot clusters. " + "Please run chkdsk /f" ); + } + errno = eo; + goto err_out; + } + na->rl = *rl; + if ( *update_from == -1 ) + *update_from = from_vcn; + *rl = ntfs_attr_find_vcn( na, cur_vcn ); + if ( !*rl ) + { + /* + * It's definitely a BUG, if we failed to find @cur_vcn, because + * we missed it during instantiating of the hole. + */ + ntfs_log_error( "Failed to find run after hole instantiation. " + "Please report to %s.\n", NTFS_DEV_LIST ); + errno = EIO; + goto err_out; + } + /* If leaved part of the hole go to the next run. */ + if ( ( *rl )->lcn < 0 ) + ( *rl )++; + /* Now LCN shoudn't be less than 0. */ + if ( ( *rl )->lcn < 0 ) + { + ntfs_log_error( "BUG! LCN is lesser than 0. " + "Please report to the %s.\n", NTFS_DEV_LIST ); + errno = EIO; + goto err_out; + } + if ( *ofs ) + { + /* Clear non-sparse region from @cur_vcn to @*ofs. */ + if ( ntfs_attr_fill_zero( na, cur_vcn << vol->cluster_size_bits, + *ofs ) ) + goto err_out; + } + if ( ( *rl )->vcn < cur_vcn ) + { + /* + * Clusters that replaced hole are merged with + * previous run, so we need to update offset. + */ + *ofs += ( cur_vcn - ( *rl )->vcn ) << vol->cluster_size_bits; + } + if ( ( *rl )->vcn > cur_vcn ) + { + /* + * We left part of the hole, so we need to update offset + */ + *ofs -= ( ( *rl )->vcn - cur_vcn ) << vol->cluster_size_bits; + } + + ret = 0; err_out: - return ret; + return ret; } -static int stuff_hole(ntfs_attr *na, const s64 pos); +static int stuff_hole( ntfs_attr *na, const s64 pos ); /** * ntfs_attr_pwrite - positioned write to an ntfs attribute - * @na: ntfs attribute to write to - * @pos: position in the attribute to write to - * @count: number of bytes to write - * @b: data buffer to write to disk + * @na: ntfs attribute to write to + * @pos: position in the attribute to write to + * @count: number of bytes to write + * @b: data buffer to write to disk * * This function will write @count bytes from data buffer @b to ntfs attribute * @na at position @pos. @@ -1317,659 +1403,723 @@ static int stuff_hole(ntfs_attr *na, const s64 pos); * appropriately to the return code of ntfs_pwrite(), or to EINVAL in case of * invalid arguments. */ -s64 ntfs_attr_pwrite(ntfs_attr *na, const s64 pos, s64 count, const void *b) +s64 ntfs_attr_pwrite( ntfs_attr *na, const s64 pos, s64 count, const void *b ) { - s64 written, to_write, ofs, old_initialized_size, old_data_size; - s64 total = 0; - VCN update_from = -1; - ntfs_volume *vol; - s64 fullcount; - ntfs_attr_search_ctx *ctx = NULL; - runlist_element *rl; - s64 hole_end; - int eo; - int compressed_part; - struct { - unsigned int undo_initialized_size : 1; - unsigned int undo_data_size : 1; - } need_to = { 0, 0 }; - BOOL makingnonresident = FALSE; - BOOL wasnonresident = FALSE; - BOOL compressed; + s64 written, to_write, ofs, old_initialized_size, old_data_size; + s64 total = 0; + VCN update_from = -1; + ntfs_volume *vol; + s64 fullcount; + ntfs_attr_search_ctx *ctx = NULL; + runlist_element *rl; + s64 hole_end; + int eo; + int compressed_part; + struct + { + unsigned int undo_initialized_size : 1; + unsigned int undo_data_size : 1; + } need_to = { 0, 0 }; + BOOL makingnonresident = FALSE; + BOOL wasnonresident = FALSE; + BOOL compressed; - ntfs_log_enter("Entering for inode %lld, attr 0x%x, pos 0x%llx, count " - "0x%llx.\n", (long long)na->ni->mft_no, na->type, - (long long)pos, (long long)count); - - if (!na || !na->ni || !na->ni->vol || !b || pos < 0 || count < 0) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - goto errno_set; - } - vol = na->ni->vol; - compressed = (na->data_flags & ATTR_COMPRESSION_MASK) - != const_cpu_to_le16(0); - /* - * Encrypted attributes are only supported in raw mode. We return - * access denied, which is what Windows NT4 does, too. - * Moreover a file cannot be both encrypted and compressed. - */ - if ((na->data_flags & ATTR_IS_ENCRYPTED) - && (compressed || !vol->efs_raw)) { - errno = EACCES; - goto errno_set; - } - /* - * Fill the gap, when writing beyond the end of a compressed - * file. This will make recursive calls - */ - if (compressed - && (na->type == AT_DATA) - && (pos > na->initialized_size) - && stuff_hole(na,pos)) - goto errno_set; - /* If this is a compressed attribute it needs special treatment. */ - wasnonresident = NAttrNonResident(na) != 0; - makingnonresident = wasnonresident /* yes : already changed */ - && !pos && (count == na->initialized_size); - /* - * Writing to compressed files is currently restricted - * to appending data. However we have to accept - * recursive write calls to make the attribute non resident. - * These are writing at position 0 up to initialized_size. - * Compression is also restricted to data streams. - * Only ATTR_IS_COMPRESSED compression mode is supported. - */ - if (compressed - && ((na->type != AT_DATA) - || ((na->data_flags & ATTR_COMPRESSION_MASK) - != ATTR_IS_COMPRESSED) - || ((pos != na->initialized_size) - && (pos || (count != na->initialized_size))))) { - // TODO: Implement writing compressed attributes! (AIA) - errno = EOPNOTSUPP; - goto errno_set; - } - - if (!count) - goto out; - /* for a compressed file, get prepared to reserve a full block */ - fullcount = count; - /* If the write reaches beyond the end, extend the attribute. */ - old_data_size = na->data_size; - if (pos + count > na->data_size) { - if (ntfs_attr_truncate(na, pos + count)) { - ntfs_log_perror("Failed to enlarge attribute"); - goto errno_set; - } - /* resizing may change the compression mode */ - compressed = (na->data_flags & ATTR_COMPRESSION_MASK) - != const_cpu_to_le16(0); - need_to.undo_data_size = 1; - } - /* - * For compressed data, a single full block was allocated - * to deal with compression, possibly in a previous call. - * We are not able to process several blocks because - * some clusters are freed after compression and - * new allocations have to be done before proceeding, - * so truncate the requested count if needed (big buffers). - */ - if (compressed) { - fullcount = na->data_size - pos; - if (count > fullcount) - count = fullcount; - } - old_initialized_size = na->initialized_size; - /* If it is a resident attribute, write the data to the mft record. */ - if (!NAttrNonResident(na)) { - char *val; + 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 (pos + count > na->initialized_size) { - if (ntfs_attr_map_whole_runlist(na)) - goto err_out; - /* - * For a compressed attribute, we must be sure there is an - * available entry, and, when reopening a compressed file, - * we may need to split a hole. So reserve the entries - * before it gets too late. - */ - if (compressed) { - na->rl = ntfs_rl_extend(na->rl,2); - if (!na->rl) - goto err_out; - } - /* Set initialized_size to @pos + @count. */ - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - goto err_out; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, - 0, NULL, 0, ctx)) - goto err_out; - - /* If write starts beyond initialized_size, zero the gap. */ - if (pos > na->initialized_size) - if (ntfs_attr_fill_zero(na, na->initialized_size, - pos - na->initialized_size)) - goto err_out; - - ctx->attr->initialized_size = cpu_to_sle64(pos + count); - /* fix data_size for compressed files */ - if (compressed) - ctx->attr->data_size = ctx->attr->initialized_size; - if (ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, - ctx->mrec)) { - /* - * Undo the change in the in-memory copy and send it - * back for writing. - */ - ctx->attr->initialized_size = - cpu_to_sle64(old_initialized_size); - ntfs_mft_record_write(vol, ctx->ntfs_ino->mft_no, - ctx->mrec); - goto err_out; - } - na->initialized_size = pos + count; - ntfs_attr_put_search_ctx(ctx); - ctx = NULL; - /* - * NOTE: At this point the initialized_size in the mft record - * has been updated BUT there is random data on disk thus if - * we decide to abort, we MUST change the initialized_size - * again. - */ - need_to.undo_initialized_size = 1; - } - /* Find the runlist element containing the vcn. */ - rl = ntfs_attr_find_vcn(na, pos >> vol->cluster_size_bits); - if (!rl) { - /* - * If the vcn is not present it is an out of bounds write. - * However, we already extended the size of the attribute, - * so getting this here must be an error of some kind. - */ - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN #3", __FUNCTION__); - } - goto err_out; - } - ofs = pos - (rl->vcn << vol->cluster_size_bits); - /* - * Determine if there is compressed data in the current - * compression block (when appending to an existing file). - * If so, decompression will be needed, and the full block - * must be allocated to be identified as uncompressed. - * This comes in two variants, depending on whether - * compression has saved at least one cluster. - * The compressed size can never be over full size by - * more than 485 (maximum for 15 compression blocks - * compressed to 4098 and the last 3640 bytes compressed - * to 3640 + 3640/8 = 4095, with 15*2 + 4095 - 3640 = 485) - * This is less than the smallest cluster, so the hole is - * is never beyond the cluster next to the position of - * the first uncompressed byte to write. - */ - compressed_part = 0; - if (compressed) { - if ((rl->lcn == (LCN)LCN_HOLE) - && wasnonresident) { - if (rl->length < na->compression_block_clusters) - compressed_part - = na->compression_block_clusters - - rl->length; - else { - compressed_part - = na->compression_block_clusters; - if (rl->length > na->compression_block_clusters) { - rl[2].lcn = rl[1].lcn; - rl[2].vcn = rl[1].vcn; - rl[2].length = rl[1].length; - rl[1].vcn -= compressed_part; - rl[1].lcn = LCN_HOLE; - rl[1].length = compressed_part; - rl[0].length -= compressed_part; - ofs -= rl->length << vol->cluster_size_bits; - rl++; - } - } - /* normal hole filling will do later */ - } else - if ((rl->lcn >= 0) && (rl[1].lcn == (LCN)LCN_HOLE)) { - s64 xofs; + if ( !na || !na->ni || !na->ni->vol || !b || pos < 0 || count < 0 ) + { + errno = EINVAL; + ntfs_log_perror( "%s", __FUNCTION__ ); + goto errno_set; + } + vol = na->ni->vol; + compressed = ( na->data_flags & ATTR_COMPRESSION_MASK ) + != const_cpu_to_le16( 0 ); + /* + * Encrypted attributes are only supported in raw mode. We return + * access denied, which is what Windows NT4 does, too. + * Moreover a file cannot be both encrypted and compressed. + */ + if ( ( na->data_flags & ATTR_IS_ENCRYPTED ) + && ( compressed || !vol->efs_raw ) ) + { + errno = EACCES; + goto errno_set; + } + /* + * Fill the gap, when writing beyond the end of a compressed + * file. This will make recursive calls + */ + if ( compressed + && ( na->type == AT_DATA ) + && ( pos > na->initialized_size ) + && stuff_hole( na, pos ) ) + goto errno_set; + /* If this is a compressed attribute it needs special treatment. */ + wasnonresident = NAttrNonResident( na ) != 0; + makingnonresident = wasnonresident /* yes : already changed */ + && !pos && ( count == na->initialized_size ); + /* + * Writing to compressed files is currently restricted + * to appending data. However we have to accept + * recursive write calls to make the attribute non resident. + * These are writing at position 0 up to initialized_size. + * Compression is also restricted to data streams. + * Only ATTR_IS_COMPRESSED compression mode is supported. + */ + if ( compressed + && ( ( na->type != AT_DATA ) + || ( ( na->data_flags & ATTR_COMPRESSION_MASK ) + != ATTR_IS_COMPRESSED ) + || ( ( pos != na->initialized_size ) + && ( pos || ( count != na->initialized_size ) ) ) ) ) + { + // TODO: Implement writing compressed attributes! (AIA) + errno = EOPNOTSUPP; + goto errno_set; + } - if (wasnonresident) - compressed_part = na->compression_block_clusters - - rl[1].length; - rl++; - xofs = 0; - if (ntfs_attr_fill_hole(na, - rl->length << vol->cluster_size_bits, - &xofs, &rl, &update_from)) - goto err_out; - /* the fist allocated cluster was not merged */ - if (!xofs) - rl--; - } - } - /* - * Scatter the data from the linear data buffer to the volume. Note, a - * partial final vcn is taken care of by the @count capping of write - * length. - */ - for (hole_end = 0; count; rl++, ofs = 0, hole_end = 0) { - if (rl->lcn == LCN_RL_NOT_MAPPED) { - rl = ntfs_attr_find_vcn(na, rl->vcn); - if (!rl) { - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN" - " #4", __FUNCTION__); - } - goto rl_err_out; - } - /* Needed for case when runs merged. */ - ofs = pos + total - (rl->vcn << vol->cluster_size_bits); - } - if (!rl->length) { - errno = EIO; - ntfs_log_perror("%s: Zero run length", __FUNCTION__); - goto rl_err_out; - } - if (rl->lcn < (LCN)0) { - hole_end = rl->vcn + rl->length; + if ( !count ) + goto out; + /* for a compressed file, get prepared to reserve a full block */ + fullcount = count; + /* If the write reaches beyond the end, extend the attribute. */ + old_data_size = na->data_size; + if ( pos + count > na->data_size ) + { + if ( ntfs_attr_truncate( na, pos + count ) ) + { + ntfs_log_perror( "Failed to enlarge attribute" ); + goto errno_set; + } + /* resizing may change the compression mode */ + compressed = ( na->data_flags & ATTR_COMPRESSION_MASK ) + != const_cpu_to_le16( 0 ); + need_to.undo_data_size = 1; + } + /* + * For compressed data, a single full block was allocated + * to deal with compression, possibly in a previous call. + * We are not able to process several blocks because + * some clusters are freed after compression and + * new allocations have to be done before proceeding, + * so truncate the requested count if needed (big buffers). + */ + if ( compressed ) + { + fullcount = na->data_size - pos; + if ( count > fullcount ) + count = fullcount; + } + old_initialized_size = na->initialized_size; + /* If it is a resident attribute, write the data to the mft record. */ + if ( !NAttrNonResident( na ) ) + { + char *val; - if (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++; - } - } + 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; + } - /* It is a real lcn, write it to the volume. */ - to_write = min(count, (rl->length << vol->cluster_size_bits) - ofs); + /* Handle writes beyond initialized_size. */ + if ( pos + count > na->initialized_size ) + { + if ( ntfs_attr_map_whole_runlist( na ) ) + goto err_out; + /* + * For a compressed attribute, we must be sure there is an + * available entry, and, when reopening a compressed file, + * we may need to split a hole. So reserve the entries + * before it gets too late. + */ + if ( compressed ) + { + na->rl = ntfs_rl_extend( na->rl, 2 ); + if ( !na->rl ) + goto err_out; + } + /* Set initialized_size to @pos + @count. */ + ctx = ntfs_attr_get_search_ctx( na->ni, NULL ); + if ( !ctx ) + goto err_out; + if ( ntfs_attr_lookup( na->type, na->name, na->name_len, 0, + 0, NULL, 0, ctx ) ) + goto err_out; + + /* If write starts beyond initialized_size, zero the gap. */ + if ( pos > na->initialized_size ) + if ( ntfs_attr_fill_zero( na, na->initialized_size, + pos - na->initialized_size ) ) + goto err_out; + + ctx->attr->initialized_size = cpu_to_sle64( pos + count ); + /* fix data_size for compressed files */ + if ( compressed ) + ctx->attr->data_size = ctx->attr->initialized_size; + if ( ntfs_mft_record_write( vol, ctx->ntfs_ino->mft_no, + ctx->mrec ) ) + { + /* + * Undo the change in the in-memory copy and send it + * back for writing. + */ + ctx->attr->initialized_size = + cpu_to_sle64( old_initialized_size ); + ntfs_mft_record_write( vol, ctx->ntfs_ino->mft_no, + ctx->mrec ); + goto err_out; + } + na->initialized_size = pos + count; + ntfs_attr_put_search_ctx( ctx ); + ctx = NULL; + /* + * NOTE: At this point the initialized_size in the mft record + * has been updated BUT there is random data on disk thus if + * we decide to abort, we MUST change the initialized_size + * again. + */ + need_to.undo_initialized_size = 1; + } + /* Find the runlist element containing the vcn. */ + rl = ntfs_attr_find_vcn( na, pos >> vol->cluster_size_bits ); + if ( !rl ) + { + /* + * If the vcn is not present it is an out of bounds write. + * However, we already extended the size of the attribute, + * so getting this here must be an error of some kind. + */ + if ( errno == ENOENT ) + { + errno = EIO; + ntfs_log_perror( "%s: Failed to find VCN #3", __FUNCTION__ ); + } + goto err_out; + } + ofs = pos - ( rl->vcn << vol->cluster_size_bits ); + /* + * Determine if there is compressed data in the current + * compression block (when appending to an existing file). + * If so, decompression will be needed, and the full block + * must be allocated to be identified as uncompressed. + * This comes in two variants, depending on whether + * compression has saved at least one cluster. + * The compressed size can never be over full size by + * more than 485 (maximum for 15 compression blocks + * compressed to 4098 and the last 3640 bytes compressed + * to 3640 + 3640/8 = 4095, with 15*2 + 4095 - 3640 = 485) + * This is less than the smallest cluster, so the hole is + * is never beyond the cluster next to the position of + * the first uncompressed byte to write. + */ + compressed_part = 0; + if ( compressed ) + { + if ( ( rl->lcn == ( LCN )LCN_HOLE ) + && wasnonresident ) + { + if ( rl->length < na->compression_block_clusters ) + compressed_part + = na->compression_block_clusters + - rl->length; + else + { + compressed_part + = na->compression_block_clusters; + if ( rl->length > na->compression_block_clusters ) + { + rl[2].lcn = rl[1].lcn; + rl[2].vcn = rl[1].vcn; + rl[2].length = rl[1].length; + rl[1].vcn -= compressed_part; + rl[1].lcn = LCN_HOLE; + rl[1].length = compressed_part; + rl[0].length -= compressed_part; + ofs -= rl->length << vol->cluster_size_bits; + rl++; + } + } + /* normal hole filling will do later */ + } + else if ( ( rl->lcn >= 0 ) && ( rl[1].lcn == ( LCN )LCN_HOLE ) ) + { + s64 xofs; + + if ( wasnonresident ) + compressed_part = na->compression_block_clusters + - rl[1].length; + rl++; + xofs = 0; + if ( ntfs_attr_fill_hole( na, + rl->length << vol->cluster_size_bits, + &xofs, &rl, &update_from ) ) + goto err_out; + /* the fist allocated cluster was not merged */ + if ( !xofs ) + rl--; + } + } + /* + * Scatter the data from the linear data buffer to the volume. Note, a + * partial final vcn is taken care of by the @count capping of write + * length. + */ + for ( hole_end = 0; count; rl++, ofs = 0, hole_end = 0 ) + { + if ( rl->lcn == LCN_RL_NOT_MAPPED ) + { + rl = ntfs_attr_find_vcn( na, rl->vcn ); + if ( !rl ) + { + if ( errno == ENOENT ) + { + errno = EIO; + ntfs_log_perror( "%s: Failed to find VCN" + " #4", __FUNCTION__ ); + } + goto rl_err_out; + } + /* Needed for case when runs merged. */ + ofs = pos + total - ( rl->vcn << vol->cluster_size_bits ); + } + if ( !rl->length ) + { + errno = EIO; + ntfs_log_perror( "%s: Zero run length", __FUNCTION__ ); + goto rl_err_out; + } + if ( rl->lcn < ( LCN )0 ) + { + hole_end = rl->vcn + rl->length; + + if ( rl->lcn != ( LCN )LCN_HOLE ) + { + errno = EIO; + ntfs_log_perror( "%s: Unexpected LCN (%lld)", + __FUNCTION__, + ( long long )rl->lcn ); + goto rl_err_out; + } + if ( ntfs_attr_fill_hole( na, fullcount, &ofs, &rl, + &update_from ) ) + goto err_out; + } + if ( compressed ) + { + while ( rl->length + && ( ofs >= ( rl->length << vol->cluster_size_bits ) ) ) + { + ofs -= rl->length << vol->cluster_size_bits; + rl++; + } + } + + /* It is a real lcn, write it to the volume. */ + to_write = min( count, ( rl->length << vol->cluster_size_bits ) - ofs ); retry: - ntfs_log_trace("Writing %lld bytes to vcn %lld, lcn %lld, ofs " - "%lld.\n", (long long)to_write, (long long)rl->vcn, - (long long)rl->lcn, (long long)ofs); - if (!NVolReadOnly(vol)) { - - s64 wpos = (rl->lcn << vol->cluster_size_bits) + ofs; - s64 wend = (rl->vcn << vol->cluster_size_bits) + ofs + to_write; - u32 bsize = vol->cluster_size; - /* Byte size needed to zero fill a cluster */ - s64 rounding = ((wend + bsize - 1) & ~(s64)(bsize - 1)) - wend; - /** - * Zero fill to cluster boundary if we're writing at the - * end of the attribute or into an ex-sparse cluster. - * This will cause the kernel not to seek and read disk - * blocks during write(2) to fill the end of the buffer - * which increases write speed by 2-10 fold typically. - * - * This is done even for compressed files, because - * data is generally first written uncompressed. - */ - if (rounding && ((wend == na->initialized_size) || - (wend < (hole_end << vol->cluster_size_bits)))){ - - char *cb; - - rounding += to_write; - - cb = ntfs_malloc(rounding); - if (!cb) - goto err_out; - - memcpy(cb, b, to_write); - memset(cb + to_write, 0, rounding - to_write); - - if (compressed) { - written = ntfs_compressed_pwrite(na, - rl, wpos, ofs, to_write, - rounding, b, compressed_part); - } else { - written = ntfs_pwrite(vol->dev, wpos, - rounding, cb); - if (written == rounding) - written = to_write; - } - - free(cb); - } else { - if (compressed) { - written = ntfs_compressed_pwrite(na, - rl, wpos, ofs, to_write, - to_write, b, compressed_part); - } else - written = ntfs_pwrite(vol->dev, wpos, - to_write, b); - } - } else - written = to_write; - /* If everything ok, update progress counters and continue. */ - if (written > 0) { - total += written; - count -= written; - fullcount -= written; - b = (const u8*)b + written; - } - if (written != to_write) { - /* Partial write cannot be dealt with, stop there */ - /* If the syscall was interrupted, try again. */ - if (written == (s64)-1 && errno == EINTR) - goto retry; - if (!written) - errno = EIO; - goto rl_err_out; - } - compressed_part = 0; - } -done: - if (ctx) - ntfs_attr_put_search_ctx(ctx); - /* Update mapping pairs if needed. */ - if ((update_from != -1) - || (compressed && !makingnonresident)) - if (ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/)) { - /* - * FIXME: trying to recover by goto rl_err_out; - * could cause driver hang by infinite looping. - */ - total = -1; - goto out; - } -out: - ntfs_log_leave("\n"); - return total; -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; + 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. */ - if (update_from != -1) - ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/); - /* Restore original data_size if needed. */ - if (need_to.undo_data_size && ntfs_attr_truncate(na, old_data_size)) - ntfs_log_perror("Failed to restore data_size"); - errno = eo; + s64 wpos = ( rl->lcn << vol->cluster_size_bits ) + ofs; + s64 wend = ( rl->vcn << vol->cluster_size_bits ) + ofs + to_write; + u32 bsize = vol->cluster_size; + /* Byte size needed to zero fill a cluster */ + s64 rounding = ( ( wend + bsize - 1 ) & ~( s64 )( bsize - 1 ) ) - wend; + /** + * Zero fill to cluster boundary if we're writing at the + * end of the attribute or into an ex-sparse cluster. + * This will cause the kernel not to seek and read disk + * blocks during write(2) to fill the end of the buffer + * which increases write speed by 2-10 fold typically. + * + * This is done even for compressed files, because + * data is generally first written uncompressed. + */ + if ( rounding && ( ( wend == na->initialized_size ) || + ( wend < ( hole_end << vol->cluster_size_bits ) ) ) ) + { + + char *cb; + + rounding += to_write; + + cb = ntfs_malloc( rounding ); + if ( !cb ) + goto err_out; + + memcpy( cb, b, to_write ); + memset( cb + to_write, 0, rounding - to_write ); + + if ( compressed ) + { + written = ntfs_compressed_pwrite( na, + rl, wpos, ofs, to_write, + rounding, b, compressed_part ); + } + else + { + written = ntfs_pwrite( vol->dev, wpos, + rounding, cb ); + if ( written == rounding ) + written = to_write; + } + + free( cb ); + } + else + { + if ( compressed ) + { + written = ntfs_compressed_pwrite( na, + rl, wpos, ofs, to_write, + to_write, b, compressed_part ); + } + else + written = ntfs_pwrite( vol->dev, wpos, + to_write, b ); + } + } + else + written = to_write; + /* If everything ok, update progress counters and continue. */ + if ( written > 0 ) + { + total += written; + count -= written; + fullcount -= written; + b = ( const u8* )b + written; + } + if ( written != to_write ) + { + /* Partial write cannot be dealt with, stop there */ + /* If the syscall was interrupted, try again. */ + if ( written == ( s64 ) - 1 && errno == EINTR ) + goto retry; + if ( !written ) + errno = EIO; + goto rl_err_out; + } + compressed_part = 0; + } +done: + if ( ctx ) + ntfs_attr_put_search_ctx( ctx ); + /* Update mapping pairs if needed. */ + if ( ( update_from != -1 ) + || ( compressed && !makingnonresident ) ) + if ( ntfs_attr_update_mapping_pairs( na, 0 /*update_from*/ ) ) + { + /* + * FIXME: trying to recover by goto rl_err_out; + * could cause driver hang by infinite looping. + */ + total = -1; + goto out; + } +out: + ntfs_log_leave( "\n" ); + return total; +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. */ + if ( update_from != -1 ) + ntfs_attr_update_mapping_pairs( na, 0 /*update_from*/ ); + /* Restore original data_size if needed. */ + if ( need_to.undo_data_size && ntfs_attr_truncate( na, old_data_size ) ) + ntfs_log_perror( "Failed to restore data_size" ); + errno = eo; errno_set: - total = -1; - goto out; + total = -1; + goto out; } -int ntfs_attr_pclose(ntfs_attr *na) +int ntfs_attr_pclose( ntfs_attr *na ) { - s64 written, ofs; - BOOL ok = TRUE; - VCN update_from = -1; - ntfs_volume *vol; - ntfs_attr_search_ctx *ctx = NULL; - runlist_element *rl; - int eo; - s64 hole; - int compressed_part; - BOOL compressed; + s64 written, ofs; + BOOL ok = TRUE; + VCN update_from = -1; + ntfs_volume *vol; + ntfs_attr_search_ctx *ctx = NULL; + runlist_element *rl; + int eo; + s64 hole; + int compressed_part; + BOOL compressed; - ntfs_log_enter("Entering for inode 0x%llx, attr 0x%x.\n", - na->ni->mft_no, na->type); - - if (!na || !na->ni || !na->ni->vol) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - goto errno_set; - } - vol = na->ni->vol; - compressed = (na->data_flags & ATTR_COMPRESSION_MASK) - != const_cpu_to_le16(0); - /* - * Encrypted non-resident attributes are not supported. We return - * access denied, which is what Windows NT4 does, too. - */ - if (NAttrEncrypted(na) && NAttrNonResident(na)) { - errno = EACCES; - goto errno_set; - } - /* If this is not a compressed attribute get out */ - /* same if it is resident */ - if (!compressed || !NAttrNonResident(na)) - goto out; + ntfs_log_enter( "Entering for inode 0x%llx, attr 0x%x.\n", + na->ni->mft_no, na->type ); - /* - * For a compressed attribute, we must be sure there is an - * available entry, so reserve it before it gets too late. - */ - if (ntfs_attr_map_whole_runlist(na)) - goto err_out; - na->rl = ntfs_rl_extend(na->rl,1); - if (!na->rl) - goto err_out; - /* Find the runlist element containing the terminal vcn. */ - rl = ntfs_attr_find_vcn(na, (na->initialized_size - 1) >> vol->cluster_size_bits); - if (!rl) { - /* - * If the vcn is not present it is an out of bounds write. - * However, we have already written the last byte uncompressed, - * so getting this here must be an error of some kind. - */ - if (errno == ENOENT) { - errno = EIO; - ntfs_log_perror("%s: Failed to find VCN #5", __FUNCTION__); - } - goto err_out; - } - /* - * Scatter the data from the linear data buffer to the volume. Note, a - * partial final vcn is taken care of by the @count capping of write - * length. - */ - compressed_part = 0; - if ((rl->lcn >= 0) && (rl[1].lcn == (LCN)LCN_HOLE)) - compressed_part - = na->compression_block_clusters - rl[1].length; - else - if (rl->lcn == (LCN)LCN_HOLE) { - if (rl->length < na->compression_block_clusters) - compressed_part - = na->compression_block_clusters - - rl->length; - else - compressed_part - = na->compression_block_clusters; - } - /* done, if the last block set was compressed */ - if (compressed_part) - goto out; + if ( !na || !na->ni || !na->ni->vol ) + { + errno = EINVAL; + ntfs_log_perror( "%s", __FUNCTION__ ); + goto errno_set; + } + vol = na->ni->vol; + compressed = ( na->data_flags & ATTR_COMPRESSION_MASK ) + != const_cpu_to_le16( 0 ); + /* + * Encrypted non-resident attributes are not supported. We return + * access denied, which is what Windows NT4 does, too. + */ + if ( NAttrEncrypted( na ) && NAttrNonResident( na ) ) + { + errno = EACCES; + goto errno_set; + } + /* If this is not a compressed attribute get out */ + /* same if it is resident */ + if ( !compressed || !NAttrNonResident( na ) ) + goto out; - ofs = na->initialized_size - (rl->vcn << vol->cluster_size_bits); + /* + * For a compressed attribute, we must be sure there is an + * available entry, so reserve it before it gets too late. + */ + if ( ntfs_attr_map_whole_runlist( na ) ) + goto err_out; + na->rl = ntfs_rl_extend( na->rl, 1 ); + if ( !na->rl ) + goto err_out; + /* Find the runlist element containing the terminal vcn. */ + rl = ntfs_attr_find_vcn( na, ( na->initialized_size - 1 ) >> vol->cluster_size_bits ); + if ( !rl ) + { + /* + * If the vcn is not present it is an out of bounds write. + * However, we have already written the last byte uncompressed, + * so getting this here must be an error of some kind. + */ + if ( errno == ENOENT ) + { + errno = EIO; + ntfs_log_perror( "%s: Failed to find VCN #5", __FUNCTION__ ); + } + goto err_out; + } + /* + * Scatter the data from the linear data buffer to the volume. Note, a + * partial final vcn is taken care of by the @count capping of write + * length. + */ + compressed_part = 0; + if ( ( rl->lcn >= 0 ) && ( rl[1].lcn == ( LCN )LCN_HOLE ) ) + compressed_part + = na->compression_block_clusters - rl[1].length; + else if ( rl->lcn == ( LCN )LCN_HOLE ) + { + if ( rl->length < na->compression_block_clusters ) + compressed_part + = na->compression_block_clusters + - rl->length; + else + compressed_part + = na->compression_block_clusters; + } + /* done, if the last block set was compressed */ + if ( compressed_part ) + goto out; - 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 ); + + if ( rl->lcn == LCN_RL_NOT_MAPPED ) + { + rl = ntfs_attr_find_vcn( na, rl->vcn ); + if ( !rl ) + { + if ( errno == ENOENT ) + { + errno = EIO; + ntfs_log_perror( "%s: Failed to find VCN" + " #6", __FUNCTION__ ); + } + goto rl_err_out; + } + /* Needed for case when runs merged. */ + ofs = na->initialized_size - ( rl->vcn << vol->cluster_size_bits ); + } + if ( !rl->length ) + { + errno = EIO; + ntfs_log_perror( "%s: Zero run length", __FUNCTION__ ); + goto rl_err_out; + } + if ( rl->lcn < ( LCN )0 ) + { + hole = rl->vcn + rl->length; + if ( rl->lcn != ( LCN )LCN_HOLE ) + { + errno = EIO; + ntfs_log_perror( "%s: Unexpected LCN (%lld)", + __FUNCTION__, + ( long long )rl->lcn ); + goto rl_err_out; + } + + if ( ntfs_attr_fill_hole( na, ( s64 )0, &ofs, &rl, &update_from ) ) + goto err_out; + } + while ( rl->length + && ( ofs >= ( rl->length << vol->cluster_size_bits ) ) ) + { + ofs -= rl->length << vol->cluster_size_bits; + rl++; + } retry: - if (!NVolReadOnly(vol)) { - - written = ntfs_compressed_close(na, rl, ofs); - /* If everything ok, update progress counters and continue. */ - if (!written) - goto done; - } - /* If the syscall was interrupted, try again. */ - if (written == (s64)-1 && errno == EINTR) - goto retry; - if (!written) - errno = EIO; - goto rl_err_out; + if ( !NVolReadOnly( vol ) ) + { + + written = ntfs_compressed_close( na, rl, ofs ); + /* If everything ok, update progress counters and continue. */ + if ( !written ) + goto done; + } + /* If the syscall was interrupted, try again. */ + if ( written == ( s64 ) - 1 && errno == EINTR ) + goto retry; + if ( !written ) + errno = EIO; + goto rl_err_out; done: - if (ctx) - ntfs_attr_put_search_ctx(ctx); - /* Update mapping pairs if needed. */ - if (ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/)) { - /* - * FIXME: trying to recover by goto rl_err_out; - * could cause driver hang by infinite looping. - */ - ok = FALSE; - goto out; - } -out: - ntfs_log_leave("\n"); - return (!ok); + if ( ctx ) + ntfs_attr_put_search_ctx( ctx ); + /* Update mapping pairs if needed. */ + if ( ntfs_attr_update_mapping_pairs( na, 0 /*update_from*/ ) ) + { + /* + * FIXME: trying to recover by goto rl_err_out; + * could cause driver hang by infinite looping. + */ + ok = FALSE; + goto out; + } +out: + ntfs_log_leave( "\n" ); + return ( !ok ); rl_err_out: - /* - * need not restore old sizes, only compressed_size - * can have changed. It has been set according to - * the current runlist while updating the mapping pairs, - * and must be kept consistent with the runlists. - */ + /* + * need not restore old sizes, only compressed_size + * can have changed. It has been set according to + * the current runlist while updating the mapping pairs, + * and must be kept consistent with the runlists. + */ err_out: - eo = errno; - if (ctx) - ntfs_attr_put_search_ctx(ctx); - /* Update mapping pairs if needed. */ - ntfs_attr_update_mapping_pairs(na, 0 /*update_from*/); - errno = eo; + eo = errno; + if ( ctx ) + ntfs_attr_put_search_ctx( ctx ); + /* Update mapping pairs if needed. */ + ntfs_attr_update_mapping_pairs( na, 0 /*update_from*/ ); + errno = eo; errno_set: - ok = FALSE; - goto out; + ok = FALSE; + goto out; } /** * ntfs_attr_mst_pread - multi sector transfer protected ntfs attribute read - * @na: multi sector transfer protected ntfs attribute to read from - * @pos: byte position in the attribute to begin reading from - * @bk_cnt: number of mst protected blocks to read - * @bk_size: size of each mst protected block in bytes - * @dst: output data buffer + * @na: multi sector transfer protected ntfs attribute to read from + * @pos: byte position in the attribute to begin reading from + * @bk_cnt: number of mst protected blocks to read + * @bk_size: size of each mst protected block in bytes + * @dst: output data buffer * * This function will read @bk_cnt blocks of size @bk_size bytes each starting * at offset @pos from the ntfs attribute @na into the data buffer @b. @@ -1992,38 +2142,39 @@ 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; } /** * ntfs_attr_mst_pwrite - multi sector transfer protected ntfs attribute write - * @na: multi sector transfer protected ntfs attribute to write to - * @pos: position in the attribute to write to - * @bk_cnt: number of mst protected blocks to write - * @bk_size: size of each mst protected block in bytes - * @src: data buffer to write to disk + * @na: multi sector transfer protected ntfs attribute to write to + * @pos: position in the attribute to write to + * @bk_cnt: number of mst protected blocks to write + * @bk_size: size of each mst protected block in bytes + * @src: data buffer to write to disk * * This function will write @bk_cnt blocks of size @bk_size bytes each from * data buffer @b to multi sector transfer (mst) protected ntfs attribute @na @@ -2047,60 +2198,64 @@ 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; } /** * ntfs_attr_find - find (next) attribute in mft record - * @type: attribute type to find - * @name: attribute name to find (optional, i.e. NULL means don't care) - * @name_len: attribute name length (only needed if @name present) - * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present) - * @val: attribute value to find (optional, resident attributes only) - * @val_len: attribute value length - * @ctx: search context with mft record and attribute to search from + * @type: attribute type to find + * @name: attribute name to find (optional, i.e. NULL means don't care) + * @name_len: attribute name length (only needed if @name present) + * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present) + * @val: attribute value to find (optional, resident attributes only) + * @val_len: attribute value length + * @ctx: search context with mft record and attribute to search from * * You shouldn't need to call this function directly. Use lookup_attr() instead. * @@ -2160,179 +2315,201 @@ s64 ntfs_attr_mst_pwrite(ntfs_attr *na, const s64 pos, s64 bk_cnt, * rely on being able to find the first extent in the base mft record. * * Warning: Never use @val when looking for attribute types which can be - * non-resident as this most likely will result in a crash! + * 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 if (name && !ntfs_names_are_equal(name, name_len, - (ntfschar*)((char*)a + le16_to_cpu(a->name_offset)), - a->name_length, ic, upcase, upcase_len)) { - register int rc; + if ( ctx->ntfs_ino ) + { + vol = ctx->ntfs_ino->vol; + upcase = vol->upcase; + upcase_len = vol->upcase_len; + } + else + { + if ( name && name != AT_UNNAMED ) + { + errno = EINVAL; + ntfs_log_perror( "%s", __FUNCTION__ ); + return -1; + } + vol = NULL; + upcase = NULL; + upcase_len = 0; + } + /* + * Iterate over attributes in mft record starting at @ctx->attr, or the + * attribute following that, if @ctx->is_first is TRUE. + */ + if ( ctx->is_first ) + { + a = ctx->attr; + ctx->is_first = FALSE; + } + else + a = ( ATTR_RECORD* )( ( char* )ctx->attr + + le32_to_cpu( ctx->attr->length ) ); + for ( ;; a = ( ATTR_RECORD* )( ( char* )a + le32_to_cpu( a->length ) ) ) + { + if ( p2n( a ) < p2n( ctx->mrec ) || ( char* )a > ( char* )ctx->mrec + + le32_to_cpu( ctx->mrec->bytes_allocated ) ) + break; + ctx->attr = a; + if ( ( ( type != AT_UNUSED ) && ( le32_to_cpu( a->type ) > + le32_to_cpu( type ) ) ) || + ( a->type == AT_END ) ) + { + errno = ENOENT; + return -1; + } + if ( !a->length ) + break; + /* If this is an enumeration return this attribute. */ + if ( type == AT_UNUSED ) + return 0; + if ( a->type != type ) + continue; + /* + * If @name is AT_UNNAMED we want an unnamed attribute. + * If @name is present, compare the two names. + * Otherwise, match any attribute. + */ + if ( name == AT_UNNAMED ) + { + /* The search failed if the found attribute is named. */ + if ( a->name_length ) + { + errno = ENOENT; + return -1; + } + } + else if ( name && !ntfs_names_are_equal( name, name_len, + ( ntfschar* )( ( char* )a + le16_to_cpu( a->name_offset ) ), + a->name_length, ic, upcase, upcase_len ) ) + { + register int rc; - rc = ntfs_names_collate(name, name_len, - (ntfschar*)((char*)a + - le16_to_cpu(a->name_offset)), - a->name_length, 1, IGNORE_CASE, - upcase, upcase_len); - /* - * If @name collates before a->name, there is no - * matching attribute. - */ - if (rc == -1) { - errno = ENOENT; - return -1; - } - /* If the strings are not equal, continue search. */ - if (rc) - continue; - rc = ntfs_names_collate(name, name_len, - (ntfschar*)((char*)a + - le16_to_cpu(a->name_offset)), - a->name_length, 1, CASE_SENSITIVE, - upcase, upcase_len); - if (rc == -1) { - errno = ENOENT; - return -1; - } - if (rc) - continue; - } - /* - * The names match or @name not present and attribute is - * unnamed. If no @val specified, we have found the attribute - * and are done. - */ - if (!val) - return 0; - /* @val is present; compare values. */ - else { - register int rc; + rc = ntfs_names_collate( name, name_len, + ( ntfschar* )( ( char* )a + + le16_to_cpu( a->name_offset ) ), + a->name_length, 1, IGNORE_CASE, + upcase, upcase_len ); + /* + * If @name collates before a->name, there is no + * matching attribute. + */ + if ( rc == -1 ) + { + errno = ENOENT; + return -1; + } + /* If the strings are not equal, continue search. */ + if ( rc ) + continue; + rc = ntfs_names_collate( name, name_len, + ( ntfschar* )( ( char* )a + + le16_to_cpu( a->name_offset ) ), + a->name_length, 1, CASE_SENSITIVE, + upcase, upcase_len ); + if ( rc == -1 ) + { + errno = ENOENT; + return -1; + } + if ( rc ) + continue; + } + /* + * The names match or @name not present and attribute is + * unnamed. If no @val specified, we have found the attribute + * and are done. + */ + if ( !val ) + return 0; + /* @val is present; compare values. */ + else + { + register int rc; - rc = memcmp(val, (char*)a +le16_to_cpu(a->value_offset), - min(val_len, - le32_to_cpu(a->value_length))); - /* - * If @val collates before the current attribute's - * value, there is no matching attribute. - */ - if (!rc) { - register u32 avl; - avl = le32_to_cpu(a->value_length); - if (val_len == avl) - return 0; - if (val_len < avl) { - errno = ENOENT; - return -1; - } - } else if (rc < 0) { - errno = ENOENT; - return -1; - } - } - } - errno = EIO; - ntfs_log_perror("%s: Corrupt inode (%lld)", __FUNCTION__, - ctx->ntfs_ino ? (long long)ctx->ntfs_ino->mft_no : -1); - return -1; + rc = memcmp( val, ( char* )a + le16_to_cpu( a->value_offset ), + min( val_len, + le32_to_cpu( a->value_length ) ) ); + /* + * If @val collates before the current attribute's + * value, there is no matching attribute. + */ + if ( !rc ) + { + register u32 avl; + avl = le32_to_cpu( a->value_length ); + if ( val_len == avl ) + return 0; + if ( val_len < avl ) + { + errno = ENOENT; + return -1; + } + } + else if ( rc < 0 ) + { + errno = ENOENT; + return -1; + } + } + } + errno = EIO; + ntfs_log_perror( "%s: Corrupt inode (%lld)", __FUNCTION__, + ctx->ntfs_ino ? ( long long )ctx->ntfs_ino->mft_no : -1 ); + return -1; } -void ntfs_attr_name_free(char **name) +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 *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; } /** * ntfs_external_attr_find - find an attribute in the attribute list of an inode - * @type: attribute type to find - * @name: attribute name to find (optional, i.e. NULL means don't care) - * @name_len: attribute name length (only needed if @name present) - * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present) - * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only) - * @val: attribute value to find (optional, resident attributes only) - * @val_len: attribute value length - * @ctx: search context with mft record and attribute to search from + * @type: attribute type to find + * @name: attribute name to find (optional, i.e. NULL means don't care) + * @name_len: attribute name length (only needed if @name present) + * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present) + * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only) + * @val: attribute value to find (optional, resident attributes only) + * @val_len: attribute value length + * @ctx: search context with mft record and attribute to search from * * You shouldn't need to call this function directly. Use ntfs_attr_lookup() * instead. @@ -2388,361 +2565,385 @@ char *ntfs_attr_name_get(const ntfschar *uname, const int uname_len) * @ctx->al_entry is set to NULL also (see above). * * The following error codes are defined: - * ENOENT Attribute not found, not an error as such. - * EINVAL Invalid arguments. - * EIO I/O error or corrupt data structures found. - * ENOMEM Not enough memory to allocate necessary buffers. + * ENOENT Attribute not found, not an error as such. + * EINVAL Invalid arguments. + * 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; + ni = ctx->ntfs_ino; + base_ni = ctx->base_ntfs_ino; + ntfs_log_trace( "Entering for inode %lld, attribute type 0x%x.\n", + ( unsigned long long )ni->mft_no, type ); + if ( !base_ni ) + { + /* First call happens with the base mft record. */ + base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino; + ctx->base_mrec = ctx->mrec; + } + if ( ni == base_ni ) + ctx->base_attr = ctx->attr; + if ( type == AT_END ) + goto not_found; + vol = base_ni->vol; + al_start = base_ni->attr_list; + al_end = al_start + base_ni->attr_list_size; + if ( !ctx->al_entry ) + { + ctx->al_entry = ( ATTR_LIST_ENTRY* )al_start; + is_first_search = TRUE; + } + /* + * Iterate over entries in attribute list starting at @ctx->al_entry, + * or the entry following that, if @ctx->is_first is TRUE. + */ + if ( ctx->is_first ) + { + al_entry = ctx->al_entry; + ctx->is_first = FALSE; + /* + * If an enumeration and the first attribute is higher than + * the attribute list itself, need to return the attribute list + * attribute. + */ + if ( ( type == AT_UNUSED ) && is_first_search && + le32_to_cpu( al_entry->type ) > + le32_to_cpu( AT_ATTRIBUTE_LIST ) ) + goto find_attr_list_attr; + } + else + { + al_entry = ( ATTR_LIST_ENTRY* )( ( char* )ctx->al_entry + + le16_to_cpu( ctx->al_entry->length ) ); + /* + * If this is an enumeration and the attribute list attribute + * is the next one in the enumeration sequence, just return the + * attribute list attribute from the base mft record as it is + * not listed in the attribute list itself. + */ + if ( ( type == AT_UNUSED ) && le32_to_cpu( ctx->al_entry->type ) < + le32_to_cpu( AT_ATTRIBUTE_LIST ) && + le32_to_cpu( al_entry->type ) > + le32_to_cpu( AT_ATTRIBUTE_LIST ) ) + { + int rc; find_attr_list_attr: - /* Check for bogus calls. */ - if (name || name_len || val || val_len || lowest_vcn) { - errno = EINVAL; - ntfs_log_perror("%s", __FUNCTION__); - return -1; - } + /* Check for bogus calls. */ + if ( name || name_len || val || val_len || lowest_vcn ) + { + errno = EINVAL; + ntfs_log_perror( "%s", __FUNCTION__ ); + return -1; + } - /* We want the base record. */ - ctx->ntfs_ino = base_ni; - ctx->mrec = ctx->base_mrec; - ctx->is_first = TRUE; - /* Sanity checks are performed elsewhere. */ - ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + - le16_to_cpu(ctx->mrec->attrs_offset)); + /* We want the base record. */ + ctx->ntfs_ino = base_ni; + ctx->mrec = ctx->base_mrec; + ctx->is_first = TRUE; + /* Sanity checks are performed elsewhere. */ + ctx->attr = ( ATTR_RECORD* )( ( u8* )ctx->mrec + + le16_to_cpu( ctx->mrec->attrs_offset ) ); - /* Find the attribute list attribute. */ - rc = ntfs_attr_find(AT_ATTRIBUTE_LIST, NULL, 0, - IGNORE_CASE, NULL, 0, ctx); + /* Find the attribute list attribute. */ + rc = ntfs_attr_find( AT_ATTRIBUTE_LIST, NULL, 0, + IGNORE_CASE, NULL, 0, ctx ); - /* - * Setup the search context so the correct - * attribute is returned next time round. - */ - ctx->al_entry = al_entry; - ctx->is_first = TRUE; + /* + * Setup the search context so the correct + * attribute is returned next time round. + */ + ctx->al_entry = al_entry; + ctx->is_first = TRUE; - /* Got it. Done. */ - if (!rc) - return 0; + /* Got it. Done. */ + if ( !rc ) + return 0; - /* Error! If other than not found return it. */ - if (errno != ENOENT) - return rc; + /* Error! If other than not found return it. */ + if ( errno != ENOENT ) + return rc; - /* Not found?!? Absurd! */ - errno = EIO; - ntfs_log_error("Attribute list wasn't found"); - return -1; - } - } - for (;; al_entry = next_al_entry) { - /* Out of bounds check. */ - if ((u8*)al_entry < base_ni->attr_list || - (u8*)al_entry > al_end) - break; /* Inode is corrupt. */ - ctx->al_entry = al_entry; - /* Catch the end of the attribute list. */ - if ((u8*)al_entry == al_end) - goto not_found; - if (!al_entry->length) - break; - if ((u8*)al_entry + 6 > al_end || (u8*)al_entry + - le16_to_cpu(al_entry->length) > al_end) - break; - next_al_entry = (ATTR_LIST_ENTRY*)((u8*)al_entry + - le16_to_cpu(al_entry->length)); - if (type != AT_UNUSED) { - if (le32_to_cpu(al_entry->type) > le32_to_cpu(type)) - goto not_found; - if (type != al_entry->type) - continue; - } - al_name_len = al_entry->name_length; - al_name = (ntfschar*)((u8*)al_entry + al_entry->name_offset); - /* - * If !@type we want the attribute represented by this - * attribute list entry. - */ - if (type == AT_UNUSED) - goto is_enumeration; - /* - * If @name is AT_UNNAMED we want an unnamed attribute. - * If @name is present, compare the two names. - * Otherwise, match any attribute. - */ - if (name == AT_UNNAMED) { - if (al_name_len) - goto not_found; - } else if (name && !ntfs_names_are_equal(al_name, al_name_len, - name, name_len, ic, vol->upcase, - vol->upcase_len)) { - register int rc; + /* Not found?!? Absurd! */ + errno = EIO; + ntfs_log_error( "Attribute list wasn't found" ); + return -1; + } + } + for ( ;; al_entry = next_al_entry ) + { + /* Out of bounds check. */ + if ( ( u8* )al_entry < base_ni->attr_list || + ( u8* )al_entry > al_end ) + break; /* Inode is corrupt. */ + ctx->al_entry = al_entry; + /* Catch the end of the attribute list. */ + if ( ( u8* )al_entry == al_end ) + goto not_found; + if ( !al_entry->length ) + break; + if ( ( u8* )al_entry + 6 > al_end || ( u8* )al_entry + + le16_to_cpu( al_entry->length ) > al_end ) + break; + next_al_entry = ( ATTR_LIST_ENTRY* )( ( u8* )al_entry + + le16_to_cpu( al_entry->length ) ); + if ( type != AT_UNUSED ) + { + if ( le32_to_cpu( al_entry->type ) > le32_to_cpu( type ) ) + goto not_found; + if ( type != al_entry->type ) + continue; + } + al_name_len = al_entry->name_length; + al_name = ( ntfschar* )( ( u8* )al_entry + al_entry->name_offset ); + /* + * If !@type we want the attribute represented by this + * attribute list entry. + */ + if ( type == AT_UNUSED ) + goto is_enumeration; + /* + * If @name is AT_UNNAMED we want an unnamed attribute. + * If @name is present, compare the two names. + * Otherwise, match any attribute. + */ + if ( name == AT_UNNAMED ) + { + if ( al_name_len ) + goto not_found; + } + else if ( name && !ntfs_names_are_equal( al_name, al_name_len, + name, name_len, ic, vol->upcase, + vol->upcase_len ) ) + { + register int rc; - rc = ntfs_names_collate(name, name_len, al_name, - al_name_len, 1, IGNORE_CASE, - vol->upcase, vol->upcase_len); - /* - * If @name collates before al_name, there is no - * matching attribute. - */ - if (rc == -1) - goto not_found; - /* If the strings are not equal, continue search. */ - if (rc) - continue; - /* - * FIXME: Reverse engineering showed 0, IGNORE_CASE but - * that is inconsistent with ntfs_attr_find(). The - * subsequent rc checks were also different. Perhaps I - * made a mistake in one of the two. Need to recheck - * which is correct or at least see what is going - * on... (AIA) - */ - rc = ntfs_names_collate(name, name_len, al_name, - al_name_len, 1, CASE_SENSITIVE, - vol->upcase, vol->upcase_len); - if (rc == -1) - goto not_found; - if (rc) - continue; - } - /* - * The names match or @name not present and attribute is - * unnamed. Now check @lowest_vcn. Continue search if the - * next attribute list entry still fits @lowest_vcn. Otherwise - * we have reached the right one or the search has failed. - */ - if (lowest_vcn && (u8*)next_al_entry >= al_start && - (u8*)next_al_entry + 6 < al_end && - (u8*)next_al_entry + le16_to_cpu( - next_al_entry->length) <= al_end && - sle64_to_cpu(next_al_entry->lowest_vcn) <= - lowest_vcn && - next_al_entry->type == al_entry->type && - next_al_entry->name_length == al_name_len && - ntfs_names_are_equal((ntfschar*)((char*) - next_al_entry + - next_al_entry->name_offset), - next_al_entry->name_length, - al_name, al_name_len, CASE_SENSITIVE, - vol->upcase, vol->upcase_len)) - continue; + rc = ntfs_names_collate( name, name_len, al_name, + al_name_len, 1, IGNORE_CASE, + vol->upcase, vol->upcase_len ); + /* + * If @name collates before al_name, there is no + * matching attribute. + */ + if ( rc == -1 ) + goto not_found; + /* If the strings are not equal, continue search. */ + if ( rc ) + continue; + /* + * FIXME: Reverse engineering showed 0, IGNORE_CASE but + * that is inconsistent with ntfs_attr_find(). The + * subsequent rc checks were also different. Perhaps I + * made a mistake in one of the two. Need to recheck + * which is correct or at least see what is going + * on... (AIA) + */ + rc = ntfs_names_collate( name, name_len, al_name, + al_name_len, 1, CASE_SENSITIVE, + vol->upcase, vol->upcase_len ); + if ( rc == -1 ) + goto not_found; + if ( rc ) + continue; + } + /* + * The names match or @name not present and attribute is + * unnamed. Now check @lowest_vcn. Continue search if the + * next attribute list entry still fits @lowest_vcn. Otherwise + * we have reached the right one or the search has failed. + */ + if ( lowest_vcn && ( u8* )next_al_entry >= al_start && + ( u8* )next_al_entry + 6 < al_end && + ( u8* )next_al_entry + le16_to_cpu( + next_al_entry->length ) <= al_end && + sle64_to_cpu( next_al_entry->lowest_vcn ) <= + lowest_vcn && + next_al_entry->type == al_entry->type && + next_al_entry->name_length == al_name_len && + ntfs_names_are_equal( ( ntfschar* )( ( char* ) + next_al_entry + + next_al_entry->name_offset ), + next_al_entry->name_length, + al_name, al_name_len, CASE_SENSITIVE, + vol->upcase, vol->upcase_len ) ) + continue; is_enumeration: - if (MREF_LE(al_entry->mft_reference) == ni->mft_no) { - if (MSEQNO_LE(al_entry->mft_reference) != - le16_to_cpu( - ni->mrec->sequence_number)) { - ntfs_log_error("Found stale mft reference in " - "attribute list!\n"); - break; - } - } else { /* Mft references do not match. */ - /* Do we want the base record back? */ - if (MREF_LE(al_entry->mft_reference) == - base_ni->mft_no) { - ni = ctx->ntfs_ino = base_ni; - ctx->mrec = ctx->base_mrec; - } else { - /* We want an extent record. */ - ni = ntfs_extent_inode_open(base_ni, - al_entry->mft_reference); - if (!ni) - break; - ctx->ntfs_ino = ni; - ctx->mrec = ni->mrec; - } - } - a = ctx->attr = (ATTR_RECORD*)((char*)ctx->mrec + - le16_to_cpu(ctx->mrec->attrs_offset)); - /* - * ctx->ntfs_ino, ctx->mrec, and ctx->attr now point to the - * mft record containing the attribute represented by the - * current al_entry. - * - * We could call into ntfs_attr_find() to find the right - * attribute in this mft record but this would be less - * efficient and not quite accurate as ntfs_attr_find() ignores - * the attribute instance numbers for example which become - * important when one plays with attribute lists. Also, because - * a proper match has been found in the attribute list entry - * above, the comparison can now be optimized. So it is worth - * re-implementing a simplified ntfs_attr_find() here. - * - * Use a manual loop so we can still use break and continue - * with the same meanings as above. - */ + if ( MREF_LE( al_entry->mft_reference ) == ni->mft_no ) + { + if ( MSEQNO_LE( al_entry->mft_reference ) != + le16_to_cpu( + ni->mrec->sequence_number ) ) + { + ntfs_log_error( "Found stale mft reference in " + "attribute list!\n" ); + break; + } + } + else /* Mft references do not match. */ + { + /* Do we want the base record back? */ + if ( MREF_LE( al_entry->mft_reference ) == + base_ni->mft_no ) + { + ni = ctx->ntfs_ino = base_ni; + ctx->mrec = ctx->base_mrec; + } + else + { + /* We want an extent record. */ + ni = ntfs_extent_inode_open( base_ni, + al_entry->mft_reference ); + if ( !ni ) + break; + ctx->ntfs_ino = ni; + ctx->mrec = ni->mrec; + } + } + a = ctx->attr = ( ATTR_RECORD* )( ( char* )ctx->mrec + + le16_to_cpu( ctx->mrec->attrs_offset ) ); + /* + * ctx->ntfs_ino, ctx->mrec, and ctx->attr now point to the + * mft record containing the attribute represented by the + * current al_entry. + * + * We could call into ntfs_attr_find() to find the right + * attribute in this mft record but this would be less + * efficient and not quite accurate as ntfs_attr_find() ignores + * the attribute instance numbers for example which become + * important when one plays with attribute lists. Also, because + * a proper match has been found in the attribute list entry + * above, the comparison can now be optimized. So it is worth + * re-implementing a simplified ntfs_attr_find() here. + * + * Use a manual loop so we can still use break and continue + * with the same meanings as above. + */ do_next_attr_loop: - if ((char*)a < (char*)ctx->mrec || (char*)a > (char*)ctx->mrec + - le32_to_cpu(ctx->mrec->bytes_allocated)) - break; - if (a->type == AT_END) - continue; - if (!a->length) - break; - if (al_entry->instance != a->instance) - goto do_next_attr; - /* - * If the type and/or the name are/is mismatched between the - * attribute list entry and the attribute record, there is - * corruption so we break and return error EIO. - */ - if (al_entry->type != a->type) - break; - if (!ntfs_names_are_equal((ntfschar*)((char*)a + - le16_to_cpu(a->name_offset)), - a->name_length, al_name, - al_name_len, CASE_SENSITIVE, - vol->upcase, vol->upcase_len)) - break; - ctx->attr = a; - /* - * If no @val specified or @val specified and it matches, we - * have found it! Also, if !@type, it is an enumeration, so we - * want the current attribute. - */ - if ((type == AT_UNUSED) || !val || (!a->non_resident && - le32_to_cpu(a->value_length) == val_len && - !memcmp((char*)a + le16_to_cpu(a->value_offset), - val, val_len))) { - return 0; - } + if ( ( char* )a < ( char* )ctx->mrec || ( char* )a > ( char* )ctx->mrec + + le32_to_cpu( ctx->mrec->bytes_allocated ) ) + break; + if ( a->type == AT_END ) + continue; + if ( !a->length ) + break; + if ( al_entry->instance != a->instance ) + goto do_next_attr; + /* + * If the type and/or the name are/is mismatched between the + * attribute list entry and the attribute record, there is + * corruption so we break and return error EIO. + */ + if ( al_entry->type != a->type ) + break; + if ( !ntfs_names_are_equal( ( ntfschar* )( ( char* )a + + le16_to_cpu( a->name_offset ) ), + a->name_length, al_name, + al_name_len, CASE_SENSITIVE, + vol->upcase, vol->upcase_len ) ) + break; + ctx->attr = a; + /* + * If no @val specified or @val specified and it matches, we + * have found it! Also, if !@type, it is an enumeration, so we + * want the current attribute. + */ + if ( ( type == AT_UNUSED ) || !val || ( !a->non_resident && + le32_to_cpu( a->value_length ) == val_len && + !memcmp( ( char* )a + le16_to_cpu( a->value_offset ), + val, val_len ) ) ) + { + return 0; + } do_next_attr: - /* Proceed to the next attribute in the current mft record. */ - a = (ATTR_RECORD*)((char*)a + le32_to_cpu(a->length)); - goto do_next_attr_loop; - } - if (ni != base_ni) { - ctx->ntfs_ino = base_ni; - ctx->mrec = ctx->base_mrec; - ctx->attr = ctx->base_attr; - } - errno = EIO; - ntfs_log_perror("Inode is corrupt (%lld)", (long long)base_ni->mft_no); - return -1; + /* Proceed to the next attribute in the current mft record. */ + a = ( ATTR_RECORD* )( ( char* )a + le32_to_cpu( a->length ) ); + goto do_next_attr_loop; + } + if ( ni != base_ni ) + { + ctx->ntfs_ino = base_ni; + ctx->mrec = ctx->base_mrec; + ctx->attr = ctx->base_attr; + } + errno = EIO; + ntfs_log_perror( "Inode is corrupt (%lld)", ( long long )base_ni->mft_no ); + return -1; not_found: - /* - * If we were looking for AT_END or we were enumerating and reached the - * end, we reset the search context @ctx and use ntfs_attr_find() to - * seek to the end of the base mft record. - */ - if (type == AT_UNUSED || type == AT_END) { - ntfs_attr_reinit_search_ctx(ctx); - return ntfs_attr_find(AT_END, name, name_len, ic, val, val_len, - ctx); - } - /* - * The attribute wasn't found. Before we return, we want to ensure - * @ctx->mrec and @ctx->attr indicate the position at which the - * attribute should be inserted in the base mft record. Since we also - * want to preserve @ctx->al_entry we cannot reinitialize the search - * context using ntfs_attr_reinit_search_ctx() as this would set - * @ctx->al_entry to NULL. Thus we do the necessary bits manually (see - * ntfs_attr_init_search_ctx() below). Note, we _only_ preserve - * @ctx->al_entry as the remaining fields (base_*) are identical to - * their non base_ counterparts and we cannot set @ctx->base_attr - * correctly yet as we do not know what @ctx->attr will be set to by - * the call to ntfs_attr_find() below. - */ - ctx->mrec = ctx->base_mrec; - ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec + - le16_to_cpu(ctx->mrec->attrs_offset)); - ctx->is_first = TRUE; - ctx->ntfs_ino = ctx->base_ntfs_ino; - ctx->base_ntfs_ino = NULL; - ctx->base_mrec = NULL; - ctx->base_attr = NULL; - /* - * In case there are multiple matches in the base mft record, need to - * keep enumerating until we get an attribute not found response (or - * another error), otherwise we would keep returning the same attribute - * over and over again and all programs using us for enumeration would - * lock up in a tight loop. - */ - { - int ret; + /* + * If we were looking for AT_END or we were enumerating and reached the + * end, we reset the search context @ctx and use ntfs_attr_find() to + * seek to the end of the base mft record. + */ + if ( type == AT_UNUSED || type == AT_END ) + { + ntfs_attr_reinit_search_ctx( ctx ); + return ntfs_attr_find( AT_END, name, name_len, ic, val, val_len, + ctx ); + } + /* + * The attribute wasn't found. Before we return, we want to ensure + * @ctx->mrec and @ctx->attr indicate the position at which the + * attribute should be inserted in the base mft record. Since we also + * want to preserve @ctx->al_entry we cannot reinitialize the search + * context using ntfs_attr_reinit_search_ctx() as this would set + * @ctx->al_entry to NULL. Thus we do the necessary bits manually (see + * ntfs_attr_init_search_ctx() below). Note, we _only_ preserve + * @ctx->al_entry as the remaining fields (base_*) are identical to + * their non base_ counterparts and we cannot set @ctx->base_attr + * correctly yet as we do not know what @ctx->attr will be set to by + * the call to ntfs_attr_find() below. + */ + ctx->mrec = ctx->base_mrec; + ctx->attr = ( ATTR_RECORD* )( ( u8* )ctx->mrec + + le16_to_cpu( ctx->mrec->attrs_offset ) ); + ctx->is_first = TRUE; + ctx->ntfs_ino = ctx->base_ntfs_ino; + ctx->base_ntfs_ino = NULL; + ctx->base_mrec = NULL; + ctx->base_attr = NULL; + /* + * In case there are multiple matches in the base mft record, need to + * keep enumerating until we get an attribute not found response (or + * another error), otherwise we would keep returning the same attribute + * over and over again and all programs using us for enumeration would + * lock up in a tight loop. + */ + { + int ret; - do { - ret = ntfs_attr_find(type, name, name_len, ic, val, - val_len, ctx); - } while (!ret); - return ret; - } + do + { + ret = ntfs_attr_find( type, name, name_len, ic, val, + val_len, ctx ); + } + while ( !ret ); + return ret; + } } /** * ntfs_attr_lookup - find an attribute in an ntfs inode - * @type: attribute type to find - * @name: attribute name to find (optional, i.e. NULL means don't care) - * @name_len: attribute name length (only needed if @name present) - * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present) - * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only) - * @val: attribute value to find (optional, resident attributes only) - * @val_len: attribute value length - * @ctx: search context with mft record and attribute to search from + * @type: attribute type to find + * @name: attribute name to find (optional, i.e. NULL means don't care) + * @name_len: attribute name length (only needed if @name present) + * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present) + * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only) + * @val: attribute value to find (optional, resident attributes only) + * @val_len: attribute value length + * @ctx: search context with mft record and attribute to search from * * Find an attribute in an ntfs inode. On first search @ctx->ntfs_ino must * be the base mft record and @ctx must have been obtained from a call to @@ -2795,48 +2996,49 @@ not_found: * * * The following error codes are defined: - * ENOENT Attribute not found, not an error as such. - * EINVAL Invalid arguments. - * EIO I/O error or corrupt data structures found. - * ENOMEM Not enough memory to allocate necessary buffers. + * ENOENT Attribute not found, not an error as such. + * EINVAL Invalid arguments. + * 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); + ntfs_log_enter( "Entering for attribute type 0x%x\n", type ); + + if ( !ctx || !ctx->mrec || !ctx->attr || ( name && name != AT_UNNAMED && + ( !ctx->ntfs_ino || !( vol = ctx->ntfs_ino->vol ) || + !vol->upcase || !vol->upcase_len ) ) ) + { + errno = EINVAL; + ntfs_log_perror( "%s", __FUNCTION__ ); + goto out; + } + + if ( ctx->base_ntfs_ino ) + base_ni = ctx->base_ntfs_ino; + else + base_ni = ctx->ntfs_ino; + if ( !base_ni || !NInoAttrList( base_ni ) || type == AT_ATTRIBUTE_LIST ) + ret = ntfs_attr_find( type, name, name_len, ic, val, val_len, ctx ); + else + ret = ntfs_external_attr_find( type, name, name_len, ic, + lowest_vcn, val, val_len, ctx ); out: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave( "\n" ); + return ret; } /** * ntfs_attr_position - find given or next attribute type in an ntfs inode - * @type: attribute type to start lookup - * @ctx: search context with mft record and attribute to search from + * @type: attribute type to start lookup + * @ctx: search context with mft record and attribute to search from * * Find an attribute type in an ntfs inode or the next attribute which is not * the AT_END attribute. Please see more details at ntfs_attr_lookup. @@ -2845,80 +3047,83 @@ out: * error code. * * The following error codes are defined: - * EINVAL Invalid arguments. - * EIO I/O error or corrupt data structures found. - * ENOMEM Not enough memory to allocate necessary buffers. - * ENOSPC No attribute was found after 'type', only AT_END. + * EINVAL Invalid arguments. + * EIO I/O error or corrupt data structures found. + * ENOMEM Not enough memory to allocate necessary buffers. + * ENOSPC No attribute was found after 'type', only AT_END. */ -int ntfs_attr_position(const ATTR_TYPES type, ntfs_attr_search_ctx *ctx) +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; } /** * ntfs_attr_init_search_ctx - initialize an attribute search context - * @ctx: attribute search context to initialize - * @ni: ntfs inode with which to initialize the search context - * @mrec: mft record with which to initialize the search context + * @ctx: attribute search context to initialize + * @ni: ntfs inode with which to initialize the search context + * @mrec: mft record with which to initialize the search context * * 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; } /** * ntfs_attr_reinit_search_ctx - reinitialize an attribute search context - * @ctx: attribute search context to reinitialize + * @ctx: attribute search context to reinitialize * * Reinitialize the attribute search context @ctx. * * This is used when a search for a new attribute is being started to reset * the search context to the beginning. */ -void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx) +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; } /** * ntfs_attr_get_search_ctx - allocate/initialize a new attribute search context - * @ni: ntfs inode with which to initialize the search context - * @mrec: mft record with which to initialize the search context + * @ni: ntfs inode with which to initialize the search context + * @mrec: mft record with which to initialize the search context * * Allocate a new attribute search context, initialize it with @ni and @mrec, * and return it. Return NULL on error with errno set. @@ -2929,37 +3134,38 @@ void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx) * be NULL and @mrec to be set. Do NOT do this unless you understand the * implications!!! For example it is no longer safe to call ntfs_attr_lookup(). */ -ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec) +ntfs_attr_search_ctx *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; } /** * ntfs_attr_put_search_ctx - release an attribute search context - * @ctx: attribute search context to free + * @ctx: attribute search context to free * * Release the attribute search context @ctx. */ -void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx) +void ntfs_attr_put_search_ctx( ntfs_attr_search_ctx *ctx ) { - // NOTE: save errno if it could change and function stays void! - free(ctx); + // NOTE: save errno if it could change and function stays void! + free( ctx ); } /** * ntfs_attr_find_in_attrdef - find an attribute in the $AttrDef system file - * @vol: ntfs volume to which the attribute belongs - * @type: attribute type which to find + * @vol: ntfs volume to which the attribute belongs + * @type: attribute type which to find * * Search for the attribute definition record corresponding to the attribute * @type in the $AttrDef system file. @@ -2967,95 +3173,100 @@ void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx) * Return the attribute type definition record if found and NULL if not found * or an error occurred. On error the error code is stored in errno. The * following error codes are defined: - * ENOENT - The attribute @type is not specified in $AttrDef. - * EINVAL - Invalid parameters (e.g. @vol is not valid). + * 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; } /** * ntfs_attr_size_bounds_check - check a size of an attribute type for validity - * @vol: ntfs volume to which the attribute belongs - * @type: attribute type which to check - * @size: size which to check + * @vol: ntfs volume to which the attribute belongs + * @type: attribute type which to check + * @size: size which to check * * Check whether the @size in bytes is valid for an attribute of @type on the * ntfs volume @vol. This information is obtained from $AttrDef system file. * * Return 0 if valid and -1 if not valid or an error occurred. On error the * error code is stored in errno. The following error codes are defined: - * ERANGE - @size is not valid for the attribute @type. - * ENOENT - The attribute @type is not specified in $AttrDef. - * EINVAL - Invalid parameters (e.g. @size is < 0 or @vol is not valid). + * ERANGE - @size is not valid for the attribute @type. + * 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; } /** * ntfs_attr_can_be_non_resident - check if an attribute can be non-resident - * @vol: ntfs volume to which the attribute belongs - * @type: attribute type which to check + * @vol: ntfs volume to which the attribute belongs + * @type: attribute type which to check * * Check whether the attribute of @type on the ntfs volume @vol is allowed to * be non-resident. This information is obtained from $AttrDef system file. @@ -3063,31 +3274,32 @@ int ntfs_attr_size_bounds_check(const ntfs_volume *vol, const ATTR_TYPES type, * Return 0 if the attribute is allowed to be non-resident and -1 if not or an * error occurred. On error the error code is stored in errno. The following * error codes are defined: - * EPERM - The attribute is not allowed to be non-resident. - * ENOENT - The attribute @type is not specified in $AttrDef. - * EINVAL - Invalid parameters (e.g. @vol is not valid). + * EPERM - The attribute is not allowed to be non-resident. + * ENOENT - The attribute @type is not specified in $AttrDef. + * EINVAL - Invalid parameters (e.g. @vol is not valid). */ -int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPES type) +int ntfs_attr_can_be_non_resident( const ntfs_volume *vol, const ATTR_TYPES type ) { - ATTR_DEF *ad; + ATTR_DEF *ad; - /* Find the attribute definition record in $AttrDef. */ - ad = ntfs_attr_find_in_attrdef(vol, type); - if (!ad) - return -1; - /* Check the flags and return the result. */ - if (ad->flags & ATTR_DEF_RESIDENT) { - errno = EPERM; - ntfs_log_trace("Attribute can't be non-resident\n"); - return -1; - } - return 0; + /* Find the attribute definition record in $AttrDef. */ + ad = ntfs_attr_find_in_attrdef( vol, type ); + if ( !ad ) + return -1; + /* Check the flags and return the result. */ + if ( ad->flags & ATTR_DEF_RESIDENT ) + { + errno = EPERM; + ntfs_log_trace( "Attribute can't be non-resident\n" ); + return -1; + } + return 0; } /** * ntfs_attr_can_be_resident - check if an attribute can be resident - * @vol: ntfs volume to which the attribute belongs - * @type: attribute type which to check + * @vol: ntfs volume to which the attribute belongs + * @type: attribute type which to check * * Check whether the attribute of @type on the ntfs volume @vol is allowed to * be resident. This information is derived from our ntfs knowledge and may @@ -3098,494 +3310,528 @@ int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPES type) * Return 0 if the attribute is allowed to be resident and -1 if not or an * error occurred. On error the error code is stored in errno. The following * error codes are defined: - * EPERM - The attribute is not allowed to be resident. - * EINVAL - Invalid parameters (e.g. @vol is not valid). + * EPERM - The attribute is not allowed to be resident. + * EINVAL - Invalid parameters (e.g. @vol is not valid). * * Warning: In the system file $MFT the attribute $Bitmap must be non-resident - * otherwise windows will not boot (blue screen of death)! We cannot - * check for this here as we don't know which inode's $Bitmap is being - * asked about so the caller needs to special case this. + * otherwise windows will not boot (blue screen of death)! We cannot + * check for this here as we don't know which inode's $Bitmap is being + * asked about so the caller needs to special case this. */ -int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPES type) +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; } /** * ntfs_make_room_for_attr - make room for an attribute inside an mft record - * @m: mft record - * @pos: position at which to make space - * @size: byte size to make available at this position + * @m: mft record + * @pos: position at which to make space + * @size: byte size to make available at this position * * @pos points to the attribute in front of which we want to make space. * * Return 0 on success or -1 on error. On error the error code is stored in * errno. Possible error codes are: - * ENOSPC - There is not enough space available to complete operation. The - * caller has to make space before calling this. - * EINVAL - Input parameters were faulty. + * ENOSPC - There is not enough space available to complete operation. The + * caller has to make space before calling this. + * EINVAL - Input parameters were faulty. */ -int ntfs_make_room_for_attr(MFT_RECORD *m, u8 *pos, u32 size) +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; } /** * ntfs_resident_attr_record_add - add resident attribute to inode - * @ni: opened ntfs inode to which MFT record add attribute - * @type: type of the new attribute - * @name: name of the new attribute - * @name_len: name length of the new attribute - * @val: value of the new attribute - * @size: size of new attribute (length of @val, if @val != NULL) - * @flags: flags of the new attribute + * @ni: opened ntfs inode to which MFT record add attribute + * @type: type of the new attribute + * @name: name of the new attribute + * @name_len: name length of the new attribute + * @val: value of the new attribute + * @size: size of new attribute (length of @val, if @val != NULL) + * @flags: flags of the new attribute * * Return offset to attribute from the beginning of the mft record on success * and -1 on error. On error the error code is stored in errno. * Possible error codes are: - * EINVAL - Invalid arguments passed to function. - * EEXIST - Attribute of such type and with same name already exists. - * EIO - I/O error occurred or damaged filesystem. + * EINVAL - Invalid arguments passed to function. + * 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 (type == AT_DATA && name == AT_UNNAMED) { - ni->data_size = size; - ni->allocated_size = (size + 7) & ~7; - } - ntfs_inode_mark_dirty(ni); - ntfs_attr_put_search_ctx(ctx); - return offset; + /* Setup record fields. */ + offset = ( ( u8* )a - ( u8* )m ); + a->type = type; + a->length = cpu_to_le32( length ); + a->non_resident = 0; + a->name_length = name_len; + a->name_offset = ( name_len + ? cpu_to_le16( offsetof( ATTR_RECORD, resident_end ) ) + : const_cpu_to_le16( 0 ) ); + a->flags = data_flags; + a->instance = m->next_attr_instance; + a->value_length = cpu_to_le32( size ); + a->value_offset = cpu_to_le16( length - ( ( size + 7 ) & ~7 ) ); + if ( val ) + memcpy( ( u8* )a + le16_to_cpu( a->value_offset ), val, size ); + else + memset( ( u8* )a + le16_to_cpu( a->value_offset ), 0, size ); + if ( type == AT_FILE_NAME ) + a->resident_flags = RESIDENT_ATTR_IS_INDEXED; + else + a->resident_flags = 0; + if ( name_len ) + memcpy( ( u8* )a + le16_to_cpu( a->name_offset ), + name, sizeof( ntfschar ) * name_len ); + m->next_attr_instance = + cpu_to_le16( ( le16_to_cpu( m->next_attr_instance ) + 1 ) & 0xffff ); + if ( ni->nr_extents == -1 ) + base_ni = ni->base_ni; + else + base_ni = ni; + if ( type != AT_ATTRIBUTE_LIST && NInoAttrList( base_ni ) ) + { + if ( ntfs_attrlist_entry_add( ni, a ) ) + { + err = errno; + ntfs_attr_record_resize( m, a, 0 ); + ntfs_log_trace( "Failed add attribute entry to " + "ATTRIBUTE_LIST.\n" ); + goto put_err_out; + } + } + if ( type == AT_DATA && name == AT_UNNAMED ) + { + ni->data_size = size; + ni->allocated_size = ( size + 7 ) & ~7; + } + ntfs_inode_mark_dirty( ni ); + ntfs_attr_put_search_ctx( ctx ); + return offset; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx( ctx ); + errno = err; + return -1; } /** * ntfs_non_resident_attr_record_add - add extent of non-resident attribute - * @ni: opened ntfs inode to which MFT record add attribute - * @type: type of the new attribute extent - * @name: name of the new attribute extent - * @name_len: name length of the new attribute extent - * @lowest_vcn: lowest vcn of the new attribute extent - * @dataruns_size: dataruns size of the new attribute extent - * @flags: flags of the new attribute extent + * @ni: opened ntfs inode to which MFT record add attribute + * @type: type of the new attribute extent + * @name: name of the new attribute extent + * @name_len: name length of the new attribute extent + * @lowest_vcn: lowest vcn of the new attribute extent + * @dataruns_size: dataruns size of the new attribute extent + * @flags: flags of the new attribute extent * * Return offset to attribute from the beginning of the mft record on success * and -1 on error. On error the error code is stored in errno. * Possible error codes are: - * EINVAL - Invalid arguments passed to function. - * EEXIST - Attribute of such type, with same lowest vcn and with same - * name already exists. - * EIO - I/O error occurred or damaged filesystem. + * EINVAL - Invalid arguments passed to function. + * EEXIST - Attribute of such type, with same lowest vcn and with same + * 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)) { - if (errno == EPERM) - ntfs_log_perror("Attribute can't be non resident"); - else - ntfs_log_perror("ntfs_attr_can_be_non_resident failed"); - return -1; - } + if ( ntfs_attr_can_be_non_resident( ni->vol, type ) ) + { + if ( errno == EPERM ) + ntfs_log_perror( "Attribute can't be non resident" ); + else + ntfs_log_perror( "ntfs_attr_can_be_non_resident failed" ); + return -1; + } - /* Locate place where record should be. */ - ctx = ntfs_attr_get_search_ctx(ni, NULL); - if (!ctx) - return -1; - /* - * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for - * attribute in @ni->mrec, not any extent inode in case if @ni is base - * file record. - */ - if (!ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, NULL, 0, - ctx)) { - err = EEXIST; - ntfs_log_perror("Attribute 0x%x already present", type); - goto put_err_out; - } - if (errno != ENOENT) { - ntfs_log_perror("ntfs_attr_find failed"); - err = EIO; - goto put_err_out; - } - a = ctx->attr; - m = ctx->mrec; + /* Locate place where record should be. */ + ctx = ntfs_attr_get_search_ctx( ni, NULL ); + if ( !ctx ) + return -1; + /* + * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for + * attribute in @ni->mrec, not any extent inode in case if @ni is base + * file record. + */ + if ( !ntfs_attr_find( type, name, name_len, CASE_SENSITIVE, NULL, 0, + ctx ) ) + { + err = EEXIST; + ntfs_log_perror( "Attribute 0x%x already present", type ); + goto put_err_out; + } + if ( errno != ENOENT ) + { + ntfs_log_perror( "ntfs_attr_find failed" ); + err = EIO; + goto put_err_out; + } + a = ctx->attr; + m = ctx->mrec; - /* Make room for attribute. */ - dataruns_size = (dataruns_size + 7) & ~7; - length = offsetof(ATTR_RECORD, compressed_size) + ((sizeof(ntfschar) * - name_len + 7) & ~7) + dataruns_size + - ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ? - sizeof(a->compressed_size) : 0); - if (ntfs_make_room_for_attr(ctx->mrec, (u8*) ctx->attr, length)) { - err = errno; - ntfs_log_perror("Failed to make room for attribute"); - goto put_err_out; - } + /* Make room for attribute. */ + dataruns_size = ( dataruns_size + 7 ) & ~7; + length = offsetof( ATTR_RECORD, compressed_size ) + ( ( sizeof( ntfschar ) * + name_len + 7 ) & ~7 ) + dataruns_size + + ( ( flags & ( ATTR_IS_COMPRESSED | ATTR_IS_SPARSE ) ) ? + sizeof( a->compressed_size ) : 0 ); + if ( ntfs_make_room_for_attr( ctx->mrec, ( u8* ) ctx->attr, length ) ) + { + err = errno; + ntfs_log_perror( "Failed to make room for attribute" ); + goto put_err_out; + } - /* Setup record fields. */ - a->type = type; - a->length = cpu_to_le32(length); - a->non_resident = 1; - a->name_length = name_len; - a->name_offset = cpu_to_le16(offsetof(ATTR_RECORD, compressed_size) + - ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ? - sizeof(a->compressed_size) : 0)); - a->flags = flags; - a->instance = m->next_attr_instance; - a->lowest_vcn = cpu_to_sle64(lowest_vcn); - a->mapping_pairs_offset = cpu_to_le16(length - dataruns_size); - a->compression_unit = (flags & ATTR_IS_COMPRESSED) - ? STANDARD_COMPRESSION_UNIT : 0; - /* If @lowest_vcn == 0, than setup empty attribute. */ - if (!lowest_vcn) { - a->highest_vcn = cpu_to_sle64(-1); - a->allocated_size = 0; - a->data_size = 0; - a->initialized_size = 0; - /* Set empty mapping pairs. */ - *((u8*)a + le16_to_cpu(a->mapping_pairs_offset)) = 0; - } - if (name_len) - memcpy((u8*)a + le16_to_cpu(a->name_offset), - name, sizeof(ntfschar) * name_len); - m->next_attr_instance = - cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff); - if (ni->nr_extents == -1) - base_ni = ni->base_ni; - else - base_ni = ni; - if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) { - if (ntfs_attrlist_entry_add(ni, a)) { - err = errno; - ntfs_log_perror("Failed add attr entry to attrlist"); - ntfs_attr_record_resize(m, a, 0); - goto put_err_out; - } - } - ntfs_inode_mark_dirty(ni); - /* - * Locate offset from start of the MFT record where new attribute is - * placed. We need relookup it, because record maybe moved during - * update of attribute list. - */ - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE, - lowest_vcn, NULL, 0, ctx)) { - ntfs_log_perror("%s: attribute lookup failed", __FUNCTION__); - ntfs_attr_put_search_ctx(ctx); - return -1; + /* Setup record fields. */ + a->type = type; + a->length = cpu_to_le32( length ); + a->non_resident = 1; + a->name_length = name_len; + a->name_offset = cpu_to_le16( offsetof( ATTR_RECORD, compressed_size ) + + ( ( flags & ( ATTR_IS_COMPRESSED | ATTR_IS_SPARSE ) ) ? + sizeof( a->compressed_size ) : 0 ) ); + a->flags = flags; + a->instance = m->next_attr_instance; + a->lowest_vcn = cpu_to_sle64( lowest_vcn ); + a->mapping_pairs_offset = cpu_to_le16( length - dataruns_size ); + a->compression_unit = ( flags & ATTR_IS_COMPRESSED ) + ? STANDARD_COMPRESSION_UNIT : 0; + /* If @lowest_vcn == 0, than setup empty attribute. */ + if ( !lowest_vcn ) + { + a->highest_vcn = cpu_to_sle64( -1 ); + a->allocated_size = 0; + a->data_size = 0; + a->initialized_size = 0; + /* Set empty mapping pairs. */ + *( ( u8* )a + le16_to_cpu( a->mapping_pairs_offset ) ) = 0; + } + if ( name_len ) + memcpy( ( u8* )a + le16_to_cpu( a->name_offset ), + name, sizeof( ntfschar ) * name_len ); + m->next_attr_instance = + cpu_to_le16( ( le16_to_cpu( m->next_attr_instance ) + 1 ) & 0xffff ); + if ( ni->nr_extents == -1 ) + base_ni = ni->base_ni; + else + base_ni = ni; + if ( type != AT_ATTRIBUTE_LIST && NInoAttrList( base_ni ) ) + { + if ( ntfs_attrlist_entry_add( ni, a ) ) + { + err = errno; + ntfs_log_perror( "Failed add attr entry to attrlist" ); + ntfs_attr_record_resize( m, a, 0 ); + goto put_err_out; + } + } + ntfs_inode_mark_dirty( ni ); + /* + * Locate offset from start of the MFT record where new attribute is + * placed. We need relookup it, because record maybe moved during + * update of attribute list. + */ + ntfs_attr_reinit_search_ctx( ctx ); + if ( ntfs_attr_lookup( type, name, name_len, CASE_SENSITIVE, + lowest_vcn, NULL, 0, ctx ) ) + { + ntfs_log_perror( "%s: attribute lookup failed", __FUNCTION__ ); + ntfs_attr_put_search_ctx( ctx ); + return -1; - } - offset = (u8*)ctx->attr - (u8*)ctx->mrec; - ntfs_attr_put_search_ctx(ctx); - return offset; + } + offset = ( u8* )ctx->attr - ( u8* )ctx->mrec; + ntfs_attr_put_search_ctx( ctx ); + return offset; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx( ctx ); + errno = err; + return -1; } /** * ntfs_attr_record_rm - remove attribute extent - * @ctx: search context describing the attribute which should be removed + * @ctx: search context describing the attribute which should be removed * * If this function succeed, user should reinit search context if he/she wants * use it anymore. * * Return 0 on success and -1 on error. On error the error code is stored in * errno. Possible error codes are: - * EINVAL - Invalid arguments passed to function. - * EIO - I/O error occurred or damaged filesystem. + * EINVAL - Invalid arguments passed to function. + * EIO - I/O error occurred or damaged filesystem. */ -int ntfs_attr_record_rm(ntfs_attr_search_ctx *ctx) +int ntfs_attr_record_rm( ntfs_attr_search_ctx *ctx ) { - ntfs_inode *base_ni, *ni; - ATTR_TYPES type; - int err; + ntfs_inode *base_ni, *ni; + ATTR_TYPES type; + int err; - if (!ctx || !ctx->ntfs_ino || !ctx->mrec || !ctx->attr) { - errno = EINVAL; - return -1; - } + if ( !ctx || !ctx->ntfs_ino || !ctx->mrec || !ctx->attr ) + { + errno = EINVAL; + return -1; + } - ntfs_log_trace("Entering for inode 0x%llx, attr 0x%x.\n", - (long long) ctx->ntfs_ino->mft_no, - (unsigned) le32_to_cpu(ctx->attr->type)); - type = ctx->attr->type; - ni = ctx->ntfs_ino; - if (ctx->base_ntfs_ino) - base_ni = ctx->base_ntfs_ino; - else - base_ni = ctx->ntfs_ino; + ntfs_log_trace( "Entering for inode 0x%llx, attr 0x%x.\n", + ( long long ) ctx->ntfs_ino->mft_no, + ( unsigned ) le32_to_cpu( ctx->attr->type ) ); + type = ctx->attr->type; + ni = ctx->ntfs_ino; + if ( ctx->base_ntfs_ino ) + base_ni = ctx->base_ntfs_ino; + else + base_ni = ctx->ntfs_ino; - /* Remove attribute itself. */ - if (ntfs_attr_record_resize(ctx->mrec, ctx->attr, 0)) { - ntfs_log_trace("Couldn't remove attribute record. Bug or damaged MFT " - "record.\n"); - if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) - if (ntfs_attrlist_entry_add(ni, ctx->attr)) - ntfs_log_trace("Rollback failed. Leaving inconstant " - "metadata.\n"); - err = EIO; - return -1; - } - ntfs_inode_mark_dirty(ni); + /* Remove attribute itself. */ + if ( ntfs_attr_record_resize( ctx->mrec, ctx->attr, 0 ) ) + { + ntfs_log_trace( "Couldn't remove attribute record. Bug or damaged MFT " + "record.\n" ); + if ( NInoAttrList( base_ni ) && type != AT_ATTRIBUTE_LIST ) + if ( ntfs_attrlist_entry_add( ni, ctx->attr ) ) + ntfs_log_trace( "Rollback failed. Leaving inconstant " + "metadata.\n" ); + err = EIO; + return -1; + } + ntfs_inode_mark_dirty( ni ); - /* - * Remove record from $ATTRIBUTE_LIST if present and we don't want - * delete $ATTRIBUTE_LIST itself. - */ - if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) { - if (ntfs_attrlist_entry_rm(ctx)) { - ntfs_log_trace("Couldn't delete record from " - "$ATTRIBUTE_LIST.\n"); - return -1; - } - } + /* + * Remove record from $ATTRIBUTE_LIST if present and we don't want + * delete $ATTRIBUTE_LIST itself. + */ + if ( NInoAttrList( base_ni ) && type != AT_ATTRIBUTE_LIST ) + { + if ( ntfs_attrlist_entry_rm( ctx ) ) + { + ntfs_log_trace( "Couldn't delete record from " + "$ATTRIBUTE_LIST.\n" ); + return -1; + } + } - /* Post $ATTRIBUTE_LIST delete setup. */ - if (type == AT_ATTRIBUTE_LIST) { - if (NInoAttrList(base_ni) && base_ni->attr_list) - free(base_ni->attr_list); - base_ni->attr_list = NULL; - NInoClearAttrList(base_ni); - NInoAttrListClearDirty(base_ni); - } + /* Post $ATTRIBUTE_LIST delete setup. */ + if ( type == AT_ATTRIBUTE_LIST ) + { + if ( NInoAttrList( base_ni ) && base_ni->attr_list ) + free( base_ni->attr_list ); + base_ni->attr_list = NULL; + NInoClearAttrList( base_ni ); + NInoAttrListClearDirty( base_ni ); + } - /* Free MFT record, if it doesn't contain attributes. */ - if (le32_to_cpu(ctx->mrec->bytes_in_use) - - le16_to_cpu(ctx->mrec->attrs_offset) == 8) { - if (ntfs_mft_record_free(ni->vol, ni)) { - // FIXME: We need rollback here. - ntfs_log_trace("Couldn't free MFT record.\n"); - errno = EIO; - return -1; - } - /* Remove done if we freed base inode. */ - if (ni == base_ni) - return 0; - } + /* Free MFT record, if it doesn't contain attributes. */ + if ( le32_to_cpu( ctx->mrec->bytes_in_use ) - + le16_to_cpu( ctx->mrec->attrs_offset ) == 8 ) + { + if ( ntfs_mft_record_free( ni->vol, ni ) ) + { + // FIXME: We need rollback here. + ntfs_log_trace( "Couldn't free MFT record.\n" ); + errno = EIO; + return -1; + } + /* Remove done if we freed base inode. */ + if ( ni == base_ni ) + return 0; + } - if (type == AT_ATTRIBUTE_LIST || !NInoAttrList(base_ni)) - return 0; + if ( type == AT_ATTRIBUTE_LIST || !NInoAttrList( base_ni ) ) + return 0; - /* Remove attribute list if we don't need it any more. */ - if (!ntfs_attrlist_need(base_ni)) { - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, CASE_SENSITIVE, - 0, NULL, 0, ctx)) { - /* - * FIXME: Should we succeed here? Definitely something - * goes wrong because NInoAttrList(base_ni) returned - * that we have got attribute list. - */ - ntfs_log_trace("Couldn't find attribute list. Succeed " - "anyway.\n"); - return 0; - } - /* Deallocate clusters. */ - if (ctx->attr->non_resident) { - runlist *al_rl; + /* Remove attribute list if we don't need it any more. */ + if ( !ntfs_attrlist_need( base_ni ) ) + { + ntfs_attr_reinit_search_ctx( ctx ); + if ( ntfs_attr_lookup( AT_ATTRIBUTE_LIST, NULL, 0, CASE_SENSITIVE, + 0, NULL, 0, ctx ) ) + { + /* + * FIXME: Should we succeed here? Definitely something + * goes wrong because NInoAttrList(base_ni) returned + * that we have got attribute list. + */ + ntfs_log_trace( "Couldn't find attribute list. Succeed " + "anyway.\n" ); + return 0; + } + /* Deallocate clusters. */ + if ( ctx->attr->non_resident ) + { + runlist *al_rl; - al_rl = ntfs_mapping_pairs_decompress(base_ni->vol, - ctx->attr, NULL); - if (!al_rl) { - ntfs_log_trace("Couldn't decompress attribute list " - "runlist. Succeed anyway.\n"); - return 0; - } - if (ntfs_cluster_free_from_rl(base_ni->vol, al_rl)) { - ntfs_log_trace("Leaking clusters! Run chkdsk. " - "Couldn't free clusters from " - "attribute list runlist.\n"); - } - free(al_rl); - } - /* Remove attribute record itself. */ - if (ntfs_attr_record_rm(ctx)) { - /* - * FIXME: Should we succeed here? BTW, chkdsk doesn't - * complain if it find MFT record with attribute list, - * but without extents. - */ - ntfs_log_trace("Couldn't remove attribute list. Succeed " - "anyway.\n"); - return 0; - } - } - return 0; + al_rl = ntfs_mapping_pairs_decompress( base_ni->vol, + ctx->attr, NULL ); + if ( !al_rl ) + { + ntfs_log_trace( "Couldn't decompress attribute list " + "runlist. Succeed anyway.\n" ); + return 0; + } + if ( ntfs_cluster_free_from_rl( base_ni->vol, al_rl ) ) + { + ntfs_log_trace( "Leaking clusters! Run chkdsk. " + "Couldn't free clusters from " + "attribute list runlist.\n" ); + } + free( al_rl ); + } + /* Remove attribute record itself. */ + if ( ntfs_attr_record_rm( ctx ) ) + { + /* + * FIXME: Should we succeed here? BTW, chkdsk doesn't + * complain if it find MFT record with attribute list, + * but without extents. + */ + ntfs_log_trace( "Couldn't remove attribute list. Succeed " + "anyway.\n" ); + return 0; + } + } + return 0; } /** * ntfs_attr_add - add attribute to inode - * @ni: opened ntfs inode to which add attribute - * @type: type of the new attribute - * @name: name in unicode of the new attribute - * @name_len: name length in unicode characters of the new attribute - * @val: value of new attribute - * @size: size of the new attribute / length of @val (if specified) + * @ni: opened ntfs inode to which add attribute + * @type: type of the new attribute + * @name: name in unicode of the new attribute + * @name_len: name length in unicode characters of the new attribute + * @val: value of new attribute + * @size: size of the new attribute / length of @val (if specified) * * @val should always be specified for always resident attributes (eg. FILE_NAME * attribute), for attributes that can become non-resident @val can be NULL @@ -3604,481 +3850,519 @@ 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)) { - if (errno != EPERM) { - err = errno; - ntfs_log_perror("ntfs_attr_can_be_non_resident failed"); - goto err_out; - } - /* @val is mandatory. */ - if (!val) { - errno = EINVAL; - ntfs_log_perror("val is mandatory for always resident " - "attributes"); - return -1; - } - if (size > ni->vol->mft_record_size) { - errno = ERANGE; - ntfs_log_perror("Attribute is too big"); - return -1; - } - } else - can_be_non_resident = TRUE; + /* Sanity checks for always resident attributes. */ + if ( ntfs_attr_can_be_non_resident( ni->vol, type ) ) + { + if ( errno != EPERM ) + { + err = errno; + ntfs_log_perror( "ntfs_attr_can_be_non_resident failed" ); + goto err_out; + } + /* @val is mandatory. */ + if ( !val ) + { + errno = EINVAL; + ntfs_log_perror( "val is mandatory for always resident " + "attributes" ); + return -1; + } + if ( size > ni->vol->mft_record_size ) + { + errno = ERANGE; + ntfs_log_perror( "Attribute is too big" ); + return -1; + } + } + else + can_be_non_resident = TRUE; - /* - * Determine resident or not will be new attribute. We add 8 to size in - * non resident case for mapping pairs. - */ - if (!ntfs_attr_can_be_resident(ni->vol, type)) { - is_resident = TRUE; - } else { - if (errno != EPERM) { - err = errno; - ntfs_log_perror("ntfs_attr_can_be_resident failed"); - goto err_out; - } - is_resident = FALSE; - } - /* Calculate attribute record size. */ - if (is_resident) - attr_rec_size = offsetof(ATTR_RECORD, resident_end) + - ((name_len * sizeof(ntfschar) + 7) & ~7) + - ((size + 7) & ~7); - else - attr_rec_size = offsetof(ATTR_RECORD, non_resident_end) + - ((name_len * sizeof(ntfschar) + 7) & ~7) + 8; + /* + * Determine resident or not will be new attribute. We add 8 to size in + * non resident case for mapping pairs. + */ + if ( !ntfs_attr_can_be_resident( ni->vol, type ) ) + { + is_resident = TRUE; + } + else + { + if ( errno != EPERM ) + { + err = errno; + ntfs_log_perror( "ntfs_attr_can_be_resident failed" ); + goto err_out; + } + is_resident = FALSE; + } + /* Calculate attribute record size. */ + if ( is_resident ) + attr_rec_size = offsetof( ATTR_RECORD, resident_end ) + + ( ( name_len * sizeof( ntfschar ) + 7 ) & ~7 ) + + ( ( size + 7 ) & ~7 ); + else + attr_rec_size = offsetof( ATTR_RECORD, non_resident_end ) + + ( ( name_len * sizeof( ntfschar ) + 7 ) & ~7 ) + 8; - /* - * If we have enough free space for the new attribute in the base MFT - * record, then add attribute to it. - */ - if (le32_to_cpu(ni->mrec->bytes_allocated) - - le32_to_cpu(ni->mrec->bytes_in_use) >= attr_rec_size) { - attr_ni = ni; - goto add_attr_record; - } + /* + * If we have enough free space for the new attribute in the base MFT + * record, then add attribute to it. + */ + if ( le32_to_cpu( ni->mrec->bytes_allocated ) - + le32_to_cpu( ni->mrec->bytes_in_use ) >= attr_rec_size ) + { + attr_ni = ni; + goto add_attr_record; + } - /* Try to add to extent inodes. */ - if (ntfs_inode_attach_all_extents(ni)) { - err = errno; - ntfs_log_perror("Failed to attach all extents to inode"); - goto err_out; - } - for (i = 0; i < ni->nr_extents; i++) { - attr_ni = ni->extent_nis[i]; - if (le32_to_cpu(attr_ni->mrec->bytes_allocated) - - le32_to_cpu(attr_ni->mrec->bytes_in_use) >= - attr_rec_size) - goto add_attr_record; - } + /* Try to add to extent inodes. */ + if ( ntfs_inode_attach_all_extents( ni ) ) + { + err = errno; + ntfs_log_perror( "Failed to attach all extents to inode" ); + goto err_out; + } + for ( i = 0; i < ni->nr_extents; i++ ) + { + attr_ni = ni->extent_nis[i]; + if ( le32_to_cpu( attr_ni->mrec->bytes_allocated ) - + le32_to_cpu( attr_ni->mrec->bytes_in_use ) >= + attr_rec_size ) + goto add_attr_record; + } - /* There is no extent that contain enough space for new attribute. */ - if (!NInoAttrList(ni)) { - /* Add attribute list not present, add it and retry. */ - if (ntfs_inode_add_attrlist(ni)) { - err = errno; - ntfs_log_perror("Failed to add attribute list"); - goto err_out; - } - return ntfs_attr_add(ni, type, name, name_len, val, size); - } - /* Allocate new extent. */ - attr_ni = ntfs_mft_record_alloc(ni->vol, ni); - if (!attr_ni) { - err = errno; - ntfs_log_perror("Failed to allocate extent record"); - goto err_out; - } + /* There is no extent that contain enough space for new attribute. */ + if ( !NInoAttrList( ni ) ) + { + /* Add attribute list not present, add it and retry. */ + if ( ntfs_inode_add_attrlist( ni ) ) + { + err = errno; + ntfs_log_perror( "Failed to add attribute list" ); + goto err_out; + } + return ntfs_attr_add( ni, type, name, name_len, val, size ); + } + /* Allocate new extent. */ + attr_ni = ntfs_mft_record_alloc( ni->vol, ni ); + if ( !attr_ni ) + { + err = errno; + ntfs_log_perror( "Failed to allocate extent record" ); + goto err_out; + } add_attr_record: - if ((ni->flags & FILE_ATTR_COMPRESSED) - && ((type == AT_DATA) - || ((type == AT_INDEX_ROOT) && (name == NTFS_INDEX_I30)))) - data_flags = ATTR_IS_COMPRESSED; - else - data_flags = const_cpu_to_le16(0); - if (is_resident) { - /* Add resident attribute. */ - offset = ntfs_resident_attr_record_add(attr_ni, type, name, - name_len, val, size, data_flags); - if (offset < 0) { - if (errno == ENOSPC && can_be_non_resident) - goto add_non_resident; - err = errno; - ntfs_log_perror("Failed to add resident attribute"); - goto free_err_out; - } - return 0; - } + if ( ( ni->flags & FILE_ATTR_COMPRESSED ) + && ( ( type == AT_DATA ) + || ( ( type == AT_INDEX_ROOT ) && ( name == NTFS_INDEX_I30 ) ) ) ) + data_flags = ATTR_IS_COMPRESSED; + else + data_flags = const_cpu_to_le16( 0 ); + if ( is_resident ) + { + /* Add resident attribute. */ + offset = ntfs_resident_attr_record_add( attr_ni, type, name, + name_len, val, size, data_flags ); + if ( offset < 0 ) + { + if ( errno == ENOSPC && can_be_non_resident ) + goto add_non_resident; + err = errno; + ntfs_log_perror( "Failed to add resident attribute" ); + goto free_err_out; + } + return 0; + } add_non_resident: - /* Add non resident attribute. */ - offset = ntfs_non_resident_attr_record_add(attr_ni, type, name, - name_len, 0, 8, data_flags); - if (offset < 0) { - err = errno; - ntfs_log_perror("Failed to add non resident attribute"); - goto free_err_out; - } + /* Add non resident attribute. */ + offset = ntfs_non_resident_attr_record_add( attr_ni, type, name, + name_len, 0, 8, data_flags ); + if ( offset < 0 ) + { + err = errno; + ntfs_log_perror( "Failed to add non resident attribute" ); + goto free_err_out; + } - /* If @size == 0, we are done. */ - if (!size) - return 0; + /* If @size == 0, we are done. */ + if ( !size ) + return 0; - /* Open new attribute and resize it. */ - na = ntfs_attr_open(ni, type, name, name_len); - if (!na) { - err = errno; - ntfs_log_perror("Failed to open just added attribute"); - goto rm_attr_err_out; - } - /* Resize and set attribute value. */ - if (ntfs_attr_truncate(na, size) || - (val && (ntfs_attr_pwrite(na, 0, size, val) != size))) { - err = errno; - ntfs_log_perror("Failed to initialize just added attribute"); - if (ntfs_attr_rm(na)) - ntfs_log_perror("Failed to remove just added attribute"); - ntfs_attr_close(na); - goto err_out; - } - ntfs_attr_close(na); - return 0; + /* Open new attribute and resize it. */ + na = ntfs_attr_open( ni, type, name, name_len ); + if ( !na ) + { + err = errno; + ntfs_log_perror( "Failed to open just added attribute" ); + goto rm_attr_err_out; + } + /* Resize and set attribute value. */ + if ( ntfs_attr_truncate( na, size ) || + ( val && ( ntfs_attr_pwrite( na, 0, size, val ) != size ) ) ) + { + err = errno; + ntfs_log_perror( "Failed to initialize just added attribute" ); + if ( ntfs_attr_rm( na ) ) + ntfs_log_perror( "Failed to remove just added attribute" ); + ntfs_attr_close( na ); + goto err_out; + } + ntfs_attr_close( na ); + return 0; rm_attr_err_out: - /* Remove just added attribute. */ - if (ntfs_attr_record_resize(attr_ni->mrec, - (ATTR_RECORD*)((u8*)attr_ni->mrec + offset), 0)) - ntfs_log_perror("Failed to remove just added attribute #2"); + /* Remove just added attribute. */ + if ( ntfs_attr_record_resize( attr_ni->mrec, + ( ATTR_RECORD* )( ( u8* )attr_ni->mrec + offset ), 0 ) ) + ntfs_log_perror( "Failed to remove just added attribute #2" ); free_err_out: - /* Free MFT record, if it doesn't contain attributes. */ - if (le32_to_cpu(attr_ni->mrec->bytes_in_use) - - le16_to_cpu(attr_ni->mrec->attrs_offset) == 8) - if (ntfs_mft_record_free(attr_ni->vol, attr_ni)) - ntfs_log_perror("Failed to free MFT record"); + /* Free MFT record, if it doesn't contain attributes. */ + if ( le32_to_cpu( attr_ni->mrec->bytes_in_use ) - + le16_to_cpu( attr_ni->mrec->attrs_offset ) == 8 ) + if ( ntfs_mft_record_free( attr_ni->vol, attr_ni ) ) + ntfs_log_perror( "Failed to free MFT record" ); err_out: - errno = err; - return -1; + errno = err; + return -1; } /* - * Change an attribute flag + * 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 + * @na: opened ntfs attribute to delete * * Remove attribute and all it's extents from ntfs inode. If attribute was non * resident also free all clusters allocated by attribute. * * Return 0 on success or -1 on error with errno set to the error code. */ -int ntfs_attr_rm(ntfs_attr *na) +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; } /** * ntfs_attr_record_resize - resize an attribute record - * @m: mft record containing attribute record - * @a: attribute record to resize - * @new_size: new size in bytes to which to resize the attribute record @a + * @m: mft record containing attribute record + * @a: attribute record to resize + * @new_size: new size in bytes to which to resize the attribute record @a * * Resize the attribute record @a, i.e. the resident part of the attribute, in * the mft record @m to @new_size bytes. * * Return 0 on success and -1 on error with errno set to the error code. * The following error codes are defined: - * ENOSPC - Not enough space in the mft record @m to perform the resize. + * ENOSPC - Not enough space in the mft record @m to perform the resize. * Note that on error no modifications have been performed whatsoever. * * Warning: If you make a record smaller without having copied all the data you - * are interested in the data may be overwritten! + * are interested in the data may be overwritten! */ -int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size) +int ntfs_attr_record_resize( MFT_RECORD *m, ATTR_RECORD *a, u32 new_size ) { - u32 old_size, alloc_size, attr_size; - - old_size = le32_to_cpu(m->bytes_in_use); - alloc_size = le32_to_cpu(m->bytes_allocated); - attr_size = le32_to_cpu(a->length); - - ntfs_log_trace("Sizes: old=%u alloc=%u attr=%u new=%u\n", - (unsigned)old_size, (unsigned)alloc_size, - (unsigned)attr_size, (unsigned)new_size); + 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; } /** * ntfs_resident_attr_value_resize - resize the value of a resident attribute - * @m: mft record containing attribute record - * @a: attribute record whose value to resize - * @new_size: new size in bytes to which to resize the attribute value of @a + * @m: mft record containing attribute record + * @a: attribute record whose value to resize + * @new_size: new size in bytes to which to resize the attribute value of @a * * Resize the value of the attribute @a in the mft record @m to @new_size bytes. * If the value is made bigger, the newly "allocated" space is cleared. * * Return 0 on success and -1 on error with errno set to the error code. * The following error codes are defined: - * ENOSPC - Not enough space in the mft record @m to perform the resize. + * 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; } /** * ntfs_attr_record_move_to - move attribute record to target inode - * @ctx: attribute search context describing the attribute record - * @ni: opened ntfs inode to which move attribute record + * @ctx: attribute search context describing the attribute record + * @ni: opened ntfs inode to which move attribute record * * If this function succeed, user should reinit search context if he/she wants * use it anymore. * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_record_move_to(ntfs_attr_search_ctx *ctx, ntfs_inode *ni) +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; + ntfs_attr_put_search_ctx( nctx ); + return 0; put_err_out: - ntfs_attr_put_search_ctx(nctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx( nctx ); + errno = err; + return -1; } /** * ntfs_attr_record_move_away - move away attribute record from it's mft record - * @ctx: attribute search context describing the attribute record - * @extra: minimum amount of free space in the new holder of record + * @ctx: attribute search context describing the attribute record + * @extra: minimum amount of free space in the new holder of record * * New attribute record holder must have free @extra bytes after moving * attribute record to it. @@ -4088,788 +4372,845 @@ put_err_out: * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attr_record_move_away(ntfs_attr_search_ctx *ctx, int extra) +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; } /** * ntfs_attr_make_non_resident - convert a resident to a non-resident attribute - * @na: open ntfs attribute to make non-resident - * @ctx: ntfs search context describing the attribute + * @na: open ntfs attribute to make non-resident + * @ctx: ntfs search context describing the attribute * * Convert a resident ntfs attribute to a non-resident one. * * Return 0 on success and -1 on error with errno set to the error code. The * following error codes are defined: - * EPERM - The attribute is not allowed to be non-resident. - * TODO: others... + * EPERM - The attribute is not allowed to be non-resident. + * TODO: others... * * NOTE to self: No changes in the attribute list are required to move from - * a resident to a non-resident attribute. + * a resident to a non-resident attribute. * * Warning: We do not set the inode dirty and we do not write out anything! - * 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. + * 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)) - return -1; + /* Check that the attribute is allowed to be non-resident. */ + if ( ntfs_attr_can_be_non_resident( vol, na->type ) ) + return -1; - new_allocated_size = (le32_to_cpu(a->value_length) + vol->cluster_size - - 1) & ~(vol->cluster_size - 1); + new_allocated_size = ( le32_to_cpu( a->value_length ) + vol->cluster_size + - 1 ) & ~( vol->cluster_size - 1 ); - if (new_allocated_size > 0) { - /* Start by allocating clusters to hold the attribute value. */ - rl = ntfs_cluster_alloc(vol, 0, new_allocated_size >> - vol->cluster_size_bits, -1, DATA_ZONE); - if (!rl) - return -1; - } else - rl = NULL; - /* - * Setup the in-memory attribute structure to be non-resident so that - * we can use ntfs_attr_pwrite(). - */ - NAttrSetNonResident(na); - na->rl = rl; - na->allocated_size = new_allocated_size; - na->data_size = na->initialized_size = le32_to_cpu(a->value_length); - /* - * FIXME: For now just clear all of these as we don't support them when - * writing. - */ - NAttrClearSparse(na); - NAttrClearEncrypted(na); - if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) { - /* set compression writing parameters */ - na->compression_block_size - = 1 << (STANDARD_COMPRESSION_UNIT + vol->cluster_size_bits); - na->compression_block_clusters = 1 << STANDARD_COMPRESSION_UNIT; - } + if ( new_allocated_size > 0 ) + { + /* Start by allocating clusters to hold the attribute value. */ + rl = ntfs_cluster_alloc( vol, 0, new_allocated_size >> + vol->cluster_size_bits, -1, DATA_ZONE ); + if ( !rl ) + return -1; + } + else + rl = NULL; + /* + * Setup the in-memory attribute structure to be non-resident so that + * we can use ntfs_attr_pwrite(). + */ + NAttrSetNonResident( na ); + na->rl = rl; + na->allocated_size = new_allocated_size; + na->data_size = na->initialized_size = le32_to_cpu( a->value_length ); + /* + * FIXME: For now just clear all of these as we don't support them when + * writing. + */ + NAttrClearSparse( na ); + NAttrClearEncrypted( na ); + if ( ( a->flags & ATTR_COMPRESSION_MASK ) == ATTR_IS_COMPRESSED ) + { + /* set compression writing parameters */ + na->compression_block_size + = 1 << ( STANDARD_COMPRESSION_UNIT + vol->cluster_size_bits ); + na->compression_block_clusters = 1 << STANDARD_COMPRESSION_UNIT; + } - if (rl) { - /* Now copy the attribute value to the allocated cluster(s). */ - bw = ntfs_attr_pwrite(na, 0, le32_to_cpu(a->value_length), - (u8*)a + le16_to_cpu(a->value_offset)); - if (bw != le32_to_cpu(a->value_length)) { - err = errno; - ntfs_log_debug("Eeek! Failed to write out attribute value " - "(bw = %lli, errno = %i). " - "Aborting...\n", (long long)bw, err); - if (bw >= 0) - err = EIO; - goto cluster_free_err_out; - } - } - /* Determine the size of the mapping pairs array. */ - mp_size = ntfs_get_size_for_mapping_pairs(vol, rl, 0, INT_MAX); - if (mp_size < 0) { - err = errno; - ntfs_log_debug("Eeek! Failed to get size for mapping pairs array. " - "Aborting...\n"); - goto cluster_free_err_out; - } - /* Calculate new offsets for the name and the mapping pairs array. */ - if (na->ni->flags & FILE_ATTR_COMPRESSED) - name_ofs = (sizeof(ATTR_REC) + 7) & ~7; - else - name_ofs = (sizeof(ATTR_REC) - sizeof(a->compressed_size) + 7) & ~7; - mp_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7; - /* - * Determine the size of the resident part of the non-resident - * attribute record. (Not compressed thus no compressed_size element - * present.) - */ - arec_size = (mp_ofs + mp_size + 7) & ~7; + if ( rl ) + { + /* Now copy the attribute value to the allocated cluster(s). */ + bw = ntfs_attr_pwrite( na, 0, le32_to_cpu( a->value_length ), + ( u8* )a + le16_to_cpu( a->value_offset ) ); + if ( bw != le32_to_cpu( a->value_length ) ) + { + err = errno; + ntfs_log_debug( "Eeek! Failed to write out attribute value " + "(bw = %lli, errno = %i). " + "Aborting...\n", ( long long )bw, err ); + if ( bw >= 0 ) + err = EIO; + goto cluster_free_err_out; + } + } + /* Determine the size of the mapping pairs array. */ + mp_size = ntfs_get_size_for_mapping_pairs( vol, rl, 0, INT_MAX ); + if ( mp_size < 0 ) + { + err = errno; + ntfs_log_debug( "Eeek! Failed to get size for mapping pairs array. " + "Aborting...\n" ); + goto cluster_free_err_out; + } + /* Calculate new offsets for the name and the mapping pairs array. */ + if ( na->ni->flags & FILE_ATTR_COMPRESSED ) + name_ofs = ( sizeof( ATTR_REC ) + 7 ) & ~7; + else + name_ofs = ( sizeof( ATTR_REC ) - sizeof( a->compressed_size ) + 7 ) & ~7; + mp_ofs = ( name_ofs + a->name_length * sizeof( ntfschar ) + 7 ) & ~7; + /* + * Determine the size of the resident part of the non-resident + * attribute record. (Not compressed thus no compressed_size element + * present.) + */ + arec_size = ( mp_ofs + mp_size + 7 ) & ~7; - /* Resize the resident part of the attribute record. */ - if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) { - err = errno; - goto cluster_free_err_out; - } + /* Resize the resident part of the attribute record. */ + if ( ntfs_attr_record_resize( ctx->mrec, a, arec_size ) < 0 ) + { + err = errno; + goto cluster_free_err_out; + } - /* - * Convert the resident part of the attribute record to describe a - * non-resident attribute. - */ - a->non_resident = 1; + /* + * Convert the resident part of the attribute record to describe a + * non-resident attribute. + */ + a->non_resident = 1; - /* Move the attribute name if it exists and update the offset. */ - if (a->name_length) - memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset), - a->name_length * sizeof(ntfschar)); - a->name_offset = cpu_to_le16(name_ofs); + /* Move the attribute name if it exists and update the offset. */ + if ( a->name_length ) + memmove( ( u8* )a + name_ofs, ( u8* )a + le16_to_cpu( a->name_offset ), + a->name_length * sizeof( ntfschar ) ); + a->name_offset = cpu_to_le16( name_ofs ); - /* Setup the fields specific to non-resident attributes. */ - a->lowest_vcn = cpu_to_sle64(0); - a->highest_vcn = cpu_to_sle64((new_allocated_size - 1) >> - vol->cluster_size_bits); + /* Setup the fields specific to non-resident attributes. */ + a->lowest_vcn = cpu_to_sle64( 0 ); + a->highest_vcn = cpu_to_sle64( ( new_allocated_size - 1 ) >> + vol->cluster_size_bits ); - a->mapping_pairs_offset = cpu_to_le16(mp_ofs); + a->mapping_pairs_offset = cpu_to_le16( mp_ofs ); - /* - * Update the flags to match the in-memory ones. - * However cannot change the compression state if we had - * a fuse_file_info open with a mark for release. - * The decisions about compression can only be made when - * creating/recreating the stream, not when making non resident. - */ - a->flags &= ~(ATTR_IS_SPARSE | ATTR_IS_ENCRYPTED); - if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) { - /* support only ATTR_IS_COMPRESSED compression mode */ - a->compression_unit = STANDARD_COMPRESSION_UNIT; - a->compressed_size = const_cpu_to_le64(0); - } else { - a->compression_unit = 0; - a->flags &= ~ATTR_COMPRESSION_MASK; - na->data_flags = a->flags; - } + /* + * Update the flags to match the in-memory ones. + * However cannot change the compression state if we had + * a fuse_file_info open with a mark for release. + * The decisions about compression can only be made when + * creating/recreating the stream, not when making non resident. + */ + a->flags &= ~( ATTR_IS_SPARSE | ATTR_IS_ENCRYPTED ); + if ( ( a->flags & ATTR_COMPRESSION_MASK ) == ATTR_IS_COMPRESSED ) + { + /* support only ATTR_IS_COMPRESSED compression mode */ + a->compression_unit = STANDARD_COMPRESSION_UNIT; + a->compressed_size = const_cpu_to_le64( 0 ); + } + else + { + a->compression_unit = 0; + a->flags &= ~ATTR_COMPRESSION_MASK; + na->data_flags = a->flags; + } - memset(&a->reserved1, 0, sizeof(a->reserved1)); + memset( &a->reserved1, 0, sizeof( a->reserved1 ) ); - a->allocated_size = cpu_to_sle64(new_allocated_size); - a->data_size = a->initialized_size = cpu_to_sle64(na->data_size); + a->allocated_size = cpu_to_sle64( new_allocated_size ); + a->data_size = a->initialized_size = cpu_to_sle64( na->data_size ); - /* Generate the mapping pairs array in the attribute record. */ - if (ntfs_mapping_pairs_build(vol, (u8*)a + mp_ofs, arec_size - mp_ofs, - rl, 0, NULL) < 0) { - // FIXME: Eeek! We need rollback! (AIA) - ntfs_log_trace("Eeek! Failed to build mapping pairs. Leaving " - "corrupt attribute record on disk. In memory " - "runlist is still intact! Error code is %i. " - "FIXME: Need to rollback instead!\n", errno); - return -1; - } + /* Generate the mapping pairs array in the attribute record. */ + if ( ntfs_mapping_pairs_build( vol, ( u8* )a + mp_ofs, arec_size - mp_ofs, + rl, 0, NULL ) < 0 ) + { + // FIXME: Eeek! We need rollback! (AIA) + ntfs_log_trace( "Eeek! Failed to build mapping pairs. Leaving " + "corrupt attribute record on disk. In memory " + "runlist is still intact! Error code is %i. " + "FIXME: Need to rollback instead!\n", errno ); + return -1; + } - /* Done! */ - return 0; + /* Done! */ + return 0; cluster_free_err_out: - if (rl && ntfs_cluster_free(vol, na, 0, -1) < 0) - ntfs_log_trace("Eeek! Failed to release allocated clusters in error " - "code path. Leaving inconsistent metadata...\n"); - NAttrClearNonResident(na); - na->allocated_size = na->data_size; - na->rl = NULL; - free(rl); - errno = err; - return -1; + if ( rl && ntfs_cluster_free( vol, na, 0, -1 ) < 0 ) + ntfs_log_trace( "Eeek! Failed to release allocated clusters in error " + "code path. Leaving inconsistent metadata...\n" ); + NAttrClearNonResident( na ); + na->allocated_size = na->data_size; + na->rl = NULL; + free( rl ); + errno = err; + return -1; } -static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize); +static int ntfs_resident_attr_resize( ntfs_attr *na, const s64 newsize ); /** * ntfs_resident_attr_resize - resize a resident, open ntfs attribute - * @na: resident ntfs attribute to resize - * @newsize: new size (in bytes) to which to resize the attribute + * @na: resident ntfs attribute to resize + * @newsize: new size (in bytes) to which to resize the attribute * * Change the size of a resident, open ntfs attribute @na to @newsize bytes. * - * On success return 0 + * On success return 0 * On error return values are: - * STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT - * STATUS_ERROR - otherwise + * STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT + * STATUS_ERROR - otherwise * The following error codes are defined: - * ENOMEM - Not enough memory to complete operation. - * ERANGE - @newsize is not valid for the attribute type of @na. - * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST. + * ENOMEM - Not enough memory to complete operation. + * 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) +static int ntfs_resident_attr_resize_i( ntfs_attr *na, const s64 newsize ) { - ntfs_attr_search_ctx *ctx; - ntfs_volume *vol; - ntfs_inode *ni; - int err, ret = STATUS_ERROR; + ntfs_attr_search_ctx *ctx; + ntfs_volume *vol; + ntfs_inode *ni; + int err, ret = STATUS_ERROR; - ntfs_log_trace("Inode 0x%llx attr 0x%x new size %lld\n", - (unsigned long long)na->ni->mft_no, na->type, - (long long)newsize); + ntfs_log_trace( "Inode 0x%llx attr 0x%x new size %lld\n", + ( unsigned long long )na->ni->mft_no, na->type, + ( long long )newsize ); - /* Get the attribute record that needs modification. */ - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - return -1; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, 0, 0, NULL, 0, - ctx)) { - err = errno; - ntfs_log_perror("ntfs_attr_lookup failed"); - goto put_err_out; - } - vol = na->ni->vol; - /* - * Check the attribute type and the corresponding minimum and maximum - * sizes against @newsize and fail if @newsize is out of bounds. - */ - if (ntfs_attr_size_bounds_check(vol, na->type, newsize) < 0) { - err = errno; - if (err == ENOENT) - err = EIO; - ntfs_log_perror("%s: bounds check failed", __FUNCTION__); - goto put_err_out; - } - /* - * If @newsize is bigger than the mft record we need to make the - * attribute non-resident if the attribute type supports it. If it is - * smaller we can go ahead and attempt the resize. - */ - if (newsize < vol->mft_record_size) { - /* Perform the resize of the attribute record. */ - if (!(ret = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr, - newsize))) { - /* Update attribute size everywhere. */ - na->data_size = na->initialized_size = newsize; - na->allocated_size = (newsize + 7) & ~7; - if ((na->data_flags & ATTR_COMPRESSION_MASK) - || NAttrSparse(na)) - na->compressed_size = na->allocated_size; - if (na->type == AT_DATA && na->name == AT_UNNAMED) { - na->ni->data_size = na->data_size; - na->ni->allocated_size = na->allocated_size; - NInoFileNameSetDirty(na->ni); - } - goto resize_done; - } - /* Prefer AT_INDEX_ALLOCATION instead of AT_ATTRIBUTE_LIST */ - if (ret == STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT) { - err = errno; - goto put_err_out; - } - } - /* There is not enough space in the mft record to perform the resize. */ + /* Get the attribute record that needs modification. */ + ctx = ntfs_attr_get_search_ctx( na->ni, NULL ); + if ( !ctx ) + return -1; + if ( ntfs_attr_lookup( na->type, na->name, na->name_len, 0, 0, NULL, 0, + ctx ) ) + { + err = errno; + ntfs_log_perror( "ntfs_attr_lookup failed" ); + goto put_err_out; + } + vol = na->ni->vol; + /* + * Check the attribute type and the corresponding minimum and maximum + * sizes against @newsize and fail if @newsize is out of bounds. + */ + if ( ntfs_attr_size_bounds_check( vol, na->type, newsize ) < 0 ) + { + err = errno; + if ( err == ENOENT ) + err = EIO; + ntfs_log_perror( "%s: bounds check failed", __FUNCTION__ ); + goto put_err_out; + } + /* + * If @newsize is bigger than the mft record we need to make the + * attribute non-resident if the attribute type supports it. If it is + * smaller we can go ahead and attempt the resize. + */ + if ( newsize < vol->mft_record_size ) + { + /* Perform the resize of the attribute record. */ + if ( !( ret = ntfs_resident_attr_value_resize( ctx->mrec, ctx->attr, + newsize ) ) ) + { + /* Update attribute size everywhere. */ + na->data_size = na->initialized_size = newsize; + na->allocated_size = ( newsize + 7 ) & ~7; + if ( ( na->data_flags & ATTR_COMPRESSION_MASK ) + || NAttrSparse( na ) ) + na->compressed_size = na->allocated_size; + if ( na->type == AT_DATA && na->name == AT_UNNAMED ) + { + na->ni->data_size = na->data_size; + na->ni->allocated_size = na->allocated_size; + NInoFileNameSetDirty( na->ni ); + } + goto resize_done; + } + /* Prefer AT_INDEX_ALLOCATION instead of AT_ATTRIBUTE_LIST */ + if ( ret == STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT ) + { + err = errno; + goto put_err_out; + } + } + /* There is not enough space in the mft record to perform the resize. */ - /* Make the attribute non-resident if possible. */ - if (!ntfs_attr_make_non_resident(na, ctx)) { - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - /* Resize non-resident attribute */ - return ntfs_attr_truncate(na, newsize); - } else if (errno != ENOSPC && errno != EPERM) { - err = errno; - ntfs_log_perror("Failed to make attribute non-resident"); - goto put_err_out; - } + /* Make the attribute non-resident if possible. */ + if ( !ntfs_attr_make_non_resident( na, ctx ) ) + { + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + ntfs_attr_put_search_ctx( ctx ); + /* Resize non-resident attribute */ + return ntfs_attr_truncate( na, newsize ); + } + else if ( errno != ENOSPC && errno != EPERM ) + { + err = errno; + ntfs_log_perror( "Failed to make attribute non-resident" ); + goto put_err_out; + } - /* Try to make other attributes non-resident and retry each time. */ - ntfs_attr_init_search_ctx(ctx, NULL, na->ni->mrec); - while (!ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx)) { - ntfs_attr *tna; - ATTR_RECORD *a; + /* Try to make other attributes non-resident and retry each time. */ + ntfs_attr_init_search_ctx( ctx, NULL, na->ni->mrec ); + while ( !ntfs_attr_lookup( AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx ) ) + { + ntfs_attr *tna; + ATTR_RECORD *a; - a = ctx->attr; - if (a->non_resident) - continue; + a = ctx->attr; + if ( a->non_resident ) + continue; - /* - * Check out whether convert is reasonable. Assume that mapping - * pairs will take 8 bytes. - */ - if (le32_to_cpu(a->length) <= offsetof(ATTR_RECORD, - compressed_size) + ((a->name_length * - sizeof(ntfschar) + 7) & ~7) + 8) - continue; + /* + * Check out whether convert is reasonable. Assume that mapping + * pairs will take 8 bytes. + */ + if ( le32_to_cpu( a->length ) <= offsetof( ATTR_RECORD, + compressed_size ) + ( ( a->name_length * + sizeof( ntfschar ) + 7 ) & ~7 ) + 8 ) + continue; - tna = ntfs_attr_open(na->ni, a->type, (ntfschar*)((u8*)a + - le16_to_cpu(a->name_offset)), a->name_length); - if (!tna) { - err = errno; - ntfs_log_perror("Couldn't open attribute"); - goto put_err_out; - } - if (ntfs_attr_make_non_resident(tna, ctx)) { - ntfs_attr_close(tna); - continue; - } - ntfs_inode_mark_dirty(tna->ni); - ntfs_attr_close(tna); - ntfs_attr_put_search_ctx(ctx); - return ntfs_resident_attr_resize(na, newsize); - } - /* Check whether error occurred. */ - if (errno != ENOENT) { - err = errno; - ntfs_log_perror("%s: Attribute lookup failed 1", __FUNCTION__); - goto put_err_out; - } - - /* - * The standard information and attribute list attributes can't be - * moved out from the base MFT record, so try to move out others. - */ - if (na->type==AT_STANDARD_INFORMATION || na->type==AT_ATTRIBUTE_LIST) { - ntfs_attr_put_search_ctx(ctx); - if (ntfs_inode_free_space(na->ni, offsetof(ATTR_RECORD, - non_resident_end) + 8)) { - ntfs_log_perror("Could not free space in MFT record"); - return -1; - } - return ntfs_resident_attr_resize(na, newsize); - } + tna = ntfs_attr_open( na->ni, a->type, ( ntfschar* )( ( u8* )a + + le16_to_cpu( a->name_offset ) ), a->name_length ); + if ( !tna ) + { + err = errno; + ntfs_log_perror( "Couldn't open attribute" ); + goto put_err_out; + } + if ( ntfs_attr_make_non_resident( tna, ctx ) ) + { + ntfs_attr_close( tna ); + continue; + } + ntfs_inode_mark_dirty( tna->ni ); + ntfs_attr_close( tna ); + ntfs_attr_put_search_ctx( ctx ); + return ntfs_resident_attr_resize( na, newsize ); + } + /* Check whether error occurred. */ + if ( errno != ENOENT ) + { + err = errno; + ntfs_log_perror( "%s: Attribute lookup failed 1", __FUNCTION__ ); + goto put_err_out; + } - /* - * 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( na, 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)) { - 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(na, newsize); - } - /* Allocate new mft record. */ - ni = ntfs_mft_record_alloc(vol, ni); - if (!ni) { - err = errno; - ntfs_log_perror("Couldn't allocate new MFT record"); - goto put_err_out; - } - /* Move attribute to it. */ - if (ntfs_attr_record_move_to(ctx, ni)) { - err = errno; - ntfs_log_perror("Couldn't move attribute to new MFT record"); - goto put_err_out; - } - /* Update ntfs attribute. */ - if (na->ni->nr_extents == -1) - na->ni = ni; + /* + * 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(na, newsize); + /* Add attribute list if not present. */ + if ( na->ni->nr_extents == -1 ) + ni = na->ni->base_ni; + else + ni = na->ni; + if ( !NInoAttrList( ni ) ) + { + ntfs_attr_put_search_ctx( ctx ); + if ( ntfs_inode_add_attrlist( ni ) ) + return -1; + return ntfs_resident_attr_resize( na, newsize ); + } + /* Allocate new mft record. */ + ni = ntfs_mft_record_alloc( vol, ni ); + if ( !ni ) + { + err = errno; + ntfs_log_perror( "Couldn't allocate new MFT record" ); + goto put_err_out; + } + /* Move attribute to it. */ + if ( ntfs_attr_record_move_to( ctx, ni ) ) + { + err = errno; + ntfs_log_perror( "Couldn't move attribute to new MFT record" ); + goto put_err_out; + } + /* Update ntfs attribute. */ + if ( na->ni->nr_extents == -1 ) + na->ni = ni; + + ntfs_attr_put_search_ctx( ctx ); + /* Try to perform resize once again. */ + return ntfs_resident_attr_resize( na, newsize ); resize_done: - /* - * Set the inode (and its base inode if it exists) dirty so it is - * written out later. - */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - return 0; + /* + * Set the inode (and its base inode if it exists) dirty so it is + * written out later. + */ + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + ntfs_attr_put_search_ctx( ctx ); + return 0; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return ret; + ntfs_attr_put_search_ctx( ctx ); + errno = err; + return ret; } -static int ntfs_resident_attr_resize(ntfs_attr *na, const s64 newsize) +static int ntfs_resident_attr_resize( ntfs_attr *na, const s64 newsize ) { - int ret; - - ntfs_log_enter("Entering\n"); - ret = ntfs_resident_attr_resize_i(na, newsize); - ntfs_log_leave("\n"); - return ret; + int ret; + + ntfs_log_enter( "Entering\n" ); + ret = ntfs_resident_attr_resize_i( na, newsize ); + ntfs_log_leave( "\n" ); + return ret; } /** * ntfs_attr_make_resident - convert a non-resident to a resident attribute - * @na: open ntfs attribute to make resident - * @ctx: ntfs search context describing the attribute + * @na: open ntfs attribute to make resident + * @ctx: ntfs search context describing the attribute * * Convert a non-resident ntfs attribute to a resident one. * * Return 0 on success and -1 on error with errno set to the error code. The * following error codes are defined: - * EINVAL - Invalid arguments passed. - * EPERM - The attribute is not allowed to be resident. - * EIO - I/O error, damaged inode or bug. - * ENOSPC - There is no enough space to perform conversion. - * EOPNOTSUPP - Requested conversion is not supported yet. + * EINVAL - Invalid arguments passed. + * EPERM - The attribute is not allowed to be resident. + * EIO - I/O error, damaged inode or bug. + * ENOSPC - There is no enough space to perform conversion. + * EOPNOTSUPP - Requested conversion is not supported yet. * * Warning: We do not set the inode dirty and we do not write out anything! - * 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. + * We expect the caller to do this as this is a fairly low level + * function and it is likely there will be further changes made. */ -static int ntfs_attr_make_resident(ntfs_attr *na, ntfs_attr_search_ctx *ctx) +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"); - err = EINVAL; - return -1; - } + /* Should be called for the first extent of the attribute. */ + if ( sle64_to_cpu( a->lowest_vcn ) ) + { + ntfs_log_trace( "Eeek! Should be called for the first extent of the " + "attribute. Aborting...\n" ); + err = EINVAL; + return -1; + } - /* Some preliminary sanity checking. */ - if (!NAttrNonResident(na)) { - ntfs_log_trace("Eeek! Trying to make resident attribute resident. " - "Aborting...\n"); - errno = EINVAL; - return -1; - } + /* Some preliminary sanity checking. */ + if ( !NAttrNonResident( na ) ) + { + ntfs_log_trace( "Eeek! Trying to make resident attribute resident. " + "Aborting...\n" ); + errno = EINVAL; + return -1; + } - /* Make sure this is not $MFT/$BITMAP or Windows will not boot! */ - if (na->type == AT_BITMAP && na->ni->mft_no == FILE_MFT) { - errno = EPERM; - return -1; - } + /* Make sure this is not $MFT/$BITMAP or Windows will not boot! */ + if ( na->type == AT_BITMAP && na->ni->mft_no == FILE_MFT ) + { + errno = EPERM; + return -1; + } - /* Check that the attribute is allowed to be resident. */ - if (ntfs_attr_can_be_resident(vol, na->type)) - return -1; + /* Check that the attribute is allowed to be resident. */ + if ( ntfs_attr_can_be_resident( vol, na->type ) ) + return -1; - if (na->data_flags & ATTR_IS_ENCRYPTED) { - ntfs_log_trace("Making encrypted streams resident is not " - "implemented yet.\n"); - errno = EOPNOTSUPP; - return -1; - } + if ( na->data_flags & ATTR_IS_ENCRYPTED ) + { + ntfs_log_trace( "Making encrypted streams resident is not " + "implemented yet.\n" ); + errno = EOPNOTSUPP; + return -1; + } - /* Work out offsets into and size of the resident attribute. */ - name_ofs = 24; /* = sizeof(resident_ATTR_REC); */ - val_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7; - arec_size = (val_ofs + na->data_size + 7) & ~7; + /* Work out offsets into and size of the resident attribute. */ + name_ofs = 24; /* = sizeof(resident_ATTR_REC); */ + val_ofs = ( name_ofs + a->name_length * sizeof( ntfschar ) + 7 ) & ~7; + arec_size = ( val_ofs + na->data_size + 7 ) & ~7; - /* Sanity check the size before we start modifying the attribute. */ - if (le32_to_cpu(ctx->mrec->bytes_in_use) - le32_to_cpu(a->length) + - arec_size > le32_to_cpu(ctx->mrec->bytes_allocated)) { - errno = ENOSPC; - ntfs_log_trace("Not enough space to make attribute resident\n"); - return -1; - } + /* Sanity check the size before we start modifying the attribute. */ + if ( le32_to_cpu( ctx->mrec->bytes_in_use ) - le32_to_cpu( a->length ) + + arec_size > le32_to_cpu( ctx->mrec->bytes_allocated ) ) + { + errno = ENOSPC; + ntfs_log_trace( "Not enough space to make attribute resident\n" ); + return -1; + } - /* Read and cache the whole runlist if not already done. */ - if (ntfs_attr_map_whole_runlist(na)) - return -1; + /* Read and cache the whole runlist if not already done. */ + if ( ntfs_attr_map_whole_runlist( na ) ) + return -1; - /* Move the attribute name if it exists and update the offset. */ - if (a->name_length) { - memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset), - a->name_length * sizeof(ntfschar)); - } - a->name_offset = cpu_to_le16(name_ofs); + /* Move the attribute name if it exists and update the offset. */ + if ( a->name_length ) + { + memmove( ( u8* )a + name_ofs, ( u8* )a + le16_to_cpu( a->name_offset ), + a->name_length * sizeof( ntfschar ) ); + } + a->name_offset = cpu_to_le16( name_ofs ); - /* Resize the resident part of the attribute record. */ - if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) { - /* - * Bug, because ntfs_attr_record_resize should not fail (we - * already checked that attribute fits MFT record). - */ - ntfs_log_error("BUG! Failed to resize attribute record. " - "Please report to the %s. Aborting...\n", - NTFS_DEV_LIST); - errno = EIO; - return -1; - } + /* Resize the resident part of the attribute record. */ + if ( ntfs_attr_record_resize( ctx->mrec, a, arec_size ) < 0 ) + { + /* + * Bug, because ntfs_attr_record_resize should not fail (we + * already checked that attribute fits MFT record). + */ + ntfs_log_error( "BUG! Failed to resize attribute record. " + "Please report to the %s. Aborting...\n", + NTFS_DEV_LIST ); + errno = EIO; + return -1; + } - /* Convert the attribute record to describe a resident attribute. */ - a->non_resident = 0; - a->flags = 0; - a->value_length = cpu_to_le32(na->data_size); - a->value_offset = cpu_to_le16(val_ofs); - /* - * If a data stream was wiped out, adjust the compression mode - * to current state of compression flag - */ - if (!na->data_size - && (na->type == AT_DATA) - && (na->ni->flags & FILE_ATTR_COMPRESSED)) { - a->flags |= ATTR_IS_COMPRESSED; - na->data_flags = a->flags; - } - /* - * File names cannot be non-resident so we would never see this here - * but at least it serves as a reminder that there may be attributes - * for which we do need to set this flag. (AIA) - */ - if (a->type == AT_FILE_NAME) - a->resident_flags = RESIDENT_ATTR_IS_INDEXED; - else - a->resident_flags = 0; - a->reservedR = 0; + /* Convert the attribute record to describe a resident attribute. */ + a->non_resident = 0; + a->flags = 0; + a->value_length = cpu_to_le32( na->data_size ); + a->value_offset = cpu_to_le16( val_ofs ); + /* + * If a data stream was wiped out, adjust the compression mode + * to current state of compression flag + */ + if ( !na->data_size + && ( na->type == AT_DATA ) + && ( na->ni->flags & FILE_ATTR_COMPRESSED ) ) + { + a->flags |= ATTR_IS_COMPRESSED; + na->data_flags = a->flags; + } + /* + * File names cannot be non-resident so we would never see this here + * but at least it serves as a reminder that there may be attributes + * for which we do need to set this flag. (AIA) + */ + if ( a->type == AT_FILE_NAME ) + a->resident_flags = RESIDENT_ATTR_IS_INDEXED; + else + a->resident_flags = 0; + a->reservedR = 0; - /* Sanity fixup... Shouldn't really happen. (AIA) */ - if (na->initialized_size > na->data_size) - na->initialized_size = na->data_size; + /* Sanity fixup... Shouldn't really happen. (AIA) */ + if ( na->initialized_size > na->data_size ) + na->initialized_size = na->data_size; - /* Copy data from run list to resident attribute value. */ - bytes_read = ntfs_rl_pread(vol, na->rl, 0, na->initialized_size, - (u8*)a + val_ofs); - if (bytes_read != na->initialized_size) { - if (bytes_read < 0) - err = errno; - ntfs_log_trace("Eeek! Failed to read attribute data. Leaving " - "inconstant metadata. Run chkdsk. " - "Aborting...\n"); - errno = err; - return -1; - } + /* Copy data from run list to resident attribute value. */ + bytes_read = ntfs_rl_pread( vol, na->rl, 0, na->initialized_size, + ( u8* )a + val_ofs ); + if ( bytes_read != na->initialized_size ) + { + if ( bytes_read < 0 ) + err = errno; + ntfs_log_trace( "Eeek! Failed to read attribute data. Leaving " + "inconstant metadata. Run chkdsk. " + "Aborting...\n" ); + errno = err; + return -1; + } - /* Clear memory in gap between initialized_size and data_size. */ - if (na->initialized_size < na->data_size) - memset((u8*)a + val_ofs + na->initialized_size, 0, - na->data_size - na->initialized_size); + /* Clear memory in gap between initialized_size and data_size. */ + if ( na->initialized_size < na->data_size ) + memset( ( u8* )a + val_ofs + na->initialized_size, 0, + na->data_size - na->initialized_size ); - /* - * Deallocate clusters from the runlist. - * - * NOTE: We can use ntfs_cluster_free() because we have already mapped - * the whole run list and thus it doesn't matter that the attribute - * record is in a transiently corrupted state at this moment in time. - */ - if (ntfs_cluster_free(vol, na, 0, -1) < 0) { - err = errno; - ntfs_log_perror("Eeek! Failed to release allocated clusters"); - ntfs_log_trace("Ignoring error and leaving behind wasted " - "clusters.\n"); - } + /* + * Deallocate clusters from the runlist. + * + * NOTE: We can use ntfs_cluster_free() because we have already mapped + * the whole run list and thus it doesn't matter that the attribute + * record is in a transiently corrupted state at this moment in time. + */ + if ( ntfs_cluster_free( vol, na, 0, -1 ) < 0 ) + { + err = errno; + ntfs_log_perror( "Eeek! Failed to release allocated clusters" ); + ntfs_log_trace( "Ignoring error and leaving behind wasted " + "clusters.\n" ); + } - /* Throw away the now unused runlist. */ - free(na->rl); - na->rl = NULL; + /* Throw away the now unused runlist. */ + free( na->rl ); + na->rl = NULL; - /* Update in-memory struct ntfs_attr. */ - NAttrClearNonResident(na); - NAttrClearSparse(na); - NAttrClearEncrypted(na); - na->initialized_size = na->data_size; - na->allocated_size = na->compressed_size = (na->data_size + 7) & ~7; - na->compression_block_size = 0; - na->compression_block_size_bits = na->compression_block_clusters = 0; - return 0; + /* Update in-memory struct ntfs_attr. */ + NAttrClearNonResident( na ); + NAttrClearSparse( na ); + NAttrClearEncrypted( na ); + na->initialized_size = na->data_size; + na->allocated_size = na->compressed_size = ( na->data_size + 7 ) & ~7; + na->compression_block_size = 0; + na->compression_block_size_bits = na->compression_block_clusters = 0; + return 0; } /* * 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->ni->allocated_size = na->compressed_size; - else - na->ni->allocated_size = na->allocated_size; - NInoFileNameSetDirty(na->ni); - } + 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->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; + return ret; +leave: ret = -1; goto out; /* return -1 */ +retry: ret = -2; goto out; error: ret = -3; goto out; } @@ -4877,306 +5218,333 @@ error: ret = -3; goto out; /** * ntfs_attr_update_mapping_pairs_i - see ntfs_attr_update_mapping_pairs */ -static int ntfs_attr_update_mapping_pairs_i(ntfs_attr *na, VCN from_vcn) +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; + ntfs_attr_search_ctx *ctx; + ntfs_inode *ni, *base_ni; + MFT_RECORD *m; + ATTR_RECORD *a; + VCN stop_vcn; + const runlist_element *stop_rl; + int err, mp_size, cur_max_mp_size, exp_max_mp_size, ret = -1; + BOOL finished_build; retry: - if (!na || !na->rl || from_vcn) { - errno = EINVAL; - ntfs_log_perror("%s: na=%p", __FUNCTION__, na); - return -1; - } + if ( !na || !na->rl || from_vcn ) + { + errno = EINVAL; + ntfs_log_perror( "%s: na=%p", __FUNCTION__, na ); + return -1; + } - ntfs_log_trace("Entering for inode %llu, attr 0x%x\n", - (unsigned long long)na->ni->mft_no, na->type); + ntfs_log_trace( "Entering for inode %llu, attr 0x%x\n", + ( unsigned long long )na->ni->mft_no, na->type ); - if (!NAttrNonResident(na)) { - errno = EINVAL; - ntfs_log_perror("%s: resident attribute", __FUNCTION__); - return -1; - } + if ( !NAttrNonResident( na ) ) + { + errno = EINVAL; + ntfs_log_perror( "%s: resident attribute", __FUNCTION__ ); + return -1; + } - if (na->ni->nr_extents == -1) - base_ni = na->ni->base_ni; - else - base_ni = na->ni; + if ( na->ni->nr_extents == -1 ) + base_ni = na->ni->base_ni; + else + base_ni = na->ni; - ctx = ntfs_attr_get_search_ctx(base_ni, NULL); - if (!ctx) - return -1; + ctx = ntfs_attr_get_search_ctx( base_ni, NULL ); + if ( !ctx ) + return -1; - /* Fill attribute records with new mapping pairs. */ - stop_vcn = 0; - stop_rl = na->rl; - finished_build = FALSE; - while (!ntfs_attr_lookup(na->type, na->name, na->name_len, - CASE_SENSITIVE, from_vcn, NULL, 0, ctx)) { - a = ctx->attr; - m = ctx->mrec; - /* - * If runlist is updating not from the beginning, then set - * @stop_vcn properly, i.e. to the lowest vcn of record that - * contain @from_vcn. Also we do not need @from_vcn anymore, - * set it to 0 to make ntfs_attr_lookup enumerate attributes. - */ - if (from_vcn) { - LCN first_lcn; + /* Fill attribute records with new mapping pairs. */ + stop_vcn = 0; + stop_rl = na->rl; + finished_build = FALSE; + while ( !ntfs_attr_lookup( na->type, na->name, na->name_len, + CASE_SENSITIVE, from_vcn, NULL, 0, ctx ) ) + { + a = ctx->attr; + m = ctx->mrec; + /* + * If runlist is updating not from the beginning, then set + * @stop_vcn properly, i.e. to the lowest vcn of record that + * contain @from_vcn. Also we do not need @from_vcn anymore, + * set it to 0 to make ntfs_attr_lookup enumerate attributes. + */ + if ( from_vcn ) + { + LCN first_lcn; - stop_vcn = sle64_to_cpu(a->lowest_vcn); - from_vcn = 0; - /* - * Check whether the first run we need to update is - * the last run in runlist, if so, then deallocate - * all attrubute extents starting this one. - */ - first_lcn = ntfs_rl_vcn_to_lcn(na->rl, stop_vcn); - if (first_lcn == LCN_EINVAL) { - errno = EIO; - ntfs_log_perror("Bad runlist"); - goto put_err_out; - } - if (first_lcn == LCN_ENOENT || - first_lcn == LCN_RL_NOT_MAPPED) - finished_build = TRUE; - } + stop_vcn = sle64_to_cpu( a->lowest_vcn ); + from_vcn = 0; + /* + * Check whether the first run we need to update is + * the last run in runlist, if so, then deallocate + * all attrubute extents starting this one. + */ + first_lcn = ntfs_rl_vcn_to_lcn( na->rl, stop_vcn ); + if ( first_lcn == LCN_EINVAL ) + { + errno = EIO; + ntfs_log_perror( "Bad runlist" ); + goto put_err_out; + } + if ( first_lcn == LCN_ENOENT || + first_lcn == LCN_RL_NOT_MAPPED ) + finished_build = TRUE; + } - /* - * Check whether we finished mapping pairs build, if so mark - * extent as need to delete (by setting highest vcn to - * NTFS_VCN_DELETE_MARK (-2), we shall check it later and - * delete extent) and continue search. - */ - if (finished_build) { - ntfs_log_trace("Mark attr 0x%x for delete in inode " - "%lld.\n", (unsigned)le32_to_cpu(a->type), - (long long)ctx->ntfs_ino->mft_no); - a->highest_vcn = cpu_to_sle64(NTFS_VCN_DELETE_MARK); - ntfs_inode_mark_dirty(ctx->ntfs_ino); - continue; - } + /* + * Check whether we finished mapping pairs build, if so mark + * extent as need to delete (by setting highest vcn to + * NTFS_VCN_DELETE_MARK (-2), we shall check it later and + * delete extent) and continue search. + */ + if ( finished_build ) + { + ntfs_log_trace( "Mark attr 0x%x for delete in inode " + "%lld.\n", ( unsigned )le32_to_cpu( a->type ), + ( long long )ctx->ntfs_ino->mft_no ); + a->highest_vcn = cpu_to_sle64( NTFS_VCN_DELETE_MARK ); + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + continue; + } - switch (ntfs_attr_update_meta(a, na, m, ctx)) { - case -1: return -1; - case -2: goto retry; - case -3: goto put_err_out; - } + switch ( ntfs_attr_update_meta( a, na, m, ctx ) ) + { + case -1: return -1; + case -2: goto retry; + case -3: goto put_err_out; + } - /* - * Determine maximum possible length of mapping pairs, - * if we shall *not* expand space for mapping pairs. - */ - cur_max_mp_size = le32_to_cpu(a->length) - - le16_to_cpu(a->mapping_pairs_offset); - /* - * Determine maximum possible length of mapping pairs in the - * current mft record, if we shall expand space for mapping - * pairs. - */ - exp_max_mp_size = le32_to_cpu(m->bytes_allocated) - - le32_to_cpu(m->bytes_in_use) + cur_max_mp_size; - /* Get the size for the rest of mapping pairs array. */ - mp_size = ntfs_get_size_for_mapping_pairs(na->ni->vol, stop_rl, - stop_vcn, exp_max_mp_size); - if (mp_size <= 0) { - ntfs_log_perror("%s: get MP size failed", __FUNCTION__); - goto put_err_out; - } - /* Test mapping pairs for fitting in the current mft record. */ - if (mp_size > exp_max_mp_size) { - /* - * Mapping pairs of $ATTRIBUTE_LIST attribute must fit - * in the base mft record. Try to move out other - * attributes and try again. - */ - if (na->type == AT_ATTRIBUTE_LIST) { - ntfs_attr_put_search_ctx(ctx); - if (ntfs_inode_free_space(na->ni, mp_size - - cur_max_mp_size)) { - ntfs_log_perror("Attribute list is too " - "big. Defragment the " - "volume\n"); - return -1; - } - goto retry; - } + /* + * Determine maximum possible length of mapping pairs, + * if we shall *not* expand space for mapping pairs. + */ + cur_max_mp_size = le32_to_cpu( a->length ) - + le16_to_cpu( a->mapping_pairs_offset ); + /* + * Determine maximum possible length of mapping pairs in the + * current mft record, if we shall expand space for mapping + * pairs. + */ + exp_max_mp_size = le32_to_cpu( m->bytes_allocated ) - + le32_to_cpu( m->bytes_in_use ) + cur_max_mp_size; + /* Get the size for the rest of mapping pairs array. */ + mp_size = ntfs_get_size_for_mapping_pairs( na->ni->vol, stop_rl, + stop_vcn, exp_max_mp_size ); + if ( mp_size <= 0 ) + { + ntfs_log_perror( "%s: get MP size failed", __FUNCTION__ ); + goto put_err_out; + } + /* Test mapping pairs for fitting in the current mft record. */ + if ( mp_size > exp_max_mp_size ) + { + /* + * Mapping pairs of $ATTRIBUTE_LIST attribute must fit + * in the base mft record. Try to move out other + * attributes and try again. + */ + if ( na->type == AT_ATTRIBUTE_LIST ) + { + ntfs_attr_put_search_ctx( ctx ); + if ( ntfs_inode_free_space( na->ni, mp_size - + cur_max_mp_size ) ) + { + ntfs_log_perror( "Attribute list is too " + "big. Defragment the " + "volume\n" ); + return -1; + } + goto retry; + } - /* Add attribute list if it isn't present, and retry. */ - if (!NInoAttrList(base_ni)) { - ntfs_attr_put_search_ctx(ctx); - if (ntfs_inode_add_attrlist(base_ni)) { - ntfs_log_perror("Can not add attrlist"); - return -1; - } - goto retry; - } + /* Add attribute list if it isn't present, and retry. */ + if ( !NInoAttrList( base_ni ) ) + { + ntfs_attr_put_search_ctx( ctx ); + if ( ntfs_inode_add_attrlist( base_ni ) ) + { + ntfs_log_perror( "Can not add attrlist" ); + return -1; + } + goto retry; + } - /* - * Set mapping pairs size to maximum possible for this - * mft record. We shall write the rest of mapping pairs - * to another MFT records. - */ - mp_size = exp_max_mp_size; - } + /* + * Set mapping pairs size to maximum possible for this + * mft record. We shall write the rest of mapping pairs + * to another MFT records. + */ + mp_size = exp_max_mp_size; + } - /* Change space for mapping pairs if we need it. */ - if (((mp_size + 7) & ~7) != cur_max_mp_size) { - if (ntfs_attr_record_resize(m, a, - le16_to_cpu(a->mapping_pairs_offset) + - mp_size)) { - errno = EIO; - ntfs_log_perror("Failed to resize attribute"); - goto put_err_out; - } - } + /* Change space for mapping pairs if we need it. */ + if ( ( ( mp_size + 7 ) & ~7 ) != cur_max_mp_size ) + { + if ( ntfs_attr_record_resize( m, a, + le16_to_cpu( a->mapping_pairs_offset ) + + mp_size ) ) + { + errno = EIO; + ntfs_log_perror( "Failed to resize attribute" ); + goto put_err_out; + } + } - /* Update lowest vcn. */ - a->lowest_vcn = cpu_to_sle64(stop_vcn); - ntfs_inode_mark_dirty(ctx->ntfs_ino); - if ((ctx->ntfs_ino->nr_extents == -1 || - NInoAttrList(ctx->ntfs_ino)) && - ctx->attr->type != AT_ATTRIBUTE_LIST) { - ctx->al_entry->lowest_vcn = cpu_to_sle64(stop_vcn); - ntfs_attrlist_mark_dirty(ctx->ntfs_ino); - } + /* Update lowest vcn. */ + a->lowest_vcn = cpu_to_sle64( stop_vcn ); + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + if ( ( ctx->ntfs_ino->nr_extents == -1 || + NInoAttrList( ctx->ntfs_ino ) ) && + ctx->attr->type != AT_ATTRIBUTE_LIST ) + { + ctx->al_entry->lowest_vcn = cpu_to_sle64( stop_vcn ); + ntfs_attrlist_mark_dirty( ctx->ntfs_ino ); + } - /* - * Generate the new mapping pairs array directly into the - * correct destination, i.e. the attribute record itself. - */ - if (!ntfs_mapping_pairs_build(na->ni->vol, (u8*)a + le16_to_cpu( - a->mapping_pairs_offset), mp_size, na->rl, - stop_vcn, &stop_rl)) - finished_build = TRUE; - if (stop_rl) - stop_vcn = stop_rl->vcn; - else - stop_vcn = 0; - if (!finished_build && errno != ENOSPC) { - ntfs_log_perror("Failed to build mapping pairs"); - goto put_err_out; - } - a->highest_vcn = cpu_to_sle64(stop_vcn - 1); - } - /* Check whether error occurred. */ - if (errno != ENOENT) { - ntfs_log_perror("%s: Attribute lookup failed", __FUNCTION__); - goto put_err_out; - } + /* + * Generate the new mapping pairs array directly into the + * correct destination, i.e. the attribute record itself. + */ + if ( !ntfs_mapping_pairs_build( na->ni->vol, ( u8* )a + le16_to_cpu( + a->mapping_pairs_offset ), mp_size, na->rl, + stop_vcn, &stop_rl ) ) + finished_build = TRUE; + if ( stop_rl ) + stop_vcn = stop_rl->vcn; + else + stop_vcn = 0; + if ( !finished_build && errno != ENOSPC ) + { + ntfs_log_perror( "Failed to build mapping pairs" ); + goto put_err_out; + } + a->highest_vcn = cpu_to_sle64( stop_vcn - 1 ); + } + /* Check whether error occurred. */ + if ( errno != ENOENT ) + { + ntfs_log_perror( "%s: Attribute lookup failed", __FUNCTION__ ); + goto put_err_out; + } - /* Deallocate not used attribute extents and return with success. */ - if (finished_build) { - ntfs_attr_reinit_search_ctx(ctx); - ntfs_log_trace("Deallocate marked extents.\n"); - while (!ntfs_attr_lookup(na->type, na->name, na->name_len, - CASE_SENSITIVE, 0, NULL, 0, ctx)) { - if (sle64_to_cpu(ctx->attr->highest_vcn) != - NTFS_VCN_DELETE_MARK) - continue; - /* Remove unused attribute record. */ - if (ntfs_attr_record_rm(ctx)) { - ntfs_log_perror("Could not remove unused attr"); - goto put_err_out; - } - ntfs_attr_reinit_search_ctx(ctx); - } - if (errno != ENOENT) { - ntfs_log_perror("%s: Attr lookup failed", __FUNCTION__); - goto put_err_out; - } - ntfs_log_trace("Deallocate done.\n"); - ntfs_attr_put_search_ctx(ctx); - goto ok; - } - ntfs_attr_put_search_ctx(ctx); - ctx = NULL; + /* Deallocate not used attribute extents and return with success. */ + if ( finished_build ) + { + ntfs_attr_reinit_search_ctx( ctx ); + ntfs_log_trace( "Deallocate marked extents.\n" ); + while ( !ntfs_attr_lookup( na->type, na->name, na->name_len, + CASE_SENSITIVE, 0, NULL, 0, ctx ) ) + { + if ( sle64_to_cpu( ctx->attr->highest_vcn ) != + NTFS_VCN_DELETE_MARK ) + continue; + /* Remove unused attribute record. */ + if ( ntfs_attr_record_rm( ctx ) ) + { + ntfs_log_perror( "Could not remove unused attr" ); + goto put_err_out; + } + ntfs_attr_reinit_search_ctx( ctx ); + } + if ( errno != ENOENT ) + { + ntfs_log_perror( "%s: Attr lookup failed", __FUNCTION__ ); + goto put_err_out; + } + ntfs_log_trace( "Deallocate done.\n" ); + ntfs_attr_put_search_ctx( ctx ); + goto ok; + } + ntfs_attr_put_search_ctx( ctx ); + ctx = NULL; - /* Allocate new MFT records for the rest of mapping pairs. */ - while (1) { - /* Calculate size of rest mapping pairs. */ - mp_size = ntfs_get_size_for_mapping_pairs(na->ni->vol, - na->rl, stop_vcn, INT_MAX); - if (mp_size <= 0) { - ntfs_log_perror("%s: get mp size failed", __FUNCTION__); - goto put_err_out; - } - /* Allocate new mft record. */ - ni = ntfs_mft_record_alloc(na->ni->vol, base_ni); - if (!ni) { - ntfs_log_perror("Could not allocate new MFT record"); - goto put_err_out; - } - m = ni->mrec; - /* - * If mapping size exceed available space, set them to - * possible maximum. - */ - cur_max_mp_size = le32_to_cpu(m->bytes_allocated) - - le32_to_cpu(m->bytes_in_use) - - (offsetof(ATTR_RECORD, compressed_size) + - (((na->data_flags & ATTR_COMPRESSION_MASK) - || NAttrSparse(na)) ? - sizeof(a->compressed_size) : 0)) - - ((sizeof(ntfschar) * na->name_len + 7) & ~7); - if (mp_size > cur_max_mp_size) - mp_size = cur_max_mp_size; - /* Add attribute extent to new record. */ - err = ntfs_non_resident_attr_record_add(ni, na->type, - na->name, na->name_len, stop_vcn, mp_size, - na->data_flags); - if (err == -1) { - err = errno; - ntfs_log_perror("Could not add attribute extent"); - if (ntfs_mft_record_free(na->ni->vol, ni)) - ntfs_log_perror("Could not free MFT record"); - errno = err; - goto put_err_out; - } - a = (ATTR_RECORD*)((u8*)m + err); + /* Allocate new MFT records for the rest of mapping pairs. */ + while ( 1 ) + { + /* Calculate size of rest mapping pairs. */ + mp_size = ntfs_get_size_for_mapping_pairs( na->ni->vol, + na->rl, stop_vcn, INT_MAX ); + if ( mp_size <= 0 ) + { + ntfs_log_perror( "%s: get mp size failed", __FUNCTION__ ); + goto put_err_out; + } + /* Allocate new mft record. */ + ni = ntfs_mft_record_alloc( na->ni->vol, base_ni ); + if ( !ni ) + { + ntfs_log_perror( "Could not allocate new MFT record" ); + goto put_err_out; + } + m = ni->mrec; + /* + * If mapping size exceed available space, set them to + * possible maximum. + */ + cur_max_mp_size = le32_to_cpu( m->bytes_allocated ) - + le32_to_cpu( m->bytes_in_use ) - + ( offsetof( ATTR_RECORD, compressed_size ) + + ( ( ( na->data_flags & ATTR_COMPRESSION_MASK ) + || NAttrSparse( na ) ) ? + sizeof( a->compressed_size ) : 0 ) ) - + ( ( sizeof( ntfschar ) * na->name_len + 7 ) & ~7 ); + if ( mp_size > cur_max_mp_size ) + mp_size = cur_max_mp_size; + /* Add attribute extent to new record. */ + err = ntfs_non_resident_attr_record_add( ni, na->type, + na->name, na->name_len, stop_vcn, mp_size, + na->data_flags ); + if ( err == -1 ) + { + err = errno; + ntfs_log_perror( "Could not add attribute extent" ); + if ( ntfs_mft_record_free( na->ni->vol, ni ) ) + ntfs_log_perror( "Could not free MFT record" ); + errno = err; + goto put_err_out; + } + a = ( ATTR_RECORD* )( ( u8* )m + err ); - err = ntfs_mapping_pairs_build(na->ni->vol, (u8*)a + - le16_to_cpu(a->mapping_pairs_offset), mp_size, na->rl, - stop_vcn, &stop_rl); - if (stop_rl) - stop_vcn = stop_rl->vcn; - else - stop_vcn = 0; - if (err < 0 && errno != ENOSPC) { - err = errno; - ntfs_log_perror("Failed to build MP"); - if (ntfs_mft_record_free(na->ni->vol, ni)) - ntfs_log_perror("Couldn't free MFT record"); - errno = err; - goto put_err_out; - } - a->highest_vcn = cpu_to_sle64(stop_vcn - 1); - ntfs_inode_mark_dirty(ni); - /* All mapping pairs has been written. */ - if (!err) - break; - } + err = ntfs_mapping_pairs_build( na->ni->vol, ( u8* )a + + le16_to_cpu( a->mapping_pairs_offset ), mp_size, na->rl, + stop_vcn, &stop_rl ); + if ( stop_rl ) + stop_vcn = stop_rl->vcn; + else + stop_vcn = 0; + if ( err < 0 && errno != ENOSPC ) + { + err = errno; + ntfs_log_perror( "Failed to build MP" ); + if ( ntfs_mft_record_free( na->ni->vol, ni ) ) + ntfs_log_perror( "Couldn't free MFT record" ); + errno = err; + goto put_err_out; + } + a->highest_vcn = cpu_to_sle64( stop_vcn - 1 ); + ntfs_inode_mark_dirty( ni ); + /* All mapping pairs has been written. */ + if ( !err ) + break; + } ok: - ret = 0; + ret = 0; out: - return ret; + return ret; put_err_out: - if (ctx) - ntfs_attr_put_search_ctx(ctx); - goto out; + if ( ctx ) + ntfs_attr_put_search_ctx( ctx ); + goto out; } #undef NTFS_VCN_DELETE_MARK /** * ntfs_attr_update_mapping_pairs - update mapping pairs for ntfs attribute - * @na: non-resident ntfs open attribute for which we need update - * @from_vcn: update runlist starting this VCN + * @na: non-resident ntfs open attribute for which we need update + * @from_vcn: update runlist starting this VCN * * Build mapping pairs from @na->rl and write them to the disk. Also, this * function updates sparse bit, allocated and compressed size (allocates/frees @@ -5193,376 +5561,411 @@ put_err_out: * * On success return 0 and on error return -1 with errno set to the error code. * The following error codes are defined: - * EINVAL - Invalid arguments passed. - * ENOMEM - Not enough memory to complete operation. - * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST - * or there is no free MFT records left to allocate. + * EINVAL - Invalid arguments passed. + * ENOMEM - Not enough memory to complete operation. + * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST + * or there is no free MFT records left to allocate. */ -int ntfs_attr_update_mapping_pairs(ntfs_attr *na, VCN from_vcn) +int 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; } /** * ntfs_non_resident_attr_shrink - shrink a non-resident, open ntfs attribute - * @na: non-resident ntfs attribute to shrink - * @newsize: new size (in bytes) to which to shrink the attribute + * @na: non-resident ntfs attribute to shrink + * @newsize: new size (in bytes) to which to shrink the attribute * * Reduce the size of a non-resident, open ntfs attribute @na to @newsize bytes. * * On success return 0 and on error return -1 with errno set to the error code. * The following error codes are defined: - * ENOMEM - Not enough memory to complete operation. - * ERANGE - @newsize is not valid for the attribute type of @na. + * ENOMEM - Not enough memory to complete operation. + * ERANGE - @newsize is not valid for the attribute type of @na. */ -static int ntfs_non_resident_attr_shrink(ntfs_attr *na, const s64 newsize) +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. */ - first_free_vcn = (newsize + vol->cluster_size - 1) >> - vol->cluster_size_bits; - /* - * Compare the new allocation with the old one and only deallocate - * clusters if there is a change. - */ - if ((na->allocated_size >> vol->cluster_size_bits) != first_free_vcn) { - if (ntfs_attr_map_whole_runlist(na)) { - ntfs_log_trace("Eeek! ntfs_attr_map_whole_runlist " - "failed.\n"); - return -1; - } - /* Deallocate all clusters starting with the first free one. */ - nr_freed_clusters = ntfs_cluster_free(vol, na, first_free_vcn, - -1); - if (nr_freed_clusters < 0) { - ntfs_log_trace("Eeek! Freeing of clusters failed. " - "Aborting...\n"); - return -1; - } + /* The first cluster outside the new allocation. */ + first_free_vcn = ( newsize + vol->cluster_size - 1 ) >> + vol->cluster_size_bits; + /* + * Compare the new allocation with the old one and only deallocate + * clusters if there is a change. + */ + if ( ( na->allocated_size >> vol->cluster_size_bits ) != first_free_vcn ) + { + if ( ntfs_attr_map_whole_runlist( na ) ) + { + ntfs_log_trace( "Eeek! ntfs_attr_map_whole_runlist " + "failed.\n" ); + return -1; + } + /* Deallocate all clusters starting with the first free one. */ + nr_freed_clusters = ntfs_cluster_free( vol, na, first_free_vcn, + -1 ); + if ( nr_freed_clusters < 0 ) + { + ntfs_log_trace( "Eeek! Freeing of clusters failed. " + "Aborting...\n" ); + return -1; + } - /* Truncate the runlist itself. */ - if (ntfs_rl_truncate(&na->rl, first_free_vcn)) { - /* - * Failed to truncate the runlist, so just throw it - * away, it will be mapped afresh on next use. - */ - free(na->rl); - na->rl = NULL; - ntfs_log_trace("Eeek! Run list truncation failed.\n"); - return -1; - } + /* Truncate the runlist itself. */ + if ( ntfs_rl_truncate( &na->rl, first_free_vcn ) ) + { + /* + * Failed to truncate the runlist, so just throw it + * away, it will be mapped afresh on next use. + */ + free( na->rl ); + na->rl = NULL; + ntfs_log_trace( "Eeek! Run list truncation failed.\n" ); + return -1; + } - /* Prepare to mapping pairs update. */ - na->allocated_size = first_free_vcn << vol->cluster_size_bits; - /* Write mapping pairs for new runlist. */ - if (ntfs_attr_update_mapping_pairs(na, 0 /*first_free_vcn*/)) { - ntfs_log_trace("Eeek! Mapping pairs update failed. " - "Leaving inconstant metadata. " - "Run chkdsk.\n"); - return -1; - } - } + /* Prepare to mapping pairs update. */ + na->allocated_size = first_free_vcn << vol->cluster_size_bits; + /* Write mapping pairs for new runlist. */ + if ( ntfs_attr_update_mapping_pairs( na, 0 /*first_free_vcn*/ ) ) + { + ntfs_log_trace( "Eeek! Mapping pairs update failed. " + "Leaving inconstant metadata. " + "Run chkdsk.\n" ); + return -1; + } + } - /* Get the first attribute record. */ - ctx = ntfs_attr_get_search_ctx(na->ni, NULL); - if (!ctx) - return -1; + /* Get the first attribute record. */ + ctx = ntfs_attr_get_search_ctx( na->ni, NULL ); + if ( !ctx ) + return -1; - if (ntfs_attr_lookup(na->type, na->name, na->name_len, CASE_SENSITIVE, - 0, NULL, 0, ctx)) { - err = errno; - if (err == ENOENT) - err = EIO; - ntfs_log_trace("Eeek! Lookup of first attribute extent failed. " - "Leaving inconstant metadata.\n"); - goto put_err_out; - } + if ( ntfs_attr_lookup( na->type, na->name, na->name_len, CASE_SENSITIVE, + 0, NULL, 0, ctx ) ) + { + err = errno; + if ( err == ENOENT ) + err = EIO; + ntfs_log_trace( "Eeek! Lookup of first attribute extent failed. " + "Leaving inconstant metadata.\n" ); + goto put_err_out; + } - /* Update data and initialized size. */ - na->data_size = newsize; - ctx->attr->data_size = cpu_to_sle64(newsize); - if (newsize < na->initialized_size) { - na->initialized_size = newsize; - ctx->attr->initialized_size = cpu_to_sle64(newsize); - } - /* Update data size in the index. */ - if (na->type == AT_DATA && na->name == AT_UNNAMED) { - na->ni->data_size = na->data_size; - NInoFileNameSetDirty(na->ni); - } + /* Update data and initialized size. */ + na->data_size = newsize; + ctx->attr->data_size = cpu_to_sle64( newsize ); + if ( newsize < na->initialized_size ) + { + na->initialized_size = newsize; + ctx->attr->initialized_size = cpu_to_sle64( newsize ); + } + /* Update data size in the index. */ + if ( na->type == AT_DATA && na->name == AT_UNNAMED ) + { + na->ni->data_size = na->data_size; + NInoFileNameSetDirty( na->ni ); + } - /* If the attribute now has zero size, make it resident. */ - if (!newsize) { - if (ntfs_attr_make_resident(na, ctx)) { - /* If couldn't make resident, just continue. */ - if (errno != EPERM) - ntfs_log_error("Failed to make attribute " - "resident. Leaving as is...\n"); - } - } + /* If the attribute now has zero size, make it resident. */ + if ( !newsize ) + { + if ( ntfs_attr_make_resident( na, ctx ) ) + { + /* If couldn't make resident, just continue. */ + if ( errno != EPERM ) + ntfs_log_error( "Failed to make attribute " + "resident. Leaving as is...\n" ); + } + } - /* Set the inode dirty so it is written out later. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - /* Done! */ - ntfs_attr_put_search_ctx(ctx); - return 0; + /* Set the inode dirty so it is written out later. */ + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + /* Done! */ + ntfs_attr_put_search_ctx( ctx ); + return 0; put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = err; - return -1; + ntfs_attr_put_search_ctx( ctx ); + errno = err; + return -1; } /** * ntfs_non_resident_attr_expand - expand a non-resident, open ntfs attribute - * @na: non-resident ntfs attribute to expand - * @newsize: new size (in bytes) to which to expand the attribute + * @na: non-resident ntfs attribute to expand + * @newsize: new size (in bytes) to which to expand the attribute * * Expand the size of a non-resident, open ntfs attribute @na to @newsize bytes, * by allocating new clusters. * * On success return 0 and on error return -1 with errno set to the error code. * The following error codes are defined: - * ENOMEM - Not enough memory to complete operation. - * ERANGE - @newsize is not valid for the attribute type of @na. - * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST. + * ENOMEM - Not enough memory to complete operation. + * ERANGE - @newsize is not valid for the attribute type of @na. + * ENOSPC - There is no enough space in base mft to resize $ATTRIBUTE_LIST. */ -static int ntfs_non_resident_attr_expand_i(ntfs_attr *na, const s64 newsize) +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->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; + if ( ntfs_attr_lookup( na->type, na->name, na->name_len, CASE_SENSITIVE, + 0, NULL, 0, ctx ) ) + { + err = errno; + ntfs_log_perror( "Lookup of first attribute extent failed" ); + if ( err == ENOENT ) + err = EIO; + if ( na->allocated_size != org_alloc_size ) + { + ntfs_attr_put_search_ctx( ctx ); + goto rollback; + } + else + goto put_err_out; + } + + /* Update data size. */ + na->data_size = newsize; + ctx->attr->data_size = cpu_to_sle64( newsize ); + /* Update data size in the index. */ + if ( na->type == AT_DATA && na->name == AT_UNNAMED ) + { + na->ni->data_size = na->data_size; + NInoFileNameSetDirty( na->ni ); + } + /* Set the inode dirty so it is written out later. */ + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + /* Done! */ + ntfs_attr_put_search_ctx( ctx ); + return 0; 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; + /* 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; + ntfs_attr_put_search_ctx( ctx ); + errno = err; + return -1; } -static int ntfs_non_resident_attr_expand(ntfs_attr *na, const s64 newsize) +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; } /** * ntfs_attr_truncate - resize an ntfs attribute - * @na: open ntfs attribute to resize - * @newsize: new size (in bytes) to which to resize the attribute + * @na: open ntfs attribute to resize + * @newsize: new size (in bytes) to which to resize the attribute * * Change the size of an open ntfs attribute @na to @newsize bytes. If the * attribute is made bigger and the attribute is resident the newly @@ -5572,342 +5975,364 @@ static int ntfs_non_resident_attr_expand(ntfs_attr *na, const s64 newsize) * * On success return 0. * On error return values are: - * STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT - * STATUS_ERROR - otherwise + * STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT + * STATUS_ERROR - otherwise * The following error codes are defined: - * EINVAL - Invalid arguments were passed to the function. - * EOPNOTSUPP - The desired resize is not implemented yet. - * EACCES - Encrypted attribute. + * EINVAL - Invalid arguments were passed to the function. + * EOPNOTSUPP - The desired resize is not implemented yet. + * EACCES - Encrypted attribute. */ -int ntfs_attr_truncate(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_info("Failed to truncate encrypted attribute"); - goto out; - } - /* - * TODO: Implement making handling of compressed attributes. - * Currently we can only expand the attribute or delete it, - * and only for ATTR_IS_COMPRESSED. This is however possible - * for resident attributes when there is no open fuse context - * (important case : $INDEX_ROOT:$I30) - */ - compressed = (na->data_flags & ATTR_COMPRESSION_MASK) - != const_cpu_to_le16(0); - if (compressed - && NAttrNonResident(na) - && (((na->data_flags & ATTR_COMPRESSION_MASK) != ATTR_IS_COMPRESSED) - || (newsize && (newsize < na->data_size)))) { - errno = EOPNOTSUPP; - ntfs_log_perror("Failed to truncate compressed attribute"); - goto out; - } - if (NAttrNonResident(na)) { - /* - * For compressed data, the last block must be fully - * allocated, and we do not known the size of compression - * block until the attribute has been made non-resident. - * Moreover we can only process a single compression - * block at a time (from where we are about to write), - * so we silently do not allocate more. - * - * Note : do not request truncate on compressed files - * unless being able to face the consequences ! - */ - if (compressed && newsize) - fullsize = (na->initialized_size - | (na->compression_block_size - 1)) + 1; - else - fullsize = newsize; - if (fullsize > na->data_size) - ret = ntfs_non_resident_attr_expand(na, fullsize); - else - ret = ntfs_non_resident_attr_shrink(na, fullsize); - } else - ret = ntfs_resident_attr_resize(na, newsize); -out: - ntfs_log_leave("Return status %d\n", ret); - return ret; + if ( na->data_size == newsize ) + { + ntfs_log_trace( "Size is already ok\n" ); + ret = STATUS_OK; + goto out; + } + /* + * Encrypted attributes are not supported. We return access denied, + * which is what Windows NT4 does, too. + */ + if ( na->data_flags & ATTR_IS_ENCRYPTED ) + { + errno = EACCES; + ntfs_log_info( "Failed to truncate encrypted attribute" ); + goto out; + } + /* + * TODO: Implement making handling of compressed attributes. + * Currently we can only expand the attribute or delete it, + * and only for ATTR_IS_COMPRESSED. This is however possible + * for resident attributes when there is no open fuse context + * (important case : $INDEX_ROOT:$I30) + */ + compressed = ( na->data_flags & ATTR_COMPRESSION_MASK ) + != const_cpu_to_le16( 0 ); + if ( compressed + && NAttrNonResident( na ) + && ( ( ( na->data_flags & ATTR_COMPRESSION_MASK ) != ATTR_IS_COMPRESSED ) + || ( newsize && ( newsize < na->data_size ) ) ) ) + { + errno = EOPNOTSUPP; + ntfs_log_perror( "Failed to truncate compressed attribute" ); + goto out; + } + if ( NAttrNonResident( na ) ) + { + /* + * For compressed data, the last block must be fully + * allocated, and we do not known the size of compression + * block until the attribute has been made non-resident. + * Moreover we can only process a single compression + * block at a time (from where we are about to write), + * so we silently do not allocate more. + * + * Note : do not request truncate on compressed files + * unless being able to face the consequences ! + */ + if ( compressed && newsize ) + fullsize = ( na->initialized_size + | ( na->compression_block_size - 1 ) ) + 1; + else + fullsize = newsize; + if ( fullsize > na->data_size ) + ret = ntfs_non_resident_attr_expand( na, fullsize ); + else + ret = ntfs_non_resident_attr_shrink( na, fullsize ); + } + else + ret = ntfs_resident_attr_resize( na, newsize ); +out: + ntfs_log_leave( "Return status %d\n", ret ); + return ret; } - + /* - * Stuff a hole in a compressed file + * Stuff a hole in a compressed file * - * An unallocated hole must be aligned on compression block size. - * If needed current block and target block are stuffed with zeroes. + * An unallocated hole must be aligned on compression block size. + * If needed current block and target block are stuffed with zeroes. * - * Returns 0 if succeeded, - * -1 if it failed (as explained in errno) + * Returns 0 if succeeded, + * -1 if it failed (as explained in errno) */ -static int stuff_hole(ntfs_attr *na, const s64 pos) +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 ); } /** * ntfs_attr_readall - read the entire data from an ntfs attribute - * @ni: open ntfs inode in which the ntfs attribute resides - * @type: attribute type - * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL - * @name_len: length of attribute @name in Unicode characters (if @name given) - * @data_size: if non-NULL then store here the data size + * @ni: open ntfs inode in which the ntfs attribute resides + * @type: attribute type + * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL + * @name_len: length of attribute @name in Unicode characters (if @name given) + * @data_size: if non-NULL then store here the data size * * This function will read the entire content of an ntfs attribute. * If @name is AT_UNNAMED then look specifically for an unnamed attribute. - * If @name is NULL then the attribute could be either named or not. + * If @name is NULL then the attribute could be either named or not. * In both those cases @name_len is not used at all. * - * On success a buffer is allocated with the content of the attribute + * On success a buffer is allocated with the content of the attribute * and which needs to be freed when it's not needed anymore. If the * @data_size parameter is non-NULL then the data size is set there. * * On error NULL is returned with errno set to the error code. */ -void *ntfs_attr_readall(ntfs_inode *ni, const ATTR_TYPES type, - ntfschar *name, u32 name_len, s64 *data_size) +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; + ntfs_attr *na; + void *data, *ret = NULL; + s64 size; + + ntfs_log_enter( "Entering\n" ); + + na = ntfs_attr_open( ni, type, name, name_len ); + if ( !na ) + { + ntfs_log_perror( "ntfs_attr_open failed" ); + goto err_exit; + } + data = ntfs_malloc( na->data_size ); + if ( !data ) + goto out; + + size = ntfs_attr_pread( na, 0, na->data_size, data ); + if ( size != na->data_size ) + { + ntfs_log_perror( "ntfs_attr_pread failed" ); + free( data ); + goto out; + } + ret = data; + if ( data_size ) + *data_size = size; out: - ntfs_attr_close(na); + ntfs_attr_close( na ); err_exit: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave( "\n" ); + return ret; } -int ntfs_attr_exist(ntfs_inode *ni, const ATTR_TYPES type, ntfschar *name, - u32 name_len) +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. */ #define BCX(x) ((x) - (((x) >> 1) & 0x77777777) - \ - (((x) >> 2) & 0x33333333) - \ - (((x) >> 3) & 0x11111111)) + (((x) >> 2) & 0x33333333) - \ + (((x) >> 3) & 0x11111111)) #define BITCOUNT(x) (((BCX(x) + (BCX(x) >> 4)) & 0x0F0F0F0F) % 255) -static u8 *ntfs_init_lut256(void) +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) +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); + 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; + free( lut ); + if ( !total || br < 0 ) + return -1; + return nr_free; } #endif diff --git a/source/libntfs/attrlist.c b/source/libntfs/attrlist.c index 9c62f316..dce3eea3 100644 --- a/source/libntfs/attrlist.c +++ b/source/libntfs/attrlist.c @@ -1,6 +1,6 @@ /** * attrlist.c - Attribute list attribute handling code. Originated from the Linux-NTFS - * project. + * project. * * Copyright (c) 2004-2005 Anton Altaparmakov * Copyright (c) 2004-2005 Yura Pakhuchiy @@ -47,7 +47,7 @@ /** * ntfs_attrlist_need - check whether inode need attribute list - * @ni: opened ntfs inode for which perform check + * @ni: opened ntfs inode for which perform check * * Check whether all are attributes belong to one MFT record, in that case * attribute list is not needed. @@ -55,260 +55,278 @@ * Return 1 if inode need attribute list, 0 if not, -1 on error with errno set * to the error code. If function succeed errno set to 0. The following error * codes are defined: - * EINVAL - Invalid arguments passed to function or attribute haven't got - * attribute list. + * EINVAL - Invalid arguments passed to function or attribute haven't got + * attribute list. */ -int ntfs_attrlist_need(ntfs_inode *ni) +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; } /** * ntfs_attrlist_entry_add - add an attribute list attribute entry - * @ni: opened ntfs inode, which contains that attribute - * @attr: attribute record to add to attribute list + * @ni: opened ntfs inode, which contains that attribute + * @attr: attribute record to add to attribute list * * Return 0 on success and -1 on error with errno set to the error code. The * following error codes are defined: - * EINVAL - Invalid arguments passed to function. - * ENOMEM - Not enough memory to allocate necessary buffers. - * EIO - I/O error occurred or damaged filesystem. - * EEXIST - Such attribute already present in attribute list. + * EINVAL - Invalid arguments passed to function. + * ENOMEM - Not enough memory to allocate necessary buffers. + * EIO - I/O error occurred or damaged filesystem. + * EEXIST - Such attribute already present in attribute list. */ -int ntfs_attrlist_entry_add(ntfs_inode *ni, ATTR_RECORD *attr) +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; + /* Set new runlist. */ + free( ni->attr_list ); + ni->attr_list = new_al; + ni->attr_list_size = ni->attr_list_size + entry_len; + NInoAttrListSetDirty( ni ); + /* Done! */ + ntfs_attr_close( na ); + return 0; err_out: - if (na) - ntfs_attr_close(na); - free(new_al); - errno = err; - return -1; + if ( na ) + ntfs_attr_close( na ); + free( new_al ); + errno = err; + return -1; } /** * ntfs_attrlist_entry_rm - remove an attribute list attribute entry - * @ctx: attribute search context describing the attribute list entry + * @ctx: attribute search context describing the attribute list entry * * Remove the attribute list entry @ctx->al_entry from the attribute list. * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_attrlist_entry_rm(ntfs_attr_search_ctx *ctx) +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; + /* Set new runlist. */ + free( base_ni->attr_list ); + base_ni->attr_list = new_al; + base_ni->attr_list_size = new_al_len; + NInoAttrListSetDirty( base_ni ); + /* Done! */ + ntfs_attr_close( na ); + return 0; err_out: - if (na) - ntfs_attr_close(na); - free(new_al); - errno = err; - return -1; + if ( na ) + ntfs_attr_close( na ); + free( new_al ); + errno = err; + return -1; } diff --git a/source/libntfs/attrlist.h b/source/libntfs/attrlist.h index 2952e48b..b1e513d9 100644 --- a/source/libntfs/attrlist.h +++ b/source/libntfs/attrlist.h @@ -1,6 +1,6 @@ /* - * attrlist.h - Exports for attribute list attribute handling. - * Originated from Linux-NTFS project. + * attrlist.h - Exports for attribute list attribute handling. + * Originated from Linux-NTFS project. * * Copyright (c) 2004 Anton Altaparmakov * Copyright (c) 2004 Yura Pakhuchiy @@ -26,26 +26,26 @@ #include "attrib.h" -extern int ntfs_attrlist_need(ntfs_inode *ni); +extern int ntfs_attrlist_need( ntfs_inode *ni ); -extern int ntfs_attrlist_entry_add(ntfs_inode *ni, ATTR_RECORD *attr); -extern int ntfs_attrlist_entry_rm(ntfs_attr_search_ctx *ctx); +extern int ntfs_attrlist_entry_add( ntfs_inode *ni, ATTR_RECORD *attr ); +extern int ntfs_attrlist_entry_rm( ntfs_attr_search_ctx *ctx ); /** * ntfs_attrlist_mark_dirty - set the attribute list dirty - * @ni: ntfs inode which base inode contain dirty attribute list + * @ni: ntfs inode which base inode contain dirty attribute list * * Set the attribute list dirty so it is written out later (at the latest at * ntfs_inode_close() time). * * This function cannot fail. */ -static __inline__ void ntfs_attrlist_mark_dirty(ntfs_inode *ni) +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..e43202a4 100644 --- a/source/libntfs/bit_ops.h +++ b/source/libntfs/bit_ops.h @@ -3,7 +3,7 @@ Functions for dealing with conversion of data between types Copyright (c) 2006 Michael "Chishm" Chisholm - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -34,24 +34,28 @@ /*----------------------------------------------------------------- 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 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..6bbe18b8 100644 --- a/source/libntfs/bitmap.c +++ b/source/libntfs/bitmap.c @@ -47,254 +47,268 @@ /** * ntfs_bit_set - set a bit in a field of bits - * @bitmap: field of bits - * @bit: bit to set - * @new_value: value to set bit to (0 or 1) + * @bitmap: field of bits + * @bit: bit to set + * @new_value: value to set bit to (0 or 1) * * Set the bit @bit in the @bitmap to @new_value. Ignore all errors. */ -void ntfs_bit_set(u8 *bitmap, const u64 bit, const u8 new_value) +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 ) ); } /** * ntfs_bit_get - get value of a bit in a field of bits - * @bitmap: field of bits - * @bit: bit to get + * @bitmap: field of bits + * @bit: bit to get * * Get and return the value of the bit @bit in @bitmap (0 or 1). * Return -1 on error. */ -char ntfs_bit_get(const u8 *bitmap, const u64 bit) +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; } /** * ntfs_bit_get_and_set - get value of a bit in a field of bits and set it - * @bitmap: field of bits - * @bit: bit to get/set - * @new_value: value to set bit to (0 or 1) + * @bitmap: field of bits + * @bit: bit to get/set + * @new_value: value to set bit to (0 or 1) * * Return the value of the bit @bit and set it to @new_value (0 or 1). * Return -1 on error. */ -char ntfs_bit_get_and_set(u8 *bitmap, const u64 bit, const u8 new_value) +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; } /** * ntfs_bitmap_set_bits_in_run - set a run of bits in a bitmap to a value - * @na: attribute containing the bitmap - * @start_bit: first bit to set - * @count: number of bits to set - * @value: value to set the bits to (i.e. 0 or 1) + * @na: attribute containing the bitmap + * @start_bit: first bit to set + * @count: number of bits to set + * @value: value to set the bits to (i.e. 0 or 1) * * Set @count bits starting at bit @start_bit in the bitmap described by the * attribute @na to @value, where @value is either 0 or 1. * * 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; + } + + /* 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; - if (lastbyte && count != 0) { - // FIXME: Eeek! BUG! - ntfs_log_error("Last buffer but count is not zero " - "(%lld). Leaving inconsistent metadata.\n", - (long long)count); - errno = EIO; - goto free_err_out; - } - } while (count > 0); - - ret = 0; - free_err_out: - free(buf); - return ret; + free( buf ); + return ret; } /** * ntfs_bitmap_set_run - set a run of bits in a bitmap - * @na: attribute containing the bitmap - * @start_bit: first bit to set - * @count: number of bits to set + * @na: attribute containing the bitmap + * @start_bit: first bit to set + * @count: number of bits to set * * Set @count bits starting at bit @start_bit in the bitmap described by the * attribute @na. * * On success return 0 and on error return -1 with errno set to the error code. */ -int ntfs_bitmap_set_run(ntfs_attr *na, s64 start_bit, s64 count) +int 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; } /** * ntfs_bitmap_clear_run - clear a run of bits in a bitmap - * @na: attribute containing the bitmap - * @start_bit: first bit to clear - * @count: number of bits to clear + * @na: attribute containing the bitmap + * @start_bit: first bit to clear + * @count: number of bits to clear * * Clear @count bits starting at bit @start_bit in the bitmap described by the * attribute @na. * * On success return 0 and on error return -1 with errno set to the error code. */ -int ntfs_bitmap_clear_run(ntfs_attr *na, s64 start_bit, s64 count) +int 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..70cddd97 100644 --- a/source/libntfs/bitmap.h +++ b/source/libntfs/bitmap.h @@ -36,38 +36,38 @@ * size of the bitmap. */ -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 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 ); /** * ntfs_bitmap_set_bit - set a bit in a bitmap - * @na: attribute containing the bitmap - * @bit: bit to set + * @na: attribute containing the bitmap + * @bit: bit to set * * Set the @bit in the bitmap described by the attribute @na. * * On success return 0 and on error return -1 with errno set to the error code. */ -static __inline__ int ntfs_bitmap_set_bit(ntfs_attr *na, s64 bit) +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 ); } /** * ntfs_bitmap_clear_bit - clear a bit in a bitmap - * @na: attribute containing the bitmap - * @bit: bit to clear + * @na: attribute containing the bitmap + * @bit: bit to clear * * Clear @bit in the bitmap described by the attribute @na. * * On success return 0 and on error return -1 with errno set to the error code. */ -static __inline__ int ntfs_bitmap_clear_bit(ntfs_attr *na, s64 bit) +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 ); } /* @@ -76,9 +76,9 @@ static __inline__ int ntfs_bitmap_clear_bit(ntfs_attr *na, s64 bit) * @word: value to rotate * @shift: bits to roll */ -static __inline__ u32 ntfs_rol32(u32 word, unsigned int shift) +static __inline__ u32 ntfs_rol32( u32 word, unsigned int shift ) { - return (word << shift) | (word >> (32 - shift)); + return ( word << shift ) | ( word >> ( 32 - shift ) ); } /* @@ -87,9 +87,9 @@ static __inline__ u32 ntfs_rol32(u32 word, unsigned int shift) * @word: value to rotate * @shift: bits to roll */ -static __inline__ u32 ntfs_ror32(u32 word, unsigned int shift) +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..a97e36dd 100644 --- a/source/libntfs/bootsect.c +++ b/source/libntfs/bootsect.c @@ -45,8 +45,8 @@ /** * ntfs_boot_sector_is_ntfs - check if buffer contains a valid ntfs boot sector - * @b: buffer containing putative boot sector to analyze - * @silent: if zero, output progress messages to stderr + * @b: buffer containing putative boot sector to analyze + * @silent: if zero, output progress messages to stderr * * Check if the buffer @b contains a valid ntfs boot sector. The buffer @b * must be at least 512 bytes in size. @@ -57,229 +57,244 @@ * * Return TRUE if @b contains a valid ntfs boot sector and FALSE if not. */ -BOOL ntfs_boot_sector_is_ntfs(NTFS_BOOT_SECTOR *b) +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; + ret = TRUE; not_ntfs: - return ret; + return ret; } static const char *last_sector_error = -"HINTS: Either the volume is a RAID/LDM but it wasn't setup yet,\n" -" or it was not setup correctly (e.g. by not using mdadm --build ...),\n" -" or a wrong device is tried to be mounted,\n" -" or the partition table is corrupt (partition is smaller than NTFS),\n" -" or the NTFS boot sector is corrupt (NTFS size is not valid).\n"; + "HINTS: Either the volume is a RAID/LDM but it wasn't setup yet,\n" + " or it was not setup correctly (e.g. by not using mdadm --build ...),\n" + " or a wrong device is tried to be mounted,\n" + " or the partition table is corrupt (partition is smaller than NTFS),\n" + " or the NTFS boot sector is corrupt (NTFS size is not valid).\n"; /** * ntfs_boot_sector_parse - setup an ntfs volume from an ntfs boot sector - * @vol: ntfs_volume to setup - * @bs: buffer containing ntfs boot sector to parse + * @vol: ntfs_volume to setup + * @bs: buffer containing ntfs boot sector to parse * * Parse the ntfs bootsector @bs and setup the ntfs volume @vol with the * obtained values. * * Return 0 on success or -1 on error with errno set to the error code EINVAL. */ -int ntfs_boot_sector_parse(ntfs_volume *vol, const NTFS_BOOT_SECTOR *bs) +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/bootsect.h b/source/libntfs/bootsect.h index a299e821..44408732 100644 --- a/source/libntfs/bootsect.h +++ b/source/libntfs/bootsect.h @@ -1,6 +1,6 @@ /* - * bootsect.h - Exports for bootsector record handling. - * Originated from the Linux-NTFS project. + * bootsect.h - Exports for bootsector record handling. + * Originated from the Linux-NTFS project. * * Copyright (c) 2000-2002 Anton Altaparmakov * Copyright (c) 2006 Szabolcs Szakacsits @@ -30,13 +30,13 @@ /** * ntfs_boot_sector_is_ntfs - check a boot sector for describing an ntfs volume - * @b: buffer containing the boot sector + * @b: buffer containing the boot sector * * This function checks the boot sector in @b for describing a valid ntfs * volume. Return TRUE if @b is a valid NTFS boot sector or FALSE otherwise. */ -extern BOOL ntfs_boot_sector_is_ntfs(NTFS_BOOT_SECTOR *b); -extern int ntfs_boot_sector_parse(ntfs_volume *vol, const NTFS_BOOT_SECTOR *bs); +extern BOOL ntfs_boot_sector_is_ntfs( NTFS_BOOT_SECTOR *b ); +extern int ntfs_boot_sector_parse( ntfs_volume *vol, const NTFS_BOOT_SECTOR *bs ); #endif /* defined _NTFS_BOOTSECT_H */ diff --git a/source/libntfs/cache.c b/source/libntfs/cache.c index dd147672..31f59a96 100644 --- a/source/libntfs/cache.c +++ b/source/libntfs/cache.c @@ -37,573 +37,637 @@ #include "logging.h" /* - * General functions to deal with LRU caches + * General functions to deal with LRU caches * - * The cached data have to be organized in a structure in which - * the first fields must follow a mandatory pattern and further - * fields may contain any fixed size data. They are stored in an - * LRU list. + * The cached data have to be organized in a structure in which + * the first fields must follow a mandatory pattern and further + * fields may contain any fixed size data. They are stored in an + * LRU list. * - * A compare function must be provided for finding a wanted entry - * in the cache. Another function may be provided for invalidating - * an entry to facilitate multiple invalidation. + * A compare function must be provided for finding a wanted entry + * in the cache. Another function may be provided for invalidating + * an entry to facilitate multiple invalidation. * - * These functions never return error codes. When there is a - * shortage of memory, data is simply not cached. - * When there is a hashing bug, hashing is dropped, and sequential - * searches are used. + * These functions never return error codes. When there is a + * shortage of memory, data is simply not cached. + * When there is a hashing bug, hashing is dropped, and sequential + * searches are used. */ /* - * Enter a new hash index, after a new record has been inserted + * Enter a new hash index, after a new record has been inserted * - * Do not call when a record has been modified (with no key change) + * 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 + * 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; + } + } } /* - * Fetch an entry from cache + * Fetch an entry from cache * - * returns the cache entry, or NULL if not available - * The returned entry may be modified, but not freed + * returns the cache entry, or NULL if not available + * 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 ); } /* - * Enter an inode number into cache - * returns the cache entry or NULL if not possible + * Enter an inode number into 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 ); } /* - * Invalidate a cache entry - * The entry is moved to the free entry list - * A specific function may be called for entry deletion + * Invalidate a cache entry + * The entry is moved to the free entry list + * 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; + 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; - } + 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 + * Invalidate entries in cache * - * Several entries may have to be invalidated (at least for inodes - * associated to directories which have been renamed), a different - * compare function may be provided to select entries to invalidate + * Several entries may have to be invalidated (at least for inodes + * associated to directories which have been renamed), a different + * compare function may be provided to select entries to invalidate * - * Returns the number of deleted entries, this can be used by - * the caller to signal a cache corruption if the entry was - * supposed to be found. + * Returns the number of deleted entries, this can be used by + * the caller to signal a cache corruption if the entry was + * 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 ); } /* - * Free memory allocated to a cache + * Free memory allocated to a cache */ -static void ntfs_free_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 ); + } } /* - * Create a cache + * Create a cache * - * Returns the cache header, or NULL if the cache could not be created + * 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 ); } /* - * Create all LRU caches + * Create all LRU caches * - * No error return, if creation is not possible, cacheing will - * just be not available + * No error return, if creation is not possible, cacheing will + * just be not available */ -void ntfs_create_lru_caches(ntfs_volume *vol) +void ntfs_create_lru_caches( ntfs_volume *vol ) { #if CACHE_INODE_SIZE - /* inode cache */ - vol->xinode_cache = ntfs_create_cache("inode",(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 } /* - * Free all LRU caches + * Free all LRU caches */ -void ntfs_free_lru_caches(ntfs_volume *vol) +void ntfs_free_lru_caches( ntfs_volume *vol ) { #if CACHE_INODE_SIZE - ntfs_free_cache(vol->xinode_cache); + ntfs_free_cache( vol->xinode_cache ); #endif #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..f248f48b 100644 --- a/source/libntfs/cache.h +++ b/source/libntfs/cache.h @@ -24,96 +24,104 @@ #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 void (*cache_free)(const struct CACHED_GENERIC *cached); -typedef int (*cache_hash)(const struct CACHED_GENERIC *cached); +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); +void ntfs_create_lru_caches( ntfs_volume *vol ); +void ntfs_free_lru_caches( ntfs_volume *vol ); #endif /* _NTFS_CACHE_H_ */ diff --git a/source/libntfs/cache2.c b/source/libntfs/cache2.c index 872f1a57..333a5da7 100644 --- a/source/libntfs/cache2.c +++ b/source/libntfs/cache2.c @@ -45,330 +45,365 @@ #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 */ -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. */ -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 */ -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; +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) +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..e2bb045e 100644 --- a/source/libntfs/cache2.h +++ b/source/libntfs/cache2.h @@ -46,21 +46,23 @@ #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; /* @@ -99,37 +101,37 @@ Precondition: offset + size <= BYTES_PER_READ /* Read several sectors from the NTFS_CACHE */ -bool _NTFS_cache_readSectors (NTFS_CACHE* NTFS_CACHE, sec_t sector, sec_t numSectors, void* buffer); +bool _NTFS_cache_readSectors ( NTFS_CACHE* NTFS_CACHE, sec_t sector, sec_t numSectors, void* buffer ); /* 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); +// return _NTFS_cache_readPartialSector (NTFS_CACHE, buffer, sector, 0, BYTES_PER_READ); //} /* 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); +// 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); +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); +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..9835c338 100644 --- a/source/libntfs/collate.c +++ b/source/libntfs/collate.c @@ -52,22 +52,23 @@ * * 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 +83,32 @@ 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 +117,43 @@ 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 +169,49 @@ 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,57 +226,58 @@ 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; } /* - * Get a pointer to appropriate collation function. + * Get a pointer to appropriate collation function. * - * Returns NULL if the needed function is not implemented + * Returns NULL if the needed function is not implemented */ -COLLATE ntfs_get_collate_function(COLLATION_RULES cr) +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/collate.h b/source/libntfs/collate.h index fe383835..59aa0b09 100644 --- a/source/libntfs/collate.h +++ b/source/libntfs/collate.h @@ -29,6 +29,6 @@ #define NTFS_COLLATION_ERROR -2 -extern COLLATE ntfs_get_collate_function(COLLATION_RULES); +extern COLLATE ntfs_get_collate_function( COLLATION_RULES ); #endif /* _NTFS_COLLATE_H */ diff --git a/source/libntfs/compat.c b/source/libntfs/compat.c index 63114a48..2d1bdd49 100644 --- a/source/libntfs/compat.c +++ b/source/libntfs/compat.c @@ -35,33 +35,38 @@ * * Returns: */ -int ffs(int x) +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 */ @@ -82,7 +87,7 @@ static const char rcsid[] = "$Id: compat.c,v 1.1.1.1.2.1 2008-08-16 15:17:44 jpa /* * Copyright (c) 1990, 1993 - * The Regents of the University of California. All rights reserved. + * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -94,8 +99,8 @@ static const char rcsid[] = "$Id: compat.c,v 1.1.1.1.2.1 2008-08-16 15:17:44 jpa * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. + * This product includes software developed by the University of + * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. @@ -120,34 +125,37 @@ 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 *************************************************************/ #endif /* HAVE_DAEMON */ @@ -169,7 +177,7 @@ static const char rcsid[] = "$Id: compat.c,v 1.1.1.1.2.1 2008-08-16 15:17:44 jpa /* * Copyright (c) 1990, 1993 - * The Regents of the University of California. All rights reserved. + * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -181,8 +189,8 @@ static const char rcsid[] = "$Id: compat.c,v 1.1.1.1.2.1 2008-08-16 15:17:44 jpa * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. + * This product includes software developed by the University of + * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. @@ -209,7 +217,7 @@ static const char rcsid[] = "$Id: compat.c,v 1.1.1.1.2.1 2008-08-16 15:17:44 jpa /* * Get next token from string *stringp, where tokens are possibly-empty - * strings separated by characters from delim. + * strings separated by characters from delim. * * Writes NULs into the string at *stringp to end tokens. * delim need not remain constant from call to call. @@ -218,32 +226,37 @@ 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 */ } -/* +/* * End: src/lib/libresolv2/common/bsd/strsep.c *************************************************************/ #endif /* HAVE_STRSEP */ diff --git a/source/libntfs/compat.h b/source/libntfs/compat.h index 957752a0..5e854c27 100644 --- a/source/libntfs/compat.h +++ b/source/libntfs/compat.h @@ -36,38 +36,38 @@ #endif #ifndef HAVE_FFS -extern int ffs(int i); +extern int ffs( int i ); #endif /* HAVE_FFS */ #ifndef HAVE_DAEMON -extern int daemon(int nochdir, int noclose); +extern int daemon( int nochdir, int noclose ); #endif /* HAVE_DAEMON */ #ifndef HAVE_STRSEP -extern char *strsep(char **stringp, const char *delim); +extern char *strsep( char **stringp, const char *delim ); #endif /* HAVE_STRSEP */ #ifdef WINDOWS -#define HAVE_STDIO_H /* mimic config.h */ +#define HAVE_STDIO_H /* mimic config.h */ #define HAVE_STDARG_H -#define atoll _atoi64 -#define fdatasync commit -#define __inline__ inline -#define __attribute__(X) /*nothing*/ +#define atoll _atoi64 +#define fdatasync commit +#define __inline__ inline +#define __attribute__(X) /*nothing*/ #else /* !defined WINDOWS */ #ifndef O_BINARY -#define O_BINARY 0 /* unix is binary by default */ +#define O_BINARY 0 /* unix is binary by default */ #endif #ifdef GEKKO #include "mem_allocate.h" -#define XATTR_CREATE 1 +#define XATTR_CREATE 1 #define XATTR_REPLACE 2 #define MINORBITS 20 @@ -75,7 +75,7 @@ extern char *strsep(char **stringp, const char *delim); #define major(dev) ((unsigned int) ((dev) >> MINORBITS)) #define minor(dev) ((unsigned int) ((dev) & MINORMASK)) -#define mkdev(ma,mi) (((ma) << MINORBITS) | (mi)) +#define mkdev(ma,mi) (((ma) << MINORBITS) | (mi)) #define random rand #endif /* defined GEKKO */ diff --git a/source/libntfs/compress.c b/source/libntfs/compress.c index fbd30ba9..986685e5 100644 --- a/source/libntfs/compress.c +++ b/source/libntfs/compress.c @@ -1,6 +1,6 @@ /** * compress.c - Compressed attribute handling code. Originated from the Linux-NTFS - * project. + * project. * * Copyright (c) 2004-2005 Anton Altaparmakov * Copyright (c) 2004-2006 Szabolcs Szakacsits @@ -28,7 +28,7 @@ * this was put into public domain in 1988 by Haruhiko OKUMURA). * * LZHUF.C English version 1.0 - * Based on Japanese version 29-NOV-1988 + * Based on Japanese version 29-NOV-1988 * LZSS coded by Haruhiko OKUMURA * Adaptive Huffman Coding coded by Haruyasu YOSHIZAKI * Edited and translated to English by Kenji RIKITAKE @@ -65,291 +65,329 @@ /** * 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 + * Initialize the match tree */ -static void ntfs_init_compress_tree(struct COMPRESS_CONTEXT *pctx) +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 */ } /* - * Insert a new node into match tree for quickly locating - * further similar strings + * Insert a new node into match tree for quickly locating + * 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 ); } /* - * Search for the longest previous string matching the - * current one + * Search for the longest previous string matching the + * current one * - * Returns the end of the longest current string which matched - * or zero if there was a bug + * Returns the end of the longest current string which matched + * 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); + do + { + rr++; + if ( pctx->match_length > 0 ) + pctx->match_length--; + if ( !pctx->len ) + { + ntfs_log_error( "compress bug : void run\n" ); + goto bug; + } + if ( --pctx->len ) + { + if ( rr >= NTFS_SB_SIZE ) + { + ntfs_log_error( "compress bug : buffer overflow\n" ); + goto bug; + } + if ( ( ( rr + bestlen ) < NTFS_SB_SIZE ) ) + { + while ( ( unsigned int )( 1 << pctx->nbt ) + <= ( rr - 1 ) ) + pctx->nbt++; + ntfs_new_node( pctx, rr ); + if ( pctx->match_length > bestlen ) + bestlen = pctx->match_length; + } + else if ( dd > 0 ) + { + rr += dd; + if ( ( int )pctx->match_length > dd ) + pctx->match_length -= dd; + else + pctx->match_length = 0; + if ( ( int )pctx->len < dd ) + { + ntfs_log_error( "compress bug : run overflows\n" ); + goto bug; + } + pctx->len -= dd; + dd = 0; + } + } + } + while ( dd-- > 0 ); + return ( rr ); bug : - return (0); + return ( 0 ); } /* - * Compress an input block + * Compress an input block * - * Returns the size of the compressed block (including header) - * or zero if there was an error + * Returns the size of the compressed block (including header) + * 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 */ + pctx = ( struct COMPRESS_CONTEXT* )malloc( sizeof( struct COMPRESS_CONTEXT ) ); + if ( pctx ) + { + pctx->inbuf = ( const unsigned char* )inbuf; + ntfs_init_compress_tree( pctx ); + xout = 2; + ntag = 0; + ptag = &outbuf[xout++]; + *ptag = 0; + rr = 0; + pctx->nbt = 4; + pctx->len = size; + pctx->match_length = 0; + ntfs_new_node( pctx, 0 ); + do + { + if ( pctx->match_length > pctx->len ) + pctx->match_length = pctx->len; + if ( pctx->match_length < THRESHOLD ) + { + pctx->match_length = 1; + if ( ntag >= 8 ) + { + ntag = 0; + ptag = &outbuf[xout++]; + *ptag = 0; + } + outbuf[xout++] = inbuf[rr]; + ntag++; + } + else + { + while ( ( unsigned int )( 1 << pctx->nbt ) + <= ( rr - 1 ) ) + pctx->nbt++; + q = ( pctx->match_position << ( 16 - pctx->nbt ) ) + + pctx->match_length - THRESHOLD; + if ( ntag >= 8 ) + { + ntag = 0; + ptag = &outbuf[xout++]; + *ptag = 0; + } + *ptag |= 1 << ntag++; + outbuf[xout++] = q & 255; + outbuf[xout++] = ( q >> 8 ) & 255; + } + last_match_length = pctx->match_length; + dd = last_match_length; + if ( dd-- > 0 ) + { + rr = ntfs_nextmatch( pctx, rr, dd ); + if ( !rr ) + goto bug; + } + /* + * stop if input is exhausted or output has exceeded + * the maximum size. Two extra bytes have to be + * reserved in output buffer, as 3 bytes may be + * output in a loop. + */ + } + while ( ( pctx->len > 0 ) + && ( rr < size ) && ( xout < ( NTFS_SB_SIZE + 2 ) ) ); + /* uncompressed must be full size, so accept if better */ + if ( xout < ( NTFS_SB_SIZE + 2 ) ) + { + outbuf[0] = ( xout - 3 ) & 255; + outbuf[1] = 0xb0 + ( ( ( xout - 3 ) >> 8 ) & 15 ); + } + else + { + memcpy( &outbuf[2], inbuf, size ); + if ( size < NTFS_SB_SIZE ) + memset( &outbuf[size+2], 0, NTFS_SB_SIZE - size ); + outbuf[0] = 0xff; + outbuf[1] = 0x3f; + xout = NTFS_SB_SIZE + 2; + } + free( pctx ); + } + else + { + xout = 0; + errno = ENOMEM; + } + return ( xout ); /* 0 for an error, > size if cannot compress */ bug : - return (0); + return ( 0 ); } /** * ntfs_decompress - decompress a compression block into an array of pages - * @dest: buffer to which to write the decompressed data - * @dest_size: size of buffer @dest in bytes - * @cb_start: compression block to decompress - * @cb_size: size of compression block @cb_start in bytes + * @dest: buffer to which to write the decompressed data + * @dest_size: size of buffer @dest in bytes + * @cb_start: compression block to decompress + * @cb_size: size of compression block @cb_start in bytes * * This decompresses the compression block @cb_start into the destination * buffer @dest. @@ -359,173 +397,182 @@ 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); + ntfs_log_trace( "Entering, cb_size = 0x%x.\n", ( unsigned )cb_size ); do_next_sb: - ntfs_log_debug("Beginning sub-block at offset = %d in the cb.\n", - (int)(cb - cb_start)); - /* - * Have we reached the end of the compression block or the end of the - * decompressed data? The latter can happen for example if the current - * position in the compression block is one byte before its end so the - * first two checks do not detect it. - */ - if (cb == cb_end || !le16_to_cpup((le16*)cb) || dest == dest_end) { - ntfs_log_debug("Completed. Returning success (0).\n"); - return 0; - } - /* Setup offset for the current sub-block destination. */ - dest_sb_start = dest; - dest_sb_end = dest + NTFS_SB_SIZE; - /* Check that we are still within allowed boundaries. */ - if (dest_sb_end > dest_end) - goto return_overflow; - /* Does the minimum size of a compressed sb overflow valid range? */ - if (cb + 6 > cb_end) - goto return_overflow; - /* Setup the current sub-block source pointers and validate range. */ - cb_sb_start = cb; - cb_sb_end = cb_sb_start + (le16_to_cpup((le16*)cb) & NTFS_SB_SIZE_MASK) - + 3; - if (cb_sb_end > cb_end) - goto return_overflow; - /* Now, we are ready to process the current sub-block (sb). */ - if (!(le16_to_cpup((le16*)cb) & NTFS_SB_IS_COMPRESSED)) { - ntfs_log_debug("Found uncompressed sub-block.\n"); - /* This sb is not compressed, just copy it into destination. */ - /* Advance source position to first data byte. */ - cb += 2; - /* An uncompressed sb must be full size. */ - if (cb_sb_end - cb != NTFS_SB_SIZE) - goto return_overflow; - /* Copy the block and advance the source position. */ - memcpy(dest, cb, NTFS_SB_SIZE); - cb += NTFS_SB_SIZE; - /* Advance destination position to next sub-block. */ - dest += NTFS_SB_SIZE; - goto do_next_sb; - } - ntfs_log_debug("Found compressed sub-block.\n"); - /* This sb is compressed, decompress it into destination. */ - /* Forward to the first tag in the sub-block. */ - cb += 2; + ntfs_log_debug( "Beginning sub-block at offset = %d in the cb.\n", + ( int )( cb - cb_start ) ); + /* + * Have we reached the end of the compression block or the end of the + * decompressed data? The latter can happen for example if the current + * position in the compression block is one byte before its end so the + * first two checks do not detect it. + */ + if ( cb == cb_end || !le16_to_cpup( ( le16* )cb ) || dest == dest_end ) + { + ntfs_log_debug( "Completed. Returning success (0).\n" ); + return 0; + } + /* Setup offset for the current sub-block destination. */ + dest_sb_start = dest; + dest_sb_end = dest + NTFS_SB_SIZE; + /* Check that we are still within allowed boundaries. */ + if ( dest_sb_end > dest_end ) + goto return_overflow; + /* Does the minimum size of a compressed sb overflow valid range? */ + if ( cb + 6 > cb_end ) + goto return_overflow; + /* Setup the current sub-block source pointers and validate range. */ + cb_sb_start = cb; + cb_sb_end = cb_sb_start + ( le16_to_cpup( ( le16* )cb ) & NTFS_SB_SIZE_MASK ) + + 3; + if ( cb_sb_end > cb_end ) + goto return_overflow; + /* Now, we are ready to process the current sub-block (sb). */ + if ( !( le16_to_cpup( ( le16* )cb ) & NTFS_SB_IS_COMPRESSED ) ) + { + ntfs_log_debug( "Found uncompressed sub-block.\n" ); + /* This sb is not compressed, just copy it into destination. */ + /* Advance source position to first data byte. */ + cb += 2; + /* An uncompressed sb must be full size. */ + if ( cb_sb_end - cb != NTFS_SB_SIZE ) + goto return_overflow; + /* Copy the block and advance the source position. */ + memcpy( dest, cb, NTFS_SB_SIZE ); + cb += NTFS_SB_SIZE; + /* Advance destination position to next sub-block. */ + dest += NTFS_SB_SIZE; + goto do_next_sb; + } + ntfs_log_debug( "Found compressed sub-block.\n" ); + /* This sb is compressed, decompress it into destination. */ + /* Forward to the first tag in the sub-block. */ + cb += 2; do_next_tag: - if (cb == cb_sb_end) { - /* Check if the decompressed sub-block was not full-length. */ - if (dest < dest_sb_end) { - int nr_bytes = dest_sb_end - dest; + if ( cb == cb_sb_end ) + { + /* Check if the decompressed sub-block was not full-length. */ + if ( dest < dest_sb_end ) + { + int nr_bytes = dest_sb_end - dest; - ntfs_log_debug("Filling incomplete sub-block with zeroes.\n"); - /* Zero remainder and update destination position. */ - memset(dest, 0, nr_bytes); - dest += nr_bytes; - } - /* We have finished the current sub-block. */ - goto do_next_sb; - } - /* Check we are still in range. */ - if (cb > cb_sb_end || dest > dest_sb_end) - goto return_overflow; - /* Get the next tag and advance to first token. */ - tag = *cb++; - /* Parse the eight tokens described by the tag. */ - for (token = 0; token < 8; token++, tag >>= 1) { - u16 lg, pt, length, max_non_overlap; - register u16 i; - u8 *dest_back_addr; + ntfs_log_debug( "Filling incomplete sub-block with zeroes.\n" ); + /* Zero remainder and update destination position. */ + memset( dest, 0, nr_bytes ); + dest += nr_bytes; + } + /* We have finished the current sub-block. */ + goto do_next_sb; + } + /* Check we are still in range. */ + if ( cb > cb_sb_end || dest > dest_sb_end ) + goto return_overflow; + /* Get the next tag and advance to first token. */ + tag = *cb++; + /* Parse the eight tokens described by the tag. */ + for ( token = 0; token < 8; token++, tag >>= 1 ) + { + u16 lg, pt, length, max_non_overlap; + register u16 i; + u8 *dest_back_addr; - /* Check if we are done / still in range. */ - if (cb >= cb_sb_end || dest > dest_sb_end) - break; - /* Determine token type and parse appropriately.*/ - if ((tag & NTFS_TOKEN_MASK) == NTFS_SYMBOL_TOKEN) { - /* - * We have a symbol token, copy the symbol across, and - * advance the source and destination positions. - */ - *dest++ = *cb++; - /* Continue with the next token. */ - continue; - } - /* - * We have a phrase token. Make sure it is not the first tag in - * the sb as this is illegal and would confuse the code below. - */ - if (dest == dest_sb_start) - goto return_overflow; - /* - * Determine the number of bytes to go back (p) and the number - * of bytes to copy (l). We use an optimized algorithm in which - * we first calculate log2(current destination position in sb), - * which allows determination of l and p in O(1) rather than - * O(n). We just need an arch-optimized log2() function now. - */ - lg = 0; - for (i = dest - dest_sb_start - 1; i >= 0x10; i >>= 1) - lg++; - /* Get the phrase token into i. */ - pt = le16_to_cpup((le16*)cb); - /* - * Calculate starting position of the byte sequence in - * the destination using the fact that p = (pt >> (12 - lg)) + 1 - * and make sure we don't go too far back. - */ - dest_back_addr = dest - (pt >> (12 - lg)) - 1; - if (dest_back_addr < dest_sb_start) - goto return_overflow; - /* Now calculate the length of the byte sequence. */ - length = (pt & (0xfff >> lg)) + 3; - /* Verify destination is in range. */ - if (dest + length > dest_sb_end) - goto return_overflow; - /* The number of non-overlapping bytes. */ - max_non_overlap = dest - dest_back_addr; - if (length <= max_non_overlap) { - /* The byte sequence doesn't overlap, just copy it. */ - memcpy(dest, dest_back_addr, length); - /* Advance destination pointer. */ - dest += length; - } else { - /* - * The byte sequence does overlap, copy non-overlapping - * part and then do a slow byte by byte copy for the - * overlapping part. Also, advance the destination - * pointer. - */ - memcpy(dest, dest_back_addr, max_non_overlap); - dest += max_non_overlap; - dest_back_addr += max_non_overlap; - length -= max_non_overlap; - while (length--) - *dest++ = *dest_back_addr++; - } - /* Advance source position and continue with the next token. */ - cb += 2; - } - /* No tokens left in the current tag. Continue with the next tag. */ - goto do_next_tag; + /* Check if we are done / still in range. */ + if ( cb >= cb_sb_end || dest > dest_sb_end ) + break; + /* Determine token type and parse appropriately.*/ + if ( ( tag & NTFS_TOKEN_MASK ) == NTFS_SYMBOL_TOKEN ) + { + /* + * We have a symbol token, copy the symbol across, and + * advance the source and destination positions. + */ + *dest++ = *cb++; + /* Continue with the next token. */ + continue; + } + /* + * We have a phrase token. Make sure it is not the first tag in + * the sb as this is illegal and would confuse the code below. + */ + if ( dest == dest_sb_start ) + goto return_overflow; + /* + * Determine the number of bytes to go back (p) and the number + * of bytes to copy (l). We use an optimized algorithm in which + * we first calculate log2(current destination position in sb), + * which allows determination of l and p in O(1) rather than + * O(n). We just need an arch-optimized log2() function now. + */ + lg = 0; + for ( i = dest - dest_sb_start - 1; i >= 0x10; i >>= 1 ) + lg++; + /* Get the phrase token into i. */ + pt = le16_to_cpup( ( le16* )cb ); + /* + * Calculate starting position of the byte sequence in + * the destination using the fact that p = (pt >> (12 - lg)) + 1 + * and make sure we don't go too far back. + */ + dest_back_addr = dest - ( pt >> ( 12 - lg ) ) - 1; + if ( dest_back_addr < dest_sb_start ) + goto return_overflow; + /* Now calculate the length of the byte sequence. */ + length = ( pt & ( 0xfff >> lg ) ) + 3; + /* Verify destination is in range. */ + if ( dest + length > dest_sb_end ) + goto return_overflow; + /* The number of non-overlapping bytes. */ + max_non_overlap = dest - dest_back_addr; + if ( length <= max_non_overlap ) + { + /* The byte sequence doesn't overlap, just copy it. */ + memcpy( dest, dest_back_addr, length ); + /* Advance destination pointer. */ + dest += length; + } + else + { + /* + * The byte sequence does overlap, copy non-overlapping + * part and then do a slow byte by byte copy for the + * overlapping part. Also, advance the destination + * pointer. + */ + memcpy( dest, dest_back_addr, max_non_overlap ); + dest += max_non_overlap; + dest_back_addr += max_non_overlap; + length -= max_non_overlap; + while ( length-- ) + *dest++ = *dest_back_addr++; + } + /* Advance source position and continue with the next token. */ + cb += 2; + } + /* No tokens left in the current tag. Continue with the next tag. */ + goto do_next_tag; return_overflow: - errno = EOVERFLOW; - ntfs_log_perror("Failed to decompress file"); - return -1; + errno = EOVERFLOW; + ntfs_log_perror( "Failed to decompress file" ); + return -1; } /** @@ -543,50 +590,52 @@ 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. - */ + /* + * The simplest case: the run starting at @cb_start_vcn contains + * @cb_clusters clusters which are all not sparse, thus the cb is not + * compressed. + */ restart: - cb_clusters -= rl->length - (cb_start_vcn - rl->vcn); - while (cb_clusters > 0) { - /* Go to the next run. */ - rl++; - /* Map the next runlist fragment if it is not mapped. */ - if (rl->lcn < LCN_HOLE || !rl->length) { - cb_start_vcn = rl->vcn; - rl = ntfs_attr_find_vcn(na, rl->vcn); - if (!rl || rl->lcn < LCN_HOLE || !rl->length) - return TRUE; - /* - * If the runs were merged need to deal with the - * resulting partial run so simply restart. - */ - if (rl->vcn < cb_start_vcn) - goto restart; - } - /* If the current run is sparse, the cb is compressed. */ - if (rl->lcn == LCN_HOLE) - return TRUE; - /* If the whole cb is not sparse, it is not compressed. */ - if (rl->length >= cb_clusters) - return FALSE; - cb_clusters -= rl->length; - }; - /* All cb_clusters were not sparse thus the cb is not compressed. */ - return FALSE; + cb_clusters -= rl->length - ( cb_start_vcn - rl->vcn ); + while ( cb_clusters > 0 ) + { + /* Go to the next run. */ + rl++; + /* Map the next runlist fragment if it is not mapped. */ + if ( rl->lcn < LCN_HOLE || !rl->length ) + { + cb_start_vcn = rl->vcn; + rl = ntfs_attr_find_vcn( na, rl->vcn ); + if ( !rl || rl->lcn < LCN_HOLE || !rl->length ) + return TRUE; + /* + * If the runs were merged need to deal with the + * resulting partial run so simply restart. + */ + if ( rl->vcn < cb_start_vcn ) + goto restart; + } + /* If the current run is sparse, the cb is compressed. */ + if ( rl->lcn == LCN_HOLE ) + return TRUE; + /* If the whole cb is not sparse, it is not compressed. */ + if ( rl->length >= cb_clusters ) + return FALSE; + cb_clusters -= rl->length; + }; + /* All cb_clusters were not sparse thus the cb is not compressed. */ + return FALSE; } /** * ntfs_compressed_attr_pread - read from a compressed attribute - * @na: ntfs attribute to read from - * @pos: byte position in the attribute to begin reading from - * @count: number of bytes to read - * @b: output data buffer + * @na: ntfs attribute to read from + * @pos: byte position in the attribute to begin reading from + * @count: number of bytes to read + * @b: output data buffer * * NOTE: You probably want to be using attrib.c::ntfs_attr_pread() instead. * @@ -602,500 +651,542 @@ restart: * to the return code of ntfs_pread(), or to EINVAL in case of invalid * arguments. */ -s64 ntfs_compressed_attr_pread(ntfs_attr *na, s64 pos, s64 count, void *b) +s64 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; + ntfs_log_trace( "Entering for inode 0x%llx, attr 0x%x, pos 0x%llx, count 0x%llx.\n", + ( unsigned long long )na->ni->mft_no, na->type, + ( long long )pos, ( long long )count ); + data_flags = na->data_flags; + compression = na->ni->flags & FILE_ATTR_COMPRESSED; + if ( !na || !na->ni || !na->ni->vol || !b + || ( ( data_flags & ATTR_COMPRESSION_MASK ) + != ATTR_IS_COMPRESSED ) + || pos < 0 || count < 0 ) + { + errno = EINVAL; + return -1; + } + /* + * Encrypted attributes are not supported. We return access denied, + * which is what Windows NT4 does, too. + */ + if ( NAttrEncrypted( na ) ) + { + errno = EACCES; + return -1; + } + if ( !count ) + return 0; + /* Truncate reads beyond end of attribute. */ + if ( pos + count > na->data_size ) + { + if ( pos >= na->data_size ) + { + return 0; + } + count = na->data_size - pos; + } + /* If it is a resident attribute, simply use ntfs_attr_pread(). */ + if ( !NAttrNonResident( na ) ) + return ntfs_attr_pread( na, pos, count, b ); + total = total2 = 0; + /* Zero out reads beyond initialized size. */ + if ( pos + count > na->initialized_size ) + { + if ( pos >= na->initialized_size ) + { + memset( b, 0, count ); + return count; + } + total2 = pos + count - na->initialized_size; + count -= total2; + memset( ( u8* )b + count, 0, total2 ); + } + vol = na->ni->vol; + cb_size = na->compression_block_size; + cb_size_mask = cb_size - 1UL; + cb_clusters = na->compression_block_clusters; + + /* Need a temporary buffer for each loaded compression block. */ + cb = ( u8* )ntfs_malloc( cb_size ); + if ( !cb ) + return -1; + + /* Need a temporary buffer for each uncompressed block. */ + dest = ( u8* )ntfs_malloc( cb_size ); + if ( !dest ) + { + free( cb ); + return -1; + } + /* + * The first vcn in the first compression block (cb) which we need to + * decompress. + */ + start_vcn = ( pos & ~cb_size_mask ) >> vol->cluster_size_bits; + /* Offset in the uncompressed cb at which to start reading data. */ + ofs = pos & cb_size_mask; + /* + * The first vcn in the cb after the last cb which we need to + * decompress. + */ + end_vcn = ( ( pos + count + cb_size - 1 ) & ~cb_size_mask ) >> + vol->cluster_size_bits; + /* Number of compression blocks (cbs) in the wanted vcn range. */ + nr_cbs = ( end_vcn - start_vcn ) << vol->cluster_size_bits >> + na->compression_block_size_bits; + cb_end = cb + cb_size; do_next_cb: - nr_cbs--; - cb_pos = cb; - vcn = start_vcn; - start_vcn += cb_clusters; + nr_cbs--; + cb_pos = cb; + vcn = start_vcn; + start_vcn += cb_clusters; - /* Check whether the compression block is sparse. */ - rl = ntfs_attr_find_vcn(na, vcn); - if (!rl || rl->lcn < LCN_HOLE) { - free(cb); - free(dest); - if (total) - return total; - /* FIXME: Do we want EIO or the error code? (AIA) */ - errno = EIO; - return -1; - } - if (rl->lcn == LCN_HOLE) { - /* Sparse cb, zero out destination range overlapping the cb. */ - ntfs_log_debug("Found sparse compression block.\n"); - to_read = min(count, cb_size - ofs); - memset(b, 0, to_read); - ofs = 0; - total += to_read; - count -= to_read; - b = (u8*)b + to_read; - } else if (!ntfs_is_cb_compressed(na, rl, vcn, cb_clusters)) { - s64 tdata_size, tinitialized_size; - /* - * Uncompressed cb, read it straight into the destination range - * overlapping the cb. - */ - ntfs_log_debug("Found uncompressed compression block.\n"); - /* - * Read the uncompressed data into the destination buffer. - * NOTE: We cheat a little bit here by marking the attribute as - * not compressed in the ntfs_attr structure so that we can - * read the data by simply using ntfs_attr_pread(). (-8 - * NOTE: we have to modify data_size and initialized_size - * temporarily as well... - */ - to_read = min(count, cb_size - ofs); - ofs += vcn << vol->cluster_size_bits; - NAttrClearCompressed(na); - na->data_flags &= ~ATTR_COMPRESSION_MASK; - tdata_size = na->data_size; - tinitialized_size = na->initialized_size; - na->data_size = na->initialized_size = na->allocated_size; - do { - br = ntfs_attr_pread(na, ofs, to_read, b); - if (br <= 0) { - 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; + /* 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; + /* + * 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; } /* - * Read data from a set of clusters + * Read data from a set of clusters * - * Returns the amount of data read + * 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 ); } /* - * Write data to a set of clusters + * Write data to a set of clusters * - * Returns the amount of data written + * 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 + * Compress and write a set of blocks * - * returns the size actually written (rounded to a full cluster) - * or 0 if all zeroes (nothing is written) - * or -1 if could not compress (nothing is written) - * or -2 if there were an irrecoverable error (errno set) + * returns the size actually written (rounded to a full cluster) + * or 0 if all zeroes (nothing is written) + * or -1 if could not compress (nothing is written) + * 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 ); } /* - * Check the validity of a compressed runlist - * The check starts at the beginning of current run and ends - * at the end of runlist - * errno is set if the runlist is not valid + * Check the validity of a compressed runlist + * The check starts at the beginning of current run and ends + * at the end of runlist + * 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 ); } /* - * Free unneeded clusters after overwriting compressed data + * Free unneeded clusters after overwriting compressed data * - * This generally requires one or two empty slots at the end of runlist, - * but we do not want to reallocate the runlist here because - * there are many pointers to it. - * So the empty slots have to be reserved beforehand + * This generally requires one or two empty slots at the end of runlist, + * but we do not want to reallocate the runlist here because + * there are many pointers to it. + * So the empty slots have to be reserved beforehand * - * Returns zero unless some error occurred (described by errno) + * Returns zero unless some error occurred (described by errno) * * +======= start of block =====+ * 0 |A chunk may overflow | <-- rl usedcnt : A + B @@ -1115,717 +1206,822 @@ 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 + * Free unneeded clusters after compression * - * This generally requires one or two empty slots at the end of runlist, - * but we do not want to reallocate the runlist here because - * there are many pointers to it. - * So the empty slots have to be reserved beforehand + * This generally requires one or two empty slots at the end of runlist, + * but we do not want to reallocate the runlist here because + * there are many pointers to it. + * So the empty slots have to be reserved beforehand * - * Returns zero unless some error occurred (described by errno) + * 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 ); } /* - * Read existing data, decompress and append buffer - * Do nothing if something fails + * Read existing data, decompress and append buffer + * 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 ); } /* - * Flush a full compression block + * Flush a full compression block * - * returns the size actually written (rounded to a full cluster) - * or 0 if could not compress (and written uncompressed) - * or -1 if there were an irrecoverable error (errno set) + * returns the size actually written (rounded to a full cluster) + * or 0 if could not compress (and written uncompressed) + * 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 ); } /* - * Write some data to be compressed. - * Compression only occurs when a few clusters (usually 16) are - * full. When this occurs an extra runlist slot may be needed, so - * it has to be reserved beforehand. + * Write some data to be compressed. + * Compression only occurs when a few clusters (usually 16) are + * full. When this occurs an extra runlist slot may be needed, so + * it has to be reserved beforehand. * - * Returns the size of uncompressed data written, - * or negative if an error occurred. - * When the returned size is less than requested, new clusters have - * to be allocated before the function is called again. + * Returns the size of uncompressed data written, + * or negative if an error occurred. + * When the returned size is less than requested, new clusters have + * 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 ); } /* - * Close a file written compressed. - * This compresses the last partial compression block of the file. - * Two empty runlist slots have to be reserved beforehand. + * Close a file written compressed. + * This compresses the last partial compression block of the file. + * Two empty runlist slots have to be reserved beforehand. * - * Returns zero if closing is successful. + * 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..b2f7dba1 100644 --- a/source/libntfs/compress.h +++ b/source/libntfs/compress.h @@ -1,6 +1,6 @@ /* - * compress.h - Exports for compressed attribute handling. - * Originated from the Linux-NTFS project. + * compress.h - Exports for compressed attribute handling. + * Originated from the Linux-NTFS project. * * Copyright (c) 2004 Anton Altaparmakov * @@ -26,16 +26,16 @@ #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/debug.c b/source/libntfs/debug.c index f1934833..4ba2a855 100644 --- a/source/libntfs/debug.c +++ b/source/libntfs/debug.c @@ -42,37 +42,43 @@ * * Returns: */ -void ntfs_debug_runlist_dump(const runlist_element *rl) +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..1569f892 100644 --- a/source/libntfs/debug.h +++ b/source/libntfs/debug.h @@ -31,17 +31,17 @@ struct _runlist_element; #ifdef DEBUG -extern void ntfs_debug_runlist_dump(const struct _runlist_element *rl); +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) \ -{ \ - int ___i; \ - ntfs_log_critical("Bug in %s(): %s\n", __FUNCTION__, msg); \ - ntfs_log_debug("Forcing segmentation fault!"); \ - ___i = ((int*)NULL)[1]; \ +#define NTFS_BUG(msg) \ +{ \ + int ___i; \ + ntfs_log_critical("Bug in %s(): %s\n", __FUNCTION__, msg); \ + ntfs_log_debug("Forcing segmentation fault!"); \ + ___i = ((int*)NULL)[1]; \ } #endif /* defined _NTFS_DEBUG_H */ diff --git a/source/libntfs/device.c b/source/libntfs/device.c index c77d8f95..611b949a 100644 --- a/source/libntfs/device.c +++ b/source/libntfs/device.c @@ -72,27 +72,27 @@ #include "misc.h" #if defined(linux) && defined(_IO) && !defined(BLKGETSIZE) -#define BLKGETSIZE _IO(0x12,96) /* Get device size in 512-byte blocks. */ +#define BLKGETSIZE _IO(0x12,96) /* Get device size in 512-byte blocks. */ #endif #if defined(linux) && defined(_IOR) && !defined(BLKGETSIZE64) -#define BLKGETSIZE64 _IOR(0x12,114,size_t) /* Get device size in bytes. */ +#define BLKGETSIZE64 _IOR(0x12,114,size_t) /* Get device size in bytes. */ #endif #if defined(linux) && !defined(HDIO_GETGEO) -#define HDIO_GETGEO 0x0301 /* Get device geometry. */ +#define HDIO_GETGEO 0x0301 /* Get device geometry. */ #endif #if defined(linux) && defined(_IO) && !defined(BLKSSZGET) -# define BLKSSZGET _IO(0x12,104) /* Get device sector size in bytes. */ +# define BLKSSZGET _IO(0x12,104) /* Get device sector size in bytes. */ #endif #if defined(linux) && defined(_IO) && !defined(BLKBSZSET) -# define BLKBSZSET _IOW(0x12,113,size_t) /* Set device block size in bytes. */ +# define BLKBSZSET _IOW(0x12,113,size_t) /* Set device block size in bytes. */ #endif /** * ntfs_device_alloc - allocate an ntfs device structure and pre-initialize it - * @name: name of the device (must be present) - * @state: initial device state (usually zero) - * @dops: ntfs device operations to use with the device (must be present) - * @priv_data: pointer to private data (optional) + * @name: name of the device (must be present) + * @state: initial device state (usually zero) + * @dops: ntfs device operations to use with the device (must be present) + * @priv_data: pointer to private data (optional) * * Allocate an ntfs device structure and pre-initialize it with the user- * specified device operations @dops, device state @state, device name @name, @@ -103,63 +103,68 @@ * 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; } /** * ntfs_device_free - free an ntfs device structure - * @dev: ntfs device structure to free + * @dev: ntfs device structure to free * * Free the ntfs device structure @dev. * * Return 0 on success or -1 on error with errno set to the error code. The * following error codes are defined: - * EINVAL Invalid pointer @dev. - * EBUSY Device is still open. Close it before freeing it! + * EINVAL Invalid pointer @dev. + * EBUSY Device is still open. Close it before freeing it! */ -int ntfs_device_free(struct ntfs_device *dev) +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; } /** * ntfs_pread - positioned read from disk - * @dev: device to read from - * @pos: position in device to read from - * @count: number of bytes to read - * @b: output data buffer + * @dev: device to read from + * @pos: position in device to read from + * @count: number of bytes to read + * @b: output data buffer * * This function will read @count bytes from device @dev at position @pos into * the data buffer @b. @@ -173,43 +178,45 @@ int ntfs_device_free(struct ntfs_device *dev) * to the return code of either seek, read, or set to EINVAL in case of * invalid arguments. */ -s64 ntfs_pread(struct ntfs_device *dev, const s64 pos, s64 count, void *b) +s64 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; } /** * ntfs_pwrite - positioned write to disk - * @dev: device to write to - * @pos: position in file descriptor to write to - * @count: number of bytes to write - * @b: data buffer to write to disk + * @dev: device to write to + * @pos: position in file descriptor to write to + * @count: number of bytes to write + * @b: data buffer to write to disk * * This function will write @count bytes from data buffer @b to the device @dev * at position @pos. @@ -223,55 +230,58 @@ 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; } /** * ntfs_mst_pread - multi sector transfer (mst) positioned read - * @dev: device to read from - * @pos: position in file descriptor to read from - * @count: number of blocks to read - * @bksize: size of each block that needs mst deprotecting - * @b: output data buffer + * @dev: device to read from + * @pos: position in file descriptor to read from + * @count: number of blocks to read + * @bksize: size of each block that needs mst deprotecting + * @b: output data buffer * * Multi sector transfer (mst) positioned read. This function will read @count * blocks of size @bksize bytes each from device @dev at position @pos into the @@ -294,40 +304,41 @@ 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; } /** * ntfs_mst_pwrite - multi sector transfer (mst) positioned write - * @dev: device to write to - * @pos: position in file descriptor to write to - * @count: number of blocks to write - * @bksize: size of each block that needs mst protecting - * @b: data buffer to write to disk + * @dev: device to write to + * @pos: position in file descriptor to write to + * @count: number of blocks to write + * @bksize: size of each block that needs mst protecting + * @b: data buffer to write to disk * * Multi sector transfer (mst) positioned write. This function will write * @count blocks of size @bksize bytes each from data buffer @b to the device @@ -351,141 +362,150 @@ 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; } /** * ntfs_cluster_read - read ntfs clusters - * @vol: volume to read from - * @lcn: starting logical cluster number - * @count: number of clusters to read - * @b: output data buffer + * @vol: volume to read from + * @lcn: starting logical cluster number + * @count: number of clusters to read + * @b: output data buffer * * Read @count ntfs clusters starting at logical cluster number @lcn from * 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; } /** * ntfs_cluster_write - write ntfs clusters - * @vol: volume to write to - * @lcn: starting logical cluster number - * @count: number of clusters to write - * @b: data buffer to write to disk + * @vol: volume to write to + * @lcn: starting logical cluster number + * @count: number of clusters to write + * @b: data buffer to write to disk * * Write @count ntfs clusters starting at logical cluster number @lcn from * 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; } /** * ntfs_device_offset_valid - test if a device offset is valid - * @dev: open device - * @ofs: offset to test for validity + * @dev: open device + * @ofs: offset to test for validity * * Test if the offset @ofs is an existing location on the device described * by the open device structure @dev. * * Return 0 if it is valid and -1 if it is not valid. */ -static int ntfs_device_offset_valid(struct ntfs_device *dev, s64 ofs) +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; } /** * ntfs_device_size_get - return the size of a device in blocks - * @dev: open device - * @block_size: block size in bytes in which to return the result + * @dev: open device + * @block_size: block size in bytes in which to return the result * * Return the number of @block_size sized blocks in the device described by the * open device @dev. @@ -494,237 +514,252 @@ static int ntfs_device_offset_valid(struct ntfs_device *dev, s64 ofs) * * On error return -1 with errno set to the error code. */ -s64 ntfs_device_size_get(struct ntfs_device *dev, int block_size) +s64 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; } /** * ntfs_device_partition_start_sector_get - get starting sector of a partition - * @dev: open device + * @dev: open device * * On success, return the starting sector of the partition @dev in the parent * block device of @dev. On error return -1 with errno set to the error code. * * The following error codes are defined: - * EINVAL Input parameter error - * EOPNOTSUPP System does not support HDIO_GETGEO ioctl - * ENOTTY @dev is a file or a device not supporting HDIO_GETGEO + * EINVAL Input parameter error + * EOPNOTSUPP System does not support HDIO_GETGEO ioctl + * ENOTTY @dev is a file or a device not supporting HDIO_GETGEO */ -s64 ntfs_device_partition_start_sector_get(struct ntfs_device *dev) +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; } /** * ntfs_device_heads_get - get number of heads of device - * @dev: open device + * @dev: open device * * On success, return the number of heads on the device @dev. On error return * -1 with errno set to the error code. * * The following error codes are defined: - * EINVAL Input parameter error - * EOPNOTSUPP System does not support HDIO_GETGEO ioctl - * ENOTTY @dev is a file or a device not supporting HDIO_GETGEO + * EINVAL Input parameter error + * EOPNOTSUPP System does not support HDIO_GETGEO ioctl + * ENOTTY @dev is a file or a device not supporting HDIO_GETGEO */ -int ntfs_device_heads_get(struct ntfs_device *dev) +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; } /** * ntfs_device_sectors_per_track_get - get number of sectors per track of device - * @dev: open device + * @dev: open device * * On success, return the number of sectors per track on the device @dev. On * error return -1 with errno set to the error code. * * The following error codes are defined: - * EINVAL Input parameter error - * EOPNOTSUPP System does not support HDIO_GETGEO ioctl - * ENOTTY @dev is a file or a device not supporting HDIO_GETGEO + * EINVAL Input parameter error + * EOPNOTSUPP System does not support HDIO_GETGEO ioctl + * ENOTTY @dev is a file or a device not supporting HDIO_GETGEO */ -int ntfs_device_sectors_per_track_get(struct ntfs_device *dev) +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; } /** * ntfs_device_sector_size_get - get sector size of a device - * @dev: open device + * @dev: open device * * On success, return the sector size in bytes of the device @dev. * On error return -1 with errno set to the error code. * * The following error codes are defined: - * EINVAL Input parameter error - * EOPNOTSUPP System does not support BLKSSZGET ioctl - * ENOTTY @dev is a file or a device not supporting BLKSSZGET + * EINVAL Input parameter error + * EOPNOTSUPP System does not support BLKSSZGET ioctl + * ENOTTY @dev is a file or a device not supporting BLKSSZGET */ -int ntfs_device_sector_size_get(struct ntfs_device *dev) +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; } /** * ntfs_device_block_size_set - set block size of a device - * @dev: open device + * @dev: open device * @block_size: block size to set @dev to * * On success, return 0. * On error return -1 with errno set to the error code. * * The following error codes are defined: - * EINVAL Input parameter error - * EOPNOTSUPP System does not support BLKBSZSET ioctl - * ENOTTY @dev is a file or a device not supporting BLKBSZSET + * EINVAL Input parameter error + * 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..6be5ac27 100644 --- a/source/libntfs/device.h +++ b/source/libntfs/device.h @@ -36,32 +36,33 @@ * * 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) -#define set_ndev_flag(nd, flag) set_bit(ND_##flag, (nd)->d_state) -#define clear_ndev_flag(nd, flag) clear_bit(ND_##flag, (nd)->d_state) +#define test_ndev_flag(nd, flag) test_bit(ND_##flag, (nd)->d_state) +#define set_ndev_flag(nd, flag) set_bit(ND_##flag, (nd)->d_state) +#define clear_ndev_flag(nd, flag) clear_bit(ND_##flag, (nd)->d_state) -#define NDevOpen(nd) test_ndev_flag(nd, Open) -#define NDevSetOpen(nd) set_ndev_flag(nd, Open) -#define NDevClearOpen(nd) clear_ndev_flag(nd, Open) +#define NDevOpen(nd) test_ndev_flag(nd, Open) +#define NDevSetOpen(nd) set_ndev_flag(nd, Open) +#define NDevClearOpen(nd) clear_ndev_flag(nd, Open) -#define NDevReadOnly(nd) test_ndev_flag(nd, ReadOnly) -#define NDevSetReadOnly(nd) set_ndev_flag(nd, ReadOnly) -#define NDevClearReadOnly(nd) clear_ndev_flag(nd, ReadOnly) +#define NDevReadOnly(nd) test_ndev_flag(nd, ReadOnly) +#define NDevSetReadOnly(nd) set_ndev_flag(nd, ReadOnly) +#define NDevClearReadOnly(nd) clear_ndev_flag(nd, ReadOnly) -#define NDevDirty(nd) test_ndev_flag(nd, Dirty) -#define NDevSetDirty(nd) set_ndev_flag(nd, Dirty) -#define NDevClearDirty(nd) clear_ndev_flag(nd, Dirty) +#define NDevDirty(nd) test_ndev_flag(nd, Dirty) +#define NDevSetDirty(nd) set_ndev_flag(nd, Dirty) +#define NDevClearDirty(nd) clear_ndev_flag(nd, Dirty) -#define NDevBlock(nd) test_ndev_flag(nd, Block) -#define NDevSetBlock(nd) set_ndev_flag(nd, Block) -#define NDevClearBlock(nd) clear_ndev_flag(nd, Block) +#define NDevBlock(nd) test_ndev_flag(nd, Block) +#define NDevSetBlock(nd) set_ndev_flag(nd, Block) +#define NDevClearBlock(nd) clear_ndev_flag(nd, Block) /** * struct ntfs_device - @@ -69,12 +70,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,44 +87,45 @@ 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 int ntfs_device_free(struct ntfs_device *dev); +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); -extern int ntfs_device_heads_get(struct ntfs_device *dev); -extern int ntfs_device_sectors_per_track_get(struct ntfs_device *dev); -extern int ntfs_device_sector_size_get(struct ntfs_device *dev); -extern int ntfs_device_block_size_set(struct ntfs_device *dev, int block_size); +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 ); +extern int ntfs_device_heads_get( struct ntfs_device *dev ); +extern int ntfs_device_sectors_per_track_get( struct ntfs_device *dev ); +extern int ntfs_device_sector_size_get( struct ntfs_device *dev ); +extern int ntfs_device_block_size_set( struct ntfs_device *dev, int block_size ); #endif /* defined _NTFS_DEVICE_H */ diff --git a/source/libntfs/device_io.h b/source/libntfs/device_io.h index fad4d85f..d9c4c857 100644 --- a/source/libntfs/device_io.h +++ b/source/libntfs/device_io.h @@ -41,28 +41,29 @@ #else /* __CYGWIN32__ */ #ifndef HDIO_GETGEO -# define HDIO_GETGEO 0x301 +# define HDIO_GETGEO 0x301 /** * 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 -# define BLKGETSIZE 0x1260 +# define BLKGETSIZE 0x1260 #endif #ifndef BLKSSZGET -# define BLKSSZGET 0x1268 +# define BLKSSZGET 0x1268 #endif #ifndef BLKGETSIZE64 -# define BLKGETSIZE64 0x80041272 +# define BLKGETSIZE64 0x80041272 #endif #ifndef BLKBSZSET -# define BLKBSZSET 0x40041271 +# define BLKBSZSET 0x40041271 #endif /* On Cygwin; use Win32 low level device operations. */ diff --git a/source/libntfs/dir.c b/source/libntfs/dir.c index 2372f3f8..d540aa5d 100644 --- a/source/libntfs/dir.c +++ b/source/libntfs/dir.c @@ -70,90 +70,99 @@ * 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 /* - * Pathname hashing + * Pathname hashing * - * Based on first char and second char (which may be '\0') + * Based on first char and second char (which may be '\0') */ -int ntfs_dir_inode_hash(const struct CACHED_GENERIC *cached) +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 + * 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 ) ); } /* - * Pathname comparing for invalidating entries in cache + * Pathname comparing for invalidating entries in cache * - * A partial path is compared in order to invalidate all paths - * related to a renamed directory - * inode numbers are also checked, as deleting a long name may - * imply deleting a short name and conversely + * A partial path is compared in order to invalidate all paths + * related to a renamed directory + * inode numbers are also checked, as deleting a long name may + * imply deleting a short name and conversely * - * Only use associated with a CACHE_NOHASH flag + * 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 @@ -161,67 +170,68 @@ static int inode_cache_inv_compare(const struct CACHED_GENERIC *cached, #if CACHE_LOOKUP_SIZE /* - * File name comparing for entering/fetching from lookup cache + * 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 ) ); } /* - * Inode number comparing for invalidating lookup cache + * Inode number comparing for invalidating lookup cache * - * All entries with designated inode number are invalidated + * All entries with designated inode number are invalidated * - * Only use associated with a CACHE_NOHASH flag + * 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 ) ) ); } /* - * Lookup hashing + * Lookup hashing * - * Based on first, second and and last char + * Based on first, second and and last char */ -int ntfs_dir_lookup_hash(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 /** * ntfs_inode_lookup_by_name - find an inode in a directory given its name - * @dir_ni: ntfs inode of the directory in which to search for the name - * @uname: Unicode name for which to search in the directory - * @uname_len: length of the name @uname in Unicode characters + * @dir_ni: ntfs inode of the directory in which to search for the name + * @uname: Unicode name for which to search in the directory + * @uname_len: length of the name @uname in Unicode characters * * Look for an inode with name @uname in the directory with inode @dir_ni. * ntfs_inode_lookup_by_name() walks the contents of the directory looking for @@ -242,411 +252,449 @@ 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; + } + + /* Get the starting vcn of the index_block holding the child node. */ + vcn = sle64_to_cpup( ( u8* )ie + le16_to_cpu( ie->length ) - 8 ); descend_into_child_node: - /* Read the index block starting at vcn. */ - br = ntfs_attr_mst_pread(ia_na, vcn << index_vcn_size_bits, 1, - index_block_size, ia); - if (br != 1) { - if (br != -1) - errno = EIO; - ntfs_log_perror("Failed to read vcn 0x%llx", - (unsigned long long)vcn); - goto close_err_out; - } + /* Read the index block starting at vcn. */ + br = ntfs_attr_mst_pread( ia_na, vcn << index_vcn_size_bits, 1, + index_block_size, ia ); + if ( br != 1 ) + { + if ( br != -1 ) + errno = EIO; + ntfs_log_perror( "Failed to read vcn 0x%llx", + ( unsigned long long )vcn ); + goto close_err_out; + } - if (sle64_to_cpu(ia->index_block_vcn) != vcn) { - ntfs_log_error("Actual VCN (0x%llx) of index buffer is different " - "from expected VCN (0x%llx).\n", - (long long)sle64_to_cpu(ia->index_block_vcn), - (long long)vcn); - errno = EIO; - goto close_err_out; - } - if (le32_to_cpu(ia->index.allocated_size) + 0x18 != index_block_size) { - ntfs_log_error("Index buffer (VCN 0x%llx) of directory inode 0x%llx " - "has a size (%u) differing from the directory " - "specified size (%u).\n", (long long)vcn, - (unsigned long long)dir_ni->mft_no, - (unsigned) le32_to_cpu(ia->index.allocated_size) + 0x18, - (unsigned)index_block_size); - errno = EIO; - goto close_err_out; - } - index_end = (u8*)&ia->index + le32_to_cpu(ia->index.index_length); - if (index_end > (u8*)ia + index_block_size) { - ntfs_log_error("Size of index buffer (VCN 0x%llx) of directory inode " - "0x%llx exceeds maximum size.\n", - (long long)vcn, (unsigned long long)dir_ni->mft_no); - errno = EIO; - goto close_err_out; - } + if ( sle64_to_cpu( ia->index_block_vcn ) != vcn ) + { + ntfs_log_error( "Actual VCN (0x%llx) of index buffer is different " + "from expected VCN (0x%llx).\n", + ( long long )sle64_to_cpu( ia->index_block_vcn ), + ( long long )vcn ); + errno = EIO; + goto close_err_out; + } + if ( le32_to_cpu( ia->index.allocated_size ) + 0x18 != index_block_size ) + { + ntfs_log_error( "Index buffer (VCN 0x%llx) of directory inode 0x%llx " + "has a size (%u) differing from the directory " + "specified size (%u).\n", ( long long )vcn, + ( unsigned long long )dir_ni->mft_no, + ( unsigned ) le32_to_cpu( ia->index.allocated_size ) + 0x18, + ( unsigned )index_block_size ); + errno = EIO; + goto close_err_out; + } + index_end = ( u8* ) & ia->index + le32_to_cpu( ia->index.index_length ); + if ( index_end > ( u8* )ia + index_block_size ) + { + ntfs_log_error( "Size of index buffer (VCN 0x%llx) of directory inode " + "0x%llx exceeds maximum size.\n", + ( long long )vcn, ( unsigned long long )dir_ni->mft_no ); + errno = EIO; + goto close_err_out; + } - /* The first index entry. */ - ie = (INDEX_ENTRY*)((u8*)&ia->index + - le32_to_cpu(ia->index.entries_offset)); - /* - * Iterate similar to above big loop but applied to index buffer, thus - * loop until we exceed valid memory (corruption case) or until we - * reach the last entry. - */ - for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) { - /* Bounds check. */ - if ((u8*)ie < (u8*)ia || (u8*)ie + - sizeof(INDEX_ENTRY_HEADER) > index_end || - (u8*)ie + le16_to_cpu(ie->key_length) > - index_end) { - ntfs_log_error("Index entry out of bounds in directory " - "inode %lld.\n", - (unsigned long long)dir_ni->mft_no); - errno = EIO; - goto close_err_out; - } - /* - * The last entry cannot contain a name. It can however contain - * a pointer to a child node in the B+tree so we just break out. - */ - if (ie->ie_flags & INDEX_ENTRY_END) - break; - - if (!le16_to_cpu(ie->length)) { - errno = EIO; - ntfs_log_error("Zero length index entry in inode %lld" - "\n", (unsigned long long)dir_ni->mft_no); - goto close_err_out; - } - /* - * Not a perfect match, need to do full blown collation so we - * know which way in the B+tree we have to go. - */ - rc = ntfs_names_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; + /* 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 = EIO; + ntfs_log_debug( "Corrupt directory. Aborting lookup.\n" ); eo_put_err_out: - ntfs_attr_put_search_ctx(ctx); - errno = eo; - return -1; + ntfs_attr_put_search_ctx( ctx ); + errno = eo; + return -1; close_err_out: - eo = errno; - free(ia); - ntfs_attr_close(ia_na); - goto eo_put_err_out; + eo = errno; + free( ia ); + ntfs_attr_close( ia_na ); + goto eo_put_err_out; } /* - * Lookup a file in a directory from its UTF-8 name + * Lookup a file in a directory from its UTF-8 name * - * The name is first fetched from cache if one is defined + * The name is first fetched from cache if one is defined * - * Returns the inode number - * or -1 if not possible (errno tells why) + * Returns the inode number + * or -1 if not possible (errno tells why) */ -u64 ntfs_inode_lookup_by_mbsname(ntfs_inode *dir_ni, const char *name) +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 ); } /* - * Update a cache lookup record when a name has been defined + * Update a cache lookup record when a name has been defined * - * The UTF-8 name is required + * The UTF-8 name is required */ -void ntfs_inode_update_mbsname(ntfs_inode *dir_ni, const char *name, u64 inum) +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 } @@ -661,294 +709,329 @@ void ntfs_inode_update_mbsname(ntfs_inode *dir_ni, const char *name, u64 inum) * then the root directory '.' will be used as the base for the search. * * Return: inode Success, the pathname was valid - * NULL Error, the pathname was invalid, or some other error occurred + * 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; + 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; + if ( ni && ( ni != parent ) ) + if ( ntfs_inode_close( ni ) && !err ) + err = errno; out: - free(ascii); - free(unicode); - if (err) - errno = err; - return result; + free( ascii ); + free( unicode ); + if ( err ) + errno = err; + return result; } /* * The little endian Unicode string ".." for ntfs_readdir(). */ -static const ntfschar dotdot[3] = { const_cpu_to_le16('.'), - const_cpu_to_le16('.'), - const_cpu_to_le16('\0') }; +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; -} index_union __attribute__((__transparent_union__)); +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; /** * ntfs_filldir - ntfs specific filldir method - * @dir_ni: ntfs inode of current directory - * @pos: current position in directory - * @ivcn_bits: log(2) of index vcn size - * @index_type: specifies whether @iu is an index root or an index allocation - * @iu: index root or index block to which @ie belongs - * @ie: current index entry - * @dirent: context for filldir callback supplied by the caller - * @filldir: filldir callback supplied by the caller + * @dir_ni: ntfs inode of current directory + * @pos: current position in directory + * @ivcn_bits: log(2) of index vcn size + * @index_type: specifies whether @iu is an index root or an index allocation + * @iu: index root or index block to which @ie belongs + * @ie: current index entry + * @dirent: context for filldir callback supplied by the caller + * @filldir: filldir callback supplied by the caller * * 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 ); } /** * ntfs_mft_get_parent_ref - find mft reference of parent directory of an inode - * @ni: ntfs inode whose parent directory to find + * @ni: ntfs inode whose parent directory to find * * Find the parent directory of the ntfs inode @ni. To do this, find the first * file name attribute in the mft record of @ni and return the parent mft @@ -964,59 +1047,63 @@ static int ntfs_filldir(ntfs_inode *dir_ni, s64 *pos, u8 ivcn_bits, * Return the mft reference of the parent directory on success or -1 on error * with errno set to the error code. */ -static MFT_REF ntfs_mft_get_parent_ref(ntfs_inode *ni) +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; + 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; + errno = EIO; err_out: - eo = errno; - ntfs_attr_put_search_ctx(ctx); - errno = eo; - return ERR_MREF(-1); + eo = errno; + ntfs_attr_put_search_ctx( ctx ); + errno = eo; + return ERR_MREF( -1 ); } /** * ntfs_readdir - read the contents of an ntfs directory - * @dir_ni: ntfs inode of current directory - * @pos: current position in directory - * @dirent: context for filldir callback supplied by the caller - * @filldir: filldir callback supplied by the caller + * @dir_ni: ntfs inode of current directory + * @pos: current position in directory + * @dirent: context for filldir callback supplied by the caller + * @filldir: filldir callback supplied by the caller * * Parse the index root and the index blocks that are marked in use in the * index bitmap and hand each found directory entry to the @filldir callback @@ -1027,368 +1114,395 @@ 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 entry if continuing previous readdir. */ + if ( ir_pos > ( u8* )ie - ( u8* )ir ) + continue; + /* + * Submit the directory entry to ntfs_filldir(), which will + * invoke the filldir() callback as appropriate. + */ + rc = ntfs_filldir( dir_ni, pos, index_vcn_size_bits, + INDEX_TYPE_ROOT, ir, ie, dirent, filldir ); + if ( rc ) + { + ntfs_attr_put_search_ctx( ctx ); + ctx = NULL; + goto err_out; + } + } + ntfs_attr_put_search_ctx( ctx ); + ctx = NULL; + + /* If there is no index allocation attribute we are finished. */ + if ( !ia_na ) + goto EOD; + + /* Advance *pos to the beginning of the index allocation. */ + *pos = vol->mft_record_size; skip_index_root: - if (!ia_na) - goto done; + if ( !ia_na ) + goto done; - /* Allocate a buffer for the current index block. */ - ia = ntfs_malloc(index_block_size); - if (!ia) - goto err_out; + /* Allocate a buffer for the current index block. */ + ia = ntfs_malloc( index_block_size ); + if ( !ia ) + goto err_out; - bmp_na = ntfs_attr_open(dir_ni, AT_BITMAP, NTFS_INDEX_I30, 4); - if (!bmp_na) { - ntfs_log_perror("Failed to open index bitmap attribute"); - goto dir_err_out; - } + bmp_na = ntfs_attr_open( dir_ni, AT_BITMAP, NTFS_INDEX_I30, 4 ); + if ( !bmp_na ) + { + ntfs_log_perror( "Failed to open index bitmap attribute" ); + goto dir_err_out; + } - /* Get the offset into the index allocation attribute. */ - ia_pos = *pos - vol->mft_record_size; + /* Get the offset into the index allocation attribute. */ + ia_pos = *pos - vol->mft_record_size; - bmp_pos = ia_pos >> index_block_size_bits; - if (bmp_pos >> 3 >= bmp_na->data_size) { - ntfs_log_error("Current index position exceeds index bitmap " - "size.\n"); - goto dir_err_out; - } + bmp_pos = ia_pos >> index_block_size_bits; + if ( bmp_pos >> 3 >= bmp_na->data_size ) + { + ntfs_log_error( "Current index position exceeds index bitmap " + "size.\n" ); + goto dir_err_out; + } - bmp_buf_size = min(bmp_na->data_size - (bmp_pos >> 3), 4096); - bmp = ntfs_malloc(bmp_buf_size); - if (!bmp) - goto err_out; + bmp_buf_size = min( bmp_na->data_size - ( bmp_pos >> 3 ), 4096 ); + bmp = ntfs_malloc( bmp_buf_size ); + if ( !bmp ) + goto err_out; - br = ntfs_attr_pread(bmp_na, bmp_pos >> 3, bmp_buf_size, bmp); - if (br != bmp_buf_size) { - if (br != -1) - errno = EIO; - ntfs_log_perror("Failed to read from index bitmap attribute"); - goto err_out; - } + br = ntfs_attr_pread( bmp_na, bmp_pos >> 3, bmp_buf_size, bmp ); + if ( br != bmp_buf_size ) + { + if ( br != -1 ) + errno = EIO; + ntfs_log_perror( "Failed to read from index bitmap attribute" ); + goto err_out; + } - bmp_buf_pos = 0; - /* If the index block is not in use find the next one that is. */ - while (!(bmp[bmp_buf_pos >> 3] & (1 << (bmp_buf_pos & 7)))) { + bmp_buf_pos = 0; + /* If the index block is not in use find the next one that is. */ + while ( !( bmp[bmp_buf_pos >> 3] & ( 1 << ( bmp_buf_pos & 7 ) ) ) ) + { find_next_index_buffer: - bmp_pos++; - bmp_buf_pos++; - /* If we have reached the end of the bitmap, we are done. */ - if (bmp_pos >> 3 >= bmp_na->data_size) - goto EOD; - ia_pos = bmp_pos << index_block_size_bits; - if (bmp_buf_pos >> 3 < bmp_buf_size) - continue; - /* Read next chunk from the index bitmap. */ - bmp_buf_pos = 0; - if ((bmp_pos >> 3) + bmp_buf_size > bmp_na->data_size) - bmp_buf_size = bmp_na->data_size - (bmp_pos >> 3); - br = ntfs_attr_pread(bmp_na, bmp_pos >> 3, bmp_buf_size, bmp); - if (br != bmp_buf_size) { - if (br != -1) - errno = EIO; - ntfs_log_perror("Failed to read from index bitmap attribute"); - goto err_out; - } - } + bmp_pos++; + bmp_buf_pos++; + /* If we have reached the end of the bitmap, we are done. */ + if ( bmp_pos >> 3 >= bmp_na->data_size ) + goto EOD; + ia_pos = bmp_pos << index_block_size_bits; + if ( bmp_buf_pos >> 3 < bmp_buf_size ) + continue; + /* Read next chunk from the index bitmap. */ + bmp_buf_pos = 0; + if ( ( bmp_pos >> 3 ) + bmp_buf_size > bmp_na->data_size ) + bmp_buf_size = bmp_na->data_size - ( bmp_pos >> 3 ); + br = ntfs_attr_pread( bmp_na, bmp_pos >> 3, bmp_buf_size, bmp ); + if ( br != bmp_buf_size ) + { + if ( br != -1 ) + errno = EIO; + ntfs_log_perror( "Failed to read from index bitmap attribute" ); + goto err_out; + } + } - ntfs_log_debug("Handling index block 0x%llx.\n", (long long)bmp_pos); + ntfs_log_debug( "Handling index block 0x%llx.\n", ( long long )bmp_pos ); - /* Read the index block starting at bmp_pos. */ - br = ntfs_attr_mst_pread(ia_na, bmp_pos << index_block_size_bits, 1, - index_block_size, ia); - if (br != 1) { - if (br != -1) - errno = EIO; - ntfs_log_perror("Failed to read index block"); - goto err_out; - } + /* Read the index block starting at bmp_pos. */ + br = ntfs_attr_mst_pread( ia_na, bmp_pos << index_block_size_bits, 1, + index_block_size, ia ); + if ( br != 1 ) + { + if ( br != -1 ) + errno = EIO; + ntfs_log_perror( "Failed to read index block" ); + goto err_out; + } - ia_start = ia_pos & ~(s64)(index_block_size - 1); - if (sle64_to_cpu(ia->index_block_vcn) != ia_start >> - index_vcn_size_bits) { - ntfs_log_error("Actual VCN (0x%llx) of index buffer is different " - "from expected VCN (0x%llx) in inode 0x%llx.\n", - (long long)sle64_to_cpu(ia->index_block_vcn), - (long long)ia_start >> index_vcn_size_bits, - (unsigned long long)dir_ni->mft_no); - goto dir_err_out; - } - if (le32_to_cpu(ia->index.allocated_size) + 0x18 != index_block_size) { - ntfs_log_error("Index buffer (VCN 0x%llx) of directory inode %lld " - "has a size (%u) differing from the directory " - "specified size (%u).\n", (long long)ia_start >> - index_vcn_size_bits, - (unsigned long long)dir_ni->mft_no, - (unsigned) le32_to_cpu(ia->index.allocated_size) - + 0x18, (unsigned)index_block_size); - goto dir_err_out; - } - index_end = (u8*)&ia->index + le32_to_cpu(ia->index.index_length); - if (index_end > (u8*)ia + index_block_size) { - ntfs_log_error("Size of index buffer (VCN 0x%llx) of directory inode " - "%lld exceeds maximum size.\n", - (long long)ia_start >> index_vcn_size_bits, - (unsigned long long)dir_ni->mft_no); - goto dir_err_out; - } - /* The first index entry. */ - ie = (INDEX_ENTRY*)((u8*)&ia->index + - le32_to_cpu(ia->index.entries_offset)); - /* - * Loop until we exceed valid memory (corruption case) or until we - * reach the last entry or until ntfs_filldir tells us it has had - * enough or signals an error (both covered by the rc test). - */ - for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) { - ntfs_log_debug("In index allocation, offset 0x%llx.\n", - (long long)ia_start + ((u8*)ie - (u8*)ia)); - /* Bounds checks. */ - if ((u8*)ie < (u8*)ia || (u8*)ie + - sizeof(INDEX_ENTRY_HEADER) > index_end || - (u8*)ie + le16_to_cpu(ie->key_length) > - index_end) { - ntfs_log_error("Index entry out of bounds in directory inode " - "%lld.\n", (unsigned long long)dir_ni->mft_no); - goto dir_err_out; - } - /* The last entry cannot contain a name. */ - if (ie->ie_flags & INDEX_ENTRY_END) - break; - - if (!le16_to_cpu(ie->length)) - goto dir_err_out; - - /* Skip index entry if continuing previous readdir. */ - if (ia_pos - ia_start > (u8*)ie - (u8*)ia) - continue; - /* - * Submit the directory entry to ntfs_filldir(), which will - * invoke the filldir() callback as appropriate. - */ - rc = ntfs_filldir(dir_ni, pos, index_vcn_size_bits, - INDEX_TYPE_ALLOCATION, ia, ie, dirent, filldir); - if (rc) - goto err_out; - } - goto find_next_index_buffer; + ia_start = ia_pos & ~( s64 )( index_block_size - 1 ); + if ( sle64_to_cpu( ia->index_block_vcn ) != ia_start >> + index_vcn_size_bits ) + { + ntfs_log_error( "Actual VCN (0x%llx) of index buffer is different " + "from expected VCN (0x%llx) in inode 0x%llx.\n", + ( long long )sle64_to_cpu( ia->index_block_vcn ), + ( long long )ia_start >> index_vcn_size_bits, + ( unsigned long long )dir_ni->mft_no ); + goto dir_err_out; + } + if ( le32_to_cpu( ia->index.allocated_size ) + 0x18 != index_block_size ) + { + ntfs_log_error( "Index buffer (VCN 0x%llx) of directory inode %lld " + "has a size (%u) differing from the directory " + "specified size (%u).\n", ( long long )ia_start >> + index_vcn_size_bits, + ( unsigned long long )dir_ni->mft_no, + ( unsigned ) le32_to_cpu( ia->index.allocated_size ) + + 0x18, ( unsigned )index_block_size ); + goto dir_err_out; + } + index_end = ( u8* ) & ia->index + le32_to_cpu( ia->index.index_length ); + if ( index_end > ( u8* )ia + index_block_size ) + { + ntfs_log_error( "Size of index buffer (VCN 0x%llx) of directory inode " + "%lld exceeds maximum size.\n", + ( long long )ia_start >> index_vcn_size_bits, + ( unsigned long long )dir_ni->mft_no ); + goto dir_err_out; + } + /* The first index entry. */ + ie = ( INDEX_ENTRY* )( ( u8* ) & ia->index + + le32_to_cpu( ia->index.entries_offset ) ); + /* + * Loop until we exceed valid memory (corruption case) or until we + * reach the last entry or until ntfs_filldir tells us it has had + * enough or signals an error (both covered by the rc test). + */ + for ( ;; ie = ( INDEX_ENTRY* )( ( u8* )ie + le16_to_cpu( ie->length ) ) ) + { + ntfs_log_debug( "In index allocation, offset 0x%llx.\n", + ( long long )ia_start + ( ( u8* )ie - ( u8* )ia ) ); + /* Bounds checks. */ + if ( ( u8* )ie < ( u8* )ia || ( u8* )ie + + sizeof( INDEX_ENTRY_HEADER ) > index_end || + ( u8* )ie + le16_to_cpu( ie->key_length ) > + index_end ) + { + ntfs_log_error( "Index entry out of bounds in directory inode " + "%lld.\n", ( unsigned long long )dir_ni->mft_no ); + goto dir_err_out; + } + /* The last entry cannot contain a name. */ + if ( ie->ie_flags & INDEX_ENTRY_END ) + break; + + if ( !le16_to_cpu( ie->length ) ) + goto dir_err_out; + + /* Skip index entry if continuing previous readdir. */ + if ( ia_pos - ia_start > ( u8* )ie - ( u8* )ia ) + continue; + /* + * Submit the directory entry to ntfs_filldir(), which will + * invoke the filldir() callback as appropriate. + */ + rc = ntfs_filldir( dir_ni, pos, index_vcn_size_bits, + INDEX_TYPE_ALLOCATION, ia, ie, dirent, filldir ); + if ( rc ) + goto err_out; + } + goto find_next_index_buffer; EOD: - /* We are finished, set *pos to EOD. */ - *pos = i_size + vol->mft_record_size; + /* We are finished, set *pos to EOD. */ + *pos = i_size + vol->mft_record_size; done: - free(ia); - free(bmp); - if (bmp_na) - ntfs_attr_close(bmp_na); - if (ia_na) - ntfs_attr_close(ia_na); - ntfs_log_debug("EOD, *pos 0x%llx, returning 0.\n", (long long)*pos); - return 0; + free( ia ); + free( bmp ); + if ( bmp_na ) + ntfs_attr_close( bmp_na ); + if ( ia_na ) + ntfs_attr_close( ia_na ); + ntfs_log_debug( "EOD, *pos 0x%llx, returning 0.\n", ( long long )*pos ); + return 0; dir_err_out: - errno = EIO; + errno = EIO; err_out: - eo = errno; - ntfs_log_trace("failed.\n"); - if (ctx) - ntfs_attr_put_search_ctx(ctx); - free(ia); - free(bmp); - if (bmp_na) - ntfs_attr_close(bmp_na); - if (ia_na) - ntfs_attr_close(ia_na); - errno = eo; - return -1; + eo = errno; + ntfs_log_trace( "failed.\n" ); + if ( ctx ) + ntfs_attr_put_search_ctx( ctx ); + free( ia ); + free( bmp ); + if ( bmp_na ) + ntfs_attr_close( bmp_na ); + if ( ia_na ) + ntfs_attr_close( ia_na ); + errno = eo; + return -1; } /** * __ntfs_create - create object on ntfs volume - * @dir_ni: ntfs inode for directory in which create new object - * @securid: id of inheritable security descriptor, 0 if none - * @name: unicode name of new object - * @name_len: length of the name in unicode characters - * @type: type of the object to create - * @dev: major and minor device numbers (obtained from makedev()) - * @target: target in unicode (only for symlinks) - * @target_len: length of target in unicode characters + * @dir_ni: ntfs inode for directory in which create new object + * @securid: id of inheritable security descriptor, 0 if none + * @name: unicode name of new object + * @name_len: length of the name in unicode characters + * @type: type of the object to create + * @dev: major and minor device numbers (obtained from makedev()) + * @target: target in unicode (only for symlinks) + * @target_len: length of target in unicode characters * * Internal, use ntfs_create{,_device,_symlink} wrappers instead. * * @type can be: - * S_IFREG to create regular file - * S_IFDIR to create directory - * S_IFBLK to create block device - * S_IFCHR to create character device - * S_IFLNK to create symbolic link - * S_IFIFO to create FIFO - * S_IFSOCK to create socket + * S_IFREG to create regular file + * S_IFDIR to create directory + * S_IFBLK to create block device + * S_IFCHR to create character device + * S_IFLNK to create symbolic link + * S_IFIFO to create FIFO + * S_IFSOCK to create socket * other values are invalid. * * @dev is used only if @type is S_IFBLK or S_IFCHR, in other cases its value @@ -1400,644 +1514,699 @@ 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; + 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"); + 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) +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) +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; } /** * ntfs_delete - delete file or directory from ntfs volume - * @ni: ntfs inode for object to delte - * @dir_ni: ntfs inode for directory in which delete object - * @name: unicode name of the object to delete - * @name_len: length of the name in unicode characters + * @ni: ntfs inode for object to delte + * @dir_ni: ntfs inode for directory in which delete object + * @name: unicode name of the object to delete + * @name_len: length of the name in unicode characters * * @ni is always closed after the call to this function (even if it failed), * user does not need to call ntfs_inode_close himself. * * 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; + ntfs_log_trace( "Entering.\n" ); + + if ( !ni || !dir_ni || !name || !name_len ) + { + ntfs_log_error( "Invalid arguments.\n" ); + errno = EINVAL; + goto err_out; + } + if ( ni->nr_extents == -1 ) + ni = ni->base_ni; + if ( dir_ni->nr_extents == -1 ) + dir_ni = dir_ni->base_ni; + /* + * Search for FILE_NAME attribute with such name. If it's in POSIX or + * WIN32_AND_DOS namespace, then simply remove it from index and inode. + * If filename in DOS or in WIN32 namespace, then remove DOS name first, + * only then remove WIN32 name. + */ + actx = ntfs_attr_get_search_ctx( ni, NULL ); + if ( !actx ) + goto err_out; search: - while (!ntfs_attr_lookup(AT_FILE_NAME, AT_UNNAMED, 0, CASE_SENSITIVE, - 0, NULL, 0, actx)) { - char *s; - BOOL case_sensitive = IGNORE_CASE; + while ( !ntfs_attr_lookup( AT_FILE_NAME, AT_UNNAMED, 0, CASE_SENSITIVE, + 0, NULL, 0, actx ) ) + { + char *s; + BOOL case_sensitive = IGNORE_CASE; - errno = 0; - fn = (FILE_NAME_ATTR*)((u8*)actx->attr + - le16_to_cpu(actx->attr->value_offset)); - s = ntfs_attr_name_get(fn->file_name, fn->file_name_length); - ntfs_log_trace("name: '%s' type: %d dos: %d win32: %d " - "case: %d\n", s, fn->file_name_type, - looking_for_dos_name, looking_for_win32_name, - case_sensitive_match); - ntfs_attr_name_free(&s); - if (looking_for_dos_name) { - if (fn->file_name_type == FILE_NAME_DOS) - break; - else - continue; - } - if (looking_for_win32_name) { - if (fn->file_name_type == FILE_NAME_WIN32) - break; - else - continue; - } - - /* Ignore hard links from other directories */ - if (dir_ni->mft_no != MREF_LE(fn->parent_directory)) { - ntfs_log_debug("MFT record numbers don't match " - "(%llu != %llu)\n", - (long long unsigned)dir_ni->mft_no, - (long long unsigned)MREF_LE(fn->parent_directory)); - continue; - } - - if (fn->file_name_type == FILE_NAME_POSIX || case_sensitive_match) - case_sensitive = CASE_SENSITIVE; - - if (ntfs_names_are_equal(fn->file_name, fn->file_name_length, - name, name_len, case_sensitive, - ni->vol->upcase, ni->vol->upcase_len)){ - - if (fn->file_name_type == FILE_NAME_WIN32) { - looking_for_dos_name = TRUE; - ntfs_attr_reinit_search_ctx(actx); - continue; - } - if (fn->file_name_type == FILE_NAME_DOS) - looking_for_dos_name = TRUE; - break; - } - } - if (errno) { - /* - * If case sensitive search failed, then try once again - * ignoring case. - */ - if (errno == ENOENT && case_sensitive_match) { - case_sensitive_match = FALSE; - ntfs_attr_reinit_search_ctx(actx); - goto search; - } - goto err_out; - } - - if (ntfs_check_unlinkable_dir(ni, fn) < 0) - goto err_out; - - if (ntfs_index_remove(dir_ni, ni, fn, le32_to_cpu(actx->attr->value_length))) - goto err_out; - - if (ntfs_attr_record_rm(actx)) - goto err_out; - - ni->mrec->link_count = cpu_to_le16(le16_to_cpu( - ni->mrec->link_count) - 1); - - ntfs_inode_mark_dirty(ni); - if (looking_for_dos_name) { - looking_for_dos_name = FALSE; - looking_for_win32_name = TRUE; - ntfs_attr_reinit_search_ctx(actx); - goto search; - } - /* TODO: Update object id, quota and securiry indexes if required. */ - /* - * If hard link count is not equal to zero then we are done. In other - * case there are no reference to this inode left, so we should free all - * non-resident attributes and mark all MFT record as not in use. - */ + errno = 0; + fn = ( FILE_NAME_ATTR* )( ( u8* )actx->attr + + le16_to_cpu( actx->attr->value_offset ) ); + s = ntfs_attr_name_get( fn->file_name, fn->file_name_length ); + ntfs_log_trace( "name: '%s' type: %d dos: %d win32: %d " + "case: %d\n", s, fn->file_name_type, + looking_for_dos_name, looking_for_win32_name, + case_sensitive_match ); + ntfs_attr_name_free( &s ); + if ( looking_for_dos_name ) + { + if ( fn->file_name_type == FILE_NAME_DOS ) + break; + else + continue; + } + if ( looking_for_win32_name ) + { + if ( fn->file_name_type == FILE_NAME_WIN32 ) + break; + else + continue; + } + + /* Ignore hard links from other directories */ + if ( dir_ni->mft_no != MREF_LE( fn->parent_directory ) ) + { + ntfs_log_debug( "MFT record numbers don't match " + "(%llu != %llu)\n", + ( long long unsigned )dir_ni->mft_no, + ( long long unsigned )MREF_LE( fn->parent_directory ) ); + continue; + } + + if ( fn->file_name_type == FILE_NAME_POSIX || case_sensitive_match ) + case_sensitive = CASE_SENSITIVE; + + if ( ntfs_names_are_equal( fn->file_name, fn->file_name_length, + name, name_len, case_sensitive, + ni->vol->upcase, ni->vol->upcase_len ) ) + { + + if ( fn->file_name_type == FILE_NAME_WIN32 ) + { + looking_for_dos_name = TRUE; + ntfs_attr_reinit_search_ctx( actx ); + continue; + } + if ( fn->file_name_type == FILE_NAME_DOS ) + looking_for_dos_name = TRUE; + break; + } + } + if ( errno ) + { + /* + * If case sensitive search failed, then try once again + * ignoring case. + */ + if ( errno == ENOENT && case_sensitive_match ) + { + case_sensitive_match = FALSE; + ntfs_attr_reinit_search_ctx( actx ); + goto search; + } + goto err_out; + } + + if ( ntfs_check_unlinkable_dir( ni, fn ) < 0 ) + goto err_out; + + if ( ntfs_index_remove( dir_ni, ni, fn, le32_to_cpu( actx->attr->value_length ) ) ) + goto err_out; + + if ( ntfs_attr_record_rm( actx ) ) + goto err_out; + + ni->mrec->link_count = cpu_to_le16( le16_to_cpu( + ni->mrec->link_count ) - 1 ); + + ntfs_inode_mark_dirty( ni ); + if ( looking_for_dos_name ) + { + looking_for_dos_name = FALSE; + looking_for_win32_name = TRUE; + ntfs_attr_reinit_search_ctx( actx ); + goto search; + } + /* TODO: Update object id, quota and securiry indexes if required. */ + /* + * If hard link count is not equal to zero then we are done. In other + * case there are no reference to this inode left, so we should free all + * non-resident attributes and mark all MFT record as not in use. + */ #if CACHE_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); + 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; + 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; + err = errno; + goto out; } /** * ntfs_link - create hard link for file or directory - * @ni: ntfs inode for object to create hard link - * @dir_ni: ntfs inode for directory in which new link should be placed - * @name: unicode name of the new link - * @name_len: length of the name in unicode characters + * @ni: ntfs inode for object to create hard link + * @dir_ni: ntfs inode for directory in which new link should be placed + * @name: unicode name of the new link + * @name_len: length of the name in unicode characters * * NOTE: At present we allow creating hardlinks to directories, we use them * in a temporary state during rename. But it's defenitely bad idea to have @@ -2047,344 +2216,374 @@ 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; + 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"); + ntfs_log_error( "Rollback failed. Leaving inconsistent metadata.\n" ); err_out: - free(fn); - errno = err; - return -1; + free( fn ); + errno = err; + return -1; } -int ntfs_link(ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, u8 name_len) +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 ) ); } /* - * Get a parent directory from an inode entry + * Get a parent directory from an inode entry * - * This is only used in situations where the path used to access - * the current file is not known for sure. The result may be different - * from the path when the file is linked in several parent directories. + * This is only used in situations where the path used to access + * the current file is not known for sure. The result may be different + * from the path when the file is linked in several parent directories. * - * Currently this is only used for translating ".." in the target - * of a Vista relative symbolic link + * Currently this is only used for translating ".." in the target + * of a Vista relative symbolic link */ -ntfs_inode *ntfs_dir_parent_inode(ntfs_inode *ni) +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 -#define MAX_DOS_NAME_LENGTH 12 +#define MAX_DOS_NAME_LENGTH 12 /* - * Get a DOS name for a file in designated directory + * Get a DOS name for a file in designated directory * - * Returns size if found - * 0 if not found - * -1 if there was an error (described by errno) + * Returns size if found + * 0 if not found + * -1 if there was an error (described by errno) */ -static int get_dos_name(ntfs_inode *ni, u64 dnum, ntfschar *dosname) +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 + * Get a long name for a file in designated directory * - * Returns size if found - * 0 if not found - * -1 if there was an error (described by errno) + * Returns size if found + * 0 if not found + * -1 if there was an error (described by errno) */ -static int get_long_name(ntfs_inode *ni, u64 dnum, ntfschar *longname) +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 + * 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) +int ntfs_get_ntfs_dos_name( ntfs_inode *ni, ntfs_inode *dir_ni, + 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 ); } /* - * Change the name space of an existing file or directory + * Change the name space of an existing file or directory * - * Returns the old namespace if successful - * -1 if an error occurred (described by errno) + * Returns the old namespace if successful + * -1 if an error occurred (described by errno) */ -static int set_namespace(ntfs_inode *ni, ntfs_inode *dir_ni, - ntfschar *name, int len, - FILE_NAME_TYPE_FLAGS nametype) +static int set_namespace( ntfs_inode *ni, ntfs_inode *dir_ni, + ntfschar *name, int len, + FILE_NAME_TYPE_FLAGS nametype ) { - ntfs_attr_search_ctx *actx; - ntfs_index_context *icx; - FILE_NAME_ATTR *fnx; - FILE_NAME_ATTR *fn = NULL; - BOOL found; - int lkup; - int ret; + 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 ); } /* - * Set a DOS name to a file and adjust name spaces + * Set a DOS name to a file and adjust name spaces * - * If the new names are collapsible (same uppercased chars) : + * If the new names are collapsible (same uppercased chars) : * * - the existing DOS name or DOS+Win32 name is made Posix * - if it was a real DOS name, the existing long name is made DOS+Win32 * and the existing DOS name is deleted * - finally the existing long name is made DOS+Win32 unless already done * - * If the new names are not collapsible : + * If the new names are not collapsible : * * - insert the short name as a DOS name * - delete the old long name or existing short name @@ -2397,264 +2596,302 @@ static int set_namespace(ntfs_inode *ni, ntfs_inode *dir_ni, * The inodes of file and parent directory are always closed * * Returns 0 if successful - * -1 if failed + * -1 if failed */ -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) +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 ) { - 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 */ + /* 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); + 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 + * Set the ntfs DOS name into an extended attribute * * The DOS name will be added as another file name attribute * using the existing file name information from the original * name or overwriting the DOS Name if one exists. * - * The inode of the file is always closed + * The inode of the file is always closed */ -int ntfs_set_ntfs_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni, - const char *value, size_t size, int flags) +int ntfs_set_ntfs_dos_name( ntfs_inode *ni, ntfs_inode *dir_ni, + 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 ); } /* - * Delete the ntfs DOS name + * Delete the ntfs DOS name */ -int ntfs_remove_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..d0c8670f 100644 --- a/source/libntfs/dir.h +++ b/source/libntfs/dir.h @@ -59,40 +59,40 @@ 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_mbsname(ntfs_inode *dir_ni, const char *name); -extern void ntfs_inode_update_mbsname(ntfs_inode *dir_ni, const char *name, - u64 inum); +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 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 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_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 ) */ -#define NTFS_DT_UNKNOWN 0 -#define NTFS_DT_FIFO 1 -#define NTFS_DT_CHR 2 -#define NTFS_DT_DIR 4 -#define NTFS_DT_BLK 6 -#define NTFS_DT_REG 8 -#define NTFS_DT_LNK 10 -#define NTFS_DT_SOCK 12 -#define NTFS_DT_WHT 14 +#define NTFS_DT_UNKNOWN 0 +#define NTFS_DT_FIFO 1 +#define NTFS_DT_CHR 2 +#define NTFS_DT_DIR 4 +#define NTFS_DT_BLK 6 +#define NTFS_DT_REG 8 +#define NTFS_DT_LNK 10 +#define NTFS_DT_SOCK 12 +#define NTFS_DT_WHT 14 /* * This is the "ntfs_filldir" function type, used by ntfs_readdir() to let @@ -100,27 +100,27 @@ 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); +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_remove_ntfs_dos_name(ntfs_inode *ni, ntfs_inode *dir_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_remove_ntfs_dos_name( ntfs_inode *ni, ntfs_inode *dir_ni ); #if CACHE_INODE_SIZE struct CACHED_GENERIC; -extern int ntfs_dir_inode_hash(const struct CACHED_GENERIC *cached); -extern int ntfs_dir_lookup_hash(const struct CACHED_GENERIC *cached); +extern int ntfs_dir_inode_hash( const struct CACHED_GENERIC *cached ); +extern int ntfs_dir_lookup_hash( const struct CACHED_GENERIC *cached ); #endif diff --git a/source/libntfs/efs.c b/source/libntfs/efs.c index 6ccec20a..25f2444b 100644 --- a/source/libntfs/efs.c +++ b/source/libntfs/efs.c @@ -1,7 +1,7 @@ /** * efs.c - Limited processing of encrypted files * - * This module is part of ntfs-3g library + * This module is part of ntfs-3g library * * Copyright (c) 2009 Martin Bene * Copyright (c) 2009-2010 Jean-Pierre Andre @@ -58,256 +58,305 @@ #include "misc.h" #include "efs.h" -#ifdef HAVE_SETXATTR /* extended attributes interface required */ +#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 + * Get the ntfs EFS info into an extended attribute */ -int ntfs_get_efs_info(ntfs_inode *ni, char *value, size_t size) +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 ); } /* - * Fix all encrypted AT_DATA attributes of an inode + * Fix all encrypted AT_DATA attributes of an inode * - * The fix may require making an attribute non resident, which - * requires more space in the MFT record, and may cause some - * attribute to be expelled and the full record to be reorganized. - * When this happens, the search for data attributes has to be - * reinitialized. + * The fix may require making an attribute non resident, which + * requires more space in the MFT record, and may cause some + * attribute to be expelled and the full record to be reorganized. + * When this happens, the search for data attributes has to be + * reinitialized. * - * Returns zero if successful. - * -1 if there is a problem. + * Returns zero if successful. + * -1 if there is a problem. */ -static int fixup_loop(ntfs_inode *ni) +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 ); } /* - * Set the efs data from an extended attribute - * Warning : the new data is not checked - * Returns 0, or -1 if there is a problem + * Set the efs data from an extended attribute + * Warning : the new data is not checked + * Returns 0, or -1 if there is a problem */ -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 ntfs_set_efs_info( ntfs_inode *ni, const char *value, size_t size, + 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 ); } /* @@ -315,125 +364,144 @@ int ntfs_set_efs_info(ntfs_inode *ni, const char *value, size_t size, * read padding length from last two bytes * truncate attribute, make non-resident, * set data size to match padding length - * set ATTR_IS_ENCRYPTED flag on attribute + * set ATTR_IS_ENCRYPTED flag on attribute * - * Return 0 if successful - * -1 if failed (errno tells why) + * Return 0 if successful + * -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); + 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); + 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..3b450907 100644 --- a/source/libntfs/efs.h +++ b/source/libntfs/efs.h @@ -21,10 +21,10 @@ #ifndef EFS_H #define EFS_H -int ntfs_get_efs_info(ntfs_inode *ni, char *value, size_t size); +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_efs_fixup_attribute(ntfs_attr_search_ctx *ctx, ntfs_attr *na); +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/endians.h b/source/libntfs/endians.h index 397f1c20..84a7d250 100644 --- a/source/libntfs/endians.h +++ b/source/libntfs/endians.h @@ -1,5 +1,5 @@ /* - * endians.h - Definitions related to handling of byte ordering. + * endians.h - Definitions related to handling of byte ordering. * Originated from the Linux-NTFS project. * * Copyright (c) 2000-2005 Anton Altaparmakov @@ -29,9 +29,9 @@ /* * Notes: - * We define the conversion functions including typecasts since the + * We define the conversion functions including typecasts since the * defaults don't necessarily perform appropriate typecasts. - * Also, using our own functions means that we can change them if it + * Also, using our own functions means that we can change them if it * turns out that we do need to use the unaligned access macros on * architectures requiring aligned memory accesses... */ @@ -53,59 +53,59 @@ #endif #ifndef __BYTE_ORDER -# if defined(_BYTE_ORDER) -# define __BYTE_ORDER _BYTE_ORDER -# define __LITTLE_ENDIAN _LITTLE_ENDIAN -# define __BIG_ENDIAN _BIG_ENDIAN -# elif defined(BYTE_ORDER) -# define __BYTE_ORDER BYTE_ORDER -# define __LITTLE_ENDIAN LITTLE_ENDIAN -# define __BIG_ENDIAN BIG_ENDIAN -# elif defined(__BYTE_ORDER__) -# define __BYTE_ORDER __BYTE_ORDER__ -# define __LITTLE_ENDIAN __LITTLE_ENDIAN__ -# define __BIG_ENDIAN __BIG_ENDIAN__ -# elif (defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)) || \ - defined(WORDS_LITTLEENDIAN) -# define __BYTE_ORDER 1 -# define __LITTLE_ENDIAN 1 -# define __BIG_ENDIAN 0 -# elif (!defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN)) || \ - defined(WORDS_BIGENDIAN) -# define __BYTE_ORDER 0 -# define __LITTLE_ENDIAN 1 -# define __BIG_ENDIAN 0 -# else -# error "__BYTE_ORDER is not defined." -# endif +# if defined(_BYTE_ORDER) +# define __BYTE_ORDER _BYTE_ORDER +# define __LITTLE_ENDIAN _LITTLE_ENDIAN +# define __BIG_ENDIAN _BIG_ENDIAN +# elif defined(BYTE_ORDER) +# define __BYTE_ORDER BYTE_ORDER +# define __LITTLE_ENDIAN LITTLE_ENDIAN +# define __BIG_ENDIAN BIG_ENDIAN +# elif defined(__BYTE_ORDER__) +# define __BYTE_ORDER __BYTE_ORDER__ +# define __LITTLE_ENDIAN __LITTLE_ENDIAN__ +# define __BIG_ENDIAN __BIG_ENDIAN__ +# elif (defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)) || \ + defined(WORDS_LITTLEENDIAN) +# define __BYTE_ORDER 1 +# define __LITTLE_ENDIAN 1 +# define __BIG_ENDIAN 0 +# elif (!defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN)) || \ + defined(WORDS_BIGENDIAN) +# define __BYTE_ORDER 0 +# define __LITTLE_ENDIAN 1 +# define __BIG_ENDIAN 0 +# else +# error "__BYTE_ORDER is not defined." +# endif #endif -#define __ntfs_bswap_constant_16(x) \ - (u16)((((u16)(x) & 0xff00) >> 8) | \ - (((u16)(x) & 0x00ff) << 8)) +#define __ntfs_bswap_constant_16(x) \ + (u16)((((u16)(x) & 0xff00) >> 8) | \ + (((u16)(x) & 0x00ff) << 8)) -#define __ntfs_bswap_constant_32(x) \ - (u32)((((u32)(x) & 0xff000000u) >> 24) | \ - (((u32)(x) & 0x00ff0000u) >> 8) | \ - (((u32)(x) & 0x0000ff00u) << 8) | \ - (((u32)(x) & 0x000000ffu) << 24)) +#define __ntfs_bswap_constant_32(x) \ + (u32)((((u32)(x) & 0xff000000u) >> 24) | \ + (((u32)(x) & 0x00ff0000u) >> 8) | \ + (((u32)(x) & 0x0000ff00u) << 8) | \ + (((u32)(x) & 0x000000ffu) << 24)) -#define __ntfs_bswap_constant_64(x) \ - (u64)((((u64)(x) & 0xff00000000000000ull) >> 56) | \ - (((u64)(x) & 0x00ff000000000000ull) >> 40) | \ - (((u64)(x) & 0x0000ff0000000000ull) >> 24) | \ - (((u64)(x) & 0x000000ff00000000ull) >> 8) | \ - (((u64)(x) & 0x00000000ff000000ull) << 8) | \ - (((u64)(x) & 0x0000000000ff0000ull) << 24) | \ - (((u64)(x) & 0x000000000000ff00ull) << 40) | \ - (((u64)(x) & 0x00000000000000ffull) << 56)) +#define __ntfs_bswap_constant_64(x) \ + (u64)((((u64)(x) & 0xff00000000000000ull) >> 56) | \ + (((u64)(x) & 0x00ff000000000000ull) >> 40) | \ + (((u64)(x) & 0x0000ff0000000000ull) >> 24) | \ + (((u64)(x) & 0x000000ff00000000ull) >> 8) | \ + (((u64)(x) & 0x00000000ff000000ull) << 8) | \ + (((u64)(x) & 0x0000000000ff0000ull) << 24) | \ + (((u64)(x) & 0x000000000000ff00ull) << 40) | \ + (((u64)(x) & 0x00000000000000ffull) << 56)) #ifdef HAVE_BYTESWAP_H -# include +# include #else -# define bswap_16(x) __ntfs_bswap_constant_16(x) -# define bswap_32(x) __ntfs_bswap_constant_32(x) -# define bswap_64(x) __ntfs_bswap_constant_64(x) +# define bswap_16(x) __ntfs_bswap_constant_16(x) +# define bswap_32(x) __ntfs_bswap_constant_32(x) +# define bswap_64(x) __ntfs_bswap_constant_64(x) #endif #if defined(__LITTLE_ENDIAN) && (__BYTE_ORDER == __LITTLE_ENDIAN) @@ -152,52 +152,52 @@ /* Unsigned from LE to CPU conversion. */ -#define le16_to_cpu(x) (u16)__le16_to_cpu((u16)(x)) -#define le32_to_cpu(x) (u32)__le32_to_cpu((u32)(x)) -#define le64_to_cpu(x) (u64)__le64_to_cpu((u64)(x)) +#define le16_to_cpu(x) (u16)__le16_to_cpu((u16)(x)) +#define le32_to_cpu(x) (u32)__le32_to_cpu((u32)(x)) +#define le64_to_cpu(x) (u64)__le64_to_cpu((u64)(x)) -#define le16_to_cpup(x) (u16)__le16_to_cpu(*(const u16*)(x)) -#define le32_to_cpup(x) (u32)__le32_to_cpu(*(const u32*)(x)) -#define le64_to_cpup(x) (u64)__le64_to_cpu(*(const u64*)(x)) +#define le16_to_cpup(x) (u16)__le16_to_cpu(*(const u16*)(x)) +#define le32_to_cpup(x) (u32)__le32_to_cpu(*(const u32*)(x)) +#define le64_to_cpup(x) (u64)__le64_to_cpu(*(const u64*)(x)) /* Signed from LE to CPU conversion. */ -#define sle16_to_cpu(x) (s16)__le16_to_cpu((s16)(x)) -#define sle32_to_cpu(x) (s32)__le32_to_cpu((s32)(x)) -#define sle64_to_cpu(x) (s64)__le64_to_cpu((s64)(x)) +#define sle16_to_cpu(x) (s16)__le16_to_cpu((s16)(x)) +#define sle32_to_cpu(x) (s32)__le32_to_cpu((s32)(x)) +#define sle64_to_cpu(x) (s64)__le64_to_cpu((s64)(x)) -#define sle16_to_cpup(x) (s16)__le16_to_cpu(*(s16*)(x)) -#define sle32_to_cpup(x) (s32)__le32_to_cpu(*(s32*)(x)) -#define sle64_to_cpup(x) (s64)__le64_to_cpu(*(s64*)(x)) +#define sle16_to_cpup(x) (s16)__le16_to_cpu(*(s16*)(x)) +#define sle32_to_cpup(x) (s32)__le32_to_cpu(*(s32*)(x)) +#define sle64_to_cpup(x) (s64)__le64_to_cpu(*(s64*)(x)) /* Unsigned from CPU to LE conversion. */ -#define cpu_to_le16(x) (u16)__cpu_to_le16((u16)(x)) -#define cpu_to_le32(x) (u32)__cpu_to_le32((u32)(x)) -#define cpu_to_le64(x) (u64)__cpu_to_le64((u64)(x)) +#define cpu_to_le16(x) (u16)__cpu_to_le16((u16)(x)) +#define cpu_to_le32(x) (u32)__cpu_to_le32((u32)(x)) +#define cpu_to_le64(x) (u64)__cpu_to_le64((u64)(x)) -#define cpu_to_le16p(x) (u16)__cpu_to_le16(*(u16*)(x)) -#define cpu_to_le32p(x) (u32)__cpu_to_le32(*(u32*)(x)) -#define cpu_to_le64p(x) (u64)__cpu_to_le64(*(u64*)(x)) +#define cpu_to_le16p(x) (u16)__cpu_to_le16(*(u16*)(x)) +#define cpu_to_le32p(x) (u32)__cpu_to_le32(*(u32*)(x)) +#define cpu_to_le64p(x) (u64)__cpu_to_le64(*(u64*)(x)) /* Signed from CPU to LE conversion. */ -#define cpu_to_sle16(x) (s16)__cpu_to_le16((s16)(x)) -#define cpu_to_sle32(x) (s32)__cpu_to_le32((s32)(x)) -#define cpu_to_sle64(x) (s64)__cpu_to_le64((s64)(x)) +#define cpu_to_sle16(x) (s16)__cpu_to_le16((s16)(x)) +#define cpu_to_sle32(x) (s32)__cpu_to_le32((s32)(x)) +#define cpu_to_sle64(x) (s64)__cpu_to_le64((s64)(x)) -#define cpu_to_sle16p(x) (s16)__cpu_to_le16(*(s16*)(x)) -#define cpu_to_sle32p(x) (s32)__cpu_to_le32(*(s32*)(x)) -#define cpu_to_sle64p(x) (s64)__cpu_to_le64(*(s64*)(x)) +#define cpu_to_sle16p(x) (s16)__cpu_to_le16(*(s16*)(x)) +#define cpu_to_sle32p(x) (s32)__cpu_to_le32(*(s32*)(x)) +#define cpu_to_sle64p(x) (s64)__cpu_to_le64(*(s64*)(x)) /* Constant endianness conversion defines. */ -#define const_le16_to_cpu(x) __constant_le16_to_cpu(x) -#define const_le32_to_cpu(x) __constant_le32_to_cpu(x) -#define const_le64_to_cpu(x) __constant_le64_to_cpu(x) +#define const_le16_to_cpu(x) __constant_le16_to_cpu(x) +#define const_le32_to_cpu(x) __constant_le32_to_cpu(x) +#define const_le64_to_cpu(x) __constant_le64_to_cpu(x) -#define const_cpu_to_le16(x) __constant_cpu_to_le16(x) -#define const_cpu_to_le32(x) __constant_cpu_to_le32(x) -#define const_cpu_to_le64(x) __constant_cpu_to_le64(x) +#define const_cpu_to_le16(x) __constant_cpu_to_le16(x) +#define const_cpu_to_le32(x) __constant_cpu_to_le32(x) +#define const_cpu_to_le64(x) __constant_cpu_to_le64(x) #endif /* defined _NTFS_ENDIANS_H */ diff --git a/source/libntfs/gekko_io.c b/source/libntfs/gekko_io.c index 48ca90d4..eef1a895 100644 --- a/source/libntfs/gekko_io.c +++ b/source/libntfs/gekko_io.c @@ -66,83 +66,93 @@ #define DEV_FD(dev) ((gekko_fd *)dev->d_private) /* Prototypes */ -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 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 int ntfs_device_gekko_io_open(struct ntfs_device *dev, int flags) +static int ntfs_device_gekko_io_open( struct ntfs_device *dev, int flags ) { - ntfs_log_trace("dev %p, flags %i\n", dev, flags); + ntfs_log_trace( "dev %p, flags %i\n", dev, flags ); // Get the device driver descriptor - gekko_fd *fd = DEV_FD(dev); - if (!fd) { + gekko_fd *fd = DEV_FD( dev ); + 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()) { - ntfs_log_perror("device failed to start\n"); + if ( !interface->startup() ) + { + ntfs_log_perror( "device failed to start\n" ); errno = EIO; return -1; } - if (!interface->isInserted()) { - ntfs_log_perror("device media is not inserted\n"); + 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)) { - ntfs_log_perror("device is busy (already open)\n"); + if ( NDevOpen( dev ) ) + { + ntfs_log_perror( "device is busy (already open)\n" ); errno = EBUSY; return -1; } // 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 { - ntfs_log_perror("read failure @ sector %d\n", fd->startSector); + } + else + { + ntfs_log_perror( "read failure @ sector %d\n", fd->startSector ); errno = EIO; return -1; } // Parse the boot sector - fd->hiddenSectors = le32_to_cpu(boot.bpb.hidden_sectors); - fd->sectorSize = le16_to_cpu(boot.bpb.bytes_per_sector); - fd->sectorCount = sle64_to_cpu(boot.number_of_sectors); + fd->hiddenSectors = le32_to_cpu( boot.bpb.hidden_sectors ); + fd->sectorSize = le16_to_cpu( boot.bpb.bytes_per_sector ); + fd->sectorCount = sle64_to_cpu( boot.number_of_sectors ); fd->pos = 0; - fd->len = (fd->sectorCount * fd->sectorSize); - fd->ino = le64_to_cpu(boot.volume_serial_number); + fd->len = ( fd->sectorCount * fd->sectorSize ); + fd->ino = le64_to_cpu( boot.volume_serial_number ); // Mark the device as read-only (if required) - if (flags & O_RDONLY) { - NDevSetReadOnly(dev); + 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); - NDevSetOpen(dev); + NDevSetBlock( dev ); + NDevSetOpen( dev ); return 0; } @@ -150,43 +160,47 @@ static int ntfs_device_gekko_io_open(struct ntfs_device *dev, int flags) /** * */ -static int ntfs_device_gekko_io_close(struct ntfs_device *dev) +static int ntfs_device_gekko_io_close( struct ntfs_device *dev ) { - ntfs_log_trace("dev %p\n", dev); + ntfs_log_trace( "dev %p\n", dev ); // Get the device driver descriptor - gekko_fd *fd = DEV_FD(dev); - if (!fd) { + gekko_fd *fd = DEV_FD( dev ); + if ( !fd ) + { errno = EBADF; return -1; } // Check that the device is actually open - if (!NDevOpen(dev)) { - ntfs_log_perror("device is not open\n"); + if ( !NDevOpen( dev ) ) + { + ntfs_log_perror( "device is not open\n" ); errno = EIO; return -1; } // Mark the device as closed - NDevClearOpen(dev); - NDevClearBlock(dev); + NDevClearOpen( dev ); + NDevClearBlock( dev ); // Flush the device (if dirty and not read-only) - if (NDevDirty(dev) && !NDevReadOnly(dev)) { - ntfs_log_debug("device is dirty, will now sync\n"); + if ( NDevDirty( dev ) && !NDevReadOnly( dev ) ) + { + ntfs_log_debug( "device is dirty, will now sync\n" ); // ...? // Mark the device as clean - NDevClearDirty(dev); + NDevClearDirty( dev ); } // Flush and destroy the cache (if required) - if (fd->cache) { - _NTFS_cache_flush(fd->cache); - _NTFS_cache_destructor(fd->cache); + if ( fd->cache ) + { + _NTFS_cache_flush( fd->cache ); + _NTFS_cache_destructor( fd->cache ); } // Shutdown the device interface @@ -196,7 +210,7 @@ static int ntfs_device_gekko_io_close(struct ntfs_device *dev) }*/ // Free the device driver private data - ntfs_free(dev->d_private); + ntfs_free( dev->d_private ); dev->d_private = NULL; return 0; @@ -205,22 +219,24 @@ static int ntfs_device_gekko_io_close(struct ntfs_device *dev) /** * */ -static s64 ntfs_device_gekko_io_seek(struct ntfs_device *dev, s64 offset, int whence) +static s64 ntfs_device_gekko_io_seek( struct ntfs_device *dev, s64 offset, int whence ) { - ntfs_log_trace("dev %p, offset %Li, whence %i\n", dev, offset, whence); + ntfs_log_trace( "dev %p, offset %Li, whence %i\n", dev, offset, whence ); // Get the device driver descriptor - gekko_fd *fd = DEV_FD(dev); - if (!fd) { + gekko_fd *fd = DEV_FD( dev ); + 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; @@ -229,115 +245,123 @@ static s64 ntfs_device_gekko_io_seek(struct ntfs_device *dev, s64 offset, int wh /** * */ -static s64 ntfs_device_gekko_io_read(struct ntfs_device *dev, void *buf, s64 count) +static s64 ntfs_device_gekko_io_read( struct ntfs_device *dev, void *buf, s64 count ) { - return ntfs_device_gekko_io_readbytes(dev, DEV_FD(dev)->pos, count, buf); + return ntfs_device_gekko_io_readbytes( dev, DEV_FD( dev )->pos, count, buf ); } /** * */ -static s64 ntfs_device_gekko_io_write(struct ntfs_device *dev, const void *buf, s64 count) +static s64 ntfs_device_gekko_io_write( struct ntfs_device *dev, const void *buf, s64 count ) { - return ntfs_device_gekko_io_writebytes(dev, DEV_FD(dev)->pos, count, buf); + return ntfs_device_gekko_io_writebytes( dev, DEV_FD( dev )->pos, count, buf ); } /** * */ -static s64 ntfs_device_gekko_io_pread(struct ntfs_device *dev, void *buf, s64 count, s64 offset) +static s64 ntfs_device_gekko_io_pread( struct ntfs_device *dev, void *buf, s64 count, s64 offset ) { - return ntfs_device_gekko_io_readbytes(dev, offset, count, buf); + return ntfs_device_gekko_io_readbytes( dev, offset, count, buf ); } /** * */ -static s64 ntfs_device_gekko_io_pwrite(struct ntfs_device *dev, const void *buf, s64 count, s64 offset) +static s64 ntfs_device_gekko_io_pwrite( struct ntfs_device *dev, const void *buf, s64 count, s64 offset ) { - return ntfs_device_gekko_io_writebytes(dev, offset, count, buf); + return ntfs_device_gekko_io_writebytes( dev, offset, count, buf ); } /** * */ -static s64 ntfs_device_gekko_io_readbytes(struct ntfs_device *dev, s64 offset, s64 count, void *buf) +static s64 ntfs_device_gekko_io_readbytes( struct ntfs_device *dev, s64 offset, s64 count, void *buf ) { - ntfs_log_trace("dev %p, offset %Li, count %Li\n", dev, offset, count); + ntfs_log_trace( "dev %p, offset %Li, count %Li\n", dev, offset, count ); // Get the device driver descriptor - gekko_fd *fd = DEV_FD(dev); - if (!fd) { + gekko_fd *fd = DEV_FD( dev ); + 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) + if ( !count ) return 0; - sec_t sec_start = (sec_t) fd->startSector; + sec_t sec_start = ( sec_t ) fd->startSector; sec_t sec_count = 1; - u32 buffer_offset = (u32) (offset % fd->sectorSize); + u32 buffer_offset = ( u32 ) ( offset % fd->sectorSize ); u8 *buffer = NULL; // Determine the range of sectors required for this read - if (offset > 0) { - sec_start += (sec_t) floor((f64) offset / (f64) fd->sectorSize); + 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)) { - ntfs_log_perror("direct read failure @ sector %d (%d sector(s) long)\n", sec_start, sec_count); + 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 ) ) + { + 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; } // 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)) { - ntfs_log_perror("buffered read failure @ sector %d (%d sector(s) long)\n", sec_start, sec_count); - ntfs_free(buffer); + 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 ) ) + { + ntfs_log_perror( "buffered read failure @ sector %d (%d sector(s) long)\n", sec_start, sec_count ); + ntfs_free( buffer ); errno = EIO; return -1; } // Copy what was requested to the destination buffer - memcpy(buf, buffer + buffer_offset, count); - ntfs_free(buffer); + memcpy( buf, buffer + buffer_offset, count ); + ntfs_free( buffer ); } @@ -347,146 +371,159 @@ static s64 ntfs_device_gekko_io_readbytes(struct ntfs_device *dev, s64 offset, s /** * */ -static s64 ntfs_device_gekko_io_writebytes(struct ntfs_device *dev, s64 offset, s64 count, const void *buf) +static s64 ntfs_device_gekko_io_writebytes( struct ntfs_device *dev, s64 offset, s64 count, const void *buf ) { - ntfs_log_trace("dev %p, offset %lli, count %lli\n", dev, offset, count); + ntfs_log_trace( "dev %p, offset %lli, count %lli\n", dev, offset, count ); // Get the device driver descriptor - gekko_fd *fd = DEV_FD(dev); - if (!fd) { + gekko_fd *fd = DEV_FD( dev ); + 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) + if ( count == 0 ) return 0; - sec_t sec_start = (sec_t) fd->startSector; + sec_t sec_start = ( sec_t ) fd->startSector; sec_t sec_count = 1; - u32 buffer_offset = (u32) (offset % fd->sectorSize); + u32 buffer_offset = ( u32 ) ( offset % fd->sectorSize ); u8 *buffer = NULL; // Determine the range of sectors required for this write - if (offset > 0) { - sec_start += (sec_t) floor((f64) offset / (f64) fd->sectorSize); + 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)) { - ntfs_log_perror("direct write failure @ sector %d (%d sector(s) long)\n", sec_start, sec_count); + 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 ) ) + { + 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) { + buffer = ( u8 * ) ntfs_alloc( sec_count * fd->sectorSize ); + 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)) { - ntfs_log_perror("read failure @ sector %d\n", sec_start); - ntfs_free(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))) { - ntfs_log_perror("read failure @ sector %d\n", sec_start + sec_count - 1); - ntfs_free(buffer); + 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; return -1; } } // Copy the data into the write buffer - memcpy(buffer + buffer_offset, buf, count); + memcpy( buffer + buffer_offset, buf, count ); // 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)) { - ntfs_log_perror("buffered write failure @ sector %d\n", sec_start); - ntfs_free(buffer); + 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 ) ) + { + ntfs_log_perror( "buffered write failure @ sector %d\n", sec_start ); + ntfs_free( buffer ); errno = EIO; return -1; } // Free the buffer - ntfs_free(buffer); + ntfs_free( buffer ); } // Mark the device as dirty (if we actually wrote anything) - NDevSetDirty(dev); + NDevSetDirty( dev ); return count; } -static bool ntfs_device_gekko_io_readsectors(struct ntfs_device *dev, sec_t sector, sec_t numSectors, void* buffer) +static bool ntfs_device_gekko_io_readsectors( struct ntfs_device *dev, sec_t sector, sec_t numSectors, void* buffer ) { // Get the device driver descriptor - gekko_fd *fd = DEV_FD(dev); - if (!fd) { + gekko_fd *fd = DEV_FD( dev ); + 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); + if ( fd->cache ) + return _NTFS_cache_readSectors( fd->cache, sector, numSectors, buffer ); else - return fd->interface->readSectors(sector, numSectors, buffer); + 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) { + gekko_fd *fd = DEV_FD( dev ); + if ( !fd ) + { errno = EBADF; return false; } // Write the sectors to disc (or cache, if enabled) - if (fd->cache) - return _NTFS_cache_writeSectors(fd->cache, sector, numSectors, buffer); + if ( fd->cache ) + return _NTFS_cache_writeSectors( fd->cache, sector, numSectors, buffer ); else - return fd->interface->writeSectors(sector, numSectors, buffer); + return fd->interface->writeSectors( sector, numSectors, buffer ); return false; } @@ -494,23 +531,26 @@ 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) +static int ntfs_device_gekko_io_sync( struct ntfs_device *dev ) { - gekko_fd *fd = DEV_FD(dev); - ntfs_log_trace("dev %p\n", 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; } // Mark the device as clean - NDevClearDirty(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; } @@ -522,28 +562,29 @@ static int ntfs_device_gekko_io_sync(struct ntfs_device *dev) /** * */ -static int ntfs_device_gekko_io_stat(struct ntfs_device *dev, struct stat *buf) +static int ntfs_device_gekko_io_stat( struct ntfs_device *dev, struct stat *buf ) { - ntfs_log_trace("dev %p, buf %p\n", dev, buf); + ntfs_log_trace( "dev %p, buf %p\n", dev, buf ); // Get the device driver descriptor - gekko_fd *fd = DEV_FD(dev); - if (!fd) { + gekko_fd *fd = DEV_FD( dev ); + if ( !fd ) + { errno = EBADF; return -1; } // Short circuit cases were we don't actually have to do anything - if (!buf) + 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)); + memset( buf, 0, sizeof( struct stat ) ); // Build the device stats buf->st_dev = fd->interface->ioType; @@ -559,71 +600,79 @@ static int ntfs_device_gekko_io_stat(struct ntfs_device *dev, struct stat *buf) /** * */ -static int ntfs_device_gekko_io_ioctl(struct ntfs_device *dev, int request, void *argp) +static int ntfs_device_gekko_io_ioctl( struct ntfs_device *dev, int request, void *argp ) { - ntfs_log_trace("dev %p, request %i, argp %p\n", dev, request, argp); + ntfs_log_trace( "dev %p, request %i, argp %p\n", dev, request, argp ); // Get the device driver descriptor - gekko_fd *fd = DEV_FD(dev); - if (!fd) { + gekko_fd *fd = DEV_FD( dev ); + 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: { - *(u32*)argp = fd->sectorCount; - return 0; - } - #endif + // Get block device size (sectors) +#if defined(BLKGETSIZE) + case BLKGETSIZE: + { + *( u32* )argp = fd->sectorCount; + return 0; + } +#endif - // Get block device size (bytes) - #if defined(BLKGETSIZE64) - case BLKGETSIZE64: { - *(u64*)argp = (fd->sectorCount * fd->sectorSize); - return 0; - } - #endif + // Get block device size (bytes) +#if defined(BLKGETSIZE64) + case BLKGETSIZE64: + { + *( u64* )argp = ( fd->sectorCount * fd->sectorSize ); + return 0; + } +#endif - // Get hard drive geometry - #if defined(HDIO_GETGEO) - case HDIO_GETGEO: { - struct hd_geometry *geo = (struct hd_geometry*)argp; - geo->sectors = 0; - geo->heads = 0; - geo->cylinders = 0; - geo->start = fd->hiddenSectors; - return -1; - } - #endif + // Get hard drive geometry +#if defined(HDIO_GETGEO) + case HDIO_GETGEO: + { + struct hd_geometry *geo = ( struct hd_geometry* )argp; + geo->sectors = 0; + geo->heads = 0; + geo->cylinders = 0; + geo->start = fd->hiddenSectors; + return -1; + } +#endif - // Get block device sector size (bytes) - #if defined(BLKSSZGET) - case BLKSSZGET: { - *(int*)argp = fd->sectorSize; - return 0; - } - #endif + // Get block device sector size (bytes) +#if defined(BLKSSZGET) + case BLKSSZGET: + { + *( int* )argp = fd->sectorSize; + return 0; + } +#endif - // Set block device block size (bytes) - #if defined(BLKBSZSET) - case BLKBSZSET: { - int sectorSize = *(int*)argp; - fd->sectorSize = sectorSize; - return 0; - } - #endif + // Set block device block size (bytes) +#if defined(BLKBSZSET) + case BLKBSZSET: + { + int sectorSize = *( int* )argp; + fd->sectorSize = sectorSize; + return 0; + } +#endif - // Unimplemented ioctrl - default: { - ntfs_log_perror("Unimplemented ioctrl %i\n", request); - errno = EOPNOTSUPP; - return -1; - } + // Unimplemented ioctrl + default: + { + ntfs_log_perror( "Unimplemented ioctrl %i\n", request ); + errno = EOPNOTSUPP; + return -1; + } } @@ -633,7 +682,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 = { +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, diff --git a/source/libntfs/gekko_io.h b/source/libntfs/gekko_io.h index d5018e89..9a288794 100644 --- a/source/libntfs/gekko_io.h +++ b/source/libntfs/gekko_io.h @@ -33,7 +33,8 @@ /** * gekko_fd - Gekko device driver descriptor */ -typedef struct _gekko_fd { +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) */ diff --git a/source/libntfs/index.c b/source/libntfs/index.c index 7df0deec..693c51a7 100644 --- a/source/libntfs/index.c +++ b/source/libntfs/index.c @@ -50,7 +50,7 @@ /** * ntfs_index_entry_mark_dirty - mark an index entry dirty - * @ictx: ntfs index context describing the index entry + * @ictx: ntfs index context describing the index entry * * Mark the index entry described by the index entry context @ictx dirty. * @@ -62,418 +62,433 @@ * attribute, set ib_dirty to TRUE, thus index block will be updated during * ntfs_index_ctx_put. */ -void ntfs_index_entry_mark_dirty(ntfs_index_context *ictx) +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) +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) +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) +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) +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; } /** * ntfs_index_ctx_get - allocate and initialize a new index context - * @ni: ntfs inode with which to initialize the context - * @name: name of the which context describes - * @name_len: length of the index name + * @ni: ntfs inode with which to initialize the context + * @name: name of the which context describes + * @name_len: length of the index name * * 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) +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 ); } /** * ntfs_index_ctx_put - release an index context - * @icx: index context to free + * @icx: index context to free * * Release the index context @icx, releasing all associated resources. */ -void ntfs_index_ctx_put(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 ); } /** * ntfs_index_ctx_reinit - reinitialize an index context - * @icx: index context to reinitialize + * @icx: index context to reinitialize * * Reinitialize the index context @icx so it can be used for ntfs_index_lookup. */ -void ntfs_index_ctx_reinit(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) +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 ) ); } /** * Get the subnode vcn to which the index entry refers. */ -VCN ntfs_ie_get_vcn(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) +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) +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) +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) +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; } -/** +/** * Find the last entry in the index block */ -static INDEX_ENTRY *ntfs_ie_get_last(INDEX_ENTRY *ie, char *ies_end) +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) +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) +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) +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) +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) +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) +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) +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) +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) +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) +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 ); } /** * Insert @ie index entry at @pos entry. Used @ih values should be ok already. */ -static void ntfs_ie_insert(INDEX_HEADER *ih, INDEX_ENTRY *ie, INDEX_ENTRY *pos) +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) +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) +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) +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)); + ntfs_log_trace( "Entering\n" ); + + *ctx = ntfs_attr_get_search_ctx( ni, NULL ); + if ( !*ctx ) + return NULL; + + if ( ntfs_attr_lookup( AT_INDEX_ROOT, name, name_len, CASE_SENSITIVE, + 0, NULL, 0, *ctx ) ) + { + ntfs_log_perror( "Failed to lookup $INDEX_ROOT" ); + goto err_out; + } + + a = ( *ctx )->attr; + if ( a->non_resident ) + { + errno = EINVAL; + ntfs_log_perror( "Non-resident $INDEX_ROOT detected" ); + goto err_out; + } + + ir = ( INDEX_ROOT * )( ( char * )a + le16_to_cpu( a->value_offset ) ); err_out: - if (!ir) { - ntfs_attr_put_search_ctx(*ctx); - *ctx = NULL; - } - return ir; + if ( !ir ) + { + ntfs_attr_put_search_ctx( *ctx ); + *ctx = NULL; + } + return ir; } -static INDEX_ROOT *ntfs_ir_lookup2(ntfs_inode *ni, ntfschar *name, u32 len) +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; } -/** +/** * Find a key in the index block. - * + * * Return values: - * STATUS_OK with errno set to ESUCCESS if we know for sure that the + * STATUS_OK with errno set to ESUCCESS if we know for sure that the * entry exists and @ie_out points to this entry. * STATUS_NOT_FOUND with errno set to ENOENT if we know for sure the * entry doesn't exist and @ie_out is the insertion point. @@ -481,164 +496,175 @@ 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) +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) +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 " - "%lld\n", (long long)pos); - return -1; - } - - if (ntfs_ia_check(icx, dst, vcn)) - return -1; - - return 0; + 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; } -static int ntfs_icx_parent_inc(ntfs_index_context *icx) +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) +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 - * @key_len: [IN] length of @key in bytes - * @icx: [IN/OUT] context describing the index and the returned entry + * @key: [IN] key for which to search in the index + * @key_len: [IN] length of @key in bytes + * @icx: [IN/OUT] context describing the index and the returned entry * * Before calling ntfs_index_lookup(), @icx must have been obtained from a * call to ntfs_index_ctx_get(). @@ -666,1206 +692,1266 @@ static int ntfs_icx_parent_dec(ntfs_index_context *icx) * the call to ntfs_index_ctx_put() to ensure that the changes are written * to disk. */ -int ntfs_index_lookup(const void *key, const int key_len, ntfs_index_context *icx) +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; + } + + ir = ntfs_ir_lookup( ni, icx->name, icx->name_len, &icx->actx ); + if ( !ir ) + { + if ( errno == ENOENT ) + errno = EIO; + return -1; + } + + icx->block_size = le32_to_cpu( ir->index_block_size ); + if ( icx->block_size < NTFS_BLOCK_SIZE ) + { + errno = EINVAL; + ntfs_log_perror( "Index block size (%d) is smaller than the " + "sector size (%d)", icx->block_size, NTFS_BLOCK_SIZE ); + goto err_out; + } + + if ( ni->vol->cluster_size <= icx->block_size ) + icx->vcn_size_bits = ni->vol->cluster_size_bits; + else + icx->vcn_size_bits = ni->vol->sector_size_bits; + /* 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; + } - 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: - icx->parent_vcn[icx->pindex] = old_vcn; - if (ntfs_icx_parent_inc(icx)) { - err = errno; - goto err_out; - } - old_vcn = vcn; + icx->parent_vcn[icx->pindex] = old_vcn; + if ( ntfs_icx_parent_inc( icx ) ) + { + err = errno; + goto err_out; + } + old_vcn = vcn; - ntfs_log_debug("Descend into node with VCN %lld\n", (long long)vcn); - - 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; - } + ntfs_log_debug( "Descend into node with VCN %lld\n", ( long long )vcn ); - if ((ib->index.ih_flags & NODE_MASK) == LEAF_NODE) { - ntfs_log_error("Index entry with child node found in a leaf " - "node in inode 0x%llx.\n", - (unsigned long long)ni->mft_no); - goto err_out; - } - - goto descend_into_child_node; + if ( 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; + free( ib ); + if ( !err ) + err = EIO; + errno = err; + return -1; done: - icx->entry = ie; - icx->data = (u8 *)ie + offsetof(INDEX_ENTRY, key); - icx->data_len = le16_to_cpu(ie->key_length); - ntfs_log_trace("Done.\n"); - if (err) { - errno = err; - return -1; - } - return 0; + icx->entry = ie; + icx->data = ( u8 * )ie + offsetof( INDEX_ENTRY, key ); + icx->data_len = le16_to_cpu( ie->key_length ); + ntfs_log_trace( "Done.\n" ); + if ( err ) + { + errno = err; + return -1; + } + return 0; } -static INDEX_BLOCK *ntfs_ib_alloc(VCN ib_vcn, u32 ib_size, - INDEX_HEADER_FLAGS node_type) +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) +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) +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) +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) +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) +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; + 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; + ntfs_attr_close( na ); + return ret; } -static int ntfs_ibm_set(ntfs_index_context *icx, VCN vcn) +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) +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) +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; -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; -} + for ( byte = 0; byte < size; byte++ ) + { -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; - } -} + if ( bm[byte] == 255 ) + continue; -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); + for ( bit = 0; bit < 8; bit++ ) + { + if ( !( bm[byte] & ( 1 << bit ) ) ) + { + vcn = ntfs_ibm_pos_to_vcn( icx, byte * 8 + bit ); + goto out; + } + } + } - free(dst); - return ret; -} - -static int ntfs_ib_cut_tail(ntfs_index_context *icx, INDEX_BLOCK *ib, - INDEX_ENTRY *ie) -{ - char *ies_start, *ies_end; - INDEX_ENTRY *ie_last; - - 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"); - - if (ntfs_ibm_add(icx)) - return -1; - - if (!ntfs_attr_exist(icx->ni, AT_INDEX_ALLOCATION, icx->name, icx->name_len)) { - - if (ntfs_attr_add(icx->ni, AT_INDEX_ALLOCATION, icx->name, - icx->name_len, NULL, 0)) { - ntfs_log_perror("Failed to add AT_INDEX_ALLOCATION"); - return -1; - } - } - - icx->ia_na = ntfs_ia_open(icx, icx->ni); - if (!icx->ia_na) - return -1; - - return 0; -} - -static int ntfs_ir_reparent(ntfs_index_context *icx) -{ - ntfs_attr_search_ctx *ctx = NULL; - INDEX_ROOT *ir; - INDEX_ENTRY *ie; - INDEX_BLOCK *ib = NULL; - VCN new_ib_vcn; - int ret = STATUS_ERROR; - - ntfs_log_trace("Entering\n"); - - ir = ntfs_ir_lookup2(icx->ni, icx->name, icx->name_len); - if (!ir) - goto out; - - if ((ir->index.ih_flags & NODE_MASK) == SMALL_INDEX) - if (ntfs_ia_add(icx)) - goto out; - - new_ib_vcn = ntfs_ibm_get_free(icx); - if (new_ib_vcn == -1) - goto out; - - ir = ntfs_ir_lookup2(icx->ni, icx->name, icx->name_len); - if (!ir) - goto clear_bmp; - - ib = ntfs_ir_to_ib(ir, new_ib_vcn); - if (ib == NULL) { - ntfs_log_perror("Failed to move index root to index block"); - goto clear_bmp; - } - - if (ntfs_ib_write(icx, ib)) - goto clear_bmp; - - ir = ntfs_ir_lookup(icx->ni, icx->name, icx->name_len, &ctx); - if (!ir) - goto clear_bmp; - - ntfs_ir_nill(ir); - - ie = ntfs_ie_get_first(&ir->index); - ie->ie_flags |= INDEX_ENTRY_NODE; - ie->length = cpu_to_le16(sizeof(INDEX_ENTRY_HEADER) + sizeof(VCN)); - - ir->index.ih_flags = LARGE_INDEX; - ir->index.index_length = cpu_to_le32(le32_to_cpu(ir->index.entries_offset) - + le16_to_cpu(ie->length)); - ir->index.allocated_size = ir->index.index_length; - - if (ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr, - sizeof(INDEX_ROOT) - sizeof(INDEX_HEADER) + - le32_to_cpu(ir->index.allocated_size))) - /* FIXME: revert index root */ - goto clear_bmp; - /* - * FIXME: do it earlier if we have enough space in IR (should always), - * so in error case we wouldn't lose the IB. - */ - ntfs_ie_set_vcn(ie, new_ib_vcn); - - ret = STATUS_OK; -err_out: - free(ib); - ntfs_attr_put_search_ctx(ctx); + vcn = ntfs_ibm_pos_to_vcn( icx, size * 8 ); out: - return ret; + 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; +} + +static void ntfs_ir_nill( INDEX_ROOT *ir ) +{ + INDEX_ENTRY *ie_last; + char *ies_start, *ies_end; + + ntfs_log_trace( "Entering\n" ); + /* + * TODO: This function could be much simpler. + */ + ies_start = ( char * )ntfs_ie_get_first( &ir->index ); + ies_end = ( char * )ntfs_ie_get_end( &ir->index ); + ie_last = ntfs_ie_get_last( ( INDEX_ENTRY * )ies_start, ies_end ); + /* + * Move the index root termination entry forward + */ + if ( ( char * )ie_last > ies_start ) + { + memmove( ies_start, ( char * )ie_last, le16_to_cpu( ie_last->length ) ); + ie_last = ( INDEX_ENTRY * )ies_start; + } +} + +static int ntfs_ib_copy_tail( ntfs_index_context *icx, INDEX_BLOCK *src, + INDEX_ENTRY *median, VCN new_vcn ) +{ + u8 *ies_end; + INDEX_ENTRY *ie_head; /* first entry after the median */ + int tail_size, ret; + INDEX_BLOCK *dst; + + 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 ) +{ + 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" ); + + if ( ntfs_ibm_add( icx ) ) + return -1; + + if ( !ntfs_attr_exist( icx->ni, AT_INDEX_ALLOCATION, icx->name, icx->name_len ) ) + { + + if ( ntfs_attr_add( icx->ni, AT_INDEX_ALLOCATION, icx->name, + icx->name_len, NULL, 0 ) ) + { + ntfs_log_perror( "Failed to add AT_INDEX_ALLOCATION" ); + return -1; + } + } + + icx->ia_na = ntfs_ia_open( icx, icx->ni ); + if ( !icx->ia_na ) + return -1; + + return 0; +} + +static int ntfs_ir_reparent( ntfs_index_context *icx ) +{ + ntfs_attr_search_ctx *ctx = NULL; + INDEX_ROOT *ir; + INDEX_ENTRY *ie; + INDEX_BLOCK *ib = NULL; + VCN new_ib_vcn; + int ret = STATUS_ERROR; + + ntfs_log_trace( "Entering\n" ); + + ir = ntfs_ir_lookup2( icx->ni, icx->name, icx->name_len ); + if ( !ir ) + goto out; + + if ( ( ir->index.ih_flags & NODE_MASK ) == SMALL_INDEX ) + if ( ntfs_ia_add( icx ) ) + goto out; + + new_ib_vcn = ntfs_ibm_get_free( icx ); + if ( new_ib_vcn == -1 ) + goto out; + + ir = ntfs_ir_lookup2( icx->ni, icx->name, icx->name_len ); + if ( !ir ) + goto clear_bmp; + + ib = ntfs_ir_to_ib( ir, new_ib_vcn ); + if ( ib == NULL ) + { + ntfs_log_perror( "Failed to move index root to index block" ); + goto clear_bmp; + } + + if ( ntfs_ib_write( icx, ib ) ) + goto clear_bmp; + + ir = ntfs_ir_lookup( icx->ni, icx->name, icx->name_len, &ctx ); + if ( !ir ) + goto clear_bmp; + + ntfs_ir_nill( ir ); + + ie = ntfs_ie_get_first( &ir->index ); + ie->ie_flags |= INDEX_ENTRY_NODE; + ie->length = cpu_to_le16( sizeof( INDEX_ENTRY_HEADER ) + sizeof( VCN ) ); + + ir->index.ih_flags = LARGE_INDEX; + ir->index.index_length = cpu_to_le32( le32_to_cpu( ir->index.entries_offset ) + + le16_to_cpu( ie->length ) ); + ir->index.allocated_size = ir->index.index_length; + + if ( ntfs_resident_attr_value_resize( ctx->mrec, ctx->attr, + sizeof( INDEX_ROOT ) - sizeof( INDEX_HEADER ) + + le32_to_cpu( ir->index.allocated_size ) ) ) + /* FIXME: revert index root */ + goto clear_bmp; + /* + * FIXME: do it earlier if we have enough space in IR (should always), + * so in error case we wouldn't lose the IB. + */ + ntfs_ie_set_vcn( ie, new_ib_vcn ); + + ret = STATUS_OK; +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_ibm_clear( icx, new_ib_vcn ); + goto err_out; } /** * ntfs_ir_truncate - Truncate index root attribute - * + * * Returns STATUS_OK, STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT or STATUS_ERROR. */ -static int ntfs_ir_truncate(ntfs_index_context *icx, int data_size) -{ - ntfs_attr *na; - int ret; +static int ntfs_ir_truncate( ntfs_index_context *icx, int data_size ) +{ + ntfs_attr *na; + int ret; - ntfs_log_trace("Entering\n"); - - na = ntfs_attr_open(icx->ni, AT_INDEX_ROOT, icx->name, icx->name_len); - if (!na) { - ntfs_log_perror("Failed to open INDEX_ROOT"); - return STATUS_ERROR; - } - /* - * INDEX_ROOT must be resident and its entries can be moved to - * INDEX_BLOCK, so ENOSPC isn't a real error. - */ - ret = ntfs_attr_truncate(na, data_size + offsetof(INDEX_ROOT, index)); - if (ret == STATUS_OK) { - - icx->ir = ntfs_ir_lookup2(icx->ni, icx->name, icx->name_len); - if (!icx->ir) - return STATUS_ERROR; - - icx->ir->index.allocated_size = cpu_to_le32(data_size); - - } else if (ret == STATUS_ERROR) - ntfs_log_perror("Failed to truncate INDEX_ROOT"); - - ntfs_attr_close(na); - return ret; + ntfs_log_trace( "Entering\n" ); + + na = ntfs_attr_open( icx->ni, AT_INDEX_ROOT, icx->name, icx->name_len ); + if ( !na ) + { + ntfs_log_perror( "Failed to open INDEX_ROOT" ); + return STATUS_ERROR; + } + /* + * INDEX_ROOT must be resident and its entries can be moved to + * INDEX_BLOCK, so ENOSPC isn't a real error. + */ + ret = ntfs_attr_truncate( na, data_size + offsetof( INDEX_ROOT, index ) ); + if ( ret == STATUS_OK ) + { + + icx->ir = ntfs_ir_lookup2( icx->ni, icx->name, icx->name_len ); + if ( !icx->ir ) + return STATUS_ERROR; + + icx->ir->index.allocated_size = cpu_to_le32( data_size ); + + } + else if ( ret == STATUS_ERROR ) + ntfs_log_perror( "Failed to truncate INDEX_ROOT" ); + + ntfs_attr_close( na ); + return ret; } - + /** * ntfs_ir_make_space - Make more space for the index root attribute - * + * * On success return STATUS_OK or STATUS_KEEP_SEARCHING. * On error return STATUS_ERROR. */ -static int ntfs_ir_make_space(ntfs_index_context *icx, int data_size) -{ - int ret; +static int ntfs_ir_make_space( ntfs_index_context *icx, int data_size ) +{ + int ret; - ntfs_log_trace("Entering\n"); + ntfs_log_trace( "Entering\n" ); - ret = ntfs_ir_truncate(icx, data_size); - if (ret == STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT) { - - ret = ntfs_ir_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; } /* * NOTE: 'ie' must be a copy of a real index entry. */ -static int ntfs_ie_add_vcn(INDEX_ENTRY **ie) +static int ntfs_ie_add_vcn( INDEX_ENTRY **ie ) { - INDEX_ENTRY *p, *old = *ie; - - old->length = cpu_to_le16(le16_to_cpu(old->length) + sizeof(VCN)); - p = realloc(old, le16_to_cpu(old->length)); - if (!p) - return STATUS_ERROR; - - p->ie_flags |= INDEX_ENTRY_NODE; - *ie = p; + 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) +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) +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); +static int ntfs_ib_split( ntfs_index_context *icx, INDEX_BLOCK *ib ); /** * On success return STATUS_OK or STATUS_KEEP_SEARCHING. * On error return STATUS_ERROR. */ -static int ntfs_ib_insert(ntfs_index_context *icx, INDEX_ENTRY *ie, VCN new_vcn) -{ - INDEX_BLOCK *ib; - u32 idx_size, allocated_size; - int err = STATUS_ERROR; - VCN old_vcn; +static int ntfs_ib_insert( ntfs_index_context *icx, INDEX_ENTRY *ie, VCN new_vcn ) +{ + INDEX_BLOCK *ib; + u32 idx_size, allocated_size; + int err = STATUS_ERROR; + VCN old_vcn; - ntfs_log_trace("Entering\n"); - - 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; } /** * ntfs_ib_split - Split an index block - * + * * On success return STATUS_OK or STATUS_KEEP_SEARCHING. * On error return is STATUS_ERROR. */ -static int ntfs_ib_split(ntfs_index_context *icx, INDEX_BLOCK *ib) -{ - INDEX_ENTRY *median; - VCN new_vcn; - int ret; +static int ntfs_ib_split( ntfs_index_context *icx, INDEX_BLOCK *ib ) +{ + INDEX_ENTRY *median; + VCN new_vcn; + int ret; - ntfs_log_trace("Entering\n"); - - if (ntfs_icx_parent_dec(icx)) - return STATUS_ERROR; - - median = ntfs_ie_get_median(&ib->index); - new_vcn = ntfs_ibm_get_free(icx); - if (new_vcn == -1) - return STATUS_ERROR; - - if (ntfs_ib_copy_tail(icx, ib, median, new_vcn)) { - ntfs_ibm_clear(icx, new_vcn); - return STATUS_ERROR; - } - - if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) - ret = ntfs_ir_insert_median(icx, median, new_vcn); - else - ret = ntfs_ib_insert(icx, median, new_vcn); - - if (ret != STATUS_OK) { - ntfs_ibm_clear(icx, new_vcn); - return ret; - } - - ret = ntfs_ib_cut_tail(icx, ib, median); - - return ret; + ntfs_log_trace( "Entering\n" ); + + if ( ntfs_icx_parent_dec( icx ) ) + return STATUS_ERROR; + + median = ntfs_ie_get_median( &ib->index ); + new_vcn = ntfs_ibm_get_free( icx ); + if ( new_vcn == -1 ) + return STATUS_ERROR; + + if ( ntfs_ib_copy_tail( icx, ib, median, new_vcn ) ) + { + ntfs_ibm_clear( icx, new_vcn ); + return STATUS_ERROR; + } + + if ( ntfs_icx_parent_vcn( icx ) == VCN_INDEX_ROOT_PARENT ) + ret = ntfs_ir_insert_median( icx, median, new_vcn ); + else + ret = ntfs_ib_insert( icx, median, new_vcn ); + + if ( ret != STATUS_OK ) + { + ntfs_ibm_clear( icx, new_vcn ); + return ret; + } + + ret = ntfs_ib_cut_tail( icx, ib, median ); + + return ret; } /* JPA static */ -int ntfs_ie_add(ntfs_index_context *icx, INDEX_ENTRY *ie) +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; + + while ( 1 ) + { + + if ( !ntfs_index_lookup( &ie->key, le16_to_cpu( ie->key_length ), icx ) ) + { + errno = EEXIST; + ntfs_log_perror( "Index already have such entry" ); + goto err_out; + } + if ( errno != ENOENT ) + { + ntfs_log_perror( "Failed to find place for new entry" ); + goto err_out; + } + + if ( icx->is_in_root ) + ih = &icx->ir->index; + else + ih = &icx->ib->index; + + allocated_size = le32_to_cpu( ih->allocated_size ); + new_size = le32_to_cpu( ih->index_length ) + le16_to_cpu( ie->length ); + + if ( new_size <= allocated_size ) + break; + + ntfs_log_trace( "index block sizes: allocated: %d needed: %d\n", + allocated_size, new_size ); + + if ( icx->is_in_root ) + { + if ( ntfs_ir_make_space( icx, new_size ) == STATUS_ERROR ) + goto err_out; + } + else + { + if ( ntfs_ib_split( icx, icx->ib ) == STATUS_ERROR ) + goto err_out; + } + + ntfs_inode_mark_dirty( icx->actx->ntfs_ino ); + ntfs_index_ctx_reinit( icx ); + } + + ntfs_ie_insert( ih, ie, icx->entry ); + ntfs_index_entry_mark_dirty( icx ); + + ret = STATUS_OK; err_out: - ntfs_log_trace("%s\n", ret ? "Failed" : "Done"); - return ret; + ntfs_log_trace( "%s\n", ret ? "Failed" : "Done" ); + return ret; } /** * ntfs_index_add_filename - add filename to directory index - * @ni: ntfs inode describing directory to which index add filename - * @fn: FILE_NAME attribute to add - * @mref: reference of the inode which @fn describes + * @ni: ntfs inode describing directory to which index add filename + * @fn: FILE_NAME attribute to add + * @mref: reference of the inode which @fn describes * * Return 0 on success or -1 on error with errno set to the error code. */ -int ntfs_index_add_filename(ntfs_inode *ni, FILE_NAME_ATTR *fn, MFT_REF mref) +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; + 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; + 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); + 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; + free( ie_roam ); + return ret; } /** * Used if an empty index block to be deleted has END entry as the parent * in the INDEX_ROOT which is the only one there. */ -static void ntfs_ir_leafify(ntfs_index_context *icx, INDEX_HEADER *ih) +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 + * 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) +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; + 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; + free( ib ); + return ret; } -static int ntfs_index_rm_node(ntfs_index_context *icx) +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; + if ( !icx->ia_na ) + { + icx->ia_na = ntfs_ia_open( icx, icx->ni ); + if ( !icx->ia_na ) + return STATUS_ERROR; + } + + ib = ntfs_malloc( icx->block_size ); + if ( !ib ) + return STATUS_ERROR; + + ie_succ = ntfs_ie_get_next( icx->entry ); + entry_pos = icx->parent_pos[icx->pindex]++; + pindex = icx->pindex; 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); + vcn = ntfs_ie_get_vcn( ie_succ ); + if ( ntfs_ib_read( icx, vcn, ib ) ) + goto out; - if (ntfs_icx_parent_inc(icx)) - goto out; - - icx->parent_vcn[icx->pindex] = vcn; - icx->parent_pos[icx->pindex] = 0; + ie_succ = ntfs_ie_get_first( &ib->index ); - if ((ib->index.ih_flags & NODE_MASK) == INDEX_NODE) - goto descend; + if ( ntfs_icx_parent_inc( icx ) ) + goto out; - if (ntfs_ih_zero_entry(&ib->index)) { - errno = EIO; - ntfs_log_perror("Empty index block"); - goto out; - } + icx->parent_vcn[icx->pindex] = vcn; + icx->parent_pos[icx->pindex] = 0; - ie = ntfs_ie_dup(ie_succ); - if (!ie) - goto out; - - if (ntfs_ie_add_vcn(&ie)) - goto out2; + if ( ( ib->index.ih_flags & NODE_MASK ) == INDEX_NODE ) + goto descend; - ntfs_ie_set_vcn(ie, ntfs_ie_get_vcn(icx->entry)); + if ( ntfs_ih_zero_entry( &ib->index ) ) + { + errno = EIO; + ntfs_log_perror( "Empty index block" ); + goto out; + } - if (icx->is_in_root) - ih = &icx->ir->index; - else - ih = &icx->ib->index; + ie = ntfs_ie_dup( ie_succ ); + if ( !ie ) + goto out; - 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_ie_add_vcn( &ie ) ) + 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; + ntfs_ie_set_vcn( ie, ntfs_ie_get_vcn( icx->entry ) ); - ret = STATUS_OK; + 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); + free( ie ); out: - free(ib); - return ret; + free( ib ); + return ret; } /** * ntfs_index_rm - remove entry from the index - * @icx: index context describing entry to delete + * @icx: index context describing entry to delete * - * Delete entry described by @icx from the index. Index context is always - * reinitialized after use of this function, so it can be used for index + * Delete entry described by @icx from the index. Index context is always + * reinitialized after use of this function, so it can be used for index * lookup once again. * * Return 0 on success or -1 on error with errno set to the error code. */ /*static JPA*/ -int ntfs_index_rm(ntfs_index_context *icx) +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; - } + 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; + return ret; err_out: - ret = STATUS_ERROR; - goto out; + ret = STATUS_ERROR; + goto out; } -int ntfs_index_remove(ntfs_inode *dir_ni, ntfs_inode *ni, - const void *key, const int keylen) +int 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; + 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; + ret = STATUS_ERROR; + ntfs_log_perror( "Delete failed" ); + goto out; } /** * ntfs_index_root_get - read the index root of an attribute - * @ni: open ntfs inode in which the ntfs attribute resides - * @attr: attribute for which we want its index root + * @ni: open ntfs inode in which the ntfs attribute resides + * @attr: attribute for which we want its index root * * This function will read the related index root an ntfs attribute. * @@ -1874,129 +1960,145 @@ err_out: * * On error NULL is returned with errno set to the error code. */ -INDEX_ROOT *ntfs_index_root_get(ntfs_inode *ni, ATTR_RECORD *attr) +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 + * 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 ); } /* - * Walk up the index tree (root bound) - * until there is a valid data entry in parent - * returns the parent entry or NULL if no more parent + * Walk up the index tree (root bound) + * until there is a valid data entry in parent + * 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 ); } /* - * Get next entry in an index according to collating sequence. - * Must be initialized through a ntfs_index_lookup() + * Get next entry in an index according to collating sequence. + * Must be initialized through a ntfs_index_lookup() * - * Returns next entry or NULL if none + * Returns next entry or NULL if none * - * Sample layout : + * Sample layout : * * +---+---+---+---+---+---+---+---+ n ptrs to subnodes * | | | 10| 25| 33| | | | n-1 keys in between @@ -2017,47 +2119,52 @@ static INDEX_ENTRY *ntfs_index_walk_up(INDEX_ENTRY *ie, * +---+---+---+---+---+---+---+---+ */ -INDEX_ENTRY *ntfs_index_next(INDEX_ENTRY *ie, ntfs_index_context *ictx) +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..3a8725df 100644 --- a/source/libntfs/index.h +++ b/source/libntfs/index.h @@ -31,7 +31,7 @@ * ... code requiring gcc 2.8 or later ... * #endif * Note - they won't work for gcc1 or glibc1, since the _MINOR macros - * were not defined then. + * were not defined then. */ #ifndef __GNUC_PREREQ @@ -61,31 +61,31 @@ #define VCN_INDEX_ROOT_PARENT ((VCN)-2) -#define MAX_PARENT_VCN 32 +#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 - - * @ni: inode containing the @entry described by this context - * @name: name of the index described by this context - * @name_len: length of the index name - * @entry: index entry (points into @ir or @ia) - * @data: index entry data (points into @entry) - * @data_len: length in bytes of @data - * @is_in_root: TRUE if @entry is in @ir or FALSE if it is in @ia - * @ir: index root if @is_in_root or NULL otherwise - * @actx: attribute search context if in root or NULL otherwise - * @ia: index block if @is_in_root is FALSE or NULL otherwise - * @ia_na: opened INDEX_ALLOCATION attribute - * @parent_pos: parent entries' positions in the index block - * @parent_vcn: entry's parent node or VCN_INDEX_ROOT_PARENT + * @ni: inode containing the @entry described by this context + * @name: name of the index described by this context + * @name_len: length of the index name + * @entry: index entry (points into @ir or @ia) + * @data: index entry data (points into @entry) + * @data_len: length in bytes of @data + * @is_in_root: TRUE if @entry is in @ir or FALSE if it is in @ia + * @ir: index root if @is_in_root or NULL otherwise + * @actx: attribute search context if in root or NULL otherwise + * @ia: index block if @is_in_root is FALSE or NULL otherwise + * @ia_na: opened INDEX_ALLOCATION attribute + * @parent_pos: parent entries' positions in the index block + * @parent_vcn: entry's parent node or VCN_INDEX_ROOT_PARENT * @new_vcn: new VCN if we need to create a new index block - * @median: move to the parent if splitting index blocks - * @ib_dirty: TRUE if index block was changed - * @block_size: index block size - * @vcn_size_bits: VCN size bits for this index block + * @median: move to the parent if splitting index blocks + * @ib_dirty: TRUE if index block was changed + * @block_size: index block size + * @vcn_size_bits: VCN size bits for this index block * * @ni is the inode this context belongs to. * @@ -112,56 +112,57 @@ 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 void ntfs_index_ctx_put(ntfs_index_context *ictx); -extern void ntfs_index_ctx_reinit(ntfs_index_context *ictx); +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); +extern INDEX_ROOT *ntfs_index_root_get( ntfs_inode *ni, ATTR_RECORD *attr ); -extern VCN ntfs_ie_get_vcn(INDEX_ENTRY *ie); +extern VCN ntfs_ie_get_vcn( INDEX_ENTRY *ie ); -extern void ntfs_index_entry_mark_dirty(ntfs_index_context *ictx); +extern void ntfs_index_entry_mark_dirty( ntfs_index_context *ictx ); -extern char *ntfs_ie_filename_get(INDEX_ENTRY *ie); -extern void ntfs_ie_filename_dump(INDEX_ENTRY *ie); -extern void ntfs_ih_filename_dump(INDEX_HEADER *ih); +extern char *ntfs_ie_filename_get( INDEX_ENTRY *ie ); +extern void ntfs_ie_filename_dump( INDEX_ENTRY *ie ); +extern void ntfs_ih_filename_dump( INDEX_HEADER *ih ); /* the following was added by JPA for use in security.c */ -extern int ntfs_ie_add(ntfs_index_context *icx, INDEX_ENTRY *ie); -extern int ntfs_index_rm(ntfs_index_context *icx); +extern int ntfs_ie_add( ntfs_index_context *icx, INDEX_ENTRY *ie ); +extern int ntfs_index_rm( ntfs_index_context *icx ); #endif /* _NTFS_INDEX_H */ diff --git a/source/libntfs/inode.c b/source/libntfs/inode.c index 6f3fa060..92a24524 100644 --- a/source/libntfs/inode.c +++ b/source/libntfs/inode.c @@ -58,16 +58,16 @@ #include "logging.h" #include "misc.h" -ntfs_inode *ntfs_inode_base(ntfs_inode *ni) +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; } /** * ntfs_inode_mark_dirty - set the inode (and its base inode if it exists) dirty - * @ni: ntfs inode to set dirty + * @ni: ntfs inode to set dirty * * Set the inode @ni dirty so it is written out later (at the latest at * ntfs_inode_close() time). If @ni is an extent inode, set the base inode @@ -75,11 +75,11 @@ ntfs_inode *ntfs_inode_base(ntfs_inode *ni) * * This function cannot fail. */ -void ntfs_inode_mark_dirty(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 ); } /** @@ -90,14 +90,14 @@ void ntfs_inode_mark_dirty(ntfs_inode *ni) * * Returns: */ -static ntfs_inode *__ntfs_inode_allocate(ntfs_volume *vol) +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; } /** @@ -108,9 +108,9 @@ static ntfs_inode *__ntfs_inode_allocate(ntfs_volume *vol) * * Returns: */ -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 ); } /** @@ -121,22 +121,22 @@ ntfs_inode *ntfs_inode_allocate(ntfs_volume *vol) * * Returns: */ -static void __ntfs_inode_release(ntfs_inode *ni) +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; } /** * ntfs_inode_open - open an inode ready for access - * @vol: volume to get the inode from - * @mref: inode number / mft record number to open + * @vol: volume to get the inode from + * @mref: inode number / mft record number to open * * Allocate an ntfs_inode structure and initialize it for the given inode * specified by @mref. @mref specifies the inode number / mft record to read, @@ -156,138 +156,153 @@ static void __ntfs_inode_release(ntfs_inode *ni) * Return a pointer to the ntfs_inode structure on success or NULL on error, * with errno set to the error code. */ -static ntfs_inode *ntfs_inode_real_open(ntfs_volume *vol, const MFT_REF mref) +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; - } + 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; + 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); + ntfs_attr_put_search_ctx( ctx ); err_out: - __ntfs_inode_release(ni); - ni = NULL; - goto out; + __ntfs_inode_release( ni ); + ni = NULL; + goto out; } /** * ntfs_inode_close - close an ntfs inode and free all associated memory - * @ni: ntfs inode to close + * @ni: ntfs inode to close * * Make sure the ntfs inode @ni is clean. * @@ -304,249 +319,272 @@ err_out: * error, @ni has not been freed. The user should attempt to handle the error * and call ntfs_inode_close() again. The following error codes are defined: * - * EBUSY @ni and/or its attribute list runlist is/are dirty and the - * attempt to write it/them to disk failed. - * EINVAL @ni is invalid (probably it is an extent inode). - * EIO I/O error while trying to write inode to disk. + * EBUSY @ni and/or its attribute list runlist is/are dirty and the + * attempt to write it/them to disk failed. + * EINVAL @ni is invalid (probably it is an extent inode). + * EIO I/O error while trying to write inode to disk. */ -int ntfs_inode_real_close(ntfs_inode *ni) +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; + /* 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; + ntfs_log_leave( "\n" ); + return ret; } #if CACHE_NIDATA_SIZE /* - * Free an inode structure when there is not more space - * in the cache + * Free an inode structure when there is not more space + * in the cache */ -void ntfs_inode_nidata_free(const struct CACHED_GENERIC *cached) +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 ); } /* - * Compute a hash value for an inode entry + * Compute a hash value for an inode entry */ -int ntfs_inode_nidata_hash(const struct CACHED_GENERIC *item) +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 + * 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 ); } /* - * Invalidate an inode entry when not needed anymore. - * The entry should have been synced, it may be reused later, - * if it is requested before it is dropped from cache. + * Invalidate an inode entry when not needed anymore. + * The entry should have been synced, it may be reused later, + * if it is requested before it is dropped from cache. */ -void ntfs_inode_invalidate(ntfs_volume *vol, const MFT_REF mref) +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 /* - * Open an inode + * Open an inode * - * When possible, an entry recorded in the cache is reused + * When possible, an entry recorded in the cache is reused * - * **NEVER REOPEN** an inode, this can lead to a duplicated - * cache entry (hard to detect), and to an obsolete one being - * reused. System files are however protected from being cached. + * **NEVER REOPEN** an inode, this can lead to a duplicated + * cache entry (hard to detect), and to an obsolete one being + * reused. System files are however protected from being cached. */ -ntfs_inode *ntfs_inode_open(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 ); } /* - * Close an inode entry + * Close an inode entry * - * If cacheing is in use, the entry is synced and kept available - * in cache for further use. + * If cacheing is in use, the entry is synced and kept available + * in cache for further use. * - * System files (inode < 16 or having the IS_4 flag) are protected - * against being cached. + * System files (inode < 16 or having the IS_4 flag) are protected + * against being cached. */ -int ntfs_inode_close(ntfs_inode *ni) +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 ); } /** * ntfs_extent_inode_open - load an extent inode and attach it to its base - * @base_ni: base ntfs inode - * @mref: mft reference of the extent inode to load (in little endian) + * @base_ni: base ntfs inode + * @mref: mft reference of the extent inode to load (in little endian) * * First check if the extent inode @mref is already attached to the base ntfs * inode @base_ni, and if so, return a pointer to the attached extent inode. @@ -568,323 +606,352 @@ int ntfs_inode_close(ntfs_inode *ni) * Note, extent inodes are never closed directly. They are automatically * disposed off by the closing of the base inode. */ -ntfs_inode *ntfs_extent_inode_open(ntfs_inode *base_ni, const MFT_REF mref) +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; + /* 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; + ntfs_log_leave( "\n" ); + return ni; err_out: - __ntfs_inode_release(ni); - ni = NULL; - goto out; + __ntfs_inode_release( ni ); + ni = NULL; + goto out; } /** * ntfs_inode_attach_all_extents - attach all extents for target inode - * @ni: opened ntfs inode for which perform attach + * @ni: opened ntfs inode for which perform attach * * Return 0 on success and -1 on error with errno set to the error code. */ -int ntfs_inode_attach_all_extents(ntfs_inode *ni) +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; } /** * ntfs_inode_sync_standard_information - update standard information attribute - * @ni: ntfs inode to update standard information + * @ni: ntfs inode to update standard information * * Return 0 on success or -1 on error with errno set to the error code. */ -static int ntfs_inode_sync_standard_information(ntfs_inode *ni) +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; } /** * ntfs_inode_sync_file_name - update FILE_NAME attributes - * @ni: ntfs inode to update FILE_NAME attributes + * @ni: ntfs inode to update FILE_NAME attributes * * Update all FILE_NAME attributes for inode @ni in the index. * * Return 0 on success or -1 on error with errno set to the error code. */ -static int ntfs_inode_sync_file_name(ntfs_inode *ni, ntfs_inode *dir_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; + 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; + if ( ctx ) + ntfs_attr_put_search_ctx( ctx ); + errno = err; + return -1; } /** * ntfs_inode_sync - write the inode (and its dirty extents) to disk - * @ni: ntfs inode to write + * @ni: ntfs inode to write * * Write the inode @ni to disk as well as its dirty extent inodes if such * exist and @ni is a base inode. If @ni is an extent inode, only @ni is @@ -897,158 +964,181 @@ err_out: * * Return 0 on success or -1 on error with errno set to the error code. * The following error codes are defined: - * EINVAL - Invalid arguments were passed to the function. - * EBUSY - Inode and/or one of its extents is busy, try again later. - * EIO - I/O error while writing the inode (or one of its extents). + * EINVAL - Invalid arguments were passed to the function. + * EBUSY - Inode and/or one of its extents is busy, try again later. + * EIO - I/O error while writing the inode (or one of its extents). */ -static int ntfs_inode_sync_in_dir(ntfs_inode *ni, ntfs_inode *dir_ni) +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 ); + } - na = ntfs_attr_open(ni, AT_ATTRIBUTE_LIST, AT_UNNAMED, 0); - if (!na) { - if (!err || errno == EIO) { - err = errno; - if (err != EIO) - err = EBUSY; - ntfs_log_perror("Attribute list sync failed " - "(open, inode %lld)", - (long long)ni->mft_no); - } - NInoAttrListSetDirty(ni); - goto sync_inode; - } - - if (na->data_size == ni->attr_list_size) { - if (ntfs_attr_pwrite(na, 0, ni->attr_list_size, - ni->attr_list) != ni->attr_list_size) { - if (!err || errno == EIO) { - err = errno; - if (err != EIO) - err = EBUSY; - ntfs_log_perror("Attribute list sync " - "failed (write, inode %lld)", - (long long)ni->mft_no); - } - NInoAttrListSetDirty(ni); - } - } else { - err = EIO; - ntfs_log_error("Attribute list sync failed (bad size, " - "inode %lld)\n", (long long)ni->mft_no); - NInoAttrListSetDirty(ni); - } - ntfs_attr_close(na); - } - sync_inode: - /* Write this inode out to the $MFT (and $MFTMirr if applicable). */ - if (NInoTestAndClearDirty(ni)) { - if (ntfs_mft_record_write(ni->vol, ni->mft_no, ni->mrec)) { - if (!err || errno == EIO) { - err = errno; - if (err != EIO) - err = EBUSY; - } - NInoSetDirty(ni); - ntfs_log_perror("MFT record sync failed, inode %lld", - (long long)ni->mft_no); - } - } + /* Write this inode out to the $MFT (and $MFTMirr if applicable). */ + if ( NInoTestAndClearDirty( ni ) ) + { + if ( ntfs_mft_record_write( ni->vol, ni->mft_no, ni->mrec ) ) + { + if ( !err || errno == EIO ) + { + err = errno; + if ( err != EIO ) + err = EBUSY; + } + NInoSetDirty( ni ); + ntfs_log_perror( "MFT record sync failed, inode %lld", + ( long long )ni->mft_no ); + } + } - /* If this is a base inode with extents write all dirty extents, too. */ - if (ni->nr_extents > 0) { - s32 i; + /* If this is a base inode with extents write all dirty extents, too. */ + if ( ni->nr_extents > 0 ) + { + s32 i; - for (i = 0; i < ni->nr_extents; ++i) { - ntfs_inode *eni; + for ( i = 0; i < ni->nr_extents; ++i ) + { + ntfs_inode *eni; - eni = ni->extent_nis[i]; - if (!NInoTestAndClearDirty(eni)) - continue; - - 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); - } - } - } + eni = ni->extent_nis[i]; + if ( !NInoTestAndClearDirty( eni ) ) + continue; - if (err) { - errno = err; - ret = -1; - } - - ntfs_log_leave("\n"); - return ret; + 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) +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 ) ); } /* - * Close an inode with an open parent inode + * Close an inode with an open parent inode */ -int ntfs_inode_close_in_dir(ntfs_inode *ni, ntfs_inode *dir_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 ); } /** @@ -1057,510 +1147,553 @@ int ntfs_inode_close_in_dir(ntfs_inode *ni, ntfs_inode *dir_ni) * * Return 0 on success or -1 on error with errno set to the error code. * The following error codes are defined: - * EINVAL - Invalid arguments were passed to the function. - * EEXIST - Attribute list already exist. - * EIO - Input/Ouput error occurred. - * ENOMEM - Not enough memory to perform add. + * EINVAL - Invalid arguments were passed to the function. + * EEXIST - Attribute list already exist. + * EIO - Input/Ouput error occurred. + * ENOMEM - Not enough memory to perform add. */ -int ntfs_inode_add_attrlist(ntfs_inode *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; + + 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); + /* Prevent ntfs_attr_recorm_rm from freeing attribute list. */ + ni->attr_list = NULL; + NInoClearAttrList( ni ); + /* Remove $ATTRIBUTE_LIST record. */ + ntfs_attr_reinit_search_ctx( ctx ); + if ( !ntfs_attr_lookup( AT_ATTRIBUTE_LIST, NULL, 0, + CASE_SENSITIVE, 0, NULL, 0, ctx ) ) + { + if ( ntfs_attr_record_rm( ctx ) ) + ntfs_log_perror( "Rollback failed to remove attrlist" ); + } + else + ntfs_log_perror( "Rollback failed to find attrlist" ); + /* Setup back in-memory runlist. */ + ni->attr_list = al; + ni->attr_list_size = al_len; + NInoSetAttrList( ni ); rollback: - /* - * Scan attribute list for attributes that placed not in the base MFT - * record and move them to it. - */ - ntfs_attr_reinit_search_ctx(ctx); - ale = (ATTR_LIST_ENTRY*)al; - while ((u8*)ale < al + al_len) { - if (MREF_LE(ale->mft_reference) != ni->mft_no) { - if (!ntfs_attr_lookup(ale->type, ale->name, - ale->name_length, - CASE_SENSITIVE, - sle64_to_cpu(ale->lowest_vcn), - NULL, 0, ctx)) { - if (ntfs_attr_record_move_to(ctx, ni)) - ntfs_log_perror("Rollback failed to " - "move attribute"); - } else - ntfs_log_perror("Rollback failed to find attr"); - ntfs_attr_reinit_search_ctx(ctx); - } - ale = (ATTR_LIST_ENTRY*)((u8*)ale + le16_to_cpu(ale->length)); - } - /* Remove in-memory attribute list. */ - ni->attr_list = NULL; - ni->attr_list_size = 0; - NInoClearAttrList(ni); - NInoAttrListClearDirty(ni); + /* + * Scan attribute list for attributes that placed not in the base MFT + * record and move them to it. + */ + ntfs_attr_reinit_search_ctx( ctx ); + ale = ( ATTR_LIST_ENTRY* )al; + while ( ( u8* )ale < al + al_len ) + { + if ( MREF_LE( ale->mft_reference ) != ni->mft_no ) + { + if ( !ntfs_attr_lookup( ale->type, ale->name, + ale->name_length, + CASE_SENSITIVE, + sle64_to_cpu( ale->lowest_vcn ), + NULL, 0, ctx ) ) + { + if ( ntfs_attr_record_move_to( ctx, ni ) ) + ntfs_log_perror( "Rollback failed to " + "move attribute" ); + } + else + ntfs_log_perror( "Rollback failed to find attr" ); + ntfs_attr_reinit_search_ctx( ctx ); + } + ale = ( ATTR_LIST_ENTRY* )( ( u8* )ale + le16_to_cpu( ale->length ) ); + } + /* Remove in-memory attribute list. */ + ni->attr_list = NULL; + ni->attr_list_size = 0; + NInoClearAttrList( ni ); + NInoAttrListClearDirty( ni ); put_err_out: - ntfs_attr_put_search_ctx(ctx); + ntfs_attr_put_search_ctx( ctx ); err_out: - free(al); - errno = err; - return -1; + free( al ); + errno = err; + return -1; } /** * ntfs_inode_free_space - free space in the MFT record of an inode - * @ni: ntfs inode in which MFT record needs more free space - * @size: amount of space needed to free + * @ni: ntfs inode in which MFT record needs more free space + * @size: amount of space needed to free * * Return 0 on success or -1 on error with errno set to the error code. */ -int ntfs_inode_free_space(ntfs_inode *ni, int size) +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; - } + /* Check whether we are done. */ + if ( size <= freed ) + { + ntfs_attr_put_search_ctx( ctx ); + return 0; + } + /* + * Reposition to first attribute after $STANDARD_INFORMATION + * and $ATTRIBUTE_LIST instead of simply skipping this attribute + * because in the case when we have got only in-memory attribute + * list then ntfs_attr_lookup will fail when it tries to find + * $ATTRIBUTE_LIST. + */ + ntfs_attr_reinit_search_ctx( ctx ); + if ( ntfs_attr_position( AT_FILE_NAME, ctx ) ) + break; + } put_err_out: - ntfs_attr_put_search_ctx(ctx); - if (errno == ENOSPC) - ntfs_log_trace("No attributes left that could be moved out.\n"); - return -1; + ntfs_attr_put_search_ctx( ctx ); + if ( errno == ENOSPC ) + ntfs_log_trace( "No attributes left that could be moved out.\n" ); + return -1; } /** * ntfs_inode_update_times - update selected time fields for ntfs inode - * @ni: ntfs inode for which update time fields - * @mask: select which time fields should be updated + * @ni: ntfs inode for which update time fields + * @mask: select which time fields should be updated * * This function updates time fields to current time. Fields to update are * selected using @mask (see enum @ntfs_time_update_flags for posssible values). */ -void ntfs_inode_update_times(ntfs_inode *ni, ntfs_time_update_flags mask) +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 ); } /** * ntfs_inode_badclus_bad - check for $Badclus:$Bad data attribute - * @mft_no: mft record number where @attr is present - * @attr: attribute record used to check for the $Bad attribute + * @mft_no: mft record number where @attr is present + * @attr: attribute record used to check for the $Bad attribute * * Check if the mft record given by @mft_no and @attr contains the bad sector * list. Please note that mft record numbers describing $Badclus extent inodes * will not match the current $Badclus:$Bad check. - * + * * On success return 1 if the file is $Badclus:$Bad, otherwise return 0. * On error return -1 with errno set to the error code. */ -int ntfs_inode_badclus_bad(u64 mft_no, ATTR_RECORD *attr) +int 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 */ +#ifdef HAVE_SETXATTR /* extended attributes interface required */ /* - * Get high precision NTFS times + * Get high precision NTFS times * - * They are returned in following order : create, update, access, change - * provided they fit in requested size. + * They are returned in following order : create, update, access, change + * provided they fit in requested size. * - * Returns the modified size if successfull (or 32 if buffer size is null) - * -errno if failed + * Returns the modified size if successfull (or 32 if buffer size is null) + * -errno if failed */ -int ntfs_inode_get_times(ntfs_inode *ni, char *value, size_t size) +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 ); } /* - * Set high precision NTFS times + * Set high precision NTFS times * - * They are expected in this order : create, update, access - * provided they are present in input. The change time is set to - * current time. + * They are expected in this order : create, update, access + * provided they are present in input. The change time is set to + * current time. * - * The times are inserted directly in the standard_information and - * file names attributes to avoid manipulating low precision times + * The times are inserted directly in the standard_information and + * file names attributes to avoid manipulating low precision times * - * Returns 0 if success - * -1 if there were an error (described by errno) + * Returns 0 if success + * -1 if there were an error (described by errno) */ -int ntfs_inode_set_times(ntfs_inode *ni, const char *value, size_t size, - int flags) +int ntfs_inode_set_times( ntfs_inode *ni, const char *value, size_t size, + 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..18a3771b 100644 --- a/source/libntfs/inode.h +++ b/source/libntfs/inode.h @@ -40,62 +40,63 @@ 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) -#define set_nino_flag(ni, flag) set_bit(NI_##flag, (ni)->state) -#define clear_nino_flag(ni, flag) clear_bit(NI_##flag, (ni)->state) +#define test_nino_flag(ni, flag) test_bit(NI_##flag, (ni)->state) +#define set_nino_flag(ni, flag) set_bit(NI_##flag, (ni)->state) +#define clear_nino_flag(ni, flag) clear_bit(NI_##flag, (ni)->state) -#define test_and_set_nino_flag(ni, flag) \ - test_and_set_bit(NI_##flag, (ni)->state) -#define test_and_clear_nino_flag(ni, flag) \ - test_and_clear_bit(NI_##flag, (ni)->state) +#define test_and_set_nino_flag(ni, flag) \ + test_and_set_bit(NI_##flag, (ni)->state) +#define test_and_clear_nino_flag(ni, flag) \ + test_and_clear_bit(NI_##flag, (ni)->state) -#define NInoDirty(ni) test_nino_flag(ni, Dirty) -#define NInoSetDirty(ni) set_nino_flag(ni, Dirty) -#define NInoClearDirty(ni) clear_nino_flag(ni, Dirty) -#define NInoTestAndSetDirty(ni) test_and_set_nino_flag(ni, Dirty) -#define NInoTestAndClearDirty(ni) test_and_clear_nino_flag(ni, Dirty) +#define NInoDirty(ni) test_nino_flag(ni, Dirty) +#define NInoSetDirty(ni) set_nino_flag(ni, Dirty) +#define NInoClearDirty(ni) clear_nino_flag(ni, Dirty) +#define NInoTestAndSetDirty(ni) test_and_set_nino_flag(ni, Dirty) +#define NInoTestAndClearDirty(ni) test_and_clear_nino_flag(ni, Dirty) -#define NInoAttrList(ni) test_nino_flag(ni, AttrList) -#define NInoSetAttrList(ni) set_nino_flag(ni, AttrList) -#define NInoClearAttrList(ni) clear_nino_flag(ni, AttrList) +#define NInoAttrList(ni) test_nino_flag(ni, AttrList) +#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) +#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) -#define test_and_set_nino_al_flag(ni, flag) \ - test_and_set_nino_flag(ni, AttrList##flag) -#define test_and_clear_nino_al_flag(ni, flag) \ - test_and_clear_nino_flag(ni, AttrList##flag) +#define test_and_set_nino_al_flag(ni, flag) \ + test_and_set_nino_flag(ni, AttrList##flag) +#define test_and_clear_nino_al_flag(ni, flag) \ + test_and_clear_nino_flag(ni, AttrList##flag) -#define NInoAttrListDirty(ni) test_nino_al_flag(ni, Dirty) -#define NInoAttrListSetDirty(ni) set_nino_al_flag(ni, Dirty) -#define NInoAttrListClearDirty(ni) clear_nino_al_flag(ni, Dirty) -#define NInoAttrListTestAndSetDirty(ni) test_and_set_nino_al_flag(ni, Dirty) +#define NInoAttrListDirty(ni) test_nino_al_flag(ni, Dirty) +#define NInoAttrListSetDirty(ni) set_nino_al_flag(ni, Dirty) +#define NInoAttrListClearDirty(ni) clear_nino_al_flag(ni, Dirty) +#define NInoAttrListTestAndSetDirty(ni) test_and_set_nino_al_flag(ni, Dirty) #define NInoAttrListTestAndClearDirty(ni) test_and_clear_nino_al_flag(ni, Dirty) #define NInoFileNameDirty(ni) test_nino_flag(ni, FileNameDirty) #define NInoFileNameSetDirty(ni) set_nino_flag(ni, FileNameDirty) #define NInoFileNameClearDirty(ni) clear_nino_flag(ni, FileNameDirty) -#define NInoFileNameTestAndSetDirty(ni) \ - test_and_set_nino_flag(ni, FileNameDirty) -#define NInoFileNameTestAndClearDirty(ni) \ - test_and_clear_nino_flag(ni, FileNameDirty) +#define NInoFileNameTestAndSetDirty(ni) \ + test_and_set_nino_flag(ni, FileNameDirty) +#define NInoFileNameTestAndClearDirty(ni) \ + test_and_clear_nino_flag(ni, FileNameDirty) /** * struct _ntfs_inode - The NTFS in-memory inode structure. @@ -103,120 +104,123 @@ 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) #define NTFS_UPDATE_AMCTIME (NTFS_UPDATE_ATIME | NTFS_UPDATE_MCTIME) -extern ntfs_inode *ntfs_inode_base(ntfs_inode *ni); +extern ntfs_inode *ntfs_inode_base( ntfs_inode *ni ); -extern ntfs_inode *ntfs_inode_allocate(ntfs_volume *vol); +extern ntfs_inode *ntfs_inode_allocate( ntfs_volume *vol ); -extern ntfs_inode *ntfs_inode_open(ntfs_volume *vol, const MFT_REF mref); +extern ntfs_inode *ntfs_inode_open( ntfs_volume *vol, const MFT_REF mref ); -extern int ntfs_inode_close(ntfs_inode *ni); -extern int ntfs_inode_close_in_dir(ntfs_inode *ni, ntfs_inode *dir_ni); +extern int ntfs_inode_close( ntfs_inode *ni ); +extern int ntfs_inode_close_in_dir( ntfs_inode *ni, ntfs_inode *dir_ni ); #if CACHE_NIDATA_SIZE struct CACHED_GENERIC; -extern int ntfs_inode_real_close(ntfs_inode *ni); -extern void ntfs_inode_invalidate(ntfs_volume *vol, const MFT_REF mref); -extern void ntfs_inode_nidata_free(const struct CACHED_GENERIC *cached); -extern int ntfs_inode_nidata_hash(const struct CACHED_GENERIC *item); +extern int ntfs_inode_real_close( ntfs_inode *ni ); +extern void ntfs_inode_invalidate( ntfs_volume *vol, const MFT_REF mref ); +extern void ntfs_inode_nidata_free( const struct CACHED_GENERIC *cached ); +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); +extern int ntfs_inode_attach_all_extents( ntfs_inode *ni ); -extern void ntfs_inode_mark_dirty(ntfs_inode *ni); +extern void ntfs_inode_mark_dirty( ntfs_inode *ni ); -extern void ntfs_inode_update_times(ntfs_inode *ni, ntfs_time_update_flags mask); +extern void ntfs_inode_update_times( ntfs_inode *ni, ntfs_time_update_flags mask ); -extern int ntfs_inode_sync(ntfs_inode *ni); +extern int ntfs_inode_sync( ntfs_inode *ni ); -extern int ntfs_inode_add_attrlist(ntfs_inode *ni); +extern int ntfs_inode_add_attrlist( ntfs_inode *ni ); -extern int ntfs_inode_free_space(ntfs_inode *ni, int size); +extern int ntfs_inode_free_space( ntfs_inode *ni, int size ); -extern int ntfs_inode_badclus_bad(u64 mft_no, ATTR_RECORD *a); +extern int ntfs_inode_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_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..b8e1747e 100644 --- a/source/libntfs/layout.h +++ b/source/libntfs/layout.h @@ -29,70 +29,72 @@ #include "support.h" /* The NTFS oem_id */ -#define magicNTFS const_cpu_to_le64(0x202020205346544e) /* "NTFS " */ -#define NTFS_SB_MAGIC 0x5346544e /* 'NTFS' */ +#define magicNTFS const_cpu_to_le64(0x202020205346544e) /* "NTFS " */ +#define NTFS_SB_MAGIC 0x5346544e /* 'NTFS' */ /* * Location of bootsector on partition: - * The standard NTFS_BOOT_SECTOR is on sector 0 of the partition. - * On NT4 and above there is one backup copy of the boot sector to - * be found on the last sector of the partition (not normally accessible - * from within Windows as the bootsector contained number of sectors - * value is one less than the actual value!). - * On versions of NT 3.51 and earlier, the backup copy was located at - * number of sectors/2 (integer divide), i.e. in the middle of the volume. + * The standard NTFS_BOOT_SECTOR is on sector 0 of the partition. + * On NT4 and above there is one backup copy of the boot sector to + * be found on the last sector of the partition (not normally accessible + * from within Windows as the bootsector contained number of sectors + * value is one less than the actual value!). + * On versions of NT 3.51 and earlier, the backup copy was located at + * number of sectors/2 (integer divide), i.e. in the middle of the volume. */ /** * 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,69 +102,70 @@ 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; /* * Generic magic comparison macros. Finally found a use for the ## preprocessor * operator! (-8 */ -#define ntfs_is_magic(x, m) ( (u32)(x) == (u32)magic_##m ) -#define ntfs_is_magicp(p, m) ( *(u32*)(p) == (u32)magic_##m ) +#define ntfs_is_magic(x, m) ( (u32)(x) == (u32)magic_##m ) +#define ntfs_is_magicp(p, m) ( *(u32*)(p) == (u32)magic_##m ) /* * Specialised magic comparison macros for the NTFS_RECORD_TYPES defined above. */ -#define ntfs_is_file_record(x) ( ntfs_is_magic (x, FILE) ) -#define ntfs_is_file_recordp(p) ( ntfs_is_magicp(p, FILE) ) -#define ntfs_is_mft_record(x) ( ntfs_is_file_record(x) ) -#define ntfs_is_mft_recordp(p) ( ntfs_is_file_recordp(p) ) -#define ntfs_is_indx_record(x) ( ntfs_is_magic (x, INDX) ) -#define ntfs_is_indx_recordp(p) ( ntfs_is_magicp(p, INDX) ) -#define ntfs_is_hole_record(x) ( ntfs_is_magic (x, HOLE) ) -#define ntfs_is_hole_recordp(p) ( ntfs_is_magicp(p, HOLE) ) +#define ntfs_is_file_record(x) ( ntfs_is_magic (x, FILE) ) +#define ntfs_is_file_recordp(p) ( ntfs_is_magicp(p, FILE) ) +#define ntfs_is_mft_record(x) ( ntfs_is_file_record(x) ) +#define ntfs_is_mft_recordp(p) ( ntfs_is_file_recordp(p) ) +#define ntfs_is_indx_record(x) ( ntfs_is_magic (x, INDX) ) +#define ntfs_is_indx_recordp(p) ( ntfs_is_magicp(p, INDX) ) +#define ntfs_is_hole_record(x) ( ntfs_is_magic (x, HOLE) ) +#define ntfs_is_hole_recordp(p) ( ntfs_is_magicp(p, HOLE) ) -#define ntfs_is_rstr_record(x) ( ntfs_is_magic (x, RSTR) ) -#define ntfs_is_rstr_recordp(p) ( ntfs_is_magicp(p, RSTR) ) -#define ntfs_is_rcrd_record(x) ( ntfs_is_magic (x, RCRD) ) -#define ntfs_is_rcrd_recordp(p) ( ntfs_is_magicp(p, RCRD) ) +#define ntfs_is_rstr_record(x) ( ntfs_is_magic (x, RSTR) ) +#define ntfs_is_rstr_recordp(p) ( ntfs_is_magicp(p, RSTR) ) +#define ntfs_is_rcrd_record(x) ( ntfs_is_magic (x, RCRD) ) +#define ntfs_is_rcrd_recordp(p) ( ntfs_is_magicp(p, RCRD) ) -#define ntfs_is_chkd_record(x) ( ntfs_is_magic (x, CHKD) ) -#define ntfs_is_chkd_recordp(p) ( ntfs_is_magicp(p, CHKD) ) +#define ntfs_is_chkd_record(x) ( ntfs_is_magic (x, CHKD) ) +#define ntfs_is_chkd_recordp(p) ( ntfs_is_magicp(p, CHKD) ) -#define ntfs_is_baad_record(x) ( ntfs_is_magic (x, BAAD) ) -#define ntfs_is_baad_recordp(p) ( ntfs_is_magicp(p, BAAD) ) +#define ntfs_is_baad_record(x) ( ntfs_is_magic (x, BAAD) ) +#define ntfs_is_baad_recordp(p) ( ntfs_is_magicp(p, BAAD) ) -#define ntfs_is_empty_record(x) ( ntfs_is_magic (x, empty) ) -#define ntfs_is_empty_recordp(p) ( ntfs_is_magicp(p, empty) ) +#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 +#define NTFS_BLOCK_SIZE 512 +#define NTFS_BLOCK_SIZE_BITS 9 /** * struct NTFS_RECORD - @@ -176,22 +179,23 @@ typedef enum { * are set to it (during writing). If they are not, an incomplete multi sector * transfer has occurred when the data was written. * The maximum size for the update sequence array is fixed to: - * maximum size = usa_ofs + (usa_count * 2) = 510 bytes + * maximum size = usa_ofs + (usa_count * 2) = 510 bytes * The 510 bytes comes from the fact that the last u16 in the array has to * (obviously) finish before the last u16 of the first 512-byte sector. * 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 +205,44 @@ 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; /** @@ -245,7 +250,7 @@ typedef enum { * * These are the so far known MFT_RECORD_* flags (16-bit) which contain * information about the mft record in which they are present. - * + * * MFT_RECORD_IS_4 exists on all $Extend sub-files. * It seems that it marks it is a metadata file with MFT record >24, however, * it is unknown if it is limited to metadata files only. @@ -254,14 +259,15 @@ 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 @@ -312,19 +318,19 @@ typedef enum { typedef u64 MFT_REF; -#define MK_MREF(m, s) ((MFT_REF)(((MFT_REF)(s) << 48) | \ - ((MFT_REF)(m) & MFT_REF_MASK_CPU))) +#define MK_MREF(m, s) ((MFT_REF)(((MFT_REF)(s) << 48) | \ + ((MFT_REF)(m) & MFT_REF_MASK_CPU))) #define MK_LE_MREF(m, s) const_cpu_to_le64(((MFT_REF)(((MFT_REF)(s) << 48) | \ - ((MFT_REF)(m) & MFT_REF_MASK_CPU)))) + ((MFT_REF)(m) & MFT_REF_MASK_CPU)))) -#define MREF(x) ((u64)((x) & MFT_REF_MASK_CPU)) -#define MSEQNO(x) ((u16)(((x) >> 48) & 0xffff)) -#define MREF_LE(x) ((u64)(const_le64_to_cpu(x) & MFT_REF_MASK_CPU)) -#define MSEQNO_LE(x) ((u16)((const_le64_to_cpu(x) >> 48) & 0xffff)) +#define MREF(x) ((u64)((x) & MFT_REF_MASK_CPU)) +#define MSEQNO(x) ((u16)(((x) >> 48) & 0xffff)) +#define MREF_LE(x) ((u64)(const_le64_to_cpu(x) & MFT_REF_MASK_CPU)) +#define MSEQNO_LE(x) ((u16)((const_le64_to_cpu(x) >> 48) & 0xffff)) -#define IS_ERR_MREF(x) (((x) & 0x0000800000000000ULL) ? 1 : 0) -#define ERR_MREF(x) ((u64)((s64)(x))) -#define MREF_ERR(x) ((int)((s64)(x))) +#define IS_ERR_MREF(x) (((x) & 0x0000800000000000ULL) ? 1 : 0) +#define ERR_MREF(x) ((u64)((s64)(x))) +#define MREF_ERR(x) ((int)((s64)(x))) /** * struct MFT_RECORD - An MFT record layout (NTFS 3.1+) @@ -335,145 +341,147 @@ 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). @@ -481,31 +489,32 @@ typedef struct { * Each attribute type has a corresponding attribute name (Unicode string of * maximum 64 character length) as described by the attribute definitions * present in the data attribute of the $AttrDef system file. - * + * * On NTFS 3.0 volumes the names are just as the types are named in the below * enum exchanging AT_ for the dollar sign ($). If that isn't a revealing * choice of symbol... (-; */ -typedef enum { - AT_UNUSED = const_cpu_to_le32( 0), - AT_STANDARD_INFORMATION = const_cpu_to_le32( 0x10), - AT_ATTRIBUTE_LIST = const_cpu_to_le32( 0x20), - AT_FILE_NAME = const_cpu_to_le32( 0x30), - AT_OBJECT_ID = const_cpu_to_le32( 0x40), - AT_SECURITY_DESCRIPTOR = const_cpu_to_le32( 0x50), - AT_VOLUME_NAME = const_cpu_to_le32( 0x60), - AT_VOLUME_INFORMATION = const_cpu_to_le32( 0x70), - AT_DATA = const_cpu_to_le32( 0x80), - AT_INDEX_ROOT = const_cpu_to_le32( 0x90), - AT_INDEX_ALLOCATION = const_cpu_to_le32( 0xa0), - AT_BITMAP = const_cpu_to_le32( 0xb0), - AT_REPARSE_POINT = const_cpu_to_le32( 0xc0), - AT_EA_INFORMATION = const_cpu_to_le32( 0xd0), - AT_EA = const_cpu_to_le32( 0xe0), - AT_PROPERTY_SET = const_cpu_to_le32( 0xf0), - AT_LOGGED_UTILITY_STREAM = const_cpu_to_le32( 0x100), - AT_FIRST_USER_DEFINED_ATTRIBUTE = const_cpu_to_le32( 0x1000), - AT_END = const_cpu_to_le32(0xffffffff), +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; /** @@ -513,54 +522,55 @@ typedef enum { * (32-bit). * * COLLATION_UNICODE_STRING - 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. + * Unicode values, except that when a character can be uppercased, the + * upper case value collates before the lower case one. * COLLATION_FILE_NAME - Collate file names as Unicode strings. The collation - * is done very much like COLLATION_UNICODE_STRING. In fact I have no idea - * what the difference is. Perhaps the difference is that file names - * would treat some special characters in an odd way (see - * unistr.c::ntfs_collate_names() and unistr.c::legal_ansi_char_array[] - * for what I mean but COLLATION_UNICODE_STRING would not give any special - * treatment to any characters at all, but this is speculation. + * is done very much like COLLATION_UNICODE_STRING. In fact I have no idea + * what the difference is. Perhaps the difference is that file names + * would treat some special characters in an odd way (see + * unistr.c::ntfs_collate_names() and unistr.c::legal_ansi_char_array[] + * for what I mean but COLLATION_UNICODE_STRING would not give any special + * treatment to any characters at all, but this is speculation. * COLLATION_NTOFS_ULONG - Sorting is done according to ascending u32 key - * values. E.g. used for $SII index in FILE_Secure, which sorts by - * security_id (u32). + * values. E.g. used for $SII index in FILE_Secure, which sorts by + * security_id (u32). * COLLATION_NTOFS_SID - Sorting is done according to ascending SID values. - * E.g. used for $O index in FILE_Extend/$Quota. + * E.g. used for $O index in FILE_Extend/$Quota. * COLLATION_NTOFS_SECURITY_HASH - Sorting is done first by ascending hash - * values and second by ascending security_id values. E.g. used for $SDH - * index in FILE_Secure. + * values and second by ascending security_id values. E.g. used for $SDH + * index in FILE_Secure. * COLLATION_NTOFS_ULONGS - Sorting is done according to a sequence of ascending - * u32 key values. E.g. used for $O index in FILE_Extend/$ObjId, which - * sorts by object_id (16-byte), by splitting up the object_id in four - * u32 values and using them as individual keys. E.g. take the following - * two security_ids, stored as follows on disk: - * 1st: a1 61 65 b7 65 7b d4 11 9e 3d 00 e0 81 10 42 59 - * 2nd: 38 14 37 d2 d2 f3 d4 11 a5 21 c8 6b 79 b1 97 45 - * To compare them, they are split into four u32 values each, like so: - * 1st: 0xb76561a1 0x11d47b65 0xe0003d9e 0x59421081 - * 2nd: 0xd2371438 0x11d4f3d2 0x6bc821a5 0x4597b179 - * Now, it is apparent why the 2nd object_id collates after the 1st: the - * first u32 value of the 1st object_id is less than the first u32 of - * the 2nd object_id. If the first u32 values of both object_ids were - * equal then the second u32 values would be compared, etc. + * u32 key values. E.g. used for $O index in FILE_Extend/$ObjId, which + * sorts by object_id (16-byte), by splitting up the object_id in four + * u32 values and using them as individual keys. E.g. take the following + * two security_ids, stored as follows on disk: + * 1st: a1 61 65 b7 65 7b d4 11 9e 3d 00 e0 81 10 42 59 + * 2nd: 38 14 37 d2 d2 f3 d4 11 a5 21 c8 6b 79 b1 97 45 + * To compare them, they are split into four u32 values each, like so: + * 1st: 0xb76561a1 0x11d47b65 0xe0003d9e 0x59421081 + * 2nd: 0xd2371438 0x11d4f3d2 0x6bc821a5 0x4597b179 + * Now, it is apparent why the 2nd object_id collates after the 1st: the + * first u32 value of the 1st object_id is less than the first u32 of + * 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 +583,32 @@ 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 +622,34 @@ 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. @@ -654,32 +668,32 @@ typedef enum { * can be stored: * * 1) The data in the block is all zero (a sparse block): - * This is stored as a sparse block in the runlist, i.e. the runlist - * entry has length = X and lcn = -1. The mapping pairs array actually - * uses a delta_lcn value length of 0, i.e. delta_lcn is not present at - * all, which is then interpreted by the driver as lcn = -1. - * NOTE: Even uncompressed files can be sparse on NTFS 3.0 volumes, then - * the same principles apply as above, except that the length is not - * restricted to being any particular value. + * This is stored as a sparse block in the runlist, i.e. the runlist + * entry has length = X and lcn = -1. The mapping pairs array actually + * uses a delta_lcn value length of 0, i.e. delta_lcn is not present at + * all, which is then interpreted by the driver as lcn = -1. + * NOTE: Even uncompressed files can be sparse on NTFS 3.0 volumes, then + * the same principles apply as above, except that the length is not + * restricted to being any particular value. * * 2) The data in the block is not compressed: - * This happens when compression doesn't reduce the size of the block - * in clusters. I.e. if compression has a small effect so that the - * compressed data still occupies X clusters, then the uncompressed data - * is stored in the block. - * This case is recognised by the fact that the runlist entry has - * length = X and lcn >= 0. The mapping pairs array stores this as - * normal with a run length of X and some specific delta_lcn, i.e. - * delta_lcn has to be present. + * This happens when compression doesn't reduce the size of the block + * in clusters. I.e. if compression has a small effect so that the + * compressed data still occupies X clusters, then the uncompressed data + * is stored in the block. + * This case is recognised by the fact that the runlist entry has + * length = X and lcn >= 0. The mapping pairs array stores this as + * normal with a run length of X and some specific delta_lcn, i.e. + * delta_lcn has to be present. * * 3) The data in the block is compressed: - * The common case. This case is recognised by the fact that the run - * list entry has length L < X and lcn >= 0. The mapping pairs array - * stores this as normal with a run length of X and some specific - * delta_lcn, i.e. delta_lcn has to be present. This runlist entry is - * immediately followed by a sparse entry with length = X - L and - * lcn = -1. The latter entry is to make up the vcn counting to the - * full compression block size X. + * The common case. This case is recognised by the fact that the run + * list entry has length L < X and lcn >= 0. The mapping pairs array + * stores this as normal with a run length of X and some specific + * delta_lcn, i.e. delta_lcn has to be present. This runlist entry is + * immediately followed by a sparse entry with length = X - L and + * lcn = -1. The latter entry is to make up the vcn counting to the + * full compression block size X. * * In fact, life is more complicated because adjacent entries of the same type * can be coalesced. This means that one has to keep track of the number of @@ -707,186 +721,195 @@ 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 @@ -901,91 +924,98 @@ typedef enum { * NOTE: Always resident. * NOTE: Present in all base file records on a volume. * NOTE: There is conflicting information about the meaning of each of the time - * fields but the meaning as defined below has been verified to be - * correct by practical experimentation on Windows NT4 SP6a and is hence - * assumed to be the one and only correct interpretation. + * fields but the meaning as defined below has been verified to be + * 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). @@ -1001,138 +1031,147 @@ typedef struct { * extent. They are ordered by lowest_vcn and have their instance set to zero. * It is not allowed to have two attributes with all sorting keys equal. * - Further restrictions: - * - If not resident, the vcn to lcn mapping array has to fit inside the - * base mft record. - * - The attribute list attribute value has a maximum size of 256kb. This - * is imposed by the Windows cache manager. + * - If not resident, the vcn to lcn mapping array has to fit inside the + * base mft record. + * - The attribute list attribute value has a maximum size of 256kb. This + * is imposed by the Windows cache manager. * - Attribute lists are only used when the attributes of mft record do not * fit inside the mft record despite all attributes (that can be made * non-resident) having been made non-resident. This can happen e.g. when: - * - File has a large number of hard links (lots of file name - * attributes present). - * - The mapping pairs array of some non-resident attribute becomes so - * large due to fragmentation that it overflows the mft record. - * - The security descriptor is very complex (not applicable to - * NTFS 3.0 volumes). - * - There are many named streams. + * - File has a large number of hard links (lots of file name + * attributes present). + * - The mapping pairs array of some non-resident attribute becomes so + * large due to fragmentation that it overflows the mft record. + * - The security descriptor is very complex (not applicable to + * 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. */ -#define NTFS_MAX_NAME_LEN 255 +#define NTFS_MAX_NAME_LEN 255 /** * 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). * * NOTE: Always resident. * NOTE: All fields, except the parent_directory, are only updated when the - * filename is changed. Until then, they just become out of sync with - * reality and the more up to date values are present in the standard - * information attribute. + * filename is changed. Until then, they just become out of sync with + * reality and the more up to date values are present in the standard + * information attribute. * NOTE: There is conflicting information about the meaning of each of the time - * fields but the meaning as defined below has been verified to be - * correct by practical experimentation on Windows NT4 SP6a and is hence - * assumed to be the one and only correct interpretation. + * fields but the meaning as defined below has been verified to be + * 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). @@ -1144,16 +1183,17 @@ typedef struct { * unique identifier (UUID). * * Example of a GUID: - * 1F010768-5A73-BC91-0010-A52216A7227B + * 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. @@ -1162,51 +1202,57 @@ typedef struct { * and the corresponding mft_record numbers as the index entry data parts. * * The data part (defined below) also contains three other object_ids: - * birth_volume_id - object_id of FILE_Volume on which the file was first - * created. Optional (i.e. can be zero). - * birth_object_id - object_id of file when it was first created. Usually - * equals the object_id. Optional (i.e. can be zero). - * domain_id - Reserved (always zero). + * birth_volume_id - object_id of FILE_Volume on which the file was first + * created. Optional (i.e. can be zero). + * birth_object_id - object_id of file when it was first created. Usually + * 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 +1261,15 @@ 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,111 +1284,112 @@ 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; /* * The universal well-known SIDs: * - * NULL_SID S-1-0-0 - * WORLD_SID S-1-1-0 - * LOCAL_SID S-1-2-0 - * CREATOR_OWNER_SID S-1-3-0 - * CREATOR_GROUP_SID S-1-3-1 - * CREATOR_OWNER_SERVER_SID S-1-3-2 - * CREATOR_GROUP_SERVER_SID S-1-3-3 + * NULL_SID S-1-0-0 + * WORLD_SID S-1-1-0 + * LOCAL_SID S-1-2-0 + * CREATOR_OWNER_SID S-1-3-0 + * CREATOR_GROUP_SID S-1-3-1 + * CREATOR_OWNER_SERVER_SID S-1-3-2 + * CREATOR_GROUP_SERVER_SID S-1-3-3 * - * (Non-unique IDs) S-1-4 + * (Non-unique IDs) S-1-4 * * NT well-known SIDs: * - * NT_AUTHORITY_SID S-1-5 - * DIALUP_SID S-1-5-1 + * NT_AUTHORITY_SID S-1-5 + * DIALUP_SID S-1-5-1 * - * NETWORD_SID S-1-5-2 - * BATCH_SID S-1-5-3 - * INTERACTIVE_SID S-1-5-4 - * SERVICE_SID S-1-5-6 - * ANONYMOUS_LOGON_SID S-1-5-7 (aka null logon session) - * PROXY_SID S-1-5-8 - * SERVER_LOGON_SID S-1-5-9 (aka domain controller account) - * SELF_SID S-1-5-10 (self RID) - * AUTHENTICATED_USER_SID S-1-5-11 - * RESTRICTED_CODE_SID S-1-5-12 (running restricted code) - * TERMINAL_SERVER_SID S-1-5-13 (running on terminal server) + * NETWORD_SID S-1-5-2 + * BATCH_SID S-1-5-3 + * INTERACTIVE_SID S-1-5-4 + * SERVICE_SID S-1-5-6 + * ANONYMOUS_LOGON_SID S-1-5-7 (aka null logon session) + * PROXY_SID S-1-5-8 + * SERVER_LOGON_SID S-1-5-9 (aka domain controller account) + * SELF_SID S-1-5-10 (self RID) + * AUTHENTICATED_USER_SID S-1-5-11 + * RESTRICTED_CODE_SID S-1-5-12 (running restricted code) + * TERMINAL_SERVER_SID S-1-5-13 (running on terminal server) * - * (Logon IDs) S-1-5-5-X-Y + * (Logon IDs) S-1-5-5-X-Y * - * (NT non-unique IDs) S-1-5-0x15-... + * (NT non-unique IDs) S-1-5-0x15-... * - * (Built-in domain) S-1-5-0x20 + * (Built-in domain) S-1-5-0x20 */ /** @@ -1349,13 +1397,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 - @@ -1364,71 +1414,74 @@ typedef union { * users or groups. SID stands for security identifier. * * The standard textual representation of the SID is of the form: - * S-R-I-S-S... + * S-R-I-S-S... * Where: * - The first "S" is the literal character 'S' identifying the following - * digits as a SID. + * digits as a SID. * - R is the revision level of the SID expressed as a sequence of digits - * in decimal. + * in decimal. * - I is the 48-bit identifier_authority, expressed as digits in decimal, - * if I < 2^32, or hexadecimal prefixed by "0x", if I >= 2^32. + * if I < 2^32, or hexadecimal prefixed by "0x", if I >= 2^32. * - S... is one or more sub_authority values, expressed as digits in - * decimal. + * decimal. * * Example SID; the domain-relative SID of the local Administrators group on * Windows NT/2k: - * S-1-5-32-544 + * S-1-5-32-544 * This translates to a SID with: - * revision = 1, - * sub_authority_count = 2, - * identifier_authority = {0,0,0,0,0,5}, // SECURITY_NT_AUTHORITY - * sub_authority[0] = 32, // SECURITY_BUILTIN_DOMAIN_RID - * sub_authority[1] = 544 // DOMAIN_ALIAS_RID_ADMINS + * revision = 1, + * sub_authority_count = 2, + * identifier_authority = {0,0,0,0,0,5}, // SECURITY_NT_AUTHORITY + * 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 +1493,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 +1521,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 +1672,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 +1689,46 @@ 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 +1738,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; /** @@ -1711,65 +1773,66 @@ typedef enum { * The security descriptor control flags (16-bit). * * SE_OWNER_DEFAULTED - This boolean flag, when set, indicates that the - * SID pointed to by the Owner field was provided by a - * defaulting mechanism rather than explicitly provided by the - * original provider of the security descriptor. This may - * affect the treatment of the SID with respect to inheritance - * of an owner. + * SID pointed to by the Owner field was provided by a + * defaulting mechanism rather than explicitly provided by the + * original provider of the security descriptor. This may + * affect the treatment of the SID with respect to inheritance + * of an owner. * * SE_GROUP_DEFAULTED - This boolean flag, when set, indicates that the - * SID in the Group field was provided by a defaulting mechanism - * rather than explicitly provided by the original provider of - * the security descriptor. This may affect the treatment of - * the SID with respect to inheritance of a primary group. + * SID in the Group field was provided by a defaulting mechanism + * rather than explicitly provided by the original provider of + * the security descriptor. This may affect the treatment of + * the SID with respect to inheritance of a primary group. * * SE_DACL_PRESENT - This boolean flag, when set, indicates that the - * security descriptor contains a discretionary ACL. If this - * flag is set and the Dacl field of the SECURITY_DESCRIPTOR is - * null, then a null ACL is explicitly being specified. + * security descriptor contains a discretionary ACL. If this + * flag is set and the Dacl field of the SECURITY_DESCRIPTOR is + * null, then a null ACL is explicitly being specified. * * SE_DACL_DEFAULTED - This boolean flag, when set, indicates that the - * ACL pointed to by the Dacl field was provided by a defaulting - * mechanism rather than explicitly provided by the original - * provider of the security descriptor. This may affect the - * treatment of the ACL with respect to inheritance of an ACL. - * This flag is ignored if the DaclPresent flag is not set. + * ACL pointed to by the Dacl field was provided by a defaulting + * mechanism rather than explicitly provided by the original + * provider of the security descriptor. This may affect the + * treatment of the ACL with respect to inheritance of an ACL. + * This flag is ignored if the DaclPresent flag is not set. * * SE_SACL_PRESENT - This boolean flag, when set, indicates that the - * security descriptor contains a system ACL pointed to by the - * Sacl field. If this flag is set and the Sacl field of the - * SECURITY_DESCRIPTOR is null, then an empty (but present) - * ACL is being specified. + * security descriptor contains a system ACL pointed to by the + * Sacl field. If this flag is set and the Sacl field of the + * SECURITY_DESCRIPTOR is null, then an empty (but present) + * ACL is being specified. * * SE_SACL_DEFAULTED - This boolean flag, when set, indicates that the - * ACL pointed to by the Sacl field was provided by a defaulting - * mechanism rather than explicitly provided by the original - * provider of the security descriptor. This may affect the - * treatment of the ACL with respect to inheritance of an ACL. - * This flag is ignored if the SaclPresent flag is not set. + * ACL pointed to by the Sacl field was provided by a defaulting + * mechanism rather than explicitly provided by the original + * provider of the security descriptor. This may affect the + * treatment of the ACL with respect to inheritance of an ACL. + * This flag is ignored if the SaclPresent flag is not set. * * SE_SELF_RELATIVE - This boolean flag, when set, indicates that the - * security descriptor is in self-relative form. In this form, - * all fields of the security descriptor are contiguous in memory - * and all pointer fields are expressed as offsets from the - * beginning of the security descriptor. + * security descriptor is in self-relative form. In this form, + * all fields of the security descriptor are contiguous in memory + * 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 +1840,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 +1873,42 @@ 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 +1968,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 +2007,27 @@ 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 +2035,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 +2047,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). @@ -2001,14 +2074,15 @@ typedef enum { * NOTE: Always resident. * NOTE: Present only in FILE_Volume. * 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. + * 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 +2091,33 @@ 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 +2130,28 @@ 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 +2172,27 @@ 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 +2203,28 @@ 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 +2239,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,81 +2294,89 @@ 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). - * + * * ========================================================== * !!!!! 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 +2387,67 @@ 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 +2459,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 - @@ -2381,34 +2477,35 @@ typedef struct { * 2. The 13 bits after this (i.e. bits 16 to 28) are reserved for future use. * 3. The most significant three bits are flags describing the reparse point. * They are defined as follows: - * bit 29: Name surrogate bit. If set, the filename is an alias for - * another object in the system. - * bit 30: High-latency bit. If set, accessing the first byte of data will - * be slow. (E.g. the data is stored on a tape drive.) - * bit 31: Microsoft bit. If set, the tag is owned by Microsoft. User - * defined tags have to use zero here. + * bit 29: Name surrogate bit. If set, the filename is an alias for + * another object in the system. + * bit 30: High-latency bit. If set, accessing the first byte of data will + * be slow. (E.g. the data is stored on a tape drive.) + * 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 +2513,42 @@ 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 +2559,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 +2577,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 +2593,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 +2630,153 @@ 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..5399503d 100644 --- a/source/libntfs/lcnalloc.c +++ b/source/libntfs/lcnalloc.c @@ -48,157 +48,177 @@ /* * Plenty possibilities for big optimizations all over in the cluster - * allocation, however at the moment the dominant bottleneck (~ 90%) is + * allocation, however at the moment the dominant bottleneck (~ 90%) is * the update of the mapping pairs which converges to the cubic Faulhaber's * formula as the function of the number of extents (fragments, runs). */ #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) +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) +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 ); } /* - * Unmark full zones when a cluster has been freed in a full zone + * Unmark full zones when a cluster has been freed in a full zone * - * Next allocation will reuse the freed cluster + * Next allocation will reuse the freed cluster */ -static void update_full_status(ntfs_volume *vol, LCN lcn) +static void update_full_status( ntfs_volume *vol, LCN lcn ) { - if (lcn >= vol->mft_zone_end) { - if (vol->full_zones & ZONE_DATA1) { - ntfs_cluster_update_zone_pos(vol, ZONE_DATA1, lcn); - vol->full_zones &= ~ZONE_DATA1; - } - } else - if (lcn < vol->mft_zone_start) { - if (vol->full_zones & ZONE_DATA2) { - ntfs_cluster_update_zone_pos(vol, ZONE_DATA2, lcn); - vol->full_zones &= ~ZONE_DATA2; - } - } else { - if (vol->full_zones & ZONE_MFT) { - ntfs_cluster_update_zone_pos(vol, ZONE_MFT, lcn); - vol->full_zones &= ~ZONE_MFT; - } - } -} - -static s64 max_empty_bit_range(unsigned char *buf, int size) -{ - int i, j, run = 0; - int max_range = 0; - s64 start_pos = -1; - - ntfs_log_trace("Entering\n"); - - i = 0; - while (i < size) { - switch (*buf) { - case 0 : - do { - buf++; - run += 8; - i++; - } while ((i < size) && !*buf); - break; - case 255 : - if (run > max_range) { - max_range = run; - start_pos = (s64)i * 8 - run; - } - run = 0; - do { - buf++; - i++; - } while ((i < size) && (*buf == 255)); - break; - default : - for (j = 0; j < 8; j++) { - - int bit = *buf & (1 << j); - - if (bit) { - if (run > max_range) { - max_range = run; - start_pos = (s64)i * 8 + (j - run); - } - run = 0; - } else - run++; - } - i++; - buf++; - - } - } - - if (run > max_range) - start_pos = (s64)i * 8 - run; - - return start_pos; + 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 int bitmap_writeback(ntfs_volume *vol, s64 pos, s64 size, void *b, - u8 *writeback) +static s64 max_empty_bit_range( unsigned char *buf, int size ) { - 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; - } + int i, j, run = 0; + int max_range = 0; + s64 start_pos = -1; - return 0; + ntfs_log_trace( "Entering\n" ); + + i = 0; + while ( i < size ) + { + switch ( *buf ) + { + case 0 : + do + { + buf++; + run += 8; + i++; + } + while ( ( i < size ) && !*buf ); + break; + case 255 : + if ( run > max_range ) + { + max_range = run; + start_pos = ( s64 )i * 8 - run; + } + run = 0; + do + { + buf++; + i++; + } + while ( ( i < size ) && ( *buf == 255 ) ); + break; + default : + for ( j = 0; j < 8; j++ ) + { + + int bit = *buf & ( 1 << j ); + + if ( bit ) + { + if ( run > max_range ) + { + max_range = run; + start_pos = ( s64 )i * 8 + ( j - run ); + } + run = 0; + } + else + run++; + } + i++; + buf++; + + } + } + + if ( run > max_range ) + start_pos = ( s64 )i * 8 - run; + + return start_pos; +} + +static int bitmap_writeback( ntfs_volume *vol, s64 pos, s64 size, void *b, + u8 *writeback ) +{ + s64 written; + + ntfs_log_trace( "Entering\n" ); + + if ( !*writeback ) + return 0; + + *writeback = 0; + + written = ntfs_attr_pwrite( vol->lcnbmp_na, pos, size, b ); + if ( written != size ) + { + if ( !written ) + errno = EIO; + ntfs_log_perror( "Bitmap write error (%lld, %lld)", + ( long long )pos, ( long long )size ); + return -1; + } + + return 0; } /** * ntfs_cluster_alloc - allocate clusters on an ntfs volume - * @vol: mounted ntfs volume on which to allocate the clusters - * @start_vcn: vcn to use for the first allocated cluster - * @count: number of clusters to allocate - * @start_lcn: starting lcn at which to allocate the clusters (or -1 if none) - * @zone: zone from which to allocate the clusters + * @vol: mounted ntfs volume on which to allocate the clusters + * @start_vcn: vcn to use for the first allocated cluster + * @count: number of clusters to allocate + * @start_lcn: starting lcn at which to allocate the clusters (or -1 if none) + * @zone: zone from which to allocate the clusters * * Allocate @count clusters preferably starting at cluster @start_lcn or at the * current allocator position if @start_lcn is -1, on the mounted ntfs volume @@ -220,437 +240,477 @@ static int bitmap_writeback(ntfs_volume *vol, s64 pos, s64 size, void *b, * expanded to cover the start of the volume in order to reserve space for the * mft bitmap attribute. * - * The complexity stems from the need of implementing the mft vs data zoned - * approach and from the fact that we have access to the lcn bitmap via up to - * NTFS_LCNALLOC_BSIZE bytes at a time, so we need to cope with crossing over - * boundaries of two buffers. Further, the fact that the allocator allows for - * caller supplied hints as to the location of where allocation should begin - * and the fact that the allocator keeps track of where in the data zones the - * next natural allocation should occur, contribute to the complexity of the - * function. But it should all be worthwhile, because this allocator: + * The complexity stems from the need of implementing the mft vs data zoned + * approach and from the fact that we have access to the lcn bitmap via up to + * NTFS_LCNALLOC_BSIZE bytes at a time, so we need to cope with crossing over + * boundaries of two buffers. Further, the fact that the allocator allows for + * caller supplied hints as to the location of where allocation should begin + * and the fact that the allocator keeps track of where in the data zones the + * next natural allocation should occur, contribute to the complexity of the + * function. But it should all be worthwhile, because this allocator: * 1) implements MFT zone reservation - * 2) causes reduction in fragmentation. + * 2) causes reduction in fragmentation. * The code is not optimized for speed. */ -runlist *ntfs_cluster_alloc(ntfs_volume *vol, VCN start_vcn, s64 count, - LCN start_lcn, const NTFS_CLUSTER_ALLOCATION_ZONES zone) +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; + } + + used_zone_pos = has_guess ? 0 : 1; + + if ( !zone_start || zone_start == vol->mft_zone_start || + zone_start == vol->mft_zone_end ) + pass = 2; + + if ( zone_start < vol->mft_zone_start ) + { + zone_end = vol->mft_zone_start; + search_zone = ZONE_DATA2; + } + else if ( zone_start < vol->mft_zone_end ) + { + zone_end = vol->mft_zone_end; + search_zone = ZONE_MFT; + } + else + { + zone_end = vol->nr_clusters; + search_zone = ZONE_DATA1; + } + + bmp_pos = zone_start; + + /* Loop until all clusters are allocated. */ + clusters = count; + rlpos = rlsize = 0; + while ( 1 ) + { + /* check whether we have exhausted the current zone */ + if ( search_zone & vol->full_zones ) + goto zone_pass_done; + last_read_pos = bmp_pos >> 3; + br = ntfs_attr_pread( vol->lcnbmp_na, last_read_pos, + NTFS_LCNALLOC_BSIZE, buf ); + if ( br <= 0 ) + { + if ( !br ) + goto zone_pass_done; + err = errno; + ntfs_log_perror( "Reading $BITMAP failed" ); + goto err_ret; + } + /* + * We might have read less than NTFS_LCNALLOC_BSIZE bytes + * if we are close to the end of the attribute. + */ + buf_size = ( int )br << 3; + lcn = bmp_pos & 7; + bmp_pos &= ~7; + writeback = 0; + + while ( lcn < buf_size ) + { + byte = buf + ( lcn >> 3 ); + bit = 1 << ( lcn & 7 ); + if ( has_guess ) + { + if ( *byte & bit ) + { + has_guess = 0; + break; + } + } + else + { + lcn = max_empty_bit_range( buf, br ); + if ( lcn < 0 ) + break; + has_guess = 1; + continue; + } + + /* First free bit is at lcn + bmp_pos. */ + + /* Reallocate memory if necessary. */ + if ( ( rlpos + 2 ) * ( int )sizeof( runlist ) >= rlsize ) + { + rlsize += 4096; + trl = realloc( rl, rlsize ); + if ( !trl ) + { + err = ENOMEM; + ntfs_log_perror( "realloc() failed" ); + goto wb_err_ret; + } + rl = trl; + } + + /* Allocate the bitmap bit. */ + *byte |= bit; + writeback = 1; + if ( vol->free_clusters <= 0 ) + ntfs_log_error( "Non-positive free clusters " + "(%lld)!\n", + ( long long )vol->free_clusters ); + else + vol->free_clusters--; + + /* + * Coalesce with previous run if adjacent LCNs. + * Otherwise, append a new run. + */ + if ( prev_lcn == lcn + bmp_pos - prev_run_len && rlpos ) + { + ntfs_log_debug( "Cluster coalesce: prev_lcn: " + "%lld lcn: %lld bmp_pos: %lld " + "prev_run_len: %lld\n", + ( long long )prev_lcn, + ( long long )lcn, ( long long )bmp_pos, + ( long long )prev_run_len ); + rl[rlpos - 1].length = ++prev_run_len; + } + else + { + if ( rlpos ) + rl[rlpos].vcn = rl[rlpos - 1].vcn + + prev_run_len; + else + { + rl[rlpos].vcn = start_vcn; + ntfs_log_debug( "Start_vcn: %lld\n", + ( long long )start_vcn ); + } + + rl[rlpos].lcn = prev_lcn = lcn + bmp_pos; + rl[rlpos].length = prev_run_len = 1; + rlpos++; + } + + ntfs_log_debug( "RUN: %-16lld %-16lld %-16lld\n", + ( long long )rl[rlpos - 1].vcn, + ( long long )rl[rlpos - 1].lcn, + ( long long )rl[rlpos - 1].length ); + /* Done? */ + if ( !--clusters ) + { + if ( used_zone_pos ) + ntfs_cluster_update_zone_pos( vol, + search_zone, lcn + bmp_pos + 1 + + NTFS_LCNALLOC_SKIP ); + goto done_ret; + } + + lcn++; + } + + if ( bitmap_writeback( vol, last_read_pos, br, buf, &writeback ) ) + { + err = errno; + goto err_ret; + } + + if ( !used_zone_pos ) + { + + used_zone_pos = 1; + + if ( search_zone == ZONE_MFT ) + zone_start = vol->mft_zone_pos; + else if ( search_zone == ZONE_DATA1 ) + zone_start = vol->data1_zone_pos; + else + zone_start = vol->data2_zone_pos; + + if ( !zone_start || zone_start == vol->mft_zone_start || + zone_start == vol->mft_zone_end ) + pass = 2; + bmp_pos = zone_start; + } + else + bmp_pos += buf_size; + + if ( bmp_pos < zone_end ) + continue; zone_pass_done: - ntfs_log_trace("Finished current zone pass(%i).\n", pass); - if (pass == 1) { - pass = 2; - zone_end = zone_start; - - if (search_zone == ZONE_MFT) - zone_start = vol->mft_zone_start; - else if (search_zone == ZONE_DATA1) - zone_start = vol->mft_zone_end; - else - zone_start = 0; - - /* Sanity check. */ - if (zone_end < zone_start) - zone_end = zone_start; - - bmp_pos = zone_start; - - continue; - } - /* pass == 2 */ + ntfs_log_trace( "Finished current zone pass(%i).\n", pass ); + if ( pass == 1 ) + { + pass = 2; + zone_end = zone_start; + + if ( search_zone == ZONE_MFT ) + zone_start = vol->mft_zone_start; + else if ( search_zone == ZONE_DATA1 ) + zone_start = vol->mft_zone_end; + else + zone_start = 0; + + /* Sanity check. */ + if ( zone_end < zone_start ) + zone_end = zone_start; + + bmp_pos = zone_start; + + continue; + } + /* pass == 2 */ done_zones_check: - done_zones |= search_zone; - vol->full_zones |= search_zone; - if (done_zones < (ZONE_MFT + ZONE_DATA1 + ZONE_DATA2)) { - ntfs_log_trace("Switching zone.\n"); - pass = 1; - if (rlpos) { - LCN tc = rl[rlpos - 1].lcn + - rl[rlpos - 1].length + NTFS_LCNALLOC_SKIP; - - if (used_zone_pos) - ntfs_cluster_update_zone_pos(vol, - search_zone, tc); - } - - switch (search_zone) { - case ZONE_MFT: - ntfs_log_trace("Zone switch: mft -> data1\n"); -switch_to_data1_zone: search_zone = ZONE_DATA1; - zone_start = vol->data1_zone_pos; - zone_end = vol->nr_clusters; - if (zone_start == vol->mft_zone_end) - pass = 2; - break; - case ZONE_DATA1: - ntfs_log_trace("Zone switch: data1 -> data2\n"); - search_zone = ZONE_DATA2; - zone_start = vol->data2_zone_pos; - zone_end = vol->mft_zone_start; - if (!zone_start) - pass = 2; - break; - case ZONE_DATA2: - if (!(done_zones & ZONE_DATA1)) { - ntfs_log_trace("data2 -> data1\n"); - goto switch_to_data1_zone; - } - ntfs_log_trace("Zone switch: data2 -> mft\n"); - search_zone = ZONE_MFT; - zone_start = vol->mft_zone_pos; - zone_end = vol->mft_zone_end; - if (zone_start == vol->mft_zone_start) - pass = 2; - break; - } - - bmp_pos = zone_start; - - if (zone_start == zone_end) { - ntfs_log_trace("Empty zone, skipped.\n"); - goto done_zones_check; - } - - continue; - } - - ntfs_log_trace("All zones are finished, no space on device.\n"); - err = ENOSPC; - goto err_ret; - } + done_zones |= search_zone; + vol->full_zones |= search_zone; + if ( done_zones < ( ZONE_MFT + ZONE_DATA1 + ZONE_DATA2 ) ) + { + ntfs_log_trace( "Switching zone.\n" ); + pass = 1; + if ( rlpos ) + { + LCN tc = rl[rlpos - 1].lcn + + rl[rlpos - 1].length + NTFS_LCNALLOC_SKIP; + + if ( used_zone_pos ) + ntfs_cluster_update_zone_pos( vol, + search_zone, tc ); + } + + switch ( search_zone ) + { + case ZONE_MFT: + ntfs_log_trace( "Zone switch: mft -> data1\n" ); +switch_to_data1_zone: search_zone = ZONE_DATA1; + zone_start = vol->data1_zone_pos; + zone_end = vol->nr_clusters; + if ( zone_start == vol->mft_zone_end ) + pass = 2; + break; + case ZONE_DATA1: + ntfs_log_trace( "Zone switch: data1 -> data2\n" ); + search_zone = ZONE_DATA2; + zone_start = vol->data2_zone_pos; + zone_end = vol->mft_zone_start; + if ( !zone_start ) + pass = 2; + break; + case ZONE_DATA2: + if ( !( done_zones & ZONE_DATA1 ) ) + { + ntfs_log_trace( "data2 -> data1\n" ); + goto switch_to_data1_zone; + } + ntfs_log_trace( "Zone switch: data2 -> mft\n" ); + search_zone = ZONE_MFT; + zone_start = vol->mft_zone_pos; + zone_end = vol->mft_zone_end; + if ( zone_start == vol->mft_zone_start ) + pass = 2; + break; + } + + bmp_pos = zone_start; + + if ( zone_start == zone_end ) + { + ntfs_log_trace( "Empty zone, skipped.\n" ); + goto done_zones_check; + } + + continue; + } + + ntfs_log_trace( "All zones are finished, no space on device.\n" ); + err = ENOSPC; + goto err_ret; + } done_ret: - ntfs_log_debug("At done_ret.\n"); - /* Add runlist terminator element. */ - rl[rlpos].vcn = rl[rlpos - 1].vcn + rl[rlpos - 1].length; - rl[rlpos].lcn = LCN_RL_NOT_MAPPED; - rl[rlpos].length = 0; - if (bitmap_writeback(vol, last_read_pos, br, buf, &writeback)) { - err = errno; - goto err_ret; - } + ntfs_log_debug( "At done_ret.\n" ); + /* Add runlist terminator element. */ + rl[rlpos].vcn = rl[rlpos - 1].vcn + rl[rlpos - 1].length; + rl[rlpos].lcn = LCN_RL_NOT_MAPPED; + rl[rlpos].length = 0; + if ( bitmap_writeback( vol, last_read_pos, br, buf, &writeback ) ) + { + err = errno; + goto err_ret; + } done_err_ret: - free(buf); - if (err) { - errno = err; - ntfs_log_perror("Failed to allocate clusters"); - rl = NULL; - } -out: - ntfs_log_leave("\n"); - return rl; + free( buf ); + if ( err ) + { + errno = err; + ntfs_log_perror( "Failed to allocate clusters" ); + rl = NULL; + } +out: + ntfs_log_leave( "\n" ); + return rl; wb_err_ret: - ntfs_log_trace("At wb_err_ret.\n"); - if (bitmap_writeback(vol, last_read_pos, br, buf, &writeback)) - err = errno; + ntfs_log_trace( "At wb_err_ret.\n" ); + if ( bitmap_writeback( vol, last_read_pos, br, buf, &writeback ) ) + err = errno; err_ret: - ntfs_log_trace("At err_ret.\n"); - if (rl) { - /* Add runlist terminator element. */ - rl[rlpos].vcn = rl[rlpos - 1].vcn + rl[rlpos - 1].length; - rl[rlpos].lcn = LCN_RL_NOT_MAPPED; - rl[rlpos].length = 0; - ntfs_debug_runlist_dump(rl); - ntfs_cluster_free_from_rl(vol, rl); - free(rl); - rl = NULL; - } - goto done_err_ret; + ntfs_log_trace( "At err_ret.\n" ); + if ( rl ) + { + /* Add runlist terminator element. */ + rl[rlpos].vcn = rl[rlpos - 1].vcn + rl[rlpos - 1].length; + rl[rlpos].lcn = LCN_RL_NOT_MAPPED; + rl[rlpos].length = 0; + ntfs_debug_runlist_dump( rl ); + ntfs_cluster_free_from_rl( vol, rl ); + free( rl ); + rl = NULL; + } + goto done_err_ret; } /** * ntfs_cluster_free_from_rl - free clusters from runlist - * @vol: mounted ntfs volume on which to free the clusters - * @rl: runlist from which deallocate clusters + * @vol: mounted ntfs volume on which to free the clusters + * @rl: runlist from which deallocate clusters * * On success return 0 and on error return -1 with errno set to the error code. */ -int ntfs_cluster_free_from_rl(ntfs_volume *vol, runlist *rl) +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; + ret = 0; out: - vol->free_clusters += nr_freed; - if (vol->free_clusters > vol->nr_clusters) - ntfs_log_error("Too many free clusters (%lld > %lld)!", - (long long)vol->free_clusters, - (long long)vol->nr_clusters); - return ret; + vol->free_clusters += nr_freed; + if ( vol->free_clusters > vol->nr_clusters ) + ntfs_log_error( "Too many free clusters (%lld > %lld)!", + ( long long )vol->free_clusters, + ( long long )vol->nr_clusters ); + return ret; } /* - * Basic cluster run free - * Returns 0 if successful + * Basic cluster run free + * Returns 0 if successful */ -int ntfs_cluster_free_basic(ntfs_volume *vol, s64 lcn, s64 count) +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; + 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; + 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; } /** * ntfs_cluster_free - free clusters on an ntfs volume - * @vol: mounted ntfs volume on which to free the clusters - * @na: attribute whose runlist describes the clusters to free - * @start_vcn: vcn in @rl at which to start freeing clusters - * @count: number of clusters to free or -1 for all clusters + * @vol: mounted ntfs volume on which to free the clusters + * @na: attribute whose runlist describes the clusters to free + * @start_vcn: vcn in @rl at which to start freeing clusters + * @count: number of clusters to free or -1 for all clusters * * Free @count clusters starting at the cluster @start_vcn in the runlist * described by the attribute @na from the mounted ntfs volume @vol. @@ -661,111 +721,120 @@ out: * On success return the number of deallocated clusters (not counting sparse * clusters) and on error return -1 with errno set to the error code. */ -int ntfs_cluster_free(ntfs_volume *vol, ntfs_attr *na, VCN start_vcn, s64 count) +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; + 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; + 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..001717a0 100644 --- a/source/libntfs/lcnalloc.h +++ b/source/libntfs/lcnalloc.h @@ -1,6 +1,6 @@ /* * lcnalloc.h - Exports for cluster (de)allocation. Originated from the Linux-NTFS - * project. + * project. * * Copyright (c) 2002 Anton Altaparmakov * Copyright (c) 2004 Yura Pakhuchiy @@ -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_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..d3c4ed4c 100644 --- a/source/libntfs/logfile.c +++ b/source/libntfs/logfile.c @@ -45,8 +45,8 @@ /** * ntfs_check_restart_page_header - check the page header for consistency - * @rp: restart page header to check - * @pos: position in logfile at which the restart page header resides + * @rp: restart page header to check + * @pos: position in logfile at which the restart page header resides * * Check the restart page header @rp for consistency and return TRUE if it is * consistent and FALSE otherwise. @@ -54,100 +54,108 @@ * This function only needs NTFS_BLOCK_SIZE bytes in @rp, i.e. it does not * require the full restart page. */ -static BOOL ntfs_check_restart_page_header(RESTART_PAGE_HEADER *rp, s64 pos) +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; - } + ntfs_log_trace( "Entering.\n" ); + /* + * If the system or log page sizes are smaller than the ntfs block size + * or either is not a power of 2 we cannot handle this log file. + */ + logfile_system_page_size = le32_to_cpu( rp->system_page_size ); + logfile_log_page_size = le32_to_cpu( rp->log_page_size ); + if ( logfile_system_page_size < NTFS_BLOCK_SIZE || + logfile_log_page_size < NTFS_BLOCK_SIZE || + logfile_system_page_size & + ( logfile_system_page_size - 1 ) || + logfile_log_page_size & ( logfile_log_page_size - 1 ) ) + { + ntfs_log_error( "$LogFile uses unsupported page size.\n" ); + return FALSE; + } + /* + * We must be either at !pos (1st restart page) or at pos = system page + * size (2nd restart page). + */ + if ( pos && pos != logfile_system_page_size ) + { + ntfs_log_error( "Found restart area in incorrect " + "position in $LogFile.\n" ); + return FALSE; + } + /* We only know how to handle version 1.1. */ + if ( sle16_to_cpu( rp->major_ver ) != 1 || + sle16_to_cpu( rp->minor_ver ) != 1 ) + { + ntfs_log_error( "$LogFile version %i.%i is not " + "supported. (This driver supports version " + "1.1 only.)\n", ( int )sle16_to_cpu( rp->major_ver ), + ( int )sle16_to_cpu( rp->minor_ver ) ); + return FALSE; + } + /* + * If chkdsk has been run the restart page may not be protected by an + * update sequence array. + */ + if ( ntfs_is_chkd_record( rp->magic ) && !le16_to_cpu( rp->usa_count ) ) + { + have_usa = FALSE; + goto skip_usa_checks; + } + /* Verify the size of the update sequence array. */ + usa_count = 1 + ( logfile_system_page_size >> NTFS_BLOCK_SIZE_BITS ); + if ( usa_count != le16_to_cpu( rp->usa_count ) ) + { + ntfs_log_error( "$LogFile restart page specifies " + "inconsistent update sequence array count.\n" ); + return FALSE; + } + /* Verify the position of the update sequence array. */ + usa_ofs = le16_to_cpu( rp->usa_ofs ); + usa_end = usa_ofs + usa_count * sizeof( u16 ); + if ( usa_ofs < sizeof( RESTART_PAGE_HEADER ) || + usa_end > NTFS_BLOCK_SIZE - sizeof( u16 ) ) + { + ntfs_log_error( "$LogFile restart page specifies " + "inconsistent update sequence array offset.\n" ); + return FALSE; + } skip_usa_checks: - /* - * Verify the position of the restart area. It must be: - * - aligned to 8-byte boundary, - * - after the update sequence array, and - * - within the system page size. - */ - ra_ofs = le16_to_cpu(rp->restart_area_offset); - if (ra_ofs & 7 || (have_usa ? ra_ofs < usa_end : - ra_ofs < sizeof(RESTART_PAGE_HEADER)) || - ra_ofs > logfile_system_page_size) { - ntfs_log_error("$LogFile restart page specifies " - "inconsistent restart area offset.\n"); - return FALSE; - } - /* - * Only restart pages modified by chkdsk are allowed to have chkdsk_lsn - * set. - */ - if (!ntfs_is_chkd_record(rp->magic) && sle64_to_cpu(rp->chkdsk_lsn)) { - ntfs_log_error("$LogFile restart page is not modified " - "by chkdsk but a chkdsk LSN is specified.\n"); - return FALSE; - } - ntfs_log_trace("Done.\n"); - return TRUE; + /* + * Verify the position of the restart area. It must be: + * - aligned to 8-byte boundary, + * - after the update sequence array, and + * - within the system page size. + */ + ra_ofs = le16_to_cpu( rp->restart_area_offset ); + if ( ra_ofs & 7 || ( have_usa ? ra_ofs < usa_end : + ra_ofs < sizeof( RESTART_PAGE_HEADER ) ) || + ra_ofs > logfile_system_page_size ) + { + ntfs_log_error( "$LogFile restart page specifies " + "inconsistent restart area offset.\n" ); + return FALSE; + } + /* + * Only restart pages modified by chkdsk are allowed to have chkdsk_lsn + * set. + */ + if ( !ntfs_is_chkd_record( rp->magic ) && sle64_to_cpu( rp->chkdsk_lsn ) ) + { + ntfs_log_error( "$LogFile restart page is not modified " + "by chkdsk but a chkdsk LSN is specified.\n" ); + return FALSE; + } + ntfs_log_trace( "Done.\n" ); + return TRUE; } /** * ntfs_check_restart_area - check the restart area for consistency - * @rp: restart page whose restart area to check + * @rp: restart page whose restart area to check * * Check the restart area of the restart page @rp for consistency and return * TRUE if it is consistent and FALSE otherwise. @@ -158,110 +166,118 @@ skip_usa_checks: * This function only needs NTFS_BLOCK_SIZE bytes in @rp, i.e. it does not * require the full restart page. */ -static BOOL ntfs_check_restart_area(RESTART_PAGE_HEADER *rp) +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; } /** * ntfs_check_log_client_array - check the log client array for consistency - * @rp: restart page whose log client array to check + * @rp: restart page whose log client array to check * * Check the log client array of the restart page @rp for consistency and * return TRUE if it is consistent and FALSE otherwise. @@ -273,60 +289,63 @@ static BOOL ntfs_check_restart_area(RESTART_PAGE_HEADER *rp) * function needs @rp->system_page_size bytes in @rp, i.e. it requires the full * restart page and the page must be multi sector transfer deprotected. */ -static BOOL ntfs_check_log_client_array(RESTART_PAGE_HEADER *rp) +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; + ntfs_log_trace( "Entering.\n" ); + ra = ( RESTART_AREA* )( ( u8* )rp + le16_to_cpu( rp->restart_area_offset ) ); + ca = ( LOG_CLIENT_RECORD* )( ( u8* )ra + + le16_to_cpu( ra->client_array_offset ) ); + /* + * Check the ra->client_free_list first and then check the + * ra->client_in_use_list. Check each of the log client records in + * each of the lists and check that the array does not overflow the + * ra->log_clients value. Also keep track of the number of records + * visited as there cannot be more than ra->log_clients records and + * that way we detect eventual loops in within a list. + */ + nr_clients = le16_to_cpu( ra->log_clients ); + idx = le16_to_cpu( ra->client_free_list ); + in_free_list = TRUE; check_list: - for (idx_is_first = TRUE; idx != LOGFILE_NO_CLIENT_CPU; nr_clients--, - idx = le16_to_cpu(cr->next_client)) { - if (!nr_clients || idx >= le16_to_cpu(ra->log_clients)) - goto err_out; - /* Set @cr to the current log client record. */ - cr = ca + idx; - /* The first log client record must not have a prev_client. */ - if (idx_is_first) { - if (cr->prev_client != LOGFILE_NO_CLIENT) - goto err_out; - idx_is_first = FALSE; - } - } - /* Switch to and check the in use list if we just did the free list. */ - if (in_free_list) { - in_free_list = FALSE; - idx = le16_to_cpu(ra->client_in_use_list); - goto check_list; - } - ntfs_log_trace("Done.\n"); - return TRUE; + for ( idx_is_first = TRUE; idx != LOGFILE_NO_CLIENT_CPU; nr_clients--, + idx = le16_to_cpu( cr->next_client ) ) + { + if ( !nr_clients || idx >= le16_to_cpu( ra->log_clients ) ) + goto err_out; + /* Set @cr to the current log client record. */ + cr = ca + idx; + /* The first log client record must not have a prev_client. */ + if ( idx_is_first ) + { + if ( cr->prev_client != LOGFILE_NO_CLIENT ) + goto err_out; + idx_is_first = FALSE; + } + } + /* Switch to and check the in use list if we just did the free list. */ + if ( in_free_list ) + { + in_free_list = FALSE; + idx = le16_to_cpu( ra->client_in_use_list ); + goto check_list; + } + ntfs_log_trace( "Done.\n" ); + return TRUE; err_out: - ntfs_log_error("$LogFile log client array is corrupt.\n"); - return FALSE; + ntfs_log_error( "$LogFile log client array is corrupt.\n" ); + return FALSE; } /** * ntfs_check_and_load_restart_page - check the restart page for consistency - * @log_na: opened ntfs attribute for journal $LogFile - * @rp: restart page to check - * @pos: position in @log_na at which the restart page resides + * @log_na: opened ntfs attribute for journal $LogFile + * @rp: restart page to check + * @pos: position in @log_na at which the restart page resides * @wrp: [OUT] copy of the multi sector transfer deprotected restart page * @lsn: [OUT] set to the current logfile lsn on success * @@ -349,103 +368,112 @@ 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 { + ntfs_log_trace( "Entering.\n" ); + /* Check the restart page header for consistency. */ + if ( !ntfs_check_restart_page_header( rp, pos ) ) + { + /* Error output already done inside the function. */ + return EINVAL; + } + /* Check the restart area for consistency. */ + if ( !ntfs_check_restart_area( rp ) ) + { + /* Error output already done inside the function. */ + return EINVAL; + } + ra = ( RESTART_AREA* )( ( u8* )rp + le16_to_cpu( rp->restart_area_offset ) ); + /* + * Allocate a buffer to store the whole restart page so we can multi + * sector transfer deprotect it. + */ + trp = ntfs_malloc( le32_to_cpu( rp->system_page_size ) ); + if ( !trp ) + return errno; + /* + * Read the whole of the restart page into the buffer. If it fits + * completely inside @rp, just copy it from there. Otherwise read it + * from disk. + */ + if ( le32_to_cpu( rp->system_page_size ) <= NTFS_BLOCK_SIZE ) + memcpy( trp, rp, le32_to_cpu( rp->system_page_size ) ); + else if ( ntfs_attr_pread( log_na, pos, + le32_to_cpu( rp->system_page_size ), trp ) != + le32_to_cpu( rp->system_page_size ) ) + { + err = errno; + ntfs_log_error( "Failed to read whole restart page into the " + "buffer.\n" ); + if ( err != ENOMEM ) + err = EIO; + goto err_out; + } + /* + * Perform the multi sector transfer deprotection on the buffer if the + * restart page is protected. + */ + if ( ( !ntfs_is_chkd_record( trp->magic ) || le16_to_cpu( trp->usa_count ) ) + && ntfs_mst_post_read_fixup( ( NTFS_RECORD* )trp, + le32_to_cpu( rp->system_page_size ) ) ) + { + /* + * A multi sector tranfer error was detected. We only need to + * abort if the restart page contents exceed the multi sector + * transfer fixup of the first sector. + */ + if ( le16_to_cpu( rp->restart_area_offset ) + + le16_to_cpu( ra->restart_area_length ) > + NTFS_BLOCK_SIZE - ( int )sizeof( u16 ) ) + { + ntfs_log_error( "Multi sector transfer error " + "detected in $LogFile restart page.\n" ); + err = EINVAL; + goto err_out; + } + } + /* + * If the restart page is modified by chkdsk or there are no active + * logfile clients, the logfile is consistent. Otherwise, need to + * check the log client records for consistency, too. + */ + err = 0; + if ( ntfs_is_rstr_record( rp->magic ) && + ra->client_in_use_list != LOGFILE_NO_CLIENT ) + { + if ( !ntfs_check_log_client_array( trp ) ) + { + err = EINVAL; + goto err_out; + } + } + if ( lsn ) + { + if ( ntfs_is_rstr_record( rp->magic ) ) + *lsn = sle64_to_cpu( ra->current_lsn ); + else /* if (ntfs_is_chkd_record(rp->magic)) */ + *lsn = sle64_to_cpu( rp->chkdsk_lsn ); + } + ntfs_log_trace( "Done.\n" ); + if ( wrp ) + *wrp = trp; + else + { err_out: - free(trp); - } - return err; + free( trp ); + } + return err; } /** * ntfs_check_logfile - check in the journal if the volume is consistent - * @log_na: ntfs attribute of loaded journal $LogFile to check + * @log_na: ntfs attribute of loaded journal $LogFile to check * @rp: [OUT] on success this is a copy of the current restart page * * Check the $LogFile journal for consistency and return TRUE if it is @@ -460,177 +488,190 @@ err_out: * if the $LogFile was created on a system with a different page size to ours * yet and mst deprotection would fail if our page size is smaller. */ -BOOL ntfs_check_logfile(ntfs_attr *log_na, RESTART_PAGE_HEADER **rp) +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); + /* + * A non-empty block means the logfile is not empty while an + * empty block after a non-empty block has been encountered + * means we are done. + */ + if ( !ntfs_is_empty_recordp( ( le32* )kaddr ) ) + logfile_is_empty = FALSE; + else if ( !logfile_is_empty ) + break; + /* + * A log record page means there cannot be a restart page after + * this so no need to continue searching. + */ + if ( ntfs_is_rcrd_recordp( ( le32* )kaddr ) ) + break; + /* If not a (modified by chkdsk) restart page, continue. */ + if ( !ntfs_is_rstr_recordp( ( le32* )kaddr ) && + !ntfs_is_chkd_recordp( ( le32* )kaddr ) ) + { + if ( !pos ) + pos = NTFS_BLOCK_SIZE >> 1; + continue; + } + /* + * Check the (modified by chkdsk) restart page for consistency + * and get a copy of the complete multi sector transfer + * deprotected restart page. + */ + err = ntfs_check_and_load_restart_page( log_na, + ( RESTART_PAGE_HEADER* )kaddr, pos, + !rstr1_ph ? &rstr1_ph : &rstr2_ph, + !rstr1_ph ? &rstr1_lsn : &rstr2_lsn ); + if ( !err ) + { + /* + * If we have now found the first (modified by chkdsk) + * restart page, continue looking for the second one. + */ + if ( !pos ) + { + pos = NTFS_BLOCK_SIZE >> 1; + continue; + } + /* + * We have now found the second (modified by chkdsk) + * restart page, so we can stop looking. + */ + break; + } + /* + * Error output already done inside the function. Note, we do + * not abort if the restart page was invalid as we might still + * find a valid one further in the file. + */ + if ( err != EINVAL ) + goto err_out; + /* Continue looking. */ + if ( !pos ) + pos = NTFS_BLOCK_SIZE >> 1; + } + if ( kaddr ) + { + free( kaddr ); + kaddr = NULL; + } + if ( logfile_is_empty ) + { + NVolSetLogFileEmpty( vol ); is_empty: - ntfs_log_trace("Done. ($LogFile is empty.)\n"); - return TRUE; - } - if (!rstr1_ph) { - if (rstr2_ph) - ntfs_log_error("BUG: rstr2_ph isn't NULL!\n"); - ntfs_log_error("Did not find any restart pages in " - "$LogFile and it was not empty.\n"); - return FALSE; - } - /* If both restart pages were found, use the more recent one. */ - if (rstr2_ph) { - /* - * If the second restart area is more recent, switch to it. - * Otherwise just throw it away. - */ - if (rstr2_lsn > rstr1_lsn) { - ntfs_log_debug("Using second restart page as it is more " - "recent.\n"); - free(rstr1_ph); - rstr1_ph = rstr2_ph; - /* rstr1_lsn = rstr2_lsn; */ - } else { - ntfs_log_debug("Using first restart page as it is more " - "recent.\n"); - free(rstr2_ph); - } - rstr2_ph = NULL; - } - /* All consistency checks passed. */ - if (rp) - *rp = rstr1_ph; - else - free(rstr1_ph); - ntfs_log_trace("Done.\n"); - return TRUE; + ntfs_log_trace( "Done. ($LogFile is empty.)\n" ); + return TRUE; + } + if ( !rstr1_ph ) + { + if ( rstr2_ph ) + ntfs_log_error( "BUG: rstr2_ph isn't NULL!\n" ); + ntfs_log_error( "Did not find any restart pages in " + "$LogFile and it was not empty.\n" ); + return FALSE; + } + /* If both restart pages were found, use the more recent one. */ + if ( rstr2_ph ) + { + /* + * If the second restart area is more recent, switch to it. + * Otherwise just throw it away. + */ + if ( rstr2_lsn > rstr1_lsn ) + { + ntfs_log_debug( "Using second restart page as it is more " + "recent.\n" ); + free( rstr1_ph ); + rstr1_ph = rstr2_ph; + /* rstr1_lsn = rstr2_lsn; */ + } + else + { + ntfs_log_debug( "Using first restart page as it is more " + "recent.\n" ); + free( rstr2_ph ); + } + rstr2_ph = NULL; + } + /* All consistency checks passed. */ + if ( rp ) + *rp = rstr1_ph; + else + free( rstr1_ph ); + ntfs_log_trace( "Done.\n" ); + return TRUE; err_out: - free(kaddr); - free(rstr1_ph); - free(rstr2_ph); - return FALSE; + free( kaddr ); + free( rstr1_ph ); + free( rstr2_ph ); + return FALSE; } /** * ntfs_is_logfile_clean - check in the journal if the volume is clean - * @log_na: ntfs attribute of loaded journal $LogFile to check + * @log_na: ntfs attribute of loaded journal $LogFile to check * @rp: copy of the current restart page * * Analyze the $LogFile journal and return TRUE if it indicates the volume was @@ -648,47 +689,51 @@ err_out: * is empty this function requires that NVolLogFileEmpty() is true otherwise an * empty volume will be reported as dirty. */ -BOOL ntfs_is_logfile_clean(ntfs_attr *log_na, RESTART_PAGE_HEADER *rp) +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; } /** * ntfs_empty_logfile - empty the contents of the $LogFile journal - * @na: ntfs attribute of journal $LogFile to empty + * @na: ntfs attribute of journal $LogFile to empty * * Empty the contents of the $LogFile journal @na and return 0 on success and * -1 on error. @@ -697,41 +742,44 @@ BOOL ntfs_is_logfile_clean(ntfs_attr *log_na, RESTART_PAGE_HEADER *rp) * checked by a call to ntfs_check_logfile() and that ntfs_is_logfile_clean() * has been used to ensure that the $LogFile is clean. */ -int ntfs_empty_logfile(ntfs_attr *na) +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..1502d1f4 100644 --- a/source/libntfs/logfile.h +++ b/source/libntfs/logfile.h @@ -52,66 +52,69 @@ */ /* Some $LogFile related constants. */ -#define MaxLogFileSize 0x100000000ULL -#define DefaultLogPageSize 4096 -#define MinLogRecordPages 48 +#define MaxLogFileSize 0x100000000ULL +#define DefaultLogPageSize 4096 +#define MinLogRecordPages 48 /** * struct RESTART_PAGE_HEADER - Log file restart page header. * * 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 * in this particular client array. Also inside the client records themselves, * this means that there are no client records preceding or following this one. */ -#define LOGFILE_NO_CLIENT const_cpu_to_le16(0xffff) -#define LOGFILE_NO_CLIENT_CPU 0xffff +#define LOGFILE_NO_CLIENT const_cpu_to_le16(0xffff) +#define LOGFILE_NO_CLIENT_CPU 0xffff /* * 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 +125,141 @@ 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 +267,42 @@ 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,90 +312,98 @@ 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); -extern int ntfs_empty_logfile(ntfs_attr *na); +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 ); +extern int ntfs_empty_logfile( ntfs_attr *na ); #endif /* defined _NTFS_LOGFILE_H */ diff --git a/source/libntfs/logging.c b/source/libntfs/logging.c index 385bcaa6..15e572a8 100644 --- a/source/libntfs/logging.c +++ b/source/libntfs/logging.c @@ -63,33 +63,35 @@ static int tab; /** * struct ntfs_logging - Control info for the logging system - * @levels: Bitfield of logging levels - * @flags: Flags which affect the output style - * @handler: Function to perform the actual logging + * @levels: Bitfield of logging levels + * @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; }; /** * ntfs_log * This struct controls all the logging within the library and tools. */ -static struct ntfs_logging ntfs_log = { +static struct ntfs_logging ntfs_log = +{ #ifdef DEBUG - NTFS_LOG_LEVEL_DEBUG | NTFS_LOG_LEVEL_TRACE | NTFS_LOG_LEVEL_ENTER | - NTFS_LOG_LEVEL_LEAVE | + NTFS_LOG_LEVEL_DEBUG | NTFS_LOG_LEVEL_TRACE | NTFS_LOG_LEVEL_ENTER | + NTFS_LOG_LEVEL_LEAVE | #endif - NTFS_LOG_LEVEL_INFO | NTFS_LOG_LEVEL_QUIET | NTFS_LOG_LEVEL_WARNING | - NTFS_LOG_LEVEL_ERROR | NTFS_LOG_LEVEL_PERROR | NTFS_LOG_LEVEL_CRITICAL | - NTFS_LOG_LEVEL_PROGRESS, - NTFS_LOG_FLAG_ONLYNAME, + NTFS_LOG_LEVEL_INFO | NTFS_LOG_LEVEL_QUIET | NTFS_LOG_LEVEL_WARNING | + NTFS_LOG_LEVEL_ERROR | NTFS_LOG_LEVEL_PERROR | NTFS_LOG_LEVEL_CRITICAL | + NTFS_LOG_LEVEL_PROGRESS, + NTFS_LOG_FLAG_ONLYNAME, #ifdef DEBUG - ntfs_log_handler_outerr + ntfs_log_handler_outerr #else - ntfs_log_handler_null + ntfs_log_handler_null #endif }; @@ -101,43 +103,43 @@ static struct ntfs_logging ntfs_log = { * * Returns: Log levels in a 32-bit field */ -u32 ntfs_log_get_levels(void) +u32 ntfs_log_get_levels( void ) { - return ntfs_log.levels; + return ntfs_log.levels; } /** * ntfs_log_set_levels - Enable extra logging levels - * @levels: 32-bit field of log levels to set + * @levels: 32-bit field of log levels to set * * Enable one or more logging levels. * The logging levels are named: NTFS_LOG_LEVEL_*. * * Returns: Log levels that were enabled before the call */ -u32 ntfs_log_set_levels(u32 levels) +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; } /** * ntfs_log_clear_levels - Disable some logging levels - * @levels: 32-bit field of log levels to clear + * @levels: 32-bit field of log levels to clear * * Disable one or more logging levels. * The logging levels are named: NTFS_LOG_LEVEL_*. * * Returns: Log levels that were enabled before the call */ -u32 ntfs_log_clear_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; } @@ -148,163 +150,167 @@ u32 ntfs_log_clear_levels(u32 levels) * * Returns: Logging flags in a 32-bit field */ -u32 ntfs_log_get_flags(void) +u32 ntfs_log_get_flags( void ) { - return ntfs_log.flags; + return ntfs_log.flags; } /** * ntfs_log_set_flags - Enable extra logging style flags - * @flags: 32-bit field of logging flags to set + * @flags: 32-bit field of logging flags to set * * Enable one or more logging flags. * The log flags are named: NTFS_LOG_LEVEL_*. * * Returns: Logging flags that were enabled before the call */ -u32 ntfs_log_set_flags(u32 flags) +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; } /** * ntfs_log_clear_flags - Disable some logging styles - * @flags: 32-bit field of logging flags to clear + * @flags: 32-bit field of logging flags to clear * * Disable one or more logging flags. * The log flags are named: NTFS_LOG_LEVEL_*. * * Returns: Logging flags that were enabled before the call */ -u32 ntfs_log_clear_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 + * @level: Log level * * By default, urgent messages are sent to "stderr". * Other messages are sent to "stdout". * * Returns: "string" Prefix to be used */ -static FILE * ntfs_log_get_stream(u32 level) +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; } /** * ntfs_log_get_prefix - Default prefixes for logging levels - * @level: Log level to be prefixed + * @level: Log level to be prefixed * * Prefixing the logging output can make it easier to parse. * * Returns: "string" Prefix to be used */ -static const char * ntfs_log_get_prefix(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 + * @handler: function to perform the logging * * This alternate handler will be called for all future logging requests. * If no @handler is specified, logging will revert to the default handler. */ -void ntfs_log_set_handler(ntfs_log_handler *handler) +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; } /** * ntfs_log_redirect - Pass on the request to the real handler - * @function: Function in which the log line occurred - * @file: File in which the log line occurred - * @line: Line number on which the log line occurred - * @level: Level at which the line is logged - * @data: User specified data, possibly specific to a handler - * @format: printf-style formatting string - * @...: Arguments to be formatted + * @function: Function in which the log line occurred + * @file: File in which the log line occurred + * @line: Line number on which the log line occurred + * @level: Level at which the line is logged + * @data: User specified data, possibly specific to a handler + * @format: printf-style formatting string + * @...: Arguments to be formatted * * This is just a redirector function. The arguments are simply passed to the * main logging handler (as defined in the global logging struct @ntfs_log). @@ -313,35 +319,35 @@ 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 - * @file: File in which the log line occurred - * @line: Line number on which the log line occurred - * @level: Level at which the line is logged - * @data: User specified data, possibly specific to a handler - * @format: printf-style formatting string - * @args: Arguments to be formatted + * @function: Function in which the log line occurred + * @file: File in which the log line occurred + * @line: Line number on which the log line occurred + * @level: Level at which the line is logged + * @data: User specified data, possibly specific to a handler + * @format: printf-style formatting string + * @args: Arguments to be formatted * * A simple syslog logging handler. Ignores colors. * @@ -353,50 +359,52 @@ int ntfs_log_redirect(const char *function, const char *file, #ifdef HAVE_SYSLOG_H -#define LOG_LINE_LEN 512 +#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; -#endif - ret = vsnprintf(logbuf, LOG_LINE_LEN, format, args); - if (ret < 0) { - vsyslog(LOG_NOTICE, format, args); - ret = 1; - goto out; - } - - if ((LOG_LINE_LEN > ret + 3) && (level & NTFS_LOG_LEVEL_PERROR)) { - strncat(logbuf, ": ", LOG_LINE_LEN - ret - 1); - strncat(logbuf, strerror(olderr), LOG_LINE_LEN - (ret + 3)); - ret = strlen(logbuf); - } - - syslog(LOG_NOTICE, "%s", logbuf); + if ( ( level & NTFS_LOG_LEVEL_PERROR ) && errno == ENOSPC ) + return 1; +#endif + ret = vsnprintf( logbuf, LOG_LINE_LEN, format, args ); + if ( ret < 0 ) + { + vsyslog( LOG_NOTICE, format, args ); + ret = 1; + goto out; + } + + if ( ( LOG_LINE_LEN > ret + 3 ) && ( level & NTFS_LOG_LEVEL_PERROR ) ) + { + strncat( logbuf, ": ", LOG_LINE_LEN - ret - 1 ); + strncat( logbuf, strerror( olderr ), LOG_LINE_LEN - ( ret + 3 ) ); + ret = strlen( logbuf ); + } + + syslog( LOG_NOTICE, "%s", logbuf ); out: - errno = olderr; - return ret; + errno = olderr; + return ret; } #endif /** * ntfs_log_handler_fprintf - Basic logging handler - * @function: Function in which the log line occurred - * @file: File in which the log line occurred - * @line: Line number on which the log line occurred - * @level: Level at which the line is logged - * @data: User specified data, possibly specific to a handler - * @format: printf-style formatting string - * @args: Arguments to be formatted + * @function: Function in which the log line occurred + * @file: File in which the log line occurred + * @line: Line number on which the log line occurred + * @level: Level at which the line is logged + * @data: User specified data, possibly specific to a handler + * @format: printf-style formatting string + * @args: Arguments to be formatted * * A simple logging handler. This is where the log line is finally displayed. * It is more likely that you will want to set the handler to either @@ -409,92 +417,93 @@ 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, " "); -#endif - if ((ntfs_log.flags & NTFS_LOG_FLAG_ONLYNAME) && - (strchr(file, PATH_SEP))) /* Abbreviate the filename */ - file = strrchr(file, PATH_SEP) + 1; + if ( level == NTFS_LOG_LEVEL_LEAVE ) + { + if ( tab ) + tab--; + return 0; + } - if (ntfs_log.flags & NTFS_LOG_FLAG_PREFIX) /* Prefix the output */ - ret += fprintf(stream, "%s", ntfs_log_get_prefix(level)); + 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_FILENAME) /* Source filename */ - ret += fprintf(stream, "%s ", file); + 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_LINE) /* Source line number */ - ret += fprintf(stream, "(%d) ", line); + if ( ntfs_log.flags & NTFS_LOG_FLAG_FILENAME ) /* Source filename */ + ret += fprintf( stream, "%s ", file ); - 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_LINE ) /* Source line number */ + ret += fprintf( stream, "(%d) ", line ); - ret += vfprintf(stream, format, args); + 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 (level & NTFS_LOG_LEVEL_PERROR) - ret += fprintf(stream, ": %s\n", strerror(olderr)); + ret += vfprintf( stream, format, args ); + + if ( level & NTFS_LOG_LEVEL_PERROR ) + ret += fprintf( stream, ": %s\n", strerror( olderr ) ); #ifdef DEBUG - if (level == NTFS_LOG_LEVEL_ENTER) - tab++; -#endif - fflush(stream); - errno = olderr; - return ret; + if ( level == NTFS_LOG_LEVEL_ENTER ) + tab++; +#endif + fflush( stream ); + errno = olderr; + return ret; } /** * ntfs_log_handler_null - Null logging handler (no output) - * @function: Function in which the log line occurred - * @file: File in which the log line occurred - * @line: Line number on which the log line occurred - * @level: Level at which the line is logged - * @data: User specified data, possibly specific to a handler - * @format: printf-style formatting string - * @args: Arguments to be formatted + * @function: Function in which the log line occurred + * @file: File in which the log line occurred + * @line: Line number on which the log line occurred + * @level: Level at which the line is logged + * @data: User specified data, possibly specific to a handler + * @format: printf-style formatting string + * @args: Arguments to be formatted * * This handler produces no output. It provides a way to temporarily disable * logging, without having to change the levels and flags. * * 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; } /** * ntfs_log_handler_stdout - All logs go to stdout - * @function: Function in which the log line occurred - * @file: File in which the log line occurred - * @line: Line number on which the log line occurred - * @level: Level at which the line is logged - * @data: User specified data, possibly specific to a handler - * @format: printf-style formatting string - * @args: Arguments to be formatted + * @function: Function in which the log line occurred + * @file: File in which the log line occurred + * @line: Line number on which the log line occurred + * @level: Level at which the line is logged + * @data: User specified data, possibly specific to a handler + * @format: printf-style formatting string + * @args: Arguments to be formatted * * Display a log message to stdout. * @@ -507,24 +516,24 @@ 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 ); } /** * ntfs_log_handler_outerr - Logs go to stdout/stderr depending on level - * @function: Function in which the log line occurred - * @file: File in which the log line occurred - * @line: Line number on which the log line occurred - * @level: Level at which the line is logged - * @data: User specified data, possibly specific to a handler - * @format: printf-style formatting string - * @args: Arguments to be formatted + * @function: Function in which the log line occurred + * @file: File in which the log line occurred + * @line: Line number on which the log line occurred + * @level: Level at which the line is logged + * @data: User specified data, possibly specific to a handler + * @format: printf-style formatting string + * @args: Arguments to be formatted * * Display a log message. The output stream will be determined by the log * level. @@ -538,24 +547,24 @@ 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 ); } /** * ntfs_log_handler_stderr - All logs go to stderr - * @function: Function in which the log line occurred - * @file: File in which the log line occurred - * @line: Line number on which the log line occurred - * @level: Level at which the line is logged - * @data: User specified data, possibly specific to a handler - * @format: printf-style formatting string - * @args: Arguments to be formatted + * @function: Function in which the log line occurred + * @file: File in which the log line occurred + * @line: Line number on which the log line occurred + * @level: Level at which the line is logged + * @data: User specified data, possibly specific to a handler + * @format: printf-style formatting string + * @args: Arguments to be formatted * * Display a log message to stderr. * @@ -568,19 +577,19 @@ 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 + * @option: Option flag * * Delegate some of the work of parsing the command line. All the options begin * with "--log-". Options cause log levels to be enabled in @ntfs_log (the @@ -591,23 +600,30 @@ int ntfs_log_handler_stderr(const char *function, const char *file, * Returns: TRUE Option understood * FALSE Invalid log option */ -BOOL ntfs_log_parse_option(const char *option) +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..39c82e46 100644 --- a/source/libntfs/logging.h +++ b/source/libntfs/logging.h @@ -34,58 +34,58 @@ #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)))); +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_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_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 ) ) ); /* Enable/disable certain log levels */ -u32 ntfs_log_set_levels(u32 levels); -u32 ntfs_log_clear_levels(u32 levels); -u32 ntfs_log_get_levels(void); +u32 ntfs_log_set_levels( u32 levels ); +u32 ntfs_log_clear_levels( u32 levels ); +u32 ntfs_log_get_levels( void ); /* Enable/disable certain log flags */ -u32 ntfs_log_set_flags(u32 flags); -u32 ntfs_log_clear_flags(u32 flags); -u32 ntfs_log_get_flags(void); +u32 ntfs_log_set_flags( u32 flags ); +u32 ntfs_log_clear_flags( u32 flags ); +u32 ntfs_log_get_flags( void ); /* Turn command-line options into logging flags */ -BOOL ntfs_log_parse_option(const char *option); +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 */ -#define NTFS_LOG_LEVEL_TRACE (1 << 1) /* Entering function x() */ -#define NTFS_LOG_LEVEL_QUIET (1 << 2) /* Quietable output */ -#define NTFS_LOG_LEVEL_INFO (1 << 3) /* Volume needs defragmenting */ -#define NTFS_LOG_LEVEL_VERBOSE (1 << 4) /* Forced to continue */ -#define NTFS_LOG_LEVEL_PROGRESS (1 << 5) /* 54% complete */ -#define NTFS_LOG_LEVEL_WARNING (1 << 6) /* You should backup before starting */ -#define NTFS_LOG_LEVEL_ERROR (1 << 7) /* Operation failed, no damage done */ -#define NTFS_LOG_LEVEL_PERROR (1 << 8) /* Message : standard error description */ -#define NTFS_LOG_LEVEL_CRITICAL (1 << 9) /* Operation failed,damage may have occurred */ -#define NTFS_LOG_LEVEL_ENTER (1 << 10) /* Enter a function */ -#define NTFS_LOG_LEVEL_LEAVE (1 << 11) /* Leave a function */ +#define NTFS_LOG_LEVEL_DEBUG (1 << 0) /* x = 42 */ +#define NTFS_LOG_LEVEL_TRACE (1 << 1) /* Entering function x() */ +#define NTFS_LOG_LEVEL_QUIET (1 << 2) /* Quietable output */ +#define NTFS_LOG_LEVEL_INFO (1 << 3) /* Volume needs defragmenting */ +#define NTFS_LOG_LEVEL_VERBOSE (1 << 4) /* Forced to continue */ +#define NTFS_LOG_LEVEL_PROGRESS (1 << 5) /* 54% complete */ +#define NTFS_LOG_LEVEL_WARNING (1 << 6) /* You should backup before starting */ +#define NTFS_LOG_LEVEL_ERROR (1 << 7) /* Operation failed, no damage done */ +#define NTFS_LOG_LEVEL_PERROR (1 << 8) /* Message : standard error description */ +#define NTFS_LOG_LEVEL_CRITICAL (1 << 9) /* Operation failed,damage may have occurred */ +#define NTFS_LOG_LEVEL_ENTER (1 << 10) /* Enter a function */ +#define NTFS_LOG_LEVEL_LEAVE (1 << 11) /* Leave a function */ /* Logging style flags - Manage the style of the output */ -#define NTFS_LOG_FLAG_PREFIX (1 << 0) /* Prefix messages with "ERROR: ", etc */ -#define NTFS_LOG_FLAG_FILENAME (1 << 1) /* Show the file origin of the message */ -#define NTFS_LOG_FLAG_LINE (1 << 2) /* Show the line number of the message */ -#define NTFS_LOG_FLAG_FUNCTION (1 << 3) /* Show the function name containing the message */ -#define NTFS_LOG_FLAG_ONLYNAME (1 << 4) /* Only display the filename, not the pathname */ +#define NTFS_LOG_FLAG_PREFIX (1 << 0) /* Prefix messages with "ERROR: ", etc */ +#define NTFS_LOG_FLAG_FILENAME (1 << 1) /* Show the file origin of the message */ +#define NTFS_LOG_FLAG_LINE (1 << 2) /* Show the line number of the message */ +#define NTFS_LOG_FLAG_FUNCTION (1 << 3) /* Show the function name containing the message */ +#define NTFS_LOG_FLAG_ONLYNAME (1 << 4) /* Only display the filename, not the pathname */ /* Macros to simplify logging. One for each level defined above. * Note, ntfs_log_debug/trace have effect only if DEBUG is defined. diff --git a/source/libntfs/mem_allocate.h b/source/libntfs/mem_allocate.h index 600e5a93..e87afbe4 100644 --- a/source/libntfs/mem_allocate.h +++ b/source/libntfs/mem_allocate.h @@ -24,20 +24,23 @@ #include -static inline void* ntfs_alloc (size_t size) { - return malloc(size); +static inline void* ntfs_alloc ( size_t size ) +{ + return malloc( size ); } -static inline void* ntfs_align (size_t size) { - #ifdef __wii__ - return memalign(32, size); - #else - return malloc(size); - #endif +static inline void* ntfs_align ( size_t size ) +{ +#ifdef __wii__ + return memalign( 32, size ); +#else + return malloc( size ); +#endif } -static inline void ntfs_free (void* mem) { - free(mem); +static inline void ntfs_free ( void* mem ) +{ + free( mem ); } #endif /* _MEM_ALLOCATE_H */ diff --git a/source/libntfs/mft.c b/source/libntfs/mft.c index e93c6646..e61609f3 100644 --- a/source/libntfs/mft.c +++ b/source/libntfs/mft.c @@ -59,10 +59,10 @@ /** * ntfs_mft_records_read - read records from the mft from disk - * @vol: volume to read from - * @mref: starting mft record number to read - * @count: number of mft records to read - * @b: output data buffer + * @vol: volume to read from + * @mref: starting mft record number to read + * @count: number of mft records to read + * @b: output data buffer * * Read @count mft records starting at @mref from volume @vol into buffer * @b. Return 0 on success or -1 on error, with errno set to the error @@ -78,50 +78,53 @@ * * 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; } /** * ntfs_mft_records_write - write mft records to disk - * @vol: volume to write to - * @mref: starting mft record number to write - * @count: number of mft records to write - * @b: data buffer containing the mft records to write + * @vol: volume to write to + * @mref: starting mft record number to write + * @count: number of mft records to write + * @b: data buffer containing the mft records to write * * Write @count mft records starting at @mref from data buffer @b to volume * @vol. Return 0 on success or -1 on error, with errno set to the error code. @@ -140,115 +143,125 @@ 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; +int ntfs_mft_record_check( const ntfs_volume *vol, const MFT_REF mref, + MFT_RECORD *m ) +{ + ATTR_RECORD *a; + int ret = -1; + + if ( !ntfs_is_file_record( m->magic ) ) + { + ntfs_log_error( "Record %llu has no FILE magic (0x%x)\n", + ( unsigned long long )MREF( mref ), *( le32 * )m ); + goto err_out; + } + + if ( le32_to_cpu( m->bytes_allocated ) != vol->mft_record_size ) + { + ntfs_log_error( "Record %llu has corrupt allocation size " + "(%u <> %u)\n", ( unsigned long long )MREF( mref ), + vol->mft_record_size, + le32_to_cpu( m->bytes_allocated ) ); + goto err_out; + } + + a = ( ATTR_RECORD * )( ( char * )m + le16_to_cpu( m->attrs_offset ) ); + if ( p2n( a ) < p2n( m ) || ( char * )a > ( char * )m + vol->mft_record_size ) + { + ntfs_log_error( "Record %llu is corrupt\n", + ( unsigned long long )MREF( mref ) ); + goto err_out; + } + + ret = 0; err_out: - if (ret) - errno = EIO; - return ret; + if ( ret ) + errno = EIO; + return ret; } /** * ntfs_file_record_read - read a FILE record from the mft from disk - * @vol: volume to read from - * @mref: mft reference specifying mft record to read - * @mrec: address of pointer in which to return the mft record - * @attr: address of pointer in which to return the first attribute + * @vol: volume to read from + * @mref: mft reference specifying mft record to read + * @mrec: address of pointer in which to return the mft record + * @attr: address of pointer in which to return the first attribute * * Read a FILE record from the mft of @vol from the storage medium. @mref * specifies the mft record to read, including the sequence number, which can @@ -272,53 +285,56 @@ err_out: * Note: Caller has to free *@mrec when finished. * * Note: We do not check if the mft record is flagged in use. The caller can - * check if desired. + * 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; + 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; + if ( m != *mrec ) + free( m ); + return -1; } /** * ntfs_mft_record_layout - layout an mft record into a memory buffer - * @vol: volume to which the mft record will belong - * @mref: mft reference specifying the mft record number - * @mrec: destination buffer of size >= @vol->mft_record_size bytes + * @vol: volume to which the mft record will belong + * @mref: mft reference specifying the mft record number + * @mrec: destination buffer of size >= @vol->mft_record_size bytes * * Layout an empty, unused mft record with the mft reference @mref into the * buffer @m. The volume @vol is needed because the mft record structure was @@ -327,106 +343,110 @@ 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; } /** * ntfs_mft_record_format - format an mft record on an ntfs volume - * @vol: volume on which to format the mft record - * @mref: mft reference specifying mft record to format + * @vol: volume on which to format the mft record + * @mref: mft reference specifying mft record to format * * Format the mft record with the mft reference @mref in $MFT/$DATA, i.e. lay * out an empty, unused mft record in memory and write it to the volume @vol. * * On success return 0 and on error return -1 with errno set to the error code. */ -int ntfs_mft_record_format(const ntfs_volume *vol, const MFT_REF mref) +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; + ntfs_log_enter( "Entering\n" ); + + m = ntfs_calloc( vol->mft_record_size ); + if ( !m ) + goto out; + + if ( ntfs_mft_record_layout( vol, mref, m ) ) + goto free_m; + + if ( ntfs_mft_record_write( vol, mref, m ) ) + goto free_m; + + ret = 0; free_m: - free(m); -out: - ntfs_log_leave("\n"); - return ret; + free( m ); +out: + ntfs_log_leave( "\n" ); + return ret; } static const char *es = " Leaving inconsistent metadata. Run chkdsk."; @@ -439,16 +459,16 @@ static const char *es = " Leaving inconsistent metadata. Run chkdsk."; * * Returns: */ -static inline unsigned int ntfs_ffz(unsigned int word) +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) +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 @@ -459,8 +479,8 @@ static int ntfs_is_mft(ntfs_inode *ni) /** * ntfs_mft_bitmap_find_free_rec - find a free mft record in the mft bitmap - * @vol: volume on which to search for a free mft record - * @base_ni: open base inode if allocating an extent mft record or NULL + * @vol: volume on which to search for a free mft record + * @base_ni: open base inode if allocating an extent mft record or NULL * * Search for a free mft record in the mft bitmap attribute on the ntfs volume * @vol. @@ -474,370 +494,396 @@ static int ntfs_is_mft(ntfs_inode *ni) * error code. An error code of ENOSPC means that there are no free mft * records in the currently initialized mft bitmap. */ -static int ntfs_mft_bitmap_find_free_rec(ntfs_volume *vol, ntfs_inode *base_ni) +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; + /* Loop until a free mft record is found. */ + for ( ; pass <= 2; size = PAGE_SIZE ) + { + /* Cap size to pass_end. */ + ofs = data_pos >> 3; + ll = ( ( pass_end + 7 ) >> 3 ) - ofs; + if ( size > ll ) + size = ll; + ll = ntfs_attr_pread( mftbmp_na, ofs, size, buf ); + if ( ll < 0 ) + { + ntfs_log_perror( "Failed to read $MFT bitmap" ); + free( buf ); + goto leave; + } + ntfs_log_debug( "Read 0x%llx bytes.\n", ( long long )ll ); + /* If we read at least one byte, search @buf for a zero bit. */ + if ( ll ) + { + size = ll << 3; + bit = data_pos & 7; + data_pos &= ~7ull; + ntfs_log_debug( "Before inner for loop: size 0x%x, " + "data_pos 0x%llx, bit 0x%llx, " + "*byte 0x%hhx, b %u.\n", size, + ( long long )data_pos, ( long long )bit, + byte ? *byte : -1, b ); + for ( ; bit < size && data_pos + bit < pass_end; + bit &= ~7ull, bit += 8 ) + { + /* + * If we're extending $MFT and running out of the first + * mft record (base record) then give up searching since + * no guarantee that the found record will be accessible. + */ + if ( ntfs_is_mft( base_ni ) && bit > 400 ) + goto out; + + byte = buf + ( bit >> 3 ); + if ( *byte == 0xff ) + continue; + + /* Note: ffz() result must be zero based. */ + b = ntfs_ffz( ( unsigned long ) * byte ); + if ( b < 8 && b >= ( bit & 7 ) ) + { + free( buf ); + ret = data_pos + ( bit & ~7ull ) + b; + goto leave; + } + } + ntfs_log_debug( "After inner for loop: size 0x%x, " + "data_pos 0x%llx, bit 0x%llx, " + "*byte 0x%hhx, b %u.\n", size, + ( long long )data_pos, ( long long )bit, + byte ? *byte : -1, b ); + data_pos += size; + /* + * If the end of the pass has not been reached yet, + * continue searching the mft bitmap for a zero bit. + */ + if ( data_pos < pass_end ) + continue; + } + /* Do the next pass. */ + pass++; + if ( pass == 2 ) + { + /* + * Starting the second pass, in which we scan the first + * part of the zone which we omitted earlier. + */ + pass_end = pass_start; + data_pos = pass_start = RESERVED_MFT_RECORDS; + ntfs_log_debug( "pass %i, pass_start 0x%llx, pass_end " + "0x%llx.\n", pass, ( long long )pass_start, + ( long long )pass_end ); + if ( data_pos >= pass_end ) + break; + } + } + /* No free mft records in currently initialized mft bitmap. */ +out: + free( buf ); + errno = ENOSPC; leave: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave( "\n" ); + return ret; } -static int ntfs_mft_attr_extend(ntfs_attr *na) +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; } /** * ntfs_mft_bitmap_extend_allocation_i - see ntfs_mft_bitmap_extend_allocation */ -static int ntfs_mft_bitmap_extend_allocation_i(ntfs_volume *vol) +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; - } + rl2 = ntfs_cluster_alloc( vol, rl[1].vcn, 1, lcn, DATA_ZONE ); + if ( !rl2 ) + { + ntfs_log_error( "Failed to allocate a cluster for " + "the mft bitmap.\n" ); + return STATUS_ERROR; + } + rl = ntfs_runlists_merge( mftbmp_na->rl, rl2 ); + if ( !rl ) + { + err = errno; + ntfs_log_error( "Failed to merge runlists for mft " + "bitmap.\n" ); + if ( ntfs_cluster_free_from_rl( vol, rl2 ) ) + ntfs_log_error( "Failed to deallocate " + "cluster.%s\n", es ); + free( rl2 ); + errno = err; + return STATUS_ERROR; + } + mftbmp_na->rl = rl; + ntfs_log_debug( "Adding one run to mft bitmap.\n" ); + /* Find the last run in the new runlist. */ + for ( ; rl[1].length; rl++ ) + ; + /* + * Update the attribute record as well. Note: @rl is the last + * (non-terminator) runlist element of mft bitmap. + */ + ctx = ntfs_attr_get_search_ctx( mftbmp_na->ni, NULL ); + if ( !ctx ) + goto undo_alloc; + + if ( ntfs_attr_lookup( mftbmp_na->type, mftbmp_na->name, + mftbmp_na->name_len, 0, rl[1].vcn, NULL, 0, ctx ) ) + { + ntfs_log_error( "Failed to find last attribute extent of " + "mft bitmap attribute.\n" ); + goto undo_alloc; + } + m = ctx->mrec; + a = ctx->attr; + ll = sle64_to_cpu( a->lowest_vcn ); + rl2 = ntfs_attr_find_vcn( mftbmp_na, ll ); + if ( !rl2 || !rl2->length ) + { + ntfs_log_error( "Failed to determine previous last " + "allocated cluster of mft bitmap attribute.\n" ); + if ( rl2 ) + errno = EIO; + goto undo_alloc; + } + /* Get the size for the new mapping pairs array for this extent. */ + mp_size = ntfs_get_size_for_mapping_pairs( vol, rl2, ll, INT_MAX ); + if ( mp_size <= 0 ) + { + ntfs_log_error( "Get size for mapping pairs failed for " + "mft bitmap attribute extent.\n" ); + goto undo_alloc; + } + /* Expand the attribute record if necessary. */ + old_alen = le32_to_cpu( a->length ); + if ( ntfs_attr_record_resize( m, a, mp_size + + le16_to_cpu( a->mapping_pairs_offset ) ) ) + { + ntfs_log_info( "extending $MFT bitmap\n" ); + ret = ntfs_mft_attr_extend( vol->mftbmp_na ); + if ( ret == STATUS_OK ) + goto ok; + if ( ret == STATUS_ERROR ) + { + ntfs_log_perror( "%s: ntfs_mft_attr_extend failed", __FUNCTION__ ); + update_mp = TRUE; + } + goto undo_alloc; + } + mp_rebuilt = TRUE; + /* Generate the mapping pairs array directly into the attr record. */ + if ( ntfs_mapping_pairs_build( vol, ( u8* )a + + le16_to_cpu( a->mapping_pairs_offset ), mp_size, rl2, ll, + NULL ) ) + { + ntfs_log_error( "Failed to build mapping pairs array for " + "mft bitmap attribute.\n" ); + errno = EIO; + goto undo_alloc; + } + /* Update the highest_vcn. */ + a->highest_vcn = cpu_to_sle64( rl[1].vcn - 1 ); + /* + * We now have extended the mft bitmap allocated_size by one cluster. + * Reflect this in the ntfs_attr structure and the attribute record. + */ + if ( a->lowest_vcn ) + { + /* + * We are not in the first attribute extent, switch to it, but + * first ensure the changes will make it to disk later. + */ + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + ntfs_attr_reinit_search_ctx( ctx ); + if ( ntfs_attr_lookup( mftbmp_na->type, mftbmp_na->name, + mftbmp_na->name_len, 0, 0, NULL, 0, ctx ) ) + { + ntfs_log_error( "Failed to find first attribute " + "extent of mft bitmap attribute.\n" ); + goto restore_undo_alloc; + } + a = ctx->attr; + } ok: - mftbmp_na->allocated_size += vol->cluster_size; - a->allocated_size = cpu_to_sle64(mftbmp_na->allocated_size); - /* Ensure the changes make it to disk. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - return STATUS_OK; + mftbmp_na->allocated_size += vol->cluster_size; + a->allocated_size = cpu_to_sle64( mftbmp_na->allocated_size ); + /* Ensure the changes make it to disk. */ + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + ntfs_attr_put_search_ctx( ctx ); + return STATUS_OK; restore_undo_alloc: - err = errno; - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_lookup(mftbmp_na->type, mftbmp_na->name, - mftbmp_na->name_len, 0, rl[1].vcn, NULL, 0, ctx)) { - ntfs_log_error("Failed to find last attribute extent of " - "mft bitmap attribute.%s\n", es); - ntfs_attr_put_search_ctx(ctx); - mftbmp_na->allocated_size += vol->cluster_size; - /* - * The only thing that is now wrong is ->allocated_size of the - * base attribute extent which chkdsk should be able to fix. - */ - errno = err; - return STATUS_ERROR; - } - m = ctx->mrec; - a = ctx->attr; - a->highest_vcn = cpu_to_sle64(rl[1].vcn - 2); - errno = err; + err = errno; + ntfs_attr_reinit_search_ctx( ctx ); + if ( ntfs_attr_lookup( mftbmp_na->type, mftbmp_na->name, + mftbmp_na->name_len, 0, rl[1].vcn, NULL, 0, ctx ) ) + { + ntfs_log_error( "Failed to find last attribute extent of " + "mft bitmap attribute.%s\n", es ); + ntfs_attr_put_search_ctx( ctx ); + mftbmp_na->allocated_size += vol->cluster_size; + /* + * The only thing that is now wrong is ->allocated_size of the + * base attribute extent which chkdsk should be able to fix. + */ + errno = err; + return STATUS_ERROR; + } + m = ctx->mrec; + a = ctx->attr; + a->highest_vcn = cpu_to_sle64( rl[1].vcn - 2 ); + errno = err; undo_alloc: - err = errno; + err = errno; - /* Remove the last run from the runlist. */ - lcn = rl->lcn; - rl->lcn = rl[1].lcn; - rl->length = 0; - - /* FIXME: use an ntfs_cluster_free_* function */ - if (ntfs_bitmap_clear_bit(vol->lcnbmp_na, lcn)) - ntfs_log_error("Failed to free cluster.%s\n", es); - else - vol->free_clusters++; - if (mp_rebuilt) { - if (ntfs_mapping_pairs_build(vol, (u8*)a + - le16_to_cpu(a->mapping_pairs_offset), - old_alen - le16_to_cpu(a->mapping_pairs_offset), - rl2, ll, NULL)) - ntfs_log_error("Failed to restore mapping " - "pairs array.%s\n", es); - if (ntfs_attr_record_resize(m, a, old_alen)) - ntfs_log_error("Failed to restore attribute " - "record.%s\n", es); - ntfs_inode_mark_dirty(ctx->ntfs_ino); - } - if (update_mp) { - if (ntfs_attr_update_mapping_pairs(vol->mftbmp_na, 0)) - ntfs_log_perror("%s: MP update failed", __FUNCTION__); - } - if (ctx) - ntfs_attr_put_search_ctx(ctx); - errno = err; - return ret; + /* Remove the last run from the runlist. */ + lcn = rl->lcn; + rl->lcn = rl[1].lcn; + rl->length = 0; + + /* FIXME: use an ntfs_cluster_free_* function */ + if ( ntfs_bitmap_clear_bit( vol->lcnbmp_na, lcn ) ) + ntfs_log_error( "Failed to free cluster.%s\n", es ); + else + vol->free_clusters++; + if ( mp_rebuilt ) + { + if ( ntfs_mapping_pairs_build( vol, ( u8* )a + + le16_to_cpu( a->mapping_pairs_offset ), + old_alen - le16_to_cpu( a->mapping_pairs_offset ), + rl2, ll, NULL ) ) + ntfs_log_error( "Failed to restore mapping " + "pairs array.%s\n", es ); + if ( ntfs_attr_record_resize( m, a, old_alen ) ) + ntfs_log_error( "Failed to restore attribute " + "record.%s\n", es ); + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + } + if ( update_mp ) + { + if ( ntfs_attr_update_mapping_pairs( vol->mftbmp_na, 0 ) ) + ntfs_log_perror( "%s: MP update failed", __FUNCTION__ ); + } + if ( ctx ) + ntfs_attr_put_search_ctx( ctx ); + errno = err; + return ret; } /** * ntfs_mft_bitmap_extend_allocation - extend mft bitmap attribute by a cluster - * @vol: volume on which to extend the mft bitmap attribute + * @vol: volume on which to extend the mft bitmap attribute * * Extend the mft bitmap attribute on the ntfs volume @vol by one cluster. * @@ -846,18 +892,18 @@ undo_alloc: * * Return 0 on success and -1 on error with errno set to the error code. */ -static int ntfs_mft_bitmap_extend_allocation(ntfs_volume *vol) +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 - * @vol: volume on which to extend the mft bitmap attribute + * @vol: volume on which to extend the mft bitmap attribute * * Extend the initialized portion of the mft bitmap attribute on the ntfs * volume @vol by 8 bytes. @@ -867,91 +913,96 @@ static int ntfs_mft_bitmap_extend_allocation(ntfs_volume *vol) * * Return 0 on success and -1 on error with errno set to the error code. */ -static int ntfs_mft_bitmap_extend_initialized(ntfs_volume *vol) +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); + 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); + ntfs_attr_put_search_ctx( ctx ); + goto err_out; + } + a = ctx->attr; + mftbmp_na->initialized_size = old_initialized_size; + a->initialized_size = cpu_to_sle64( old_initialized_size ); + if ( mftbmp_na->data_size != old_data_size ) + { + mftbmp_na->data_size = old_data_size; + a->data_size = cpu_to_sle64( old_data_size ); + } + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + ntfs_attr_put_search_ctx( ctx ); + ntfs_log_debug( "Restored status of mftbmp: allocated_size 0x%llx, " + "data_size 0x%llx, initialized_size 0x%llx.\n", + ( long long )mftbmp_na->allocated_size, + ( long long )mftbmp_na->data_size, + ( long long )mftbmp_na->initialized_size ); err_out: - errno = err; + errno = err; out: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave( "\n" ); + return ret; } /** * ntfs_mft_data_extend_allocation - extend mft data attribute - * @vol: volume on which to extend the mft data attribute + * @vol: volume on which to extend the mft data attribute * * Extend the mft data attribute on the ntfs volume @vol by 16 mft records * worth of clusters or if not enough space for this by one mft record worth @@ -962,549 +1013,579 @@ out: * * Return 0 on success and -1 on error with errno set to the error code. */ -static int ntfs_mft_data_extend_allocation(ntfs_volume *vol) +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; - } + mft_na = vol->mft_na; + /* + * Determine the preferred allocation location, i.e. the last lcn of + * the mft data attribute. The allocated size of the mft data + * attribute cannot be zero so we are ok to do this. + */ + rl = ntfs_attr_find_vcn( mft_na, + ( mft_na->allocated_size - 1 ) >> vol->cluster_size_bits ); + + if ( !rl || !rl->length || rl->lcn < 0 ) + { + ntfs_log_error( "Failed to determine last allocated " + "cluster of mft data attribute.\n" ); + if ( rl ) + errno = EIO; + goto out; + } + + lcn = rl->lcn + rl->length; + ntfs_log_debug( "Last lcn of mft data attribute is 0x%llx.\n", ( long long )lcn ); + /* Minimum allocation is one mft record worth of clusters. */ + min_nr = vol->mft_record_size >> vol->cluster_size_bits; + if ( !min_nr ) + min_nr = 1; + /* Want to allocate 16 mft records worth of clusters. */ + nr = vol->mft_record_size << 4 >> vol->cluster_size_bits; + if ( !nr ) + nr = min_nr; + + old_last_vcn = rl[1].vcn; + do + { + rl2 = ntfs_cluster_alloc( vol, old_last_vcn, nr, lcn, MFT_ZONE ); + if ( rl2 ) + break; + if ( errno != ENOSPC || nr == min_nr ) + { + ntfs_log_perror( "Failed to allocate (%lld) clusters " + "for $MFT", ( long long )nr ); + goto out; + } + /* + * There is not enough space to do the allocation, but there + * might be enough space to do a minimal allocation so try that + * before failing. + */ + nr = min_nr; + ntfs_log_debug( "Retrying mft data allocation with minimal cluster " + "count %lli.\n", ( long long )nr ); + } + while ( 1 ); + + ntfs_log_debug( "Allocated %lld clusters.\n", ( long long )nr ); + + rl = ntfs_runlists_merge( mft_na->rl, rl2 ); + if ( !rl ) + { + err = errno; + ntfs_log_error( "Failed to merge runlists for mft data " + "attribute.\n" ); + if ( ntfs_cluster_free_from_rl( vol, rl2 ) ) + ntfs_log_error( "Failed to deallocate clusters " + "from the mft data attribute.%s\n", es ); + free( rl2 ); + errno = err; + goto out; + } + mft_na->rl = rl; + + /* Find the last run in the new runlist. */ + for ( ; rl[1].length; rl++ ) + ; + /* Update the attribute record as well. */ + ctx = ntfs_attr_get_search_ctx( mft_na->ni, NULL ); + if ( !ctx ) + goto undo_alloc; + + if ( ntfs_attr_lookup( mft_na->type, mft_na->name, mft_na->name_len, 0, + rl[1].vcn, NULL, 0, ctx ) ) + { + ntfs_log_error( "Failed to find last attribute extent of " + "mft data attribute.\n" ); + goto undo_alloc; + } + m = ctx->mrec; + a = ctx->attr; + ll = sle64_to_cpu( a->lowest_vcn ); + rl2 = ntfs_attr_find_vcn( mft_na, ll ); + if ( !rl2 || !rl2->length ) + { + ntfs_log_error( "Failed to determine previous last " + "allocated cluster of mft data attribute.\n" ); + if ( rl2 ) + errno = EIO; + goto undo_alloc; + } + /* Get the size for the new mapping pairs array for this extent. */ + mp_size = ntfs_get_size_for_mapping_pairs( vol, rl2, ll, INT_MAX ); + if ( mp_size <= 0 ) + { + ntfs_log_error( "Get size for mapping pairs failed for " + "mft data attribute extent.\n" ); + goto undo_alloc; + } + /* Expand the attribute record if necessary. */ + old_alen = le32_to_cpu( a->length ); + if ( ntfs_attr_record_resize( m, a, + mp_size + le16_to_cpu( a->mapping_pairs_offset ) ) ) + { + ret = ntfs_mft_attr_extend( vol->mft_na ); + if ( ret == STATUS_OK ) + goto ok; + if ( ret == STATUS_ERROR ) + { + ntfs_log_perror( "%s: ntfs_mft_attr_extend failed", __FUNCTION__ ); + update_mp = TRUE; + } + goto undo_alloc; + } + mp_rebuilt = TRUE; + /* + * Generate the mapping pairs array directly into the attribute record. + */ + if ( ntfs_mapping_pairs_build( vol, + ( u8* )a + le16_to_cpu( a->mapping_pairs_offset ), mp_size, + rl2, ll, NULL ) ) + { + ntfs_log_error( "Failed to build mapping pairs array of " + "mft data attribute.\n" ); + errno = EIO; + goto undo_alloc; + } + /* Update the highest_vcn. */ + a->highest_vcn = cpu_to_sle64( rl[1].vcn - 1 ); + /* + * We now have extended the mft data allocated_size by nr clusters. + * Reflect this in the ntfs_attr structure and the attribute record. + * @rl is the last (non-terminator) runlist element of mft data + * attribute. + */ + if ( a->lowest_vcn ) + { + /* + * We are not in the first attribute extent, switch to it, but + * first ensure the changes will make it to disk later. + */ + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + ntfs_attr_reinit_search_ctx( ctx ); + if ( ntfs_attr_lookup( mft_na->type, mft_na->name, + mft_na->name_len, 0, 0, NULL, 0, ctx ) ) + { + ntfs_log_error( "Failed to find first attribute " + "extent of mft data attribute.\n" ); + goto restore_undo_alloc; + } + a = ctx->attr; + } ok: - mft_na->allocated_size += nr << vol->cluster_size_bits; - a->allocated_size = cpu_to_sle64(mft_na->allocated_size); - /* Ensure the changes make it to disk. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - ret = STATUS_OK; + mft_na->allocated_size += nr << vol->cluster_size_bits; + a->allocated_size = cpu_to_sle64( mft_na->allocated_size ); + /* Ensure the changes make it to disk. */ + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + ntfs_attr_put_search_ctx( ctx ); + ret = STATUS_OK; out: - ntfs_log_leave("\n"); - return ret; + ntfs_log_leave( "\n" ); + return ret; restore_undo_alloc: - err = errno; - ntfs_attr_reinit_search_ctx(ctx); - if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0, - rl[1].vcn, NULL, 0, ctx)) { - ntfs_log_error("Failed to find last attribute extent of " - "mft data attribute.%s\n", es); - ntfs_attr_put_search_ctx(ctx); - mft_na->allocated_size += nr << vol->cluster_size_bits; - /* - * The only thing that is now wrong is ->allocated_size of the - * base attribute extent which chkdsk should be able to fix. - */ - errno = err; - ret = STATUS_ERROR; - goto out; - } - m = ctx->mrec; - a = ctx->attr; - a->highest_vcn = cpu_to_sle64(old_last_vcn - 1); - errno = err; + err = errno; + ntfs_attr_reinit_search_ctx( ctx ); + if ( ntfs_attr_lookup( mft_na->type, mft_na->name, mft_na->name_len, 0, + rl[1].vcn, NULL, 0, ctx ) ) + { + ntfs_log_error( "Failed to find last attribute extent of " + "mft data attribute.%s\n", es ); + ntfs_attr_put_search_ctx( ctx ); + mft_na->allocated_size += nr << vol->cluster_size_bits; + /* + * The only thing that is now wrong is ->allocated_size of the + * base attribute extent which chkdsk should be able to fix. + */ + errno = err; + ret = STATUS_ERROR; + goto out; + } + m = ctx->mrec; + a = ctx->attr; + a->highest_vcn = cpu_to_sle64( old_last_vcn - 1 ); + errno = err; undo_alloc: - err = errno; - if (ntfs_cluster_free(vol, mft_na, old_last_vcn, -1) < 0) - ntfs_log_error("Failed to free clusters from mft data " - "attribute.%s\n", es); - if (ntfs_rl_truncate(&mft_na->rl, old_last_vcn)) - ntfs_log_error("Failed to truncate mft data attribute " - "runlist.%s\n", es); - if (mp_rebuilt) { - if (ntfs_mapping_pairs_build(vol, (u8*)a + - le16_to_cpu(a->mapping_pairs_offset), - old_alen - le16_to_cpu(a->mapping_pairs_offset), - rl2, ll, NULL)) - ntfs_log_error("Failed to restore mapping pairs " - "array.%s\n", es); - if (ntfs_attr_record_resize(m, a, old_alen)) - ntfs_log_error("Failed to restore attribute " - "record.%s\n", es); - ntfs_inode_mark_dirty(ctx->ntfs_ino); - } - if (update_mp) { - if (ntfs_attr_update_mapping_pairs(vol->mft_na, 0)) - ntfs_log_perror("%s: MP update failed", __FUNCTION__); - } - if (ctx) - ntfs_attr_put_search_ctx(ctx); - errno = err; - goto out; + err = errno; + if ( ntfs_cluster_free( vol, mft_na, old_last_vcn, -1 ) < 0 ) + ntfs_log_error( "Failed to free clusters from mft data " + "attribute.%s\n", es ); + if ( ntfs_rl_truncate( &mft_na->rl, old_last_vcn ) ) + ntfs_log_error( "Failed to truncate mft data attribute " + "runlist.%s\n", es ); + if ( mp_rebuilt ) + { + if ( ntfs_mapping_pairs_build( vol, ( u8* )a + + le16_to_cpu( a->mapping_pairs_offset ), + old_alen - le16_to_cpu( a->mapping_pairs_offset ), + rl2, ll, NULL ) ) + ntfs_log_error( "Failed to restore mapping pairs " + "array.%s\n", es ); + if ( ntfs_attr_record_resize( m, a, old_alen ) ) + ntfs_log_error( "Failed to restore attribute " + "record.%s\n", es ); + ntfs_inode_mark_dirty( ctx->ntfs_ino ); + } + if ( update_mp ) + { + if ( ntfs_attr_update_mapping_pairs( vol->mft_na, 0 ) ) + ntfs_log_perror( "%s: MP update failed", __FUNCTION__ ); + } + if ( ctx ) + ntfs_attr_put_search_ctx( ctx ); + errno = err; + goto out; } -static int ntfs_mft_record_init(ntfs_volume *vol, s64 size) +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; + + 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; - if (ntfs_attr_lookup(mft_na->type, mft_na->name, mft_na->name_len, 0, - 0, NULL, 0, ctx)) { - ntfs_log_error("Failed to find first attribute extent of " - "mft data attribute.\n"); - ntfs_attr_put_search_ctx(ctx); - goto undo_data_init; - } - ctx->attr->initialized_size = cpu_to_sle64(mft_na->initialized_size); - ctx->attr->data_size = cpu_to_sle64(mft_na->data_size); - ctx->attr->allocated_size = cpu_to_sle64(mft_na->allocated_size); - - /* Ensure the changes make it to disk. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - ntfs_log_debug("Status of mft data after mft record initialization: " - "allocated_size 0x%llx, data_size 0x%llx, " - "initialized_size 0x%llx.\n", - (long long)mft_na->allocated_size, - (long long)mft_na->data_size, - (long long)mft_na->initialized_size); - - /* Sanity checks. */ - if (mft_na->data_size > mft_na->allocated_size || - mft_na->initialized_size > mft_na->data_size) - NTFS_BUG("mft_na sanity checks failed"); - - /* Sync MFT to minimize data loss if there won't be clean unmount. */ - if (ntfs_inode_sync(mft_na->ni)) - goto undo_data_init; - - ret = 0; -out: - ntfs_log_leave("\n"); - return ret; - undo_data_init: - mft_na->initialized_size = old_data_initialized; - mft_na->data_size = old_data_size; - goto out; + mft_na->initialized_size = old_data_initialized; + mft_na->data_size = old_data_size; + goto out; } -static int ntfs_mft_rec_init(ntfs_volume *vol, s64 size) +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" ); + + 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; - /* CHECKME: ctx->attr->allocation_size is already ok? */ - - /* Ensure the changes make it to disk. */ - ntfs_inode_mark_dirty(ctx->ntfs_ino); - ntfs_attr_put_search_ctx(ctx); - - /* Sanity checks. */ - if (mft_na->data_size > mft_na->allocated_size || - mft_na->initialized_size > mft_na->data_size) - NTFS_BUG("mft_na sanity checks failed"); -out: - ntfs_log_leave("\n"); - return ret; - undo_data_init: - mft_na->initialized_size = old_data_initialized; - mft_na->data_size = old_data_size; - goto out; + mft_na->initialized_size = old_data_initialized; + mft_na->data_size = old_data_size; + goto out; } -static ntfs_inode *ntfs_mft_rec_alloc(ntfs_volume *vol) +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; + + errno = ENOSPC; + /* strerror() is intentionally used below, we want to log this error. */ + ntfs_log_error( "No free mft record for $MFT: %s\n", strerror( errno ) ); + goto err_out; found_free_rec: - if (ntfs_bitmap_set_bit(mftbmp_na, bit)) { - ntfs_log_error("Failed to allocate bit in mft bitmap #2\n"); - goto err_out; - } - - 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; - } + if ( ntfs_bitmap_set_bit( mftbmp_na, bit ) ) + { + ntfs_log_error( "Failed to allocate bit in mft bitmap #2\n" ); + 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; + 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; - 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); + 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; + ntfs_log_leave( "\n" ); + return ni; undo_mftbmp_alloc: - err = errno; - if (ntfs_bitmap_clear_bit(mftbmp_na, bit)) - ntfs_log_error("Failed to clear bit in mft bitmap.%s\n", es); - errno = err; + err = errno; + if ( ntfs_bitmap_clear_bit( mftbmp_na, bit ) ) + ntfs_log_error( "Failed to clear bit in mft bitmap.%s\n", es ); + errno = err; err_out: - if (!errno) - errno = EIO; - ni = NULL; - goto out; + if ( !errno ) + errno = EIO; + ni = NULL; + goto out; } /** * ntfs_mft_record_alloc - allocate an mft record on an ntfs volume - * @vol: volume on which to allocate the mft record - * @base_ni: open base inode if allocating an extent mft record or NULL + * @vol: volume on which to allocate the mft record + * @base_ni: open base inode if allocating an extent mft record or NULL * * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol. * @@ -1558,12 +1639,12 @@ err_out: * superfluous bits are padded with zeroes. * * Thus, when we return successfully (return value non-zero), we will have: - * - initialized / extended the mft bitmap if necessary, - * - initialized / extended the mft data if necessary, - * - set the bit corresponding to the mft record being allocated in the - * mft bitmap, - * - open an ntfs_inode for the allocated mft record, and we will - * - return the ntfs_inode. + * - initialized / extended the mft bitmap if necessary, + * - initialized / extended the mft data if necessary, + * - set the bit corresponding to the mft record being allocated in the + * mft bitmap, + * - open an ntfs_inode for the allocated mft record, and we will + * - return the ntfs_inode. * * On error (return value zero), nothing will have changed. If we had changed * anything before the error occurred, we will have reverted back to the @@ -1584,230 +1665,245 @@ err_out: * when reading the bitmap but if we are careful, we should be able to avoid * all problems. */ -ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, ntfs_inode *base_ni) +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); + if ( ret == STATUS_ERROR ) + goto err_out; + if ( ret == STATUS_KEEP_SEARCHING ) + { + ret = ntfs_mft_bitmap_extend_allocation( vol ); + if ( ret != STATUS_OK ) + goto err_out; + } + + ntfs_log_debug( "Status of mftbmp after allocation extension: " + "allocated_size 0x%llx, data_size 0x%llx, " + "initialized_size 0x%llx.\n", + ( long long )mftbmp_na->allocated_size, + ( long long )mftbmp_na->data_size, + ( long long )mftbmp_na->initialized_size ); + } + /* + * We now have sufficient allocated space, extend the initialized_size + * as well as the data_size if necessary and fill the new space with + * zeroes. + */ + bit = mftbmp_na->initialized_size << 3; + if ( ntfs_mft_bitmap_extend_initialized( vol ) ) + goto err_out; + ntfs_log_debug( "Status of mftbmp after initialized extension: " + "allocated_size 0x%llx, data_size 0x%llx, " + "initialized_size 0x%llx.\n", + ( long long )mftbmp_na->allocated_size, + ( long long )mftbmp_na->data_size, + ( long long )mftbmp_na->initialized_size ); + ntfs_log_debug( "found free record (#3) at %lld\n", ( long long )bit ); 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; + /* @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; + } - /* - * 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; + /* 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; - 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--; + /* + * 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; + ntfs_log_leave( "\n" ); + return ni; undo_mftbmp_alloc: - err = errno; - if (ntfs_bitmap_clear_bit(mftbmp_na, bit)) - ntfs_log_error("Failed to clear bit in mft bitmap.%s\n", es); - errno = err; + err = errno; + if ( ntfs_bitmap_clear_bit( mftbmp_na, bit ) ) + ntfs_log_error( "Failed to clear bit in mft bitmap.%s\n", es ); + errno = err; err_out: - if (!errno) - errno = EIO; - ni = NULL; - goto out; + if ( !errno ) + errno = EIO; + ni = NULL; + goto out; } /** * ntfs_mft_record_free - free an mft record on an ntfs volume - * @vol: volume on which to free the mft record - * @ni: open ntfs inode of the mft record to free + * @vol: volume on which to free the mft record + * @ni: open ntfs inode of the mft record to free * * Free the mft record of the open inode @ni on the mounted ntfs volume @vol. * Note that this function calls ntfs_inode_close() internally and hence you @@ -1815,95 +1911,101 @@ err_out: * * On success return 0 and on error return -1 with errno set to the error code. */ -int ntfs_mft_record_free(ntfs_volume *vol, ntfs_inode *ni) +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... */ + /* Rollback what we did... */ bitmap_rollback: - if (ntfs_bitmap_set_bit(vol->mftbmp_na, mft_no)) - ntfs_log_debug("Eeek! Rollback failed in ntfs_mft_record_free(). " - "Leaving inconsistent metadata!\n"); + if ( ntfs_bitmap_set_bit( vol->mftbmp_na, mft_no ) ) + ntfs_log_debug( "Eeek! Rollback failed in ntfs_mft_record_free(). " + "Leaving inconsistent metadata!\n" ); sync_rollback: - ni->mrec->flags |= MFT_RECORD_IN_USE; - ni->mrec->sequence_number = old_seq_no; - ntfs_inode_mark_dirty(ni); - errno = err; - return -1; + ni->mrec->flags |= MFT_RECORD_IN_USE; + ni->mrec->sequence_number = old_seq_no; + ntfs_inode_mark_dirty( ni ); + errno = err; + return -1; } /** * ntfs_mft_usn_dec - Decrement USN by one - * @mrec: pointer to an mft record + * @mrec: pointer to an mft record * * On success return 0 and on error return -1 with errno set. */ -int ntfs_mft_usn_dec(MFT_RECORD *mrec) +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..1402a766 100644 --- a/source/libntfs/mft.h +++ b/source/libntfs/mft.h @@ -29,14 +29,14 @@ #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 - * @vol: volume to read from - * @mref: mft record number to read - * @b: output data buffer + * @vol: volume to read from + * @mref: mft record number to read + * @b: output data buffer * * Read the mft record specified by @mref from volume @vol into buffer @b. * Return 0 on success or -1 on error, with errno set to the error code. @@ -47,31 +47,31 @@ 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 - * @vol: volume to write to - * @mref: mft record number to write - * @b: data buffer containing the mft record to write + * @vol: volume to write to + * @mref: mft record number to write + * @b: data buffer containing the mft record to write * * Write the mft record specified by @mref from buffer @b to volume @vol. * Return 0 on success or -1 on error, with errno set to the error code. @@ -82,20 +82,20 @@ 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; } /** * ntfs_mft_record_get_data_size - return number of bytes used in mft record @b - * @m: mft record to get the data size of + * @m: mft record to get the data size of * * Takes the mft record @m and returns the number of bytes used in the record * or 0 on error (i.e. @m is not a valid mft record). Zero is not a valid size @@ -109,24 +109,24 @@ static __inline__ int ntfs_mft_record_write(const ntfs_volume *vol, * non-existent (don't know if Windows' NTFS driver/chkdsk wouldn't view this * as corruption in itself though). */ -static __inline__ u32 ntfs_mft_record_get_data_size(const MFT_RECORD *m) +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); +extern int ntfs_mft_record_format( const ntfs_volume *vol, const MFT_REF mref ); -extern ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, ntfs_inode *base_ni); +extern ntfs_inode *ntfs_mft_record_alloc( ntfs_volume *vol, ntfs_inode *base_ni ); -extern int ntfs_mft_record_free(ntfs_volume *vol, ntfs_inode *ni); +extern int ntfs_mft_record_free( ntfs_volume *vol, ntfs_inode *ni ); -extern int ntfs_mft_usn_dec(MFT_RECORD *mrec); +extern int ntfs_mft_usn_dec( MFT_RECORD *mrec ); #endif /* defined _NTFS_MFT_H */ diff --git a/source/libntfs/misc.c b/source/libntfs/misc.c index b2e17cbf..cc68d264 100644 --- a/source/libntfs/misc.c +++ b/source/libntfs/misc.c @@ -1,6 +1,6 @@ /** * misc.c : miscellaneous : - * - dealing with errors in memory allocation + * - dealing with errors in memory allocation * * Copyright (c) 2008 Jean-Pierre Andre * @@ -37,25 +37,25 @@ /** * ntfs_calloc - * + * * Return a pointer to the allocated memory or NULL if the request fails. */ -void *ntfs_calloc(size_t size) +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 *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/misc.h b/source/libntfs/misc.h index a03e964e..288e3671 100644 --- a/source/libntfs/misc.h +++ b/source/libntfs/misc.h @@ -1,6 +1,6 @@ /* * misc.h : miscellaneous exports - * - memory allocation + * - memory allocation * * Copyright (c) 2008 Jean-Pierre Andre * @@ -23,8 +23,8 @@ #ifndef _NTFS_MISC_H_ #define _NTFS_MISC_H_ -void *ntfs_calloc(size_t size); -void *ntfs_malloc(size_t size); +void *ntfs_calloc( size_t size ); +void *ntfs_malloc( size_t size ); #endif /* _NTFS_MISC_H_ */ diff --git a/source/libntfs/mst.c b/source/libntfs/mst.c index 470942d6..63ff08f5 100644 --- a/source/libntfs/mst.c +++ b/source/libntfs/mst.c @@ -33,8 +33,8 @@ /** * ntfs_mst_post_read_fixup - deprotect multi sector transfer protected data - * @b: pointer to the data to deprotect - * @size: size in bytes of @b + * @b: pointer to the data to deprotect + * @size: size in bytes of @b * * Perform the necessary post read multi sector transfer fixups and detect the * presence of incomplete multi sector transfers. - In that case, overwrite the @@ -43,85 +43,89 @@ * * Return 0 on success and -1 on error, with errno set to the error code. The * following error codes are defined: - * EINVAL Invalid arguments or invalid NTFS record in buffer @b. - * EIO Multi sector transfer error was detected. Magic of the NTFS - * record in @b will have been set to "BAAD". + * EINVAL Invalid arguments or invalid NTFS record in buffer @b. + * EIO Multi sector transfer error was detected. Magic of the NTFS + * record in @b will have been set to "BAAD". */ -int ntfs_mst_post_read_fixup(NTFS_RECORD *b, const u32 size) +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; } /** * ntfs_mst_pre_write_fixup - apply multi sector transfer protection - * @b: pointer to the data to protect - * @size: size in bytes of @b + * @b: pointer to the data to protect + * @size: size in bytes of @b * * Perform the necessary pre write multi sector transfer fixup on the data * pointer to by @b of @size. @@ -138,94 +142,98 @@ int ntfs_mst_post_read_fixup(NTFS_RECORD *b, const u32 size) * otherwise a random word will be used (whatever was in the record at that * position at that time). */ -int ntfs_mst_pre_write_fixup(NTFS_RECORD *b, const u32 size) +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; } /** * ntfs_mst_post_write_fixup - deprotect multi sector transfer protected data - * @b: pointer to the data to deprotect + * @b: pointer to the data to deprotect * * Perform the necessary post write multi sector transfer fixup, not checking * for any errors, because we assume we have just used * ntfs_mst_pre_write_fixup(), thus the data will be fine or we would never * have gotten here. */ -void ntfs_mst_post_write_fixup(NTFS_RECORD *b) +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/mst.h b/source/libntfs/mst.h index ca813821..a5d15ea5 100644 --- a/source/libntfs/mst.h +++ b/source/libntfs/mst.h @@ -26,9 +26,9 @@ #include "types.h" #include "layout.h" -extern int ntfs_mst_post_read_fixup(NTFS_RECORD *b, const u32 size); -extern int ntfs_mst_pre_write_fixup(NTFS_RECORD *b, const u32 size); -extern void ntfs_mst_post_write_fixup(NTFS_RECORD *b); +extern int ntfs_mst_post_read_fixup( NTFS_RECORD *b, const u32 size ); +extern int ntfs_mst_pre_write_fixup( NTFS_RECORD *b, const u32 size ); +extern void ntfs_mst_post_write_fixup( NTFS_RECORD *b ); #endif /* defined _NTFS_MST_H */ diff --git a/source/libntfs/ntfs.c b/source/libntfs/ntfs.c index 10451e47..7d81c5f2 100644 --- a/source/libntfs/ntfs.c +++ b/source/libntfs/ntfs.c @@ -41,9 +41,10 @@ #include "cache.h" // NTFS device driver devoptab -static const devoptab_t devops_ntfs = { +static const devoptab_t devops_ntfs = +{ NULL, /* Device name */ - sizeof (ntfs_file_state), + sizeof ( ntfs_file_state ), ntfs_open_r, ntfs_close_r, ntfs_write_r, @@ -56,7 +57,7 @@ static const devoptab_t devops_ntfs = { ntfs_chdir_r, ntfs_rename_r, ntfs_mkdir_r, - sizeof (ntfs_dir_state), + sizeof ( ntfs_dir_state ), ntfs_diropen_r, ntfs_dirreset_r, ntfs_dirnext_r, @@ -67,20 +68,21 @@ static const devoptab_t devops_ntfs = { NULL /* Device data */ }; -void ntfsInit (void) +void ntfsInit ( void ) { static bool isInit = false; // Initialise ntfs-3g (if not already done so) - if (!isInit) { + if ( !isInit ) + { isInit = true; // Set the log handler - #ifdef NTFS_ENABLE_LOG - ntfs_log_set_handler(ntfs_log_handler_stderr); - #else - ntfs_log_set_handler(ntfs_log_handler_null); - #endif +#ifdef NTFS_ENABLE_LOG + ntfs_log_set_handler( ntfs_log_handler_stderr ); +#else + ntfs_log_set_handler( ntfs_log_handler_null ); +#endif // Set our current local ntfs_set_locale(); @@ -89,7 +91,7 @@ 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; @@ -98,7 +100,8 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) sec_t part_lba = 0; int i; - union { + union + { u8 buffer[512]; MASTER_BOOT_RECORD mbr; EXTENDED_BOOT_RECORD ebr; @@ -106,156 +109,191 @@ int ntfsFindPartitions (const DISC_INTERFACE *interface, sec_t **partitions) } sector; // Sanity check - if (!interface) { + if ( !interface ) + { errno = EINVAL; return -1; } - if (!partitions) + 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) { - memcpy(&mbr, §or, sizeof(MASTER_BOOT_RECORD)); - ntfs_log_debug("Valid Master Boot Record found\n"); + 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); + 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); + 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 ); // Figure out what type of partition this is - switch (partition->type) { + switch ( partition->type ) + { - // Ignore empty partitions + // Ignore empty partitions case PARTITION_TYPE_EMPTY: continue; - // NTFS partition - case PARTITION_TYPE_NTFS: { - ntfs_log_debug("Partition %i: Claims to be NTFS\n", i + 1); + // 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) { - ntfs_log_debug("Partition %i: Valid NTFS boot sector found\n", i + 1); - if (partition_count < NTFS_MAX_PARTITIONS) { - partition_starts[partition_count] = part_lba; - partition_count++; + // Read and validate the NTFS partition + 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 ) + { + partition_starts[partition_count] = part_lba; + partition_count++; + } + } + else + { + ntfs_log_debug( "Partition %i: Invalid NTFS boot sector, not actually NTFS\n", i + 1 ); } - } else { - ntfs_log_debug("Partition %i: Invalid NTFS boot sector, not actually NTFS\n", i + 1); } + + break; + } - break; - - } - - // 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: { - ntfs_log_debug("Partition %i: Claims to be Extended\n", i + 1); + 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 { + // Walk the extended partition chain, finding all NTFS partitions within it + sec_t ebr_lba = part_lba; + sec_t next_erb_lba = 0; + do + { - // Read and validate the extended boot record - if (interface->readSectors(ebr_lba + next_erb_lba, 1, §or)) { - if (sector.ebr.signature == EBR_SIGNATURE) { - ntfs_log_debug("Logical Partition @ %d: type 0x%x\n", ebr_lba + next_erb_lba, - sector.ebr.partition.status == PARTITION_STATUS_BOOTABLE ? "bootable (active)" : "non-bootable", - sector.ebr.partition.type); + // Read and validate the extended boot record + if ( interface->readSectors( ebr_lba + next_erb_lba, 1, §or ) ) + { + if ( sector.ebr.signature == EBR_SIGNATURE ) + { + ntfs_log_debug( "Logical Partition @ %d: type 0x%x\n", ebr_lba + next_erb_lba, + sector.ebr.partition.status == PARTITION_STATUS_BOOTABLE ? "bootable (active)" : "non-bootable", + sector.ebr.partition.type ); - // Get the start sector of the current partition - // and the next extended boot record in the chain - part_lba = ebr_lba + next_erb_lba + le32_to_cpu(sector.ebr.partition.lba_start); - next_erb_lba = le32_to_cpu(sector.ebr.next_ebr.lba_start); + // Get the start sector of the current partition + // and the next extended boot record in the chain + part_lba = ebr_lba + next_erb_lba + le32_to_cpu( sector.ebr.partition.lba_start ); + 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) { - ntfs_log_debug("Logical Partition @ %d: Valid NTFS boot sector found\n", part_lba); - 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) { - partition_starts[partition_count] = part_lba; - partition_count++; + // 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 ) + { + ntfs_log_debug( "Logical Partition @ %d: Valid NTFS boot sector found\n", part_lba ); + 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 ) + { + partition_starts[partition_count] = part_lba; + partition_count++; + } } } + + } + else + { + next_erb_lba = 0; } - - } else { - next_erb_lba = 0; } + } + while ( next_erb_lba ); - } while (next_erb_lba); + break; - break; - - } - - // 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) { - ntfs_log_debug("Partition %i: Valid NTFS boot sector found\n", i + 1); - 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) { - partition_starts[partition_count] = part_lba; - partition_count++; - } - } } - break; + // 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 ) + { + ntfs_log_debug( "Partition %i: Valid NTFS boot sector found\n", i + 1 ); + 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 ) + { + partition_starts[partition_count] = part_lba; + partition_count++; + } + } + } + + break; + + } } } - // Else it is assumed this device has no master boot record - } else { - ntfs_log_debug("No Master Boot Record was found!\n"); + // 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) { - ntfs_log_debug("Valid NTFS boot sector found at sector %d!\n", i); - if (partition_count < NTFS_MAX_PARTITIONS) { + 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 ) + { partition_starts[partition_count] = i; partition_count++; } @@ -269,10 +307,12 @@ 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) { - memcpy(*partitions, &partition_starts, sizeof(sec_t) * partition_count); + 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 +320,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,26 +335,34 @@ 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++) { + partition_count = ntfsFindPartitions( disc->interface, &partitions ); + if ( partition_count > 0 && partitions ) + { + for ( j = 0, k = 0; j < partition_count; j++ ) + { // Find the next unused mount name - do { - sprintf(name, "%s%i", NTFS_MOUNT_PREFIX, k++); - if (k >= NTFS_MAX_MOUNTS) { - ntfs_free(partitions); + do + { + sprintf( name, "%s%i", NTFS_MOUNT_PREFIX, k++ ); + if ( k >= NTFS_MAX_MOUNTS ) + { + ntfs_free( partitions ); errno = EADDRNOTAVAIL; return -1; } - } while (ntfsGetDevice(name, false)); + } + 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)) { - strcpy(mount_points[mount_count].name, name); + 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]; mount_count++; @@ -322,15 +370,17 @@ int ntfsMountAll (ntfs_md **mounts, u32 flags) } } - ntfs_free(partitions); + ntfs_free( partitions ); } } // Return the mounts (if any) - 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); + 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 +388,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 +400,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,27 +410,36 @@ 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++) { + partition_count = ntfsFindPartitions( disc->interface, &partitions ); + if ( partition_count > 0 && partitions ) + { + for ( j = 0, k = 0; j < partition_count; j++ ) + { // Find the next unused mount name - do { - sprintf(name, "%s%i", NTFS_MOUNT_PREFIX, k++); - if (k >= NTFS_MAX_MOUNTS) { - ntfs_free(partitions); + do + { + sprintf( name, "%s%i", NTFS_MOUNT_PREFIX, k++ ); + if ( k >= NTFS_MAX_MOUNTS ) + { + ntfs_free( partitions ); errno = EADDRNOTAVAIL; return -1; } - } while (ntfsGetDevice(name, false)); + } + 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)) { - strcpy(mount_points[mount_count].name, name); + 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]; mount_count++; @@ -387,23 +447,26 @@ int ntfsMountDevice (const DISC_INTERFACE *interface, ntfs_md **mounts, u32 flag } } - ntfs_free(partitions); + ntfs_free( partitions ); } break; } } // 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) { - memcpy(*mounts, &mount_points, sizeof(ntfs_md) * mount_count); + 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 +474,14 @@ 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 +490,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; } @@ -451,14 +518,15 @@ bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSe vd->gid = 0; vd->fmask = 0; vd->dmask = 0; - vd->atime = ((flags & NTFS_UPDATE_ACCESS_TIMES) ? ATIME_ENABLED : ATIME_DISABLED); - vd->showHiddenFiles = (flags & NTFS_SHOW_HIDDEN_FILES); - vd->showSystemFiles = (flags & NTFS_SHOW_SYSTEM_FILES); + vd->atime = ( ( flags & NTFS_UPDATE_ACCESS_TIMES ) ? ATIME_ENABLED : ATIME_DISABLED ); + vd->showHiddenFiles = ( flags & NTFS_SHOW_HIDDEN_FILES ); + vd->showSystemFiles = ( flags & NTFS_SHOW_SYSTEM_FILES ); // Allocate the device driver descriptor - fd = (gekko_fd*)ntfs_alloc(sizeof(gekko_fd)); - if (!fd) { - ntfs_free(vd); + fd = ( gekko_fd* )ntfs_alloc( sizeof( gekko_fd ) ); + if ( !fd ) + { + ntfs_free( vd ); errno = ENOMEM; return false; } @@ -472,89 +540,94 @@ bool ntfsMount (const char *name, const DISC_INTERFACE *interface, sec_t startSe fd->cachePageSize = cachePageSize; // Allocate the device driver - vd->dev = ntfs_device_alloc(name, 0, &ntfs_device_gekko_io_ops, fd); - if (!vd->dev) { - ntfs_free(fd); - ntfs_free(vd); + vd->dev = ntfs_device_alloc( name, 0, &ntfs_device_gekko_io_ops, fd ); + if ( !vd->dev ) + { + ntfs_free( fd ); + ntfs_free( vd ); return false; } // Build the mount flags - if (flags & NTFS_READ_ONLY) - vd->flags |= MS_RDONLY; + if ( flags & NTFS_READ_ONLY ) + vd->flags |= MS_RDONLY; else { - if (!(interface->features & FEATURE_MEDIUM_CANWRITE)) - vd->flags |= MS_RDONLY; - if ((interface->features & FEATURE_MEDIUM_CANREAD) && (interface->features & FEATURE_MEDIUM_CANWRITE)) - vd->flags |= MS_EXCLUSIVE; + 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) + if ( flags & NTFS_RECOVER ) vd->flags |= MS_RECOVER; - if (flags & NTFS_IGNORE_HIBERFILE) + 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); + if ( vd->flags & MS_RDONLY ) + ntfs_log_debug( "Mounting \"%s\" as read-only\n", name ); // Mount the device - vd->vol = ntfs_device_mount(vd->dev, vd->flags); - if (!vd->vol) { - switch(ntfs_volume_error(errno)) { + 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; } - ntfs_device_free(vd->dev); - ntfs_free(vd); + ntfs_device_free( vd->dev ); + ntfs_free( vd ); return false; } // Initialise the volume descriptor - if (ntfsInitVolume(vd)) { - ntfs_umount(vd->vol, true); - ntfs_free(vd); + if ( ntfsInitVolume( vd ) ) + { + ntfs_umount( vd->vol, true ); + ntfs_free( vd ); return false; } // Add the device to the devoptab table - if (ntfsAddDevice(name, vd)) { - ntfsDeinitVolume(vd); - ntfs_umount(vd->vol, true); - ntfs_free(vd); + if ( ntfsAddDevice( name, vd ) ) + { + ntfsDeinitVolume( vd ); + ntfs_umount( vd->vol, true ); + ntfs_free( vd ); return false; } return true; } -void ntfsUnmount (const char *name, bool force) +void ntfsUnmount ( const char *name, bool force ) { ntfs_vd *vd = NULL; // Get the devices volume descriptor - vd = ntfsGetVolume(name); - if (!vd) + vd = ntfsGetVolume( name ); + if ( !vd ) return; // Remove the device from the devoptab table - ntfsRemoveDevice(name); + ntfsRemoveDevice( name ); // Deinitialise the volume descriptor - ntfsDeinitVolume(vd); + ntfsDeinitVolume( vd ); // Unmount the volume - ntfs_umount(vd->vol, force); + ntfs_umount( vd->vol, force ); // Free the volume descriptor - ntfs_free(vd); + ntfs_free( vd ); return; } -const char *ntfsGetVolumeName (const char *name) +const char *ntfsGetVolumeName ( const char *name ) { ntfs_vd *vd = NULL; //ntfs_attr *na = NULL; @@ -562,79 +635,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) { + vd = ntfsGetVolume( name ); + 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; + + // Lock + ntfsLock(vd); + + // Check if the volume name attribute exists + na = ntfs_attr_open(vd->vol->vol_ni, AT_VOLUME_NAME, NULL, 0); + if (!na) { + ntfsUnlock(vd); + errno = ENOENT; + return false; + } + + // Allocate a buffer to store the raw volume name + ulabel = ntfs_alloc(na->data_size * sizeof(ntfschar)); + if (!ulabel) { + ntfsUnlock(vd); + errno = ENOMEM; + return false; + } + + // Read the volume name + if (ntfs_attr_pread(na, 0, na->data_size, ulabel) != na->data_size) { + ntfs_free(ulabel); + ntfsUnlock(vd); + errno = EIO; + return false; + } + + // Convert the volume name to the current local + if (ntfsUnicodeToLocal(ulabel, na->data_size, &volumeName, 0) < 0) { + errno = EINVAL; + ntfs_free(ulabel); + ntfsUnlock(vd); + return false; + } + + // If the volume name was read then cache it (for future fetches) + if (volumeName) + strcpy(vd->name, volumeName); + + // Close the volume name attribute + if (na) + ntfs_attr_close(na); + + // Clean up + ntfs_free(volumeName); + ntfs_free(ulabel); + + // Unlock + ntfsUnlock(vd); - // If the volume name has already been cached then just use that - if (vd->name[0]) return vd->name; - - // Lock - ntfsLock(vd); - - // Check if the volume name attribute exists - na = ntfs_attr_open(vd->vol->vol_ni, AT_VOLUME_NAME, NULL, 0); - if (!na) { - ntfsUnlock(vd); - errno = ENOENT; - return false; - } - - // Allocate a buffer to store the raw volume name - ulabel = ntfs_alloc(na->data_size * sizeof(ntfschar)); - if (!ulabel) { - ntfsUnlock(vd); - errno = ENOMEM; - return false; - } - - // Read the volume name - if (ntfs_attr_pread(na, 0, na->data_size, ulabel) != na->data_size) { - ntfs_free(ulabel); - ntfsUnlock(vd); - errno = EIO; - return false; - } - - // Convert the volume name to the current local - if (ntfsUnicodeToLocal(ulabel, na->data_size, &volumeName, 0) < 0) { - errno = EINVAL; - ntfs_free(ulabel); - ntfsUnlock(vd); - return false; - } - - // If the volume name was read then cache it (for future fetches) - if (volumeName) - strcpy(vd->name, volumeName); - - // Close the volume name attribute - if (na) - ntfs_attr_close(na); - - // Clean up - ntfs_free(volumeName); - ntfs_free(ulabel); - - // Unlock - ntfsUnlock(vd); - - return vd->name; -*/ + */ } -bool ntfsSetVolumeName (const char *name, const char *volumeName) +bool ntfsSetVolumeName ( const char *name, const char *volumeName ) { ntfs_vd *vd = NULL; ntfs_attr *na = NULL; @@ -642,53 +717,62 @@ 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) { + vd = ntfsGetVolume( name ); + if ( !vd ) + { errno = ENODEV; return false; } // Lock - ntfsLock(vd); + ntfsLock( vd ); // Convert the new volume name to unicode - ulabel_len = ntfsLocalToUnicode(volumeName, &ulabel) * sizeof(ntfschar); - if (ulabel_len < 0) { - ntfsUnlock(vd); + ulabel_len = ntfsLocalToUnicode( volumeName, &ulabel ) * sizeof( ntfschar ); + if ( ulabel_len < 0 ) + { + ntfsUnlock( vd ); errno = EINVAL; return false; } // Check if the volume name attribute exists - na = ntfs_attr_open(vd->vol->vol_ni, AT_VOLUME_NAME, NULL, 0); - if (na) { + na = ntfs_attr_open( vd->vol->vol_ni, AT_VOLUME_NAME, NULL, 0 ); + if ( na ) + { // It does, resize it to match the length of the new volume name - if (ntfs_attr_truncate(na, ulabel_len)) { - ntfs_free(ulabel); - ntfsUnlock(vd); + if ( ntfs_attr_truncate( na, ulabel_len ) ) + { + ntfs_free( ulabel ); + ntfsUnlock( vd ); return false; } // Write the new volume name - if (ntfs_attr_pwrite(na, 0, ulabel_len, ulabel) != ulabel_len) { - ntfs_free(ulabel); - ntfsUnlock(vd); + 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)) { - ntfs_free(ulabel); - ntfsUnlock(vd); + if ( ntfs_attr_add( vd->vol->vol_ni, AT_VOLUME_NAME, NULL, 0, ( u8* )ulabel, ulabel_len ) ) + { + ntfs_free( ulabel ); + ntfsUnlock( vd ); return false; } @@ -698,26 +782,27 @@ 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)) { - ntfs_free(ulabel); - ntfsUnlock(vd); + if ( ntfs_inode_sync( vd->vol->vol_ni ) ) + { + ntfs_free( ulabel ); + ntfsUnlock( vd ); return false; } // Clean up - ntfs_free(ulabel); + ntfs_free( ulabel ); // Unlock - ntfsUnlock(vd); + ntfsUnlock( vd ); return true; } -const devoptab_t *ntfsGetDevOpTab (void) +const devoptab_t *ntfsGetDevOpTab ( void ) { return &devops_ntfs; } diff --git a/source/libntfs/ntfs.h b/source/libntfs/ntfs.h index d805f4c2..5cf81b75 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 */ @@ -51,96 +52,97 @@ 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..90c54570 100644 --- a/source/libntfs/ntfsdir.c +++ b/source/libntfs/ntfsdir.c @@ -47,23 +47,24 @@ #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) + 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); + ntfs_free( dir->first->name ); + ntfs_free( dir->first ); dir->first = next; } // 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,264 +74,280 @@ 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) + if ( !st || !path ) return 0; - ntfs_log_trace("path %s, st %p\n", path, st); + ntfs_log_trace( "path %s, st %p\n", path, st ); ntfs_vd *vd = NULL; ntfs_inode *ni = NULL; // Get the volume descriptor for this path - vd = ntfsGetVolume(path); - if (!vd) { + vd = ntfsGetVolume( path ); + 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)); + memset( st, 0, sizeof( struct stat ) ); st->st_mode = S_IFDIR; return 0; } // Lock - ntfsLock(vd); + ntfsLock( vd ); // Find the entry - ni = ntfsOpenEntry(vd, path); - if (!ni) { + ni = ntfsOpenEntry( vd, path ); + if ( !ni ) + { r->_errno = errno; - ntfsUnlock(vd); + ntfsUnlock( vd ); return -1; } // Get the entry stats - int ret = ntfsStat(vd, ni, st); - if (ret) + int ret = ntfsStat( vd, ni, st ); + if ( ret ) r->_errno = errno; // Close the entry - ntfsCloseEntry(vd, ni); + ntfsCloseEntry( vd, ni ); - ntfsUnlock(vd); + ntfsUnlock( vd ); return 0; } -int ntfs_link_r (struct _reent *r, const char *existing, const char *newLink) +int ntfs_link_r ( struct _reent *r, const char *existing, const char *newLink ) { - ntfs_log_trace("existing %s, newLink %s\n", existing, newLink); + ntfs_log_trace( "existing %s, newLink %s\n", existing, newLink ); ntfs_vd *vd = NULL; ntfs_inode *ni = NULL; // Get the volume descriptor for this path - vd = ntfsGetVolume(existing); - if (!vd) { + vd = ntfsGetVolume( existing ); + if ( !vd ) + { r->_errno = ENODEV; return -1; } // Lock - ntfsLock(vd); + ntfsLock( vd ); // Create a symbolic link between the two paths - ni = ntfsCreate(vd, existing, S_IFLNK, newLink); - if (!ni) { - ntfsUnlock(vd); + ni = ntfsCreate( vd, existing, S_IFLNK, newLink ); + if ( !ni ) + { + ntfsUnlock( vd ); r->_errno = errno; return -1; } // Close the symbolic link - ntfsCloseEntry(vd, ni); + ntfsCloseEntry( vd, ni ); // Unlock - ntfsUnlock(vd); + ntfsUnlock( vd ); 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); + ntfs_log_trace( "name %s\n", name ); // Unlink the entry - int ret = ntfsUnlink(ntfsGetVolume(name), name); - if (ret) + int ret = ntfsUnlink( ntfsGetVolume( name ), name ); + 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); + ntfs_log_trace( "name %s\n", name ); ntfs_vd *vd = NULL; ntfs_inode *ni = NULL; // Get the volume descriptor for this path - vd = ntfsGetVolume(name); - if (!vd) { + vd = ntfsGetVolume( name ); + if ( !vd ) + { r->_errno = ENODEV; return -1; } // Lock - ntfsLock(vd); + ntfsLock( vd ); // Find the directory - ni = ntfsOpenEntry(vd, name); - if (!ni) { - ntfsUnlock(vd); + ni = ntfsOpenEntry( vd, name ); + 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)) { - ntfsCloseEntry(vd, ni); - ntfsUnlock(vd); + if ( !( ni->mrec->flags && MFT_RECORD_IS_DIRECTORY ) ) + { + ntfsCloseEntry( vd, ni ); + ntfsUnlock( vd ); r->_errno = ENOTDIR; return -1; } // 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; // Unlock - ntfsUnlock(vd); + ntfsUnlock( vd ); return 0; } -int ntfs_rename_r (struct _reent *r, const char *oldName, const char *newName) +int ntfs_rename_r ( struct _reent *r, const char *oldName, const char *newName ) { - ntfs_log_trace("oldName %s, newName %s\n", oldName, newName); + ntfs_log_trace( "oldName %s, newName %s\n", oldName, newName ); ntfs_vd *vd = NULL; ntfs_inode *ni = NULL; // Get the volume descriptor for this path - vd = ntfsGetVolume(oldName); - if (!vd) { + vd = ntfsGetVolume( oldName ); + if ( !vd ) + { r->_errno = ENODEV; return -1; } // Lock - ntfsLock(vd); + ntfsLock( vd ); // You cannot rename between devices - if(vd != ntfsGetVolume(newName)) { - ntfsUnlock(vd); + if ( vd != ntfsGetVolume( newName ) ) + { + ntfsUnlock( vd ); r->_errno = EXDEV; return -1; } // Check that there is no existing entry with the new name - ni = ntfsOpenEntry(vd, newName); - if (ni) { - ntfsCloseEntry(vd, ni); - ntfsUnlock(vd); + ni = ntfsOpenEntry( vd, newName ); + if ( ni ) + { + ntfsCloseEntry( vd, ni ); + ntfsUnlock( vd ); r->_errno = EEXIST; return -1; } // Link the old entry with the new one - if (ntfsLink(vd, oldName, newName)) { - ntfsUnlock(vd); + if ( ntfsLink( vd, oldName, newName ) ) + { + ntfsUnlock( vd ); return -1; } // Unlink the old entry - if (ntfsUnlink(vd, oldName)) { - if (ntfsUnlink(vd, newName)) { - ntfsUnlock(vd); + if ( ntfsUnlink( vd, oldName ) ) + { + if ( ntfsUnlink( vd, newName ) ) + { + ntfsUnlock( vd ); return -1; } - ntfsUnlock(vd); + ntfsUnlock( vd ); return -1; } // Unlock - ntfsUnlock(vd); + ntfsUnlock( vd ); return 0; } -int ntfs_mkdir_r (struct _reent *r, const char *path, int mode) +int ntfs_mkdir_r ( struct _reent *r, const char *path, int mode ) { - ntfs_log_trace("path %s, mode %i\n", path, mode); + ntfs_log_trace( "path %s, mode %i\n", path, mode ); ntfs_vd *vd = NULL; ntfs_inode *ni = NULL; // Get the volume descriptor for this path - vd = ntfsGetVolume(path); - if (!vd) { + vd = ntfsGetVolume( path ); + if ( !vd ) + { r->_errno = ENODEV; return -1; } // Lock - ntfsLock(vd); + ntfsLock( vd ); // Create the directory - ni = ntfsCreate(vd, path, S_IFDIR, NULL); - if (!ni) { - ntfsUnlock(vd); + ni = ntfsCreate( vd, path, S_IFDIR, NULL ); + if ( !ni ) + { + ntfsUnlock( vd ); r->_errno = errno; return -1; } // Close the directory - ntfsCloseEntry(vd, ni); + ntfsCloseEntry( vd, ni ); // Unlock - ntfsUnlock(vd); + ntfsUnlock( vd ); return 0; } -int ntfs_statvfs_r (struct _reent *r, const char *path, struct statvfs *buf) +int ntfs_statvfs_r ( struct _reent *r, const char *path, struct statvfs *buf ) { - ntfs_log_trace("path %s, buf %p\n", path, buf); + ntfs_log_trace( "path %s, buf %p\n", path, buf ); ntfs_vd *vd = NULL; s64 size; int delta_bits; // Get the volume descriptor for this path - vd = ntfsGetVolume(path); - if (!vd) { + vd = ntfsGetVolume( path ); + if ( !vd ) + { r->_errno = ENODEV; return -1; } // Short circuit cases were we don't actually have to do anything - if (!buf) + if ( !buf ) return 0; // Lock - ntfsLock(vd); + ntfsLock( vd ); // Zero out the stat buffer - memset(buf, 0, sizeof(struct statvfs)); + 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); + ntfsUnlock( vd ); return -1; } @@ -344,34 +361,34 @@ int ntfs_statvfs_r (struct _reent *r, const char *path, struct statvfs *buf) buf->f_blocks = vd->vol->nr_clusters; // Free blocks available for all and for non-privileged processes - size = MAX(vd->vol->free_clusters, 0); + size = MAX( vd->vol->free_clusters, 0 ); buf->f_bfree = buf->f_bavail = size; // Free inodes on the free space delta_bits = vd->vol->cluster_size_bits - vd->vol->mft_record_size_bits; - if (delta_bits >= 0) + if ( delta_bits >= 0 ) 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; + buf->f_files = ( vd->vol->mftbmp_na->allocated_size << 3 ) + size; // Free inodes available for all and for non-privileged processes size += vd->vol->free_mft_records; - buf->f_ffree = buf->f_favail = MAX(size, 0); + buf->f_ffree = buf->f_favail = MAX( size, 0 ); // File system id buf->f_fsid = vd->id; // Bit mask of f_flag values. - buf->f_flag = (NVolReadOnly(vd->vol) ? ST_RDONLY : 0); + buf->f_flag = ( NVolReadOnly( vd->vol ) ? ST_RDONLY : 0 ); // Maximum length of filenames buf->f_namemax = NTFS_MAX_NAME_LEN; // Unlock - ntfsUnlock(vd); + ntfsUnlock( vd ); return 0; } @@ -379,74 +396,83 @@ 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_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) + ntfs_inode *ni = ntfs_pathname_to_inode( dir->vd->vol, dir->ni, entry_name ); + 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)) { - ntfs_inode_close(ni); + if ( ( ( ni->flags & FILE_ATTR_HIDDEN ) && !dir->vd->showHiddenFiles ) || + ( ( ni->flags & FILE_ATTR_SYSTEM ) && !dir->vd->showSystemFiles ) ) + { + ntfs_inode_close( ni ); return 0; } // Close the entry - ntfs_inode_close(ni); + ntfs_inode_close( ni ); } // Allocate a new directory entry - entry = (ntfs_dir_entry *) ntfs_alloc(sizeof(ntfs_dir_entry)); - if (!entry) + entry = ( ntfs_dir_entry * ) ntfs_alloc( sizeof( ntfs_dir_entry ) ); + if ( !entry ) return -1; // Setup the entry entry->name = entry_name; entry->next = NULL; - entry->mref = MREF(mref); + 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,44 +481,48 @@ int ntfs_readdir_filler (DIR_ITER *dirState, const ntfschar *name, const int nam return 0; } -DIR_ITER *ntfs_diropen_r (struct _reent *r, DIR_ITER *dirState, const char *path) +DIR_ITER *ntfs_diropen_r ( struct _reent *r, DIR_ITER *dirState, const char *path ) { - ntfs_log_trace("dirState %p, path %s\n", dirState, path); + ntfs_log_trace( "dirState %p, path %s\n", dirState, path ); - ntfs_dir_state* dir = STATE(dirState); + ntfs_dir_state* dir = STATE( dirState ); s64 position = 0; // Get the volume descriptor for this path - dir->vd = ntfsGetVolume(path); - if (!dir->vd) { + dir->vd = ntfsGetVolume( path ); + if ( !dir->vd ) + { r->_errno = ENODEV; return NULL; } // Lock - ntfsLock(dir->vd); + ntfsLock( dir->vd ); // Find the directory - dir->ni = ntfsOpenEntry(dir->vd, path); - if (!dir->ni) { - ntfsUnlock(dir->vd); + dir->ni = ntfsOpenEntry( dir->vd, path ); + 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)) { - ntfsCloseEntry(dir->vd, dir->ni); - ntfsUnlock(dir->vd); + if ( !( dir->ni->mrec->flags && MFT_RECORD_IS_DIRECTORY ) ) + { + ntfsCloseEntry( dir->vd, dir->ni ); + ntfsUnlock( dir->vd ); r->_errno = ENOTDIR; return NULL; } // Read the directory dir->first = dir->current = NULL; - if (ntfs_readdir(dir->ni, &position, dirState, (ntfs_filldir_t)ntfs_readdir_filler)) { - ntfsCloseDir(dir); - ntfsUnlock(dir->vd); + if ( ntfs_readdir( dir->ni, &position, dirState, ( ntfs_filldir_t )ntfs_readdir_filler ) ) + { + ntfsCloseDir( dir ); + ntfsUnlock( dir->vd ); r->_errno = errno; return NULL; } @@ -501,13 +531,16 @@ DIR_ITER *ntfs_diropen_r (struct _reent *r, DIR_ITER *dirState, const char *path dir->current = dir->first; // Update directory times - ntfsUpdateTimes(dir->vd, dir->ni, NTFS_UPDATE_ATIME); + 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; @@ -516,76 +549,80 @@ DIR_ITER *ntfs_diropen_r (struct _reent *r, DIR_ITER *dirState, const char *path dir->vd->openDirCount++; // Unlock - ntfsUnlock(dir->vd); + ntfsUnlock( dir->vd ); 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_log_trace( "dirState %p\n", dirState ); - ntfs_dir_state* dir = STATE(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; } // Lock - ntfsLock(dir->vd); + ntfsLock( dir->vd ); // Move to the first entry in the directory dir->current = dir->first; // Update directory times - ntfsUpdateTimes(dir->vd, dir->ni, NTFS_UPDATE_ATIME); + ntfsUpdateTimes( dir->vd, dir->ni, NTFS_UPDATE_ATIME ); // Unlock - ntfsUnlock(dir->vd); + ntfsUnlock( dir->vd ); return 0; } -int ntfs_dirnext_r (struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *filestat) +int ntfs_dirnext_r ( struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *filestat ) { - ntfs_log_trace("dirState %p, filename %p, filestat %p\n", dirState, filename, filestat); + ntfs_log_trace( "dirState %p, filename %p, filestat %p\n", dirState, filename, filestat ); - ntfs_dir_state* dir = STATE(dirState); + ntfs_dir_state* dir = STATE( dirState ); ntfs_inode *ni = NULL; // Sanity check - if (!dir || !dir->vd || !dir->ni) { + if ( !dir || !dir->vd || !dir->ni ) + { r->_errno = EBADF; return -1; } // Lock - ntfsLock(dir->vd); + ntfsLock( dir->vd ); // Check that there is a entry waiting to be fetched - if (!dir->current) { - ntfsUnlock(dir->vd); + if ( !dir->current ) + { + ntfsUnlock( dir->vd ); r->_errno = ENOENT; return -1; } // Fetch the current entry - strcpy(filename, dir->current->name); - if(filestat != NULL) + strcpy( filename, dir->current->name ); + 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)); + memset( filestat, 0, sizeof( struct stat ) ); filestat->st_mode = S_IFDIR; } else { - ni = ntfsOpenEntry(dir->vd, dir->current->name); - if (ni) { - ntfsStat(dir->vd, ni, filestat); - ntfsCloseEntry(dir->vd, ni); + ni = ntfsOpenEntry( dir->vd, dir->current->name ); + if ( ni ) + { + ntfsStat( dir->vd, ni, filestat ); + ntfsCloseEntry( dir->vd, ni ); } } } @@ -594,43 +631,44 @@ int ntfs_dirnext_r (struct _reent *r, DIR_ITER *dirState, char *filename, struct dir->current = dir->current->next; // Update directory times - ntfsUpdateTimes(dir->vd, dir->ni, NTFS_UPDATE_ATIME); + ntfsUpdateTimes( dir->vd, dir->ni, NTFS_UPDATE_ATIME ); // Unlock - ntfsUnlock(dir->vd); + ntfsUnlock( dir->vd ); 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_log_trace( "dirState %p\n", dirState ); - ntfs_dir_state* dir = STATE(dirState); + ntfs_dir_state* dir = STATE( dirState ); // Sanity check - if (!dir || !dir->vd) { + if ( !dir || !dir->vd ) + { r->_errno = EBADF; return -1; } // Lock - ntfsLock(dir->vd); + ntfsLock( dir->vd ); // Close the directory - ntfsCloseDir(dir); + ntfsCloseDir( dir ); // Remove the directory from the double-linked FILO list of open directories dir->vd->openDirCount--; - if (dir->nextOpenDir) + if ( dir->nextOpenDir ) dir->nextOpenDir->prevOpenDir = dir->prevOpenDir; - if (dir->prevOpenDir) + if ( dir->prevOpenDir ) dir->prevOpenDir->nextOpenDir = dir->nextOpenDir; else dir->vd->firstOpenDir = dir->nextOpenDir; // Unlock - ntfsUnlock(dir->vd); + ntfsUnlock( dir->vd ); return 0; } diff --git a/source/libntfs/ntfsdir.h b/source/libntfs/ntfsdir.h index 0550592f..c7adbe9b 100644 --- a/source/libntfs/ntfsdir.h +++ b/source/libntfs/ntfsdir.h @@ -28,7 +28,8 @@ /** * ntfs_dir_entry - Directory entry */ -typedef struct _ntfs_dir_entry { +typedef struct _ntfs_dir_entry +{ char *name; u64 mref; struct _ntfs_dir_entry *next; @@ -37,7 +38,8 @@ typedef struct _ntfs_dir_entry { /** * ntfs_dir_state - Directory state */ -typedef struct _ntfs_dir_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 */ @@ -47,22 +49,22 @@ typedef struct _ntfs_dir_state { } 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 5db85168..7e3a20d2 100644 --- a/source/libntfs/ntfsfile.c +++ b/source/libntfs/ntfsfile.c @@ -45,36 +45,36 @@ #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) + 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); + if ( file->encrypted ) + 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); + 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,114 +89,132 @@ void ntfsCloseFile (ntfs_file_state *file) return; } -int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags, int mode) +int ntfs_open_r ( struct _reent *r, void *fileStruct, const char *path, int flags, int mode ) { - ntfs_log_trace("fileStruct %p, path %s, flags %i, mode %i\n", fileStruct, path, flags, mode); + ntfs_log_trace( "fileStruct %p, path %s, flags %i, mode %i\n", fileStruct, path, flags, mode ); - ntfs_file_state* file = STATE(fileStruct); + ntfs_file_state* file = STATE( fileStruct ); // Get the volume descriptor for this path - file->vd = ntfsGetVolume(path); - if (!file->vd) { + file->vd = ntfsGetVolume( path ); + if ( !file->vd ) + { r->_errno = ENODEV; return -1; } // Lock - ntfsLock(file->vd); + ntfsLock( file->vd ); // 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) { + file->append = ( flags & O_APPEND ); + } + else if ( ( flags & 0x03 ) == O_RDWR ) + { file->read = true; file->write = true; - file->append = (flags & O_APPEND); - } else { + file->append = ( flags & O_APPEND ); + } + else + { r->_errno = EACCES; - ntfsUnlock(file->vd); + ntfsUnlock( file->vd ); return -1; } // Try and find the file and (if found) ensure that it is not a directory - file->ni = ntfsOpenEntry(file->vd, path); - if (file->ni && (file->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) { - ntfsCloseEntry(file->vd, file->ni); - ntfsUnlock(file->vd); + file->ni = ntfsOpenEntry( file->vd, path ); + if ( file->ni && ( file->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY ) ) + { + ntfsCloseEntry( file->vd, file->ni ); + ntfsUnlock( file->vd ); r->_errno = EISDIR; return -1; } // Are we creating this file? - if (flags & O_CREAT) { + if ( flags & O_CREAT ) + { // The file SHOULD NOT already exist - if (file->ni) { - ntfsCloseEntry(file->vd, file->ni); - ntfsUnlock(file->vd); + if ( file->ni ) + { + ntfsCloseEntry( file->vd, file->ni ); + ntfsUnlock( file->vd ); r->_errno = EEXIST; return -1; } // Create the file - file->ni = ntfsCreate(file->vd, path, S_IFREG, NULL); - if (!file->ni) { - ntfsUnlock(file->vd); + file->ni = ntfsCreate( file->vd, path, S_IFREG, NULL ); + if ( !file->ni ) + { + ntfsUnlock( file->vd ); return -1; } } // Sanity check, the file should be open by now - if (!file->ni) { - ntfsUnlock(file->vd); + if ( !file->ni ) + { + ntfsUnlock( file->vd ); r->_errno = ENOENT; return -1; } // Open the files data attribute - file->data_na = ntfs_attr_open(file->ni, AT_DATA, AT_UNNAMED, 0); - if(!file->data_na) { - ntfsCloseEntry(file->vd, file->ni); - ntfsUnlock(file->vd); + file->data_na = ntfs_attr_open( file->ni, AT_DATA, AT_UNNAMED, 0 ); + if ( !file->data_na ) + { + ntfsCloseEntry( file->vd, file->ni ); + ntfsUnlock( file->vd ); return -1; } // Determine if this files data is compressed and/or encrypted - file->compressed = NAttrCompressed(file->data_na) || (file->ni->flags & FILE_ATTR_COMPRESSED); - file->encrypted = NAttrEncrypted(file->data_na) || (file->ni->flags & FILE_ATTR_ENCRYPTED); + file->compressed = NAttrCompressed( file->data_na ) || ( file->ni->flags & FILE_ATTR_COMPRESSED ); + file->encrypted = NAttrEncrypted( file->data_na ) || ( file->ni->flags & FILE_ATTR_ENCRYPTED ); // We cannot read/write encrypted files - if (file->encrypted) { - ntfs_attr_close(file->data_na); - ntfsCloseEntry(file->vd, file->ni); - ntfsUnlock(file->vd); + if ( file->encrypted ) + { + ntfs_attr_close( file->data_na ); + ntfsCloseEntry( file->vd, file->ni ); + ntfsUnlock( file->vd ); r->_errno = EACCES; return -1; } // Make sure we aren't trying to write to a read-only file - if ((file->ni->flags & FILE_ATTR_READONLY) && file->write) { - ntfs_attr_close(file->data_na); - ntfsCloseEntry(file->vd, file->ni); - ntfsUnlock(file->vd); + if ( ( file->ni->flags & FILE_ATTR_READONLY ) && file->write ) + { + ntfs_attr_close( file->data_na ); + ntfsCloseEntry( file->vd, file->ni ); + ntfsUnlock( file->vd ); r->_errno = EROFS; return -1; } // Truncate the file if requested - 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); + 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 ); r->_errno = errno; return -1; } @@ -206,16 +224,19 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags file->pos = 0; file->len = file->data_na->data_size; - ntfs_log_trace("file->len %d\n", file->len); + ntfs_log_trace( "file->len %d\n", file->len ); // Update file times - ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_ATIME); + 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; @@ -223,84 +244,91 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags file->vd->openFileCount++; // Unlock - ntfsUnlock(file->vd); + 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_log_trace( "fd %p\n", fd ); - ntfs_file_state* file = STATE(fd); + ntfs_file_state* file = STATE( fd ); // Sanity check - if (!file || !file->vd) { + if ( !file || !file->vd ) + { r->_errno = EBADF; return -1; } // Lock - ntfsLock(file->vd); + ntfsLock( file->vd ); // Close the file - ntfsCloseFile(file); + ntfsCloseFile( file ); // Remove the file from the double-linked FILO list of open files file->vd->openFileCount--; - if (file->nextOpenFile) + if ( file->nextOpenFile ) file->nextOpenFile->prevOpenFile = file->prevOpenFile; - if (file->prevOpenFile) + if ( file->prevOpenFile ) file->prevOpenFile->nextOpenFile = file->nextOpenFile; else file->vd->firstOpenFile = file->nextOpenFile; // Unlock - ntfsUnlock(file->vd); + ntfsUnlock( file->vd ); return 0; } -ssize_t ntfs_write_r (struct _reent *r, int fd, const char *ptr, size_t len) +ssize_t ntfs_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) { - ntfs_log_trace("fd %p, ptr %p, len %Li\n", fd, ptr, len); + ntfs_log_trace( "fd %p, ptr %p, len %Li\n", fd, ptr, len ); - ntfs_file_state* file = STATE(fd); + ntfs_file_state* file = STATE( fd ); ssize_t written = 0; off_t old_pos = 0; // Sanity check - if (!file || !file->vd || !file->ni || !file->data_na) { + 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; } // Lock - ntfsLock(file->vd); + ntfsLock( file->vd ); // Check that we are allowed to write to this file - if (!file->write) { - ntfsUnlock(file->vd); + 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) { - ssize_t ret = ntfs_attr_pwrite(file->data_na, file->pos, len, ptr); - if (ret <= 0) { - ntfsUnlock(file->vd); + while ( len ) + { + ssize_t ret = ntfs_attr_pwrite( file->data_na, file->pos, len, ptr ); + if ( ret <= 0 ) + { + ntfsUnlock( file->vd ); r->_errno = errno; return -1; } @@ -310,65 +338,72 @@ 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) + if ( written ) file->ni->flags |= FILE_ATTR_ARCHIVE; // Update the files data length file->len = file->data_na->data_size; // Unlock - ntfsUnlock(file->vd); + ntfsUnlock( file->vd ); return written; } -ssize_t ntfs_read_r (struct _reent *r, int fd, char *ptr, size_t len) +ssize_t ntfs_read_r ( struct _reent *r, int fd, char *ptr, size_t len ) { - ntfs_log_trace("fd %p, ptr %p, len %Li\n", fd, ptr, len); + ntfs_log_trace( "fd %p, ptr %p, len %Li\n", fd, ptr, len ); - ntfs_file_state* file = STATE(fd); + ntfs_file_state* file = STATE( fd ); 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; } // Lock - ntfsLock(file->vd); + ntfsLock( file->vd ); // Check that we are allowed to read from this file - if (!file->read) { - ntfsUnlock(file->vd); + 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( "EOVERFLOW" ); } - ntfs_log_trace("file->pos:%d, len:%d, file->len:%d \n", (u32)file->pos, (u32)len, (u32)file->len); + ntfs_log_trace( "file->pos:%d, len:%d, file->len:%d \n", ( u32 )file->pos, ( u32 )len, ( u32 )file->len ); // Read from the files data attribute - while (len) { - ssize_t ret = ntfs_attr_pread(file->data_na, file->pos, len, ptr); - if (ret <= 0 || ret > len) { - ntfsUnlock(file->vd); + while ( len ) + { + ssize_t ret = ntfs_attr_pread( file->data_na, file->pos, len, ptr ); + if ( ret <= 0 || ret > len ) + { + ntfsUnlock( file->vd ); r->_errno = errno; return -1; } @@ -381,154 +416,166 @@ ssize_t ntfs_read_r (struct _reent *r, int fd, char *ptr, size_t len) // Update file times (if we actually read something) // Unlock - ntfsUnlock(file->vd); + ntfsUnlock( file->vd ); return read; } -off_t ntfs_seek_r (struct _reent *r, int fd, off_t pos, int dir) +off_t ntfs_seek_r ( struct _reent *r, int fd, off_t pos, int dir ) { - ntfs_log_trace("fd %p, pos %Li, dir %i\n", fd, pos, dir); + ntfs_log_trace( "fd %p, pos %Li, dir %i\n", fd, pos, dir ); - ntfs_file_state* file = STATE(fd); + ntfs_file_state* file = STATE( fd ); 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; } // Lock - ntfsLock(file->vd); + 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 - ntfsUnlock(file->vd); + ntfsUnlock( file->vd ); return position; } -int ntfs_fstat_r (struct _reent *r, int fd, struct stat *st) +int ntfs_fstat_r ( struct _reent *r, int fd, struct stat *st ) { - ntfs_log_trace("fd %p\n", fd); + ntfs_log_trace( "fd %p\n", fd ); - ntfs_file_state* file = STATE(fd); + ntfs_file_state* file = STATE( 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; } // Short circuit cases were we don't actually have to do anything - if (!st) + if ( !st ) return 0; // Get the file stats - ret = ntfsStat(file->vd, file->ni, st); - if (ret) + ret = ntfsStat( file->vd, file->ni, st ); + if ( ret ) r->_errno = errno; return ret; } -int ntfs_ftruncate_r (struct _reent *r, int fd, off_t len) +int ntfs_ftruncate_r ( struct _reent *r, int fd, off_t len ) { - ntfs_log_trace("fd %p, len %Li\n", fd, len); + ntfs_log_trace( "fd %p, len %Li\n", fd, len ); - ntfs_file_state* file = STATE(fd); + 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; } // Lock - ntfsLock(file->vd); + ntfsLock( file->vd ); // Check that we are allowed to write to this file - if (!file->write) { - ntfsUnlock(file->vd); + 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) { - ntfsUnlock(file->vd); + 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) { - ntfsUnlock(file->vd); + 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)) { - ntfsUnlock(file->vd); + } + else + { + if ( ntfs_attr_truncate( file->data_na, len ) ) + { + ntfsUnlock( file->vd ); r->_errno = errno; return -1; } } // Mark the file for archiving (if we actually changed something) - if (file->len != file->data_na->data_size) + 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; // Sync the file (and its attributes) to disc - ntfsSync(file->vd, file->ni); + ntfsSync( file->vd, file->ni ); // Unlock - ntfsUnlock(file->vd); + ntfsUnlock( file->vd ); return 0; } -int ntfs_fsync_r (struct _reent *r, int fd) +int ntfs_fsync_r ( struct _reent *r, int fd ) { - ntfs_log_trace("fd %p\n", fd); + ntfs_log_trace( "fd %p\n", fd ); - ntfs_file_state* file = STATE(fd); + ntfs_file_state* file = STATE( 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; } // Lock - ntfsLock(file->vd); + ntfsLock( file->vd ); // Sync the file (and its attributes) to disc - ret = ntfsSync(file->vd, file->ni); - if (ret) + ret = ntfsSync( file->vd, file->ni ); + if ( ret ) r->_errno = errno; // Unlock - ntfsUnlock(file->vd); + ntfsUnlock( file->vd ); return ret; } diff --git a/source/libntfs/ntfsfile.h b/source/libntfs/ntfsfile.h index 8e5ffcc6..8e23a688 100644 --- a/source/libntfs/ntfsfile.h +++ b/source/libntfs/ntfsfile.h @@ -32,7 +32,8 @@ /** * ntfs_file_state - File state */ -typedef struct _ntfs_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 */ @@ -49,17 +50,17 @@ typedef struct _ntfs_file_state { } 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 55823789..4ebd6193 100644 --- a/source/libntfs/ntfsfile_frag.c +++ b/source/libntfs/ntfsfile_frag.c @@ -6,7 +6,7 @@ * * This program/include file is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as published - * by the Free Software Foundation; either version 2 of the License, or + * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program/include file is distributed in the hope that it will be @@ -50,36 +50,36 @@ #if 0 -void ntfsCloseFile (ntfs_file_state *file) +void ntfsCloseFile ( ntfs_file_state *file ) { // Sanity check - if (!file || !file->vd) + 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); + if ( file->encrypted ) + 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); + 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; @@ -94,114 +94,132 @@ void ntfsCloseFile (ntfs_file_state *file) return; } -int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags, int mode) +int ntfs_open_r ( struct _reent *r, void *fileStruct, const char *path, int flags, int mode ) { - ntfs_log_trace("fileStruct %p, path %s, flags %i, mode %i\n", fileStruct, path, flags, mode); + ntfs_log_trace( "fileStruct %p, path %s, flags %i, mode %i\n", fileStruct, path, flags, mode ); - ntfs_file_state* file = STATE(fileStruct); + ntfs_file_state* file = STATE( fileStruct ); // Get the volume descriptor for this path - file->vd = ntfsGetVolume(path); - if (!file->vd) { + file->vd = ntfsGetVolume( path ); + if ( !file->vd ) + { r->_errno = ENODEV; return -1; } // Lock - ntfsLock(file->vd); + ntfsLock( file->vd ); // 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) { + file->append = ( flags & O_APPEND ); + } + else if ( ( flags & 0x03 ) == O_RDWR ) + { file->read = true; file->write = true; - file->append = (flags & O_APPEND); - } else { + file->append = ( flags & O_APPEND ); + } + else + { r->_errno = EACCES; - ntfsUnlock(file->vd); + ntfsUnlock( file->vd ); return -1; } // Try and find the file and (if found) ensure that it is not a directory - file->ni = ntfsOpenEntry(file->vd, path); - if (file->ni && (file->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) { - ntfsCloseEntry(file->vd, file->ni); - ntfsUnlock(file->vd); + file->ni = ntfsOpenEntry( file->vd, path ); + if ( file->ni && ( file->ni->mrec->flags & MFT_RECORD_IS_DIRECTORY ) ) + { + ntfsCloseEntry( file->vd, file->ni ); + ntfsUnlock( file->vd ); r->_errno = EISDIR; return -1; } // Are we creating this file? - if (flags & O_CREAT) { + if ( flags & O_CREAT ) + { // The file SHOULD NOT already exist - if (file->ni) { - ntfsCloseEntry(file->vd, file->ni); - ntfsUnlock(file->vd); + if ( file->ni ) + { + ntfsCloseEntry( file->vd, file->ni ); + ntfsUnlock( file->vd ); r->_errno = EEXIST; return -1; } // Create the file - file->ni = ntfsCreate(file->vd, path, S_IFREG, NULL); - if (!file->ni) { - ntfsUnlock(file->vd); + file->ni = ntfsCreate( file->vd, path, S_IFREG, NULL ); + if ( !file->ni ) + { + ntfsUnlock( file->vd ); return -1; } } // Sanity check, the file should be open by now - if (!file->ni) { - ntfsUnlock(file->vd); + if ( !file->ni ) + { + ntfsUnlock( file->vd ); r->_errno = ENOENT; return -1; } // Open the files data attribute - file->data_na = ntfs_attr_open(file->ni, AT_DATA, AT_UNNAMED, 0); - if(!file->data_na) { - ntfsCloseEntry(file->vd, file->ni); - ntfsUnlock(file->vd); + file->data_na = ntfs_attr_open( file->ni, AT_DATA, AT_UNNAMED, 0 ); + if ( !file->data_na ) + { + ntfsCloseEntry( file->vd, file->ni ); + ntfsUnlock( file->vd ); return -1; } // Determine if this files data is compressed and/or encrypted - file->compressed = NAttrCompressed(file->data_na) || (file->ni->flags & FILE_ATTR_COMPRESSED); - file->encrypted = NAttrEncrypted(file->data_na) || (file->ni->flags & FILE_ATTR_ENCRYPTED); + file->compressed = NAttrCompressed( file->data_na ) || ( file->ni->flags & FILE_ATTR_COMPRESSED ); + file->encrypted = NAttrEncrypted( file->data_na ) || ( file->ni->flags & FILE_ATTR_ENCRYPTED ); // We cannot read/write encrypted files - if (file->encrypted) { - ntfs_attr_close(file->data_na); - ntfsCloseEntry(file->vd, file->ni); - ntfsUnlock(file->vd); + if ( file->encrypted ) + { + ntfs_attr_close( file->data_na ); + ntfsCloseEntry( file->vd, file->ni ); + ntfsUnlock( file->vd ); r->_errno = EACCES; return -1; } // Make sure we aren't trying to write to a read-only file - if ((file->ni->flags & FILE_ATTR_READONLY) && file->write) { - ntfs_attr_close(file->data_na); - ntfsCloseEntry(file->vd, file->ni); - ntfsUnlock(file->vd); + if ( ( file->ni->flags & FILE_ATTR_READONLY ) && file->write ) + { + ntfs_attr_close( file->data_na ); + ntfsCloseEntry( file->vd, file->ni ); + ntfsUnlock( file->vd ); r->_errno = EROFS; return -1; } // Truncate the file if requested - 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); + 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 ); r->_errno = errno; return -1; } @@ -211,16 +229,19 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags file->pos = 0; file->len = file->data_na->data_size; - ntfs_log_trace("file->len %d\n", file->len); + ntfs_log_trace( "file->len %d\n", file->len ); // Update file times - ntfsUpdateTimes(file->vd, file->ni, NTFS_UPDATE_ATIME); + 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; @@ -228,84 +249,91 @@ int ntfs_open_r (struct _reent *r, void *fileStruct, const char *path, int flags file->vd->openFileCount++; // Unlock - ntfsUnlock(file->vd); + 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_log_trace( "fd %p\n", fd ); - ntfs_file_state* file = STATE(fd); + ntfs_file_state* file = STATE( fd ); // Sanity check - if (!file || !file->vd) { + if ( !file || !file->vd ) + { r->_errno = EBADF; return -1; } // Lock - ntfsLock(file->vd); + ntfsLock( file->vd ); // Close the file - ntfsCloseFile(file); + ntfsCloseFile( file ); // Remove the file from the double-linked FILO list of open files file->vd->openFileCount--; - if (file->nextOpenFile) + if ( file->nextOpenFile ) file->nextOpenFile->prevOpenFile = file->prevOpenFile; - if (file->prevOpenFile) + if ( file->prevOpenFile ) file->prevOpenFile->nextOpenFile = file->nextOpenFile; else file->vd->firstOpenFile = file->nextOpenFile; // Unlock - ntfsUnlock(file->vd); + ntfsUnlock( file->vd ); return 0; } -ssize_t ntfs_write_r (struct _reent *r, int fd, const char *ptr, size_t len) +ssize_t ntfs_write_r ( struct _reent *r, int fd, const char *ptr, size_t len ) { - ntfs_log_trace("fd %p, ptr %p, len %Li\n", fd, ptr, len); + ntfs_log_trace( "fd %p, ptr %p, len %Li\n", fd, ptr, len ); - ntfs_file_state* file = STATE(fd); + ntfs_file_state* file = STATE( fd ); ssize_t written = 0; off_t old_pos = 0; // Sanity check - if (!file || !file->vd || !file->ni || !file->data_na) { + 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; } // Lock - ntfsLock(file->vd); + ntfsLock( file->vd ); // Check that we are allowed to write to this file - if (!file->write) { - ntfsUnlock(file->vd); + 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) { - ssize_t ret = ntfs_attr_pwrite(file->data_na, file->pos, len, ptr); - if (ret <= 0) { - ntfsUnlock(file->vd); + while ( len ) + { + ssize_t ret = ntfs_attr_pwrite( file->data_na, file->pos, len, ptr ); + if ( ret <= 0 ) + { + ntfsUnlock( file->vd ); r->_errno = errno; return -1; } @@ -315,30 +343,31 @@ 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) + if ( written ) file->ni->flags |= FILE_ATTR_ARCHIVE; // Update the files data length file->len = file->data_na->data_size; // Unlock - ntfsUnlock(file->vd); + ntfsUnlock( file->vd ); return written; } #endif -s64 ntfs_attr_getfragments(ntfs_attr *na, const s64 pos, s64 count, u64 offset, - _ntfs_frag_append_t append_fragment, void *callback_data); +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; @@ -347,15 +376,16 @@ 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; } @@ -365,9 +395,9 @@ int _NTFS_get_fragments (const char *path, return 0; } */ - + // Lock - ntfsLock(file->vd); + ntfsLock( file->vd ); /* // Check that we are allowed to read from this file @@ -376,7 +406,7 @@ int _NTFS_get_fragments (const char *path, r->_errno = EACCES; return -1; } - + // Don't read past the end of file if (file->pos + len > file->len) { r->_errno = EOVERFLOW; @@ -389,14 +419,16 @@ int _NTFS_get_fragments (const char *path, u64 len = file->len; // Read from the files data attribute - while (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); + while ( 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 ); //r->_errno = errno; ret_val = -14; - if (ret < 0) ret_val = ret; + if ( ret < 0 ) ret_val = ret; goto out; } offset += ret; @@ -406,7 +438,7 @@ 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; @@ -419,159 +451,171 @@ int _NTFS_get_fragments (const char *path, out: // Unlock - ntfsUnlock(file->vd); + ntfsUnlock( file->vd ); // Close the file - ntfs_close_r (&r, fd); + ntfs_close_r ( &r, fd ); return ret_val; } #if 0 -off_t ntfs_seek_r (struct _reent *r, int fd, off_t pos, int dir) +off_t ntfs_seek_r ( struct _reent *r, int fd, off_t pos, int dir ) { - ntfs_log_trace("fd %p, pos %Li, dir %i\n", fd, pos, dir); - - ntfs_file_state* file = STATE(fd); + ntfs_log_trace( "fd %p, pos %Li, dir %i\n", fd, pos, dir ); + + ntfs_file_state* file = STATE( fd ); off_t position = 0; - + // Sanity check - if (!file || !file->vd || !file->ni || !file->data_na) { + if ( !file || !file->vd || !file->ni || !file->data_na ) + { r->_errno = EINVAL; return -1; } - + // Lock - ntfsLock(file->vd); - + 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 - ntfsUnlock(file->vd); - + + // Unlock + ntfsUnlock( file->vd ); + return position; } -int ntfs_fstat_r (struct _reent *r, int fd, struct stat *st) +int ntfs_fstat_r ( struct _reent *r, int fd, struct stat *st ) { - ntfs_log_trace("fd %p\n", fd); + ntfs_log_trace( "fd %p\n", fd ); - ntfs_file_state* file = STATE(fd); + ntfs_file_state* file = STATE( 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; } - + // Short circuit cases were we don't actually have to do anything - if (!st) + if ( !st ) return 0; - + // Get the file stats - ret = ntfsStat(file->vd, file->ni, st); - if (ret) + ret = ntfsStat( file->vd, file->ni, st ); + if ( ret ) r->_errno = errno; - + return ret; } -int ntfs_ftruncate_r (struct _reent *r, int fd, off_t len) +int ntfs_ftruncate_r ( struct _reent *r, int fd, off_t len ) { - ntfs_log_trace("fd %p, len %Li\n", fd, len); - - ntfs_file_state* file = STATE(fd); - + 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; } - + // Lock - ntfsLock(file->vd); - + ntfsLock( file->vd ); + // Check that we are allowed to write to this file - if (!file->write) { - ntfsUnlock(file->vd); + 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) { - ntfsUnlock(file->vd); + 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) { - ntfsUnlock(file->vd); + 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)) { - ntfsUnlock(file->vd); + } + else + { + if ( ntfs_attr_truncate( file->data_na, len ) ) + { + ntfsUnlock( file->vd ); r->_errno = errno; return -1; } } // Mark the file for archiving (if we actually changed something) - if (file->len != file->data_na->data_size) + 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; - // Sync the file (and its attributes) to disc - ntfsSync(file->vd, file->ni); + // Sync the file (and its attributes) to disc + ntfsSync( file->vd, file->ni ); // Unlock - ntfsUnlock(file->vd); - + ntfsUnlock( file->vd ); + return 0; } -int ntfs_fsync_r (struct _reent *r, int fd) +int ntfs_fsync_r ( struct _reent *r, int fd ) { - ntfs_log_trace("fd %p\n", fd); + ntfs_log_trace( "fd %p\n", fd ); - ntfs_file_state* file = STATE(fd); + ntfs_file_state* file = STATE( 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; } - + // Lock - ntfsLock(file->vd); - + ntfsLock( file->vd ); + // Sync the file (and its attributes) to disc - ret = ntfsSync(file->vd, file->ni); - if (ret) + ret = ntfsSync( file->vd, file->ni ); + if ( ret ) r->_errno = errno; - + // Unlock - ntfsUnlock(file->vd); - + ntfsUnlock( file->vd ); + return ret; } diff --git a/source/libntfs/ntfsinternal.c b/source/libntfs/ntfsinternal.c index fed15bce..36291d82 100644 --- a/source/libntfs/ntfsinternal.c +++ b/source/libntfs/ntfsinternal.c @@ -43,7 +43,8 @@ #include #include -const INTERFACE_ID ntfs_disc_interfaces[] = { +const INTERFACE_ID ntfs_disc_interfaces[] = +{ { "sd", &__io_wiisd }, { "usb", &__io_usbstorage }, { "carda", &__io_gcsda }, @@ -54,7 +55,8 @@ const INTERFACE_ID ntfs_disc_interfaces[] = { #elif defined(__gamecube__) #include -const INTERFACE_ID ntfs_disc_interfaces[] = { +const INTERFACE_ID ntfs_disc_interfaces[] = +{ { "carda", &__io_gcsda }, { "cardb", &__io_gcsdb }, { NULL, NULL } @@ -62,7 +64,7 @@ const INTERFACE_ID ntfs_disc_interfaces[] = { #endif -int ntfsAddDevice (const char *name, void *deviceData) +int ntfsAddDevice ( const char *name, void *deviceData ) { const devoptab_t *devoptab_ntfs = ntfsGetDevOpTab(); devoptab_t *dev = NULL; @@ -70,30 +72,34 @@ 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) { + dev = ( devoptab_t * ) ntfs_alloc( sizeof( devoptab_t ) + strlen( name ) + 1 ); + 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); - strcpy(devname, name); + devname = ( char* )( dev + 1 ); + strcpy( devname, name ); // Setup the devoptab - memcpy(dev, devoptab_ntfs, sizeof(devoptab_t)); + memcpy( dev, devoptab_ntfs, sizeof( devoptab_t ) ); dev->name = devname; 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,26 +110,29 @@ int ntfsAddDevice (const char *name, void *deviceData) return -1; } -void ntfsRemoveDevice (const char *path) +void ntfsRemoveDevice ( const char *path ) { const devoptab_t *devoptab = NULL; char name[128] = {0}; int i; // Get the device name from the path - strncpy(name, path, 127); - strtok(name, ":/"); + strncpy( name, path, 127 ); + strtok( name, ":/" ); // Find and remove the specified device from the devoptab table // 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,24 +141,27 @@ void ntfsRemoveDevice (const char *path) return; } -const devoptab_t *ntfsGetDevice (const char *path, bool useDefaultDevice) +const devoptab_t *ntfsGetDevice ( const char *path, bool useDefaultDevice ) { const devoptab_t *devoptab = NULL; char name[128] = {0}; int i; // Get the device name from the path - strncpy(name, path, 127); - strtok(name, ":/"); + strncpy( name, path, 127 ); + strtok( name, ":/" ); // Search the devoptab table for the specified device name // 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,39 +170,40 @@ 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; + const devoptab_t *devoptab = ntfsGetDevice( path, true ); + 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; } // Initialise the volume lock - LWP_MutexInit(&vd->lock, false); + LWP_MutexInit( &vd->lock, false ); // Reset the volumes name cache vd->name[0] = '\0'; @@ -207,30 +220,33 @@ 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; } // Lock - ntfsLock(vd); + ntfsLock( vd ); // Close any directories which are still open (lazy programmers!) ntfs_dir_state *nextDir = vd->firstOpenDir; - while (nextDir) { - ntfs_log_warning("Cleaning up orphaned directory @ %p\n", nextDir); - ntfsCloseDir(nextDir); + while ( nextDir ) + { + ntfs_log_warning( "Cleaning up orphaned directory @ %p\n", nextDir ); + ntfsCloseDir( nextDir ); nextDir = nextDir->nextOpenDir; } // Close any files which are still open (lazy programmers!) ntfs_file_state *nextFile = vd->firstOpenFile; - while (nextFile) { - ntfs_log_warning("Cleaning up orphaned file @ %p\n", nextFile); - ntfsCloseFile(nextFile); + while ( nextFile ) + { + ntfs_log_warning( "Cleaning up orphaned file @ %p\n", nextFile ); + ntfsCloseFile( nextFile ); nextFile = nextFile->nextOpenFile; } @@ -242,81 +258,89 @@ 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 - vd->dev->d_ops->sync(vd->dev); + vd->dev->d_ops->sync( vd->dev ); // Unlock - ntfsUnlock(vd); + ntfsUnlock( vd ); // Deinitialise the volume lock - LWP_MutexDestroy(vd->lock); + LWP_MutexDestroy( vd->lock ); return; } -ntfs_inode *ntfsOpenEntry (ntfs_vd *vd, const char *path) +ntfs_inode *ntfsOpenEntry ( ntfs_vd *vd, const char *path ) { - return ntfsParseEntry(vd, path, 1); + 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) { + path = ntfsRealPath( 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++); + 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); + 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) { - ntfsCloseEntry(vd, ni); + if ( reparseLevel > NTFS_MAX_SYMLINK_DEPTH ) + { + ntfsCloseEntry( vd, ni ); errno = ELOOP; return NULL; } // Get the target path of this entry - target = ntfs_make_symlink(ni, path, &attr_size); - if (!target) { - ntfsCloseEntry(vd, ni); + target = ntfs_make_symlink( ni, path, &attr_size ); + if ( !target ) + { + ntfsCloseEntry( vd, ni ); return NULL; } // Close the entry (we are no longer interested in it) - ntfsCloseEntry(vd, ni); + ntfsCloseEntry( vd, ni ); // Parse the entries target - ni = ntfsParseEntry(vd, target, reparseLevel++); + ni = ntfsParseEntry( vd, target, reparseLevel++ ); // Clean up - ntfs_free(target); + ntfs_free( target ); } } @@ -324,32 +348,33 @@ 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; } // Lock - ntfsLock(vd); + 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); + ntfs_inode_close( ni ); // Unlock - ntfsUnlock(vd); + ntfsUnlock( vd ); 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,123 +383,134 @@ 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; } } // Get the actual paths of the entry - path = ntfsRealPath(path); - target = ntfsRealPath(target); - if (!path) { + path = ntfsRealPath( path ); + target = ntfsRealPath( target ); + if ( !path ) + { errno = EINVAL; return NULL; } // Lock - ntfsLock(vd); + ntfsLock( vd ); // Get the unicode name for the entry and find its parent directory // TODO: This looks horrible, clean it up - dir = strdup(path); - if (!dir) { + dir = strdup( path ); + if ( !dir ) + { errno = EINVAL; goto cleanup; } - name = strrchr(dir, '/'); - if (name) + name = strrchr( dir, '/' ); + if ( name ) name++; else name = dir; - uname_len = ntfsLocalToUnicode(name, &uname); - if (uname_len < 0) { + uname_len = ntfsLocalToUnicode( name, &uname ); + if ( uname_len < 0 ) + { errno = EINVAL; goto cleanup; } - name = strrchr(dir, '/'); - if(name) + name = strrchr( dir, '/' ); + if ( name ) { name++; name[0] = 0; } // Open the entries parent directory - dir_ni = ntfsOpenEntry(vd, dir); - if (!dir_ni) { + dir_ni = ntfsOpenEntry( vd, dir ); + if ( !dir_ni ) + { goto cleanup; } // Create the entry - switch (type) { + switch ( type ) + { - // Symbolic link + // Symbolic link case S_IFLNK: - if (!target) { + if ( !target ) + { errno = EINVAL; goto cleanup; } - utarget_len = ntfsLocalToUnicode(target, &utarget); - if (utarget_len < 0) { + utarget_len = ntfsLocalToUnicode( target, &utarget ); + if ( utarget_len < 0 ) + { errno = EINVAL; goto cleanup; } - ni = ntfs_create_symlink(dir_ni, 0, uname, uname_len, utarget, utarget_len); + 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); + ni = ntfs_create( dir_ni, 0, uname, uname_len, type ); break; } // If the entry was created - if (ni) { + if ( ni ) + { // Mark the entry for archiving ni->flags |= FILE_ATTR_ARCHIVE; // Mark the entry as dirty - NInoSetDirty(ni); + NInoSetDirty( ni ); // Sync the entry to disc - ntfsSync(vd, ni); + ntfsSync( vd, ni ); // Update parent directories times - ntfsUpdateTimes(vd, dir_ni, NTFS_UPDATE_MCTIME); + ntfsUpdateTimes( vd, dir_ni, NTFS_UPDATE_MCTIME ); } 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); + ntfsUnlock( vd ); 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,96 +520,104 @@ 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; } // Get the actual paths of the entry - old_path = ntfsRealPath(old_path); - new_path = ntfsRealPath(new_path); - if (!old_path || !new_path) { + old_path = ntfsRealPath( old_path ); + new_path = ntfsRealPath( new_path ); + if ( !old_path || !new_path ) + { errno = EINVAL; return -1; } // Lock - ntfsLock(vd); + ntfsLock( vd ); // 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) { + dir = strdup( new_path ); + if ( !dir ) + { errno = EINVAL; goto cleanup; } - name = strrchr(dir, '/'); - if (name) + name = strrchr( dir, '/' ); + if ( name ) name++; else name = dir; - uname_len = ntfsLocalToUnicode(name, &uname); - if (uname_len < 0) { + uname_len = ntfsLocalToUnicode( name, &uname ); + if ( uname_len < 0 ) + { errno = EINVAL; goto cleanup; } *name = 0; // Find the entry - ni = ntfsOpenEntry(vd, old_path); - if (!ni) { + ni = ntfsOpenEntry( vd, old_path ); + if ( !ni ) + { errno = ENOENT; res = -1; goto cleanup; } // Open the entries new parent directory - dir_ni = ntfsOpenEntry(vd, dir); - if (!dir_ni) { + dir_ni = ntfsOpenEntry( vd, dir ); + 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; } // Update entry times - ntfsUpdateTimes(vd, dir_ni, NTFS_UPDATE_MCTIME); + ntfsUpdateTimes( vd, dir_ni, NTFS_UPDATE_MCTIME ); // Sync the entry to disc - ntfsSync(vd, ni); + ntfsSync( vd, ni ); 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); + ntfsUnlock( vd ); 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,170 +627,185 @@ 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) { + path = ntfsRealPath( path ); + if ( !path ) + { errno = EINVAL; return -1; } // Lock - ntfsLock(vd); + ntfsLock( vd ); // Get the unicode name for the entry and find its parent directory // TODO: This looks horrible - dir = strdup(path); - if (!dir) { + dir = strdup( path ); + if ( !dir ) + { errno = EINVAL; goto cleanup; } - name = strrchr(dir, '/'); - if (name) + name = strrchr( dir, '/' ); + if ( name ) name++; else name = dir; - uname_len = ntfsLocalToUnicode(name, &uname); - if (uname_len < 0) { + uname_len = ntfsLocalToUnicode( name, &uname ); + if ( uname_len < 0 ) + { errno = EINVAL; goto cleanup; } - name = strrchr(dir, '/'); - if(name) + name = strrchr( dir, '/' ); + if ( name ) { name++; name[0] = 0; } // Find the entry - ni = ntfsOpenEntry(vd, path); - if (!ni) { + ni = ntfsOpenEntry( vd, path ); + if ( !ni ) + { errno = ENOENT; res = -1; goto cleanup; } // Open the entries parent directory - dir_ni = ntfsOpenEntry(vd, dir); - if (!dir_ni) { + dir_ni = ntfsOpenEntry( vd, dir ); + 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; } // Force the underlying device to sync - vd->dev->d_ops->sync(vd->dev); + vd->dev->d_ops->sync( vd->dev ); // ntfs_delete() ALWAYS closes ni and dir_ni; so no need for us to anymore dir_ni = ni = NULL; 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); + ntfsUnlock( vd ); 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; } // Lock - ntfsLock(vd); + ntfsLock( vd ); // Sync the entry - res = ntfs_inode_sync(ni); + res = ntfs_inode_sync( ni ); // Force the underlying device to sync - vd->dev->d_ops->sync(vd->dev); + vd->dev->d_ops->sync( vd->dev ); // Unlock - ntfsUnlock(vd); + ntfsUnlock( vd ); return res; } -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) + if ( !st ) return 0; // Lock - ntfsLock(vd); + ntfsLock( vd ); // Zero out the stat buffer - memset(st, 0, sizeof(struct stat)); + memset( st, 0, sizeof( struct stat ) ); // Is this entry a directory - if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) { - st->st_mode = S_IFDIR | (0777 & ~vd->dmask); + 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) { + na = ntfs_attr_open( ni, AT_INDEX_ALLOCATION, NTFS_INDEX_I30, 4 ); + if ( na ) + { st->st_size = na->data_size; st->st_blocks = na->allocated_size >> 9; - ntfs_attr_close(na); + ntfs_attr_close( na ); } - // Else it must be a file - } else { - st->st_mode = S_IFREG | (0777 & ~vd->fmask); + // 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; - st->st_nlink = le16_to_cpu(ni->mrec->link_count); + st->st_blocks = ( ni->allocated_size + 511 ) >> 9; + st->st_nlink = le16_to_cpu( ni->mrec->link_count ); } // Fill in the generic entry stats @@ -759,74 +818,81 @@ int ntfsStat (ntfs_vd *vd, ntfs_inode *ni, struct stat *st) st->st_mtime = ni->last_data_change_time; // Update entry times - ntfsUpdateTimes(vd, ni, NTFS_UPDATE_ATIME); + ntfsUpdateTimes( vd, ni, NTFS_UPDATE_ATIME ); // Unlock - ntfsUnlock(vd); + ntfsUnlock( vd ); 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) + 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) + if ( !path ) return NULL; // Move the path pointer to the start of the actual path - if (strchr(path, ':') != NULL) { - path = strchr(path, ':') + 1; + if ( strchr( path, ':' ) != NULL ) + { + 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) + 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) { + len = ntfs_ucstombs( ins, ins_len, outs, outs_len ); + 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) { - *outs = (char *) ntfs_alloc(ins_len + 1); - if (!*outs) { + if ( !*outs || outs_len >= ins_len ) + { + if ( !*outs ) + { + *outs = ( char * ) ntfs_alloc( ins_len + 1 ); + if ( !*outs ) + { errno = ENOMEM; return -1; } } - for (i = 0; i < ins_len; i++) { - ntfschar uc = le16_to_cpu(ins[i]); - if (uc > 0xff) - uc = (ntfschar)'_'; - *outs[i] = (char)uc; + for ( i = 0; i < ins_len; i++ ) + { + ntfschar uc = le16_to_cpu( ins[i] ); + if ( uc > 0xff ) + uc = ( ntfschar )'_'; + *outs[i] = ( char )uc; } - *outs[ins_len] = (ntfschar)'\0'; + *outs[ins_len] = ( ntfschar )'\0'; len = ins_len; } @@ -835,12 +901,12 @@ 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) + if ( !ins || !outs ) return 0; // Convert the local string to unicode - return ntfs_mbstoucs(ins, outs); + return ntfs_mbstoucs( ins, outs ); } diff --git a/source/libntfs/ntfsinternal.h b/source/libntfs/ntfsinternal.h index 11dfb8fd..46b9be20 100644 --- a/source/libntfs/ntfsinternal.h +++ b/source/libntfs/ntfsinternal.h @@ -69,39 +69,43 @@ struct _ntfs_dir_state; /** * PRIMARY_PARTITION - Block device partition record */ -typedef struct _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; +} __attribute__( ( __packed__ ) ) PARTITION_RECORD; /** * MASTER_BOOT_RECORD - Block device master boot record */ -typedef struct _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; +} __attribute__( ( __packed__ ) ) MASTER_BOOT_RECORD; /** * EXTENDED_PARTITION - Block device extended boot record */ -typedef struct _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; +} __attribute__( ( __packed__ ) ) EXTENDED_BOOT_RECORD; /** * INTERFACE_ID - Disc interface identifier */ -typedef struct _INTERFACE_ID { +typedef struct _INTERFACE_ID +{ const char *name; /* Interface name */ const DISC_INTERFACE *interface; /* Disc interface */ } INTERFACE_ID; @@ -109,7 +113,8 @@ typedef struct _INTERFACE_ID { /** * ntfs_atime_t - File access time update strategies */ -typedef enum { +typedef enum +{ ATIME_ENABLED, /* Update access times */ ATIME_DISABLED /* Don't update access times */ } ntfs_atime_t; @@ -117,7 +122,8 @@ typedef enum { /** * ntfs_vd - NTFS volume descriptor */ -typedef struct _ntfs_vd { +typedef struct _ntfs_vd +{ struct ntfs_device *dev; /* NTFS device handle */ ntfs_volume *vol; /* NTFS volume handle */ mutex_t lock; /* Volume lock mutex */ @@ -139,40 +145,40 @@ typedef struct _ntfs_vd { } ntfs_vd; /* Lock volume */ -static inline void ntfsLock (ntfs_vd *vd) +static inline void ntfsLock ( ntfs_vd *vd ) { - LWP_MutexLock(vd->lock); + LWP_MutexLock( vd->lock ); } /* Unlock volume */ -static inline void ntfsUnlock (ntfs_vd *vd) +static inline void ntfsUnlock ( ntfs_vd *vd ) { - LWP_MutexUnlock(vd->lock); + 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..ffc4a24c 100644 --- a/source/libntfs/ntfstime.h +++ b/source/libntfs/ntfstime.h @@ -55,19 +55,19 @@ typedef sle64 ntfs_time; * * Return: A Unix time (number of seconds since 1970, and nanoseconds) */ -static __inline__ struct timespec ntfs2timespec(ntfs_time ntfstime) +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 ); } /** @@ -86,36 +86,36 @@ static __inline__ struct timespec ntfs2timespec(ntfs_time ntfstime) * * Return: An NTFS time (100ns units since Jan 1601) */ -static __inline__ ntfs_time timespec2ntfs(struct timespec spec) +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 ) ); } /* - * Return the current time in ntfs format + * Return the current time in ntfs format */ -static __inline__ ntfs_time ntfs_current_time(void) +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..28a9ddba 100644 --- a/source/libntfs/object_id.c +++ b/source/libntfs/object_id.c @@ -1,7 +1,7 @@ /** * object_id.c - Processing of object ids * - * This module is part of ntfs-3g library + * This module is part of ntfs-3g library * * Copyright (c) 2009 Jean-Pierre Andre * @@ -60,15 +60,15 @@ #include "misc.h" /* - * Endianness considerations + * Endianness considerations * - * According to RFC 4122, GUIDs should be printed with the most - * significant byte first, and the six fields be compared individually - * for ordering. RFC 4122 does not define the internal representation. + * According to RFC 4122, GUIDs should be printed with the most + * significant byte first, and the six fields be compared individually + * for ordering. RFC 4122 does not define the internal representation. * - * Here we always copy disk images with no endianness change, - * and, for indexing, GUIDs are compared as if they were a sequence - * of four unsigned 32 bit integers. + * Here we always copy disk images with no endianness change, + * and, for indexing, GUIDs are compared as if they were a sequence + * of four unsigned 32 bit integers. * * --------------------- begin from RFC 4122 ---------------------- * Consider each field of the UUID to be an unsigned integer as shown @@ -106,532 +106,592 @@ * ---------------------- 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') }; -#ifdef HAVE_SETXATTR /* extended attributes interface required */ +static ntfschar objid_index_name[] = { const_cpu_to_le16( '$' ), + const_cpu_to_le16( 'O' ) + }; +#ifdef HAVE_SETXATTR /* extended attributes interface required */ /* - * Set the index for a new object id + * Set the index for a new object id * - * Returns 0 if success - * -1 if failure, explained by errno + * Returns 0 if success + * -1 if failure, explained by errno */ -static int set_object_id_index(ntfs_inode *ni, ntfs_index_context *xo, - const OBJECT_ID_ATTR *object_id) +static int set_object_id_index( ntfs_inode *ni, ntfs_index_context *xo, + 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 */ /* - * Open the $Extend/$ObjId file and its index + * Open the $Extend/$ObjId file and its index * - * Return the index context if opened - * or NULL if an error occurred (errno tells why) + * Return the index context if opened + * or NULL if an error occurred (errno tells why) * - * The index has to be freed and inode closed when not needed any more. + * The index has to be freed and inode closed when not needed any more. */ -static ntfs_index_context *open_object_id_index(ntfs_volume *vol) +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 */ +#ifdef HAVE_SETXATTR /* extended attributes interface required */ /* - * Merge object_id data stored in the index into - * a full object_id struct. + * Merge object_id data stored in the index into + * a full object_id struct. * - * returns 0 if merging successful - * -1 if no data could be merged. This is generally not an error + * returns 0 if merging successful + * -1 if no data could be merged. This is generally not an error */ -static int merge_index_data(ntfs_inode *ni, - const OBJECT_ID_ATTR *objectid_attr, - OBJECT_ID_ATTR *full_objectid) +static int merge_index_data( ntfs_inode *ni, + 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 */ /* - * Remove an object id index entry if attribute present + * Remove an object id index entry if attribute present * - * Returns the size of existing object id - * (the existing object_d is returned) - * -1 if failure, explained by errno + * Returns the size of existing object id + * (the existing object_d is returned) + * -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 */ +#ifdef HAVE_SETXATTR /* extended attributes interface required */ /* - * Update the object id and index + * Update the object id and index * - * The object_id attribute should have been created and the - * non-duplication of the GUID should have been checked before. + * The object_id attribute should have been created and the + * non-duplication of the GUID should have been checked before. * - * Returns 0 if success - * -1 if failure, explained by errno - * If could not remove the existing index, nothing is done, - * If could not write the new data, no index entry is inserted - * If failed to insert the index, data is removed + * Returns 0 if success + * -1 if failure, explained by errno + * If could not remove the existing index, nothing is done, + * If could not write the new data, no index entry is inserted + * If failed to insert the index, data is removed */ -static int update_object_id(ntfs_inode *ni, ntfs_index_context *xo, - const OBJECT_ID_ATTR *value, size_t size) +static int update_object_id( ntfs_inode *ni, ntfs_index_context *xo, + 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 ); } /* - * Add a (dummy) object id to an inode if it does not exist + * Add a (dummy) object id to an inode if it does not exist * - * returns 0 if attribute was inserted (or already present) - * -1 if adding failed (explained by errno) + * returns 0 if attribute was inserted (or already present) + * -1 if adding failed (explained by errno) */ -static int add_object_id(ntfs_inode *ni, int flags) +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 */ /* - * Delete an object_id index entry + * Delete an object_id index entry * - * Returns 0 if success - * -1 if failure, explained by errno + * Returns 0 if success + * -1 if failure, explained by errno */ -int ntfs_delete_object_id_index(ntfs_inode *ni) +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 */ +#ifdef HAVE_SETXATTR /* extended attributes interface required */ /* - * Get the ntfs object id into an extended attribute + * Get the ntfs object id into an extended attribute * - * If present, the object_id from the attribute and the GUIDs - * from the index are returned (formatted as OBJECT_ID_ATTR) + * If present, the object_id from the attribute and the GUIDs + * from the index are returned (formatted as OBJECT_ID_ATTR) * - * Returns the global size (can be 0, 16 or 64) - * and the buffer is updated if it is long enough + * Returns the global size (can be 0, 16 or 64) + * and the buffer is updated if it is long enough */ -int ntfs_get_ntfs_object_id(ntfs_inode *ni, char *value, size_t size) +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 ); } /* - * Set the object id from an extended attribute + * Set the object id from an extended attribute * - * If the size is 64, the attribute and index are set. - * else if the size is not less than 16 only the attribute is set. - * The object id index is set accordingly. + * If the size is 64, the attribute and index are set. + * else if the size is not less than 16 only the attribute is set. + * The object id index is set accordingly. * - * Returns 0, or -1 if there is a problem + * Returns 0, or -1 if there is a problem */ -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 ) { - 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 ); } /* - * Remove the object id + * Remove the object id * - * Returns 0, or -1 if there is a problem + * Returns 0, or -1 if there is a problem */ -int ntfs_remove_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..ab35e51d 100644 --- a/source/libntfs/object_id.h +++ b/source/libntfs/object_id.h @@ -24,12 +24,12 @@ #ifndef OBJECT_ID_H #define OBJECT_ID_H -int ntfs_get_ntfs_object_id(ntfs_inode *ni, char *value, size_t size); +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_remove_ntfs_object_id(ntfs_inode *ni); +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); +int ntfs_delete_object_id_index( ntfs_inode *ni ); #endif /* OBJECT_ID_H */ diff --git a/source/libntfs/param.h b/source/libntfs/param.h index f21bd653..59a24ee3 100644 --- a/source/libntfs/param.h +++ b/source/libntfs/param.h @@ -22,58 +22,59 @@ #ifndef _NTFS_PARAM_H #define _NTFS_PARAM_H -#define CACHE_INODE_SIZE 32 /* inode cache, zero or >= 3 and not too big */ -#define CACHE_NIDATA_SIZE 64 /* idata cache, zero or >= 3 and not too big */ -#define CACHE_LOOKUP_SIZE 64 /* lookup cache, zero or >= 3 and not too big */ +#define CACHE_INODE_SIZE 32 /* inode cache, zero or >= 3 and not too big */ +#define CACHE_NIDATA_SIZE 64 /* idata cache, zero or >= 3 and not too big */ +#define CACHE_LOOKUP_SIZE 64 /* lookup cache, zero or >= 3 and not too big */ #define CACHE_SECURID_SIZE 16 /* securid cache, zero or >= 3 and not too big */ #define CACHE_LEGACY_SIZE 8 /* legacy cache size, zero or >= 3 and not too big */ -#define FORCE_FORMAT_v1x 0 /* Insert security data as in NTFS v1.x */ -#define OWNERFROMACL 1 /* Get the owner from ACL (not Windows owner) */ +#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 + * 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 /* - * Permission checking modes for high level and low level + * Permission checking modes for high level and low level * - * The choices for high and low lowel are independent, they have - * no effect on the library + * The choices for high and low lowel are independent, they have + * no effect on the library * - * Stick to the recommended values unless you understand the consequences - * on protection and performances. Use of cacheing is good for - * performances, but bad on security. + * Stick to the recommended values unless you understand the consequences + * on protection and performances. Use of cacheing is good for + * performances, but bad on security. * - * Possible values for high level : - * 1 : no cache, kernel control (recommended) - * 4 : no cache, file system control - * 7 : no cache, kernel control for ACLs + * Possible values for high level : + * 1 : no cache, kernel control (recommended) + * 4 : no cache, file system control + * 7 : no cache, kernel control for ACLs * - * Possible values for low level : - * 2 : no cache, kernel control - * 3 : use kernel/fuse cache, kernel control - * 5 : no cache, file system control (recommended) - * 8 : no cache, kernel control for ACLs + * Possible values for low level : + * 2 : no cache, kernel control + * 3 : use kernel/fuse cache, kernel control + * 5 : no cache, file system control (recommended) + * 8 : no cache, kernel control for ACLs * - * Use of options 7 and 8 requires a patch to fuse - * When Posix ACLs are selected in the configure options, a value - * of 6 is added in the mount report. + * Use of options 7 and 8 requires a patch to fuse + * When Posix ACLs are selected in the configure options, a value + * of 6 is added in the mount report. */ #define HPERMSCONFIG 1 diff --git a/source/libntfs/reparse.c b/source/libntfs/reparse.c index 0f6360e1..e40dd022 100644 --- a/source/libntfs/reparse.c +++ b/source/libntfs/reparse.c @@ -1,7 +1,7 @@ /** * reparse.c - Processing of reparse points * - * This module is part of ntfs-3g library + * This module is part of ntfs-3g library * * Copyright (c) 2008-2009 Jean-Pierre Andre * @@ -71,1152 +71,1258 @@ #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/"; /* - * Fix a file name with doubtful case in some directory index - * and return the name with the casing used in directory. + * Fix a file name with doubtful case in some directory index + * and return the name with the casing used in directory. * - * Should only be used to translate paths stored with case insensitivity - * (such as directory junctions) when no case conflict is expected. - * If there some ambiguity, the name which collates first is returned. + * Should only be used to translate paths stored with case insensitivity + * (such as directory junctions) when no case conflict is expected. + * If there some ambiguity, the name which collates first is returned. * - * The name is converted to upper case and searched the usual way. - * The collation rules for file names are such that we should get the - * first candidate if any. + * The name is converted to upper case and searched the usual way. + * The collation rules for file names are such that we should get the + * 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 ); } /* - * Search for a directory junction or a symbolic link - * along the target path, with target defined as a full absolute path + * Search for a directory junction or a symbolic link + * along the target path, with target defined as a full absolute path * - * Returns the path translated to a Linux path - * or NULL if the path is not valid + * Returns the path translated to a Linux path + * 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 ); } /* - * Search for a symbolic link along the target path, - * with the target defined as a relative path + * Search for a symbolic link along the target path, + * with the target defined as a relative path * - * Note : the path used to access the current inode, may be - * different from the one implied in the target definition, - * when an inode has names in several directories. + * Note : the path used to access the current inode, may be + * different from the one implied in the target definition, + * when an inode has names in several directories. * - * Returns the path translated to a Linux path - * or NULL if the path is not valid + * Returns the path translated to a Linux path + * or NULL if the path is not valid */ -static char *search_relative(ntfs_inode *ni, ntfschar *path, int count) +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 ); } /* - * Check whether a drive letter has been defined in .NTFS-3G + * Check whether a drive letter has been defined in .NTFS-3G * - * Returns 1 if found, - * 0 if not found, - * -1 if there was an error (described by errno) + * Returns 1 if found, + * 0 if not found, + * -1 if there was an error (described by errno) */ -static int ntfs_drive_letter(ntfs_volume *vol, ntfschar letter) +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 ); } /* - * Do some sanity checks on reparse data + * Do some sanity checks on reparse data * - * The only general check is about the size (at least the tag must - * be present) - * If the reparse data looks like a junction point or symbolic - * link, more checks can be done. + * The only general check is about the size (at least the tag must + * be present) + * If the reparse data looks like a junction point or symbolic + * link, more checks can be done. * */ -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 ); } /* - * Check and translate the target of a junction point or - * a full absolute symbolic link. + * Check and translate the target of a junction point or + * a full absolute symbolic link. * - * A full target definition begins with "\??\" or "\\?\" + * A full target definition begins with "\??\" or "\\?\" * - * The fully defined target is redefined as a relative link, - * - either to the target if found on the same device. - * - or into the /.NTFS-3G directory for the user to define - * In the first situation, the target is translated to case-sensitive path. + * The fully defined target is redefined as a relative link, + * - either to the target if found on the same device. + * - or into the /.NTFS-3G directory for the user to define + * In the first situation, the target is translated to case-sensitive path. * - * returns the target converted to a relative symlink - * or NULL if there were some problem, as described by errno + * returns the target converted to a relative symlink + * 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:\ - * 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); + 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 ); } /* - * Check and translate the target of an absolute symbolic link. + * Check and translate the target of an absolute symbolic link. * - * An absolute target definition begins with "\" or "x:\" + * An absolute target definition begins with "\" or "x:\" * - * The absolute target is redefined as a relative link, - * - either to the target if found on the same device. - * - or into the /.NTFS-3G directory for the user to define - * In the first situation, the target is translated to case-sensitive path. + * The absolute target is redefined as a relative link, + * - either to the target if found on the same device. + * - or into the /.NTFS-3G directory for the user to define + * In the first situation, the target is translated to case-sensitive path. * - * returns the target converted to a relative symlink - * or NULL if there were some problem, as described by errno + * returns the target converted to a relative symlink + * 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:\ - * 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 >= 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); + 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 >= 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 ); } /* - * Check and translate the target of a relative symbolic link. + * Check and translate the target of a relative symbolic link. * - * A relative target definition does not begin with "\" + * A relative target definition does not begin with "\" * - * The original definition of relative target is kept, it is just - * translated to a case-sensitive path. + * The original definition of relative target is kept, it is just + * translated to a case-sensitive path. * - * returns the target converted to a relative symlink - * or NULL if there were some problem, as described by errno + * returns the target converted to a relative symlink + * or NULL if there were some problem, as described by errno */ -static char *ntfs_get_rellink(ntfs_inode *ni, ntfschar *junction, int count) +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 ); } /* - * Get the target for a junction point or symbolic link - * Should only be called for files or directories with reparse data + * Get the target for a junction point or symbolic link + * Should only be called for files or directories with reparse data * - * returns the target converted to a relative path, or NULL - * if some error occurred, as described by errno - * errno is EOPNOTSUPP if the reparse point is not a valid - * symbolic link or directory junction + * returns the target converted to a relative path, or NULL + * if some error occurred, as described by errno + * errno is EOPNOTSUPP if the reparse point is not a valid + * 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 ); } /* - * Check whether a reparse point looks like a junction point - * or a symbolic link. - * Should only be called for files or directories with reparse data + * Check whether a reparse point looks like a junction point + * or a symbolic link. + * Should only be called for files or directories with reparse data * - * The validity of the target is not checked. + * The validity of the target is not checked. */ -BOOL ntfs_possible_symlink(ntfs_inode *ni) +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 */ +#ifdef HAVE_SETXATTR /* extended attributes interface required */ /* - * Set the index for new reparse data + * Set the index for new reparse data * - * Returns 0 if success - * -1 if failure, explained by errno + * Returns 0 if success + * -1 if failure, explained by errno */ -static int set_reparse_index(ntfs_inode *ni, ntfs_index_context *xr, - le32 reparse_tag) +static int set_reparse_index( ntfs_inode *ni, ntfs_index_context *xr, + le32 reparse_tag ) { - struct REPARSE_INDEX indx; - u64 file_id_cpu; - le64 file_id; - le16 seqn; + 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 */ /* - * Remove a reparse data index entry if attribute present + * Remove a reparse data index entry if attribute present * - * Returns the size of existing reparse data - * (the existing reparse tag is returned) - * -1 if failure, explained by errno + * Returns the size of existing reparse data + * (the existing reparse tag is returned) + * -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 ); } /* - * Open the $Extend/$Reparse file and its index + * Open the $Extend/$Reparse file and its index * - * Return the index context if opened - * or NULL if an error occurred (errno tells why) + * Return the index context if opened + * or NULL if an error occurred (errno tells why) * - * The index has to be freed and inode closed when not needed any more. + * The index has to be freed and inode closed when not needed any more. */ -static ntfs_index_context *open_reparse_index(ntfs_volume *vol) +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 */ +#ifdef HAVE_SETXATTR /* extended attributes interface required */ /* - * Update the reparse data and index + * Update the reparse data and index * - * The reparse data attribute should have been created, and - * an existing index is expected if there is an existing value. + * The reparse data attribute should have been created, and + * an existing index is expected if there is an existing value. * - * Returns 0 if success - * -1 if failure, explained by errno - * If could not remove the existing index, nothing is done, - * If could not write the new data, no index entry is inserted - * If failed to insert the index, data is removed + * Returns 0 if success + * -1 if failure, explained by errno + * If could not remove the existing index, nothing is done, + * If could not write the new data, no index entry is inserted + * If failed to insert the index, data is removed */ -static int update_reparse_data(ntfs_inode *ni, ntfs_index_context *xr, - const char *value, size_t size) +static int update_reparse_data( ntfs_inode *ni, ntfs_index_context *xr, + const char *value, size_t size ) { - int res; - int written; - int oldsize; - ntfs_attr *na; - le32 reparse_tag; + 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 */ /* - * Delete a reparse index entry + * Delete a reparse index entry * - * Returns 0 if success - * -1 if failure, explained by errno + * Returns 0 if success + * -1 if failure, explained by errno */ -int ntfs_delete_reparse_index(ntfs_inode *ni) +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 */ +#ifdef HAVE_SETXATTR /* extended attributes interface required */ /* - * Get the ntfs reparse data into an extended attribute + * Get the ntfs reparse data into an extended attribute * - * Returns the reparse data size - * and the buffer is updated if it is long enough + * Returns the reparse data size + * and the buffer is updated if it is long enough */ -int ntfs_get_ntfs_reparse_data(ntfs_inode *ni, char *value, size_t size) +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 ); } /* - * Set the reparse data from an extended attribute + * Set the reparse data from an extended attribute * - * Warning : the new data is not checked + * Warning : the new data is not checked * - * Returns 0, or -1 if there is a problem + * Returns 0, or -1 if there is a problem */ -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 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 ); } /* - * Remove the reparse data + * Remove the reparse data * - * Returns 0, or -1 if there is a problem + * Returns 0, or -1 if there is a problem */ -int ntfs_remove_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..4623fad4 100644 --- a/source/libntfs/reparse.h +++ b/source/libntfs/reparse.h @@ -24,16 +24,16 @@ #ifndef REPARSE_H #define REPARSE_H -char *ntfs_make_symlink(ntfs_inode *ni, const char *mnt_point, - int *pattr_size); -BOOL ntfs_possible_symlink(ntfs_inode *ni); +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_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_remove_ntfs_reparse_data(ntfs_inode *ni); +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); +int ntfs_delete_reparse_index( ntfs_inode *ni ); #endif /* REPARSE_H */ diff --git a/source/libntfs/runlist.c b/source/libntfs/runlist.c index cea24672..2fe86eb7 100644 --- a/source/libntfs/runlist.c +++ b/source/libntfs/runlist.c @@ -60,10 +60,10 @@ * * Returns: */ -static void ntfs_rl_mm(runlist_element *base, int dst, int src, int size) +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,132 +78,138 @@ 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 ) ); } /** * ntfs_rl_realloc - Reallocate memory for runlists - * @rl: original runlist - * @old_size: number of runlist elements in the original runlist @rl - * @new_size: number of runlist elements we need space for + * @rl: original runlist + * @old_size: number of runlist elements in the original runlist @rl + * @new_size: number of runlist elements we need space for * * As the runlists grow, more memory will be required. To prevent large * numbers of small reallocations of memory, this function returns a 4kiB block * of memory. * - * N.B. If the new allocation doesn't require a different number of 4kiB - * blocks in memory, the function will return the original pointer. + * N.B. If the new allocation doesn't require a different number of 4kiB + * blocks in memory, the function will return the original pointer. * * 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 ); } /* - * Extend a runlist by some entry count - * The runlist may have to be reallocated + * Extend a runlist by some entry count + * The runlist may have to be reallocated * - * Returns the reallocated runlist - * or NULL if reallocation was not possible (with errno set) - * the runlist is left unchanged if the reallocation fails + * Returns the reallocated runlist + * or NULL if reallocation was not possible (with errno set) + * 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 ); } /** * ntfs_rl_are_mergeable - test if two runlists can be joined together - * @dst: original runlist - * @src: new runlist to test for mergeability with @dst + * @dst: original runlist + * @src: new runlist to test for mergeability with @dst * * Test if two runlists can be joined together. For this, their VCNs and LCNs * must be adjacent. * * Return: TRUE Success, the runlists can be merged. - * FALSE Failure, the runlists cannot be merged. + * FALSE Failure, the runlists cannot be merged. */ -static BOOL ntfs_rl_are_mergeable(runlist_element *dst, runlist_element *src) +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; } /** * __ntfs_rl_merge - merge two runlists without testing if they can be merged - * @dst: original, destination runlist - * @src: new runlist to merge with @dst + * @dst: original, destination runlist + * @src: new runlist to merge with @dst * * Merge the two runlists, writing into the destination runlist @dst. The * caller must make sure the runlists can be merged or this will corrupt the * destination runlist. */ -static void __ntfs_rl_merge(runlist_element *dst, runlist_element *src) +static void __ntfs_rl_merge( runlist_element *dst, runlist_element *src ) { - dst->length += src->length; + dst->length += src->length; } /** * ntfs_rl_append - append a runlist after a given element - * @dst: original runlist to be worked on - * @dsize: number of elements in @dst (including end marker) - * @src: runlist to be inserted into @dst - * @ssize: number of elements in @src (excluding end marker) - * @loc: append the new runlist @src after this element in @dst + * @dst: original runlist to be worked on + * @dsize: number of elements in @dst (including end marker) + * @src: runlist to be inserted into @dst + * @ssize: number of elements in @src (excluding end marker) + * @loc: append the new runlist @src after this element in @dst * * Append the runlist @src after element @loc in @dst. Merge the right end of * the new runlist, if necessary. Adjust the size of the hole before the @@ -217,60 +223,61 @@ 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; } /** * ntfs_rl_insert - insert a runlist into another - * @dst: original runlist to be worked on - * @dsize: number of elements in @dst (including end marker) - * @src: new runlist to be inserted - * @ssize: number of elements in @src (excluding end marker) - * @loc: insert the new runlist @src before this element in @dst + * @dst: original runlist to be worked on + * @dsize: number of elements in @dst (including end marker) + * @src: new runlist to be inserted + * @ssize: number of elements in @src (excluding end marker) + * @loc: insert the new runlist @src before this element in @dst * * Insert the runlist @src before element @loc in the runlist @dst. Merge the * left end of the new runlist, if necessary. Adjust the size of the hole @@ -284,90 +291,96 @@ 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; } /** * ntfs_rl_replace - overwrite a runlist element with another runlist - * @dst: original runlist to be worked on - * @dsize: number of elements in @dst (including end marker) - * @src: new runlist to be inserted - * @ssize: number of elements in @src (excluding end marker) - * @loc: index in runlist @dst to overwrite with @src + * @dst: original runlist to be worked on + * @dsize: number of elements in @dst (including end marker) + * @src: new runlist to be inserted + * @ssize: number of elements in @src (excluding end marker) + * @loc: index in runlist @dst to overwrite with @src * * Replace the runlist element @dst at @loc with @src. Merge the left and * right ends of the inserted runlist, if necessary. @@ -380,81 +393,83 @@ 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; } /** * ntfs_rl_split - insert a runlist into the centre of a hole - * @dst: original runlist to be worked on - * @dsize: number of elements in @dst (including end marker) - * @src: new runlist to be inserted - * @ssize: number of elements in @src (excluding end marker) - * @loc: index in runlist @dst at which to split and insert @src + * @dst: original runlist to be worked on + * @dsize: number of elements in @dst (including end marker) + * @src: new runlist to be inserted + * @ssize: number of elements in @src (excluding end marker) + * @loc: index in runlist @dst at which to split and insert @src * * Split the runlist @dst at @loc into two and insert @new in between the two * fragments. No merging of runlists is necessary. Adjust the size of the @@ -468,251 +483,268 @@ 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; + /* The merge was completed successfully. */ + ntfs_log_debug( "Merged runlist:\n" ); + ntfs_debug_runlist_dump( drl ); + return drl; critical_error: - /* Critical error! We cannot afford to fail here. */ - ntfs_log_perror("libntfs: Critical error"); - ntfs_log_debug("Forcing segmentation fault!\n"); - marker_vcn = ((runlist*)NULL)->lcn; - return drl; + /* Critical error! We cannot afford to fail here. */ + ntfs_log_perror( "libntfs: Critical error" ); + ntfs_log_debug( "Forcing segmentation fault!\n" ); + marker_vcn = ( ( runlist* )NULL )->lcn; + return drl; } /** * ntfs_runlists_merge - merge two runlists into one - * @drl: original runlist to be worked on - * @srl: new runlist to be merged into @drl + * @drl: original runlist to be worked on + * @srl: new runlist to be merged into @drl * * First we sanity check the two runlists @srl and @drl to make sure that they * are sensible and can be merged. The runlist @srl must be either after the @@ -723,10 +755,10 @@ critical_error: * 2. When new clusters are allocated to fill a hole or extend a file. * * There are four possible ways @srl can be merged. It can: - * - be inserted at the beginning of a hole, - * - split the hole in two and be inserted between the two fragments, - * - be appended at the end of a hole, or it can - * - replace the whole hole. + * - be inserted at the beginning of a hole, + * - split the hole in two and be inserted between the two fragments, + * - be appended at the end of a hole, or it can + * - replace the whole hole. * It can also be appended to the end of the runlist, which is just a variant * of the insert case. * @@ -737,26 +769,26 @@ critical_error: * * On error, return NULL, with errno set to the error code. Both runlists are * left unmodified. The following error codes are defined: - * ENOMEM Not enough memory to allocate runlist array. - * EINVAL Invalid parameters were passed in. - * ERANGE The runlists overlap and cannot be merged. + * ENOMEM Not enough memory to allocate runlist array. + * 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; } /** * ntfs_mapping_pairs_decompress - convert mapping pairs array to runlist - * @vol: ntfs volume on which the attribute resides - * @attr: attribute record whose mapping pairs array to decompress - * @old_rl: optional runlist in which to insert @attr's runlist + * @vol: ntfs volume on which the attribute resides + * @attr: attribute record whose mapping pairs array to decompress + * @old_rl: optional runlist in which to insert @attr's runlist * * Decompress the attribute @attr's mapping pairs array into a runlist. On * success, return the decompressed runlist. @@ -769,255 +801,276 @@ runlist_element *ntfs_runlists_merge(runlist_element *drl, * unmodified in that case. * * The following error codes are defined: - * ENOMEM Not enough memory to allocate runlist array. - * EIO Corrupt runlist. - * EINVAL Invalid parameters were passed in. - * ERANGE The two runlists overlap. + * ENOMEM Not enough memory to allocate runlist array. + * EIO Corrupt runlist. + * EINVAL Invalid parameters were passed in. + * ERANGE The two runlists overlap. * * FIXME: For now we take the conceptionally simplest approach of creating the * new runlist disregarding the already existing one and then splicing the * 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) { + /* Check lcn is not below -1. */ + if ( lcn < ( LCN ) - 1 ) + { + ntfs_log_debug( "Invalid LCN < -1 in mapping pairs " + "array.\n" ); + goto err_out; + } + /* Enter the current lcn into the runlist element. */ + rl[rlpos].lcn = lcn; + } + /* Get to the next runlist element. */ + rlpos++; + /* Increment the buffer position to the next mapping pair. */ + buf += ( *buf & 0xf ) + ( ( *buf >> 4 ) & 0xf ) + 1; + } + if ( buf >= attr_end ) + goto io_error; + /* + * If there is a highest_vcn specified, it must be equal to the final + * vcn in the runlist - 1, or something has gone badly wrong. + */ + deltaxcn = sle64_to_cpu( attr->highest_vcn ); + if ( deltaxcn && vcn - 1 != deltaxcn ) + { mpa_err: - ntfs_log_debug("Corrupt mapping pairs array in non-resident " - "attribute.\n"); - goto err_out; - } - /* Setup not mapped runlist element if this is the base extent. */ - if (!attr->lowest_vcn) { - VCN max_cluster; + ntfs_log_debug( "Corrupt mapping pairs array in non-resident " + "attribute.\n" ); + goto err_out; + } + /* Setup not mapped runlist element if this is the base extent. */ + if ( !attr->lowest_vcn ) + { + VCN max_cluster; - max_cluster = ((sle64_to_cpu(attr->allocated_size) + - vol->cluster_size - 1) >> - vol->cluster_size_bits) - 1; - /* - * A highest_vcn of zero means this is a single extent - * attribute so simply terminate the runlist with LCN_ENOENT). - */ - if (deltaxcn) { - /* - * If there is a difference between the highest_vcn and - * the highest cluster, the runlist is either corrupt - * or, more likely, there are more extents following - * this one. - */ - if (deltaxcn < max_cluster) { - ntfs_log_debug("More extents to follow; deltaxcn = " - "0x%llx, max_cluster = 0x%llx\n", - (long long)deltaxcn, - (long long)max_cluster); - rl[rlpos].vcn = vcn; - vcn += rl[rlpos].length = max_cluster - deltaxcn; - rl[rlpos].lcn = (LCN)LCN_RL_NOT_MAPPED; - rlpos++; - } else if (deltaxcn > max_cluster) { - ntfs_log_debug("Corrupt attribute. deltaxcn = " - "0x%llx, max_cluster = 0x%llx\n", - (long long)deltaxcn, - (long long)max_cluster); - goto mpa_err; - } - } - rl[rlpos].lcn = (LCN)LCN_ENOENT; - } else /* Not the base extent. There may be more extents to follow. */ - rl[rlpos].lcn = (LCN)LCN_RL_NOT_MAPPED; + max_cluster = ( ( sle64_to_cpu( attr->allocated_size ) + + vol->cluster_size - 1 ) >> + vol->cluster_size_bits ) - 1; + /* + * A highest_vcn of zero means this is a single extent + * attribute so simply terminate the runlist with LCN_ENOENT). + */ + if ( deltaxcn ) + { + /* + * If there is a difference between the highest_vcn and + * the highest cluster, the runlist is either corrupt + * or, more likely, there are more extents following + * this one. + */ + if ( deltaxcn < max_cluster ) + { + ntfs_log_debug( "More extents to follow; deltaxcn = " + "0x%llx, max_cluster = 0x%llx\n", + ( long long )deltaxcn, + ( long long )max_cluster ); + rl[rlpos].vcn = vcn; + vcn += rl[rlpos].length = max_cluster - deltaxcn; + rl[rlpos].lcn = ( LCN )LCN_RL_NOT_MAPPED; + rlpos++; + } + else if ( deltaxcn > max_cluster ) + { + ntfs_log_debug( "Corrupt attribute. deltaxcn = " + "0x%llx, max_cluster = 0x%llx\n", + ( long long )deltaxcn, + ( long long )max_cluster ); + goto mpa_err; + } + } + rl[rlpos].lcn = ( LCN )LCN_ENOENT; + } + else /* Not the base extent. There may be more extents to follow. */ + rl[rlpos].lcn = ( LCN )LCN_RL_NOT_MAPPED; - /* Setup terminating runlist element. */ - rl[rlpos].vcn = vcn; - rl[rlpos].length = (s64)0; - /* If no existing runlist was specified, we are done. */ - if (!old_rl) { - ntfs_log_debug("Mapping pairs array successfully decompressed:\n"); - ntfs_debug_runlist_dump(rl); - return rl; - } - /* Now combine the new and old runlists checking for overlaps. */ - old_rl = ntfs_runlists_merge(old_rl, rl); - if (old_rl) - return old_rl; - err = errno; - free(rl); - ntfs_log_debug("Failed to merge runlists.\n"); - errno = err; - return NULL; + /* Setup terminating runlist element. */ + rl[rlpos].vcn = vcn; + rl[rlpos].length = ( s64 )0; + /* If no existing runlist was specified, we are done. */ + if ( !old_rl ) + { + ntfs_log_debug( "Mapping pairs array successfully decompressed:\n" ); + ntfs_debug_runlist_dump( rl ); + return rl; + } + /* Now combine the new and old runlists checking for overlaps. */ + old_rl = ntfs_runlists_merge( old_rl, rl ); + if ( old_rl ) + return old_rl; + err = errno; + free( rl ); + ntfs_log_debug( "Failed to merge runlists.\n" ); + errno = err; + return NULL; io_error: - ntfs_log_debug("Corrupt attribute.\n"); + ntfs_log_debug( "Corrupt attribute.\n" ); err_out: - free(rl); - errno = EIO; - return NULL; + free( rl ); + errno = EIO; + return NULL; } -runlist_element *ntfs_mapping_pairs_decompress(const ntfs_volume *vol, - const ATTR_RECORD *attr, runlist_element *old_rl) +runlist_element *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; } /** * ntfs_rl_vcn_to_lcn - convert a vcn into a lcn given a runlist - * @rl: runlist to use for conversion - * @vcn: vcn to convert + * @rl: runlist to use for conversion + * @vcn: vcn to convert * * Convert the virtual cluster number @vcn of an attribute into a logical * cluster number (lcn) of a device using the runlist @rl to map vcns to their @@ -1025,56 +1078,58 @@ runlist_element *ntfs_mapping_pairs_decompress(const ntfs_volume *vol, * * Since lcns must be >= 0, we use negative return values with special meaning: * - * Return value Meaning / Description + * Return value Meaning / Description * ================================================== - * -1 = LCN_HOLE Hole / not allocated on disk. - * -2 = LCN_RL_NOT_MAPPED This is part of the runlist which has not been - * inserted into the runlist yet. - * -3 = LCN_ENOENT There is no such vcn in the attribute. - * -4 = LCN_EINVAL Input parameter error. + * -1 = LCN_HOLE Hole / not allocated on disk. + * -2 = LCN_RL_NOT_MAPPED This is part of the runlist which has not been + * inserted into the runlist yet. + * -3 = LCN_ENOENT There is no such vcn in the attribute. + * -4 = LCN_EINVAL Input parameter error. */ -LCN ntfs_rl_vcn_to_lcn(const runlist_element *rl, const VCN vcn) +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; } /** * ntfs_rl_pread - gather read from disk - * @vol: ntfs volume to read from - * @rl: runlist specifying where to read the data from - * @pos: byte position within runlist @rl at which to begin the read - * @count: number of bytes to read - * @b: data buffer into which to read from disk + * @vol: ntfs volume to read from + * @rl: runlist specifying where to read the data from + * @pos: byte position within runlist @rl at which to begin the read + * @count: number of bytes to read + * @b: data buffer into which to read from disk * * This function will read @count bytes from the volume @vol to the data buffer * @b gathering the data as specified by the runlist @rl. The read begins at @@ -1092,80 +1147,84 @@ 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); + if ( !vol || !rl || pos < 0 || count < 0 ) + { + errno = EINVAL; + ntfs_log_perror( "Failed to read runlist [vol: %p rl: %p " + "pos: %lld count: %lld]", vol, rl, + ( long long )pos, ( long long )count ); + return -1; + } + if ( !count ) + return count; + /* Seek in @rl to the run containing @pos. */ + for ( ofs = 0; rl->length && ( ofs + ( rl->length << + vol->cluster_size_bits ) <= pos ); rl++ ) + ofs += ( rl->length << vol->cluster_size_bits ); + /* Offset in the run at which to begin reading. */ + ofs = pos - ofs; + for ( total = 0LL; count; rl++, ofs = 0 ) + { + if ( !rl->length ) + goto rl_err_out; + if ( rl->lcn < ( LCN )0 ) + { + if ( rl->lcn != ( LCN )LCN_HOLE ) + goto rl_err_out; + /* It is a hole. Just fill buffer @b with zeroes. */ + to_read = min( count, ( rl->length << + vol->cluster_size_bits ) - ofs ); + memset( b, 0, to_read ); + /* Update counters and proceed with next run. */ + total += to_read; + count -= to_read; + b = ( u8* )b + to_read; + continue; + } + /* It is a real lcn, read it from the volume. */ + to_read = min( count, ( rl->length << vol->cluster_size_bits ) - + ofs ); retry: - bytes_read = ntfs_pread(vol->dev, (rl->lcn << - vol->cluster_size_bits) + ofs, to_read, b); - /* If everything ok, update progress counters and continue. */ - if (bytes_read > 0) { - total += bytes_read; - count -= bytes_read; - b = (u8*)b + bytes_read; - continue; - } - /* If the syscall was interrupted, try again. */ - if (bytes_read == (s64)-1 && errno == EINTR) - goto retry; - if (bytes_read == (s64)-1) - err = errno; - goto rl_err_out; - } - /* Finally, return the number of bytes read. */ - return total; + bytes_read = ntfs_pread( vol->dev, ( rl->lcn << + vol->cluster_size_bits ) + ofs, to_read, b ); + /* If everything ok, update progress counters and continue. */ + if ( bytes_read > 0 ) + { + total += bytes_read; + count -= bytes_read; + b = ( u8* )b + bytes_read; + continue; + } + /* If the syscall was interrupted, try again. */ + if ( bytes_read == ( s64 ) - 1 && errno == EINTR ) + goto retry; + if ( bytes_read == ( s64 ) - 1 ) + err = errno; + goto rl_err_out; + } + /* Finally, return the number of bytes read. */ + return total; rl_err_out: - if (total) - return total; - errno = err; - return -1; + if ( total ) + return total; + errno = err; + return -1; } /** * ntfs_rl_pwrite - scatter write to disk - * @vol: ntfs volume to write to - * @rl: runlist entry specifying where to write the data to - * @ofs: offset in file for runlist element indicated in @rl - * @pos: byte position from runlist beginning at which to begin the write - * @count: number of bytes to write - * @b: data buffer to write to disk + * @vol: ntfs volume to write to + * @rl: runlist entry specifying where to write the data to + * @ofs: offset in file for runlist element indicated in @rl + * @pos: byte position from runlist beginning at which to begin the write + * @count: number of bytes to write + * @b: data buffer to write to disk * * This function will write @count bytes from data buffer @b to the volume @vol * scattering the data as specified by the runlist @rl. The write begins at @@ -1181,83 +1240,88 @@ 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); + if ( rl->lcn != ( LCN )LCN_HOLE ) + goto rl_err_out; + + to_write = min( count, ( rl->length << + vol->cluster_size_bits ) - ofs ); + + total += to_write; + count -= to_write; + b = ( u8* )b + to_write; + continue; + } + /* It is a real lcn, write it to the volume. */ + to_write = min( count, ( rl->length << vol->cluster_size_bits ) - + ofs ); retry: - if (!NVolReadOnly(vol)) - written = ntfs_pwrite(vol->dev, (rl->lcn << - vol->cluster_size_bits) + ofs, - to_write, b); - else - written = to_write; - /* If everything ok, update progress counters and continue. */ - if (written > 0) { - total += written; - count -= written; - b = (u8*)b + written; - continue; - } - /* If the syscall was interrupted, try again. */ - if (written == (s64)-1 && errno == EINTR) - goto retry; - if (written == (s64)-1) - err = errno; - goto rl_err_out; - } + if ( !NVolReadOnly( vol ) ) + written = ntfs_pwrite( vol->dev, ( rl->lcn << + vol->cluster_size_bits ) + ofs, + to_write, b ); + else + written = to_write; + /* If everything ok, update progress counters and continue. */ + if ( written > 0 ) + { + total += written; + count -= written; + b = ( u8* )b + written; + continue; + } + /* If the syscall was interrupted, try again. */ + if ( written == ( s64 ) - 1 && errno == EINTR ) + goto retry; + if ( written == ( s64 ) - 1 ) + err = errno; + goto rl_err_out; + } out: - return total; + return total; rl_err_out: - if (total) - goto out; - errno = err; + if ( total ) + goto out; + errno = err; errno_set: - total = -1; - goto out; + total = -1; + goto out; } /** * ntfs_get_nr_significant_bytes - get number of bytes needed to store a number - * @n: number for which to get the number of bytes for + * @n: number for which to get the number of bytes for * * Return the number of bytes required to store @n unambiguously as * a signed number. @@ -1268,28 +1332,31 @@ errno_set: * * Return the number of bytes written. This function cannot fail. */ -int ntfs_get_nr_significant_bytes(const s64 n) +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; } /** * ntfs_get_size_for_mapping_pairs - get bytes needed for mapping pairs array - * @vol: ntfs volume (needed for the ntfs version) - * @rl: runlist for which to determine the size of the mapping pairs - * @start_vcn: vcn at which to start the mapping pairs array + * @vol: ntfs volume (needed for the ntfs version) + * @rl: runlist for which to determine the size of the mapping pairs + * @start_vcn: vcn at which to start the mapping pairs array * * Walk the runlist @rl and calculate the size in bytes of the mapping pairs * array corresponding to the runlist @rl, starting at vcn @start_vcn. This @@ -1300,107 +1367,115 @@ int ntfs_get_nr_significant_bytes(const s64 n) * * Return the calculated size in bytes on success. On error, return -1 with * errno set to the error code. The following error codes are defined: - * EINVAL - Run list contains unmapped elements. Make sure to only pass - * fully mapped runlists to this function. - * - @start_vcn is invalid. - * EIO - The runlist is corrupt. + * EINVAL - Run list contains unmapped elements. Make sure to only pass + * fully mapped runlists to this function. + * - @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; + /* We know rl->length != 0 already. */ + if ( rl->length < 0 || rl->lcn < LCN_HOLE ) + goto err_out; + delta = start_vcn - rl->vcn; + /* Header byte + length. */ + rls += 1 + ntfs_get_nr_significant_bytes( rl->length - delta ); + /* + * If the logical cluster number (lcn) denotes a hole and we + * are on NTFS 3.0+, we don't store it at all, i.e. we need + * zero space. On earlier NTFS versions we just store the lcn. + * Note: this assumes that on NTFS 1.2-, holes are stored with + * an lcn of -1 and not a delta_lcn of -1 (unless both are -1). + */ + if ( rl->lcn >= 0 || vol->major_ver < 3 ) + { + prev_lcn = rl->lcn; + if ( rl->lcn >= 0 ) + prev_lcn += delta; + /* Change in lcn. */ + rls += ntfs_get_nr_significant_bytes( prev_lcn ); + } + /* Go to next runlist element. */ + rl++; + } + /* Do the full runs. */ + for ( ; rl->length && ( rls <= max_size ); rl++ ) + { + if ( rl->length < 0 || rl->lcn < LCN_HOLE ) + goto err_out; + /* Header byte + length. */ + rls += 1 + ntfs_get_nr_significant_bytes( rl->length ); + /* + * If the logical cluster number (lcn) denotes a hole and we + * are on NTFS 3.0+, we don't store it at all, i.e. we need + * zero space. On earlier NTFS versions we just store the lcn. + * Note: this assumes that on NTFS 1.2-, holes are stored with + * an lcn of -1 and not a delta_lcn of -1 (unless both are -1). + */ + if ( rl->lcn >= 0 || vol->major_ver < 3 ) + { + /* Change in lcn. */ + rls += ntfs_get_nr_significant_bytes( rl->lcn - + prev_lcn ); + prev_lcn = rl->lcn; + } + } +out: + return rls; err_out: - if (rl->lcn == LCN_RL_NOT_MAPPED) - errno = EINVAL; - else - errno = EIO; -errno_set: - rls = -1; - goto out; + if ( rl->lcn == LCN_RL_NOT_MAPPED ) + errno = EINVAL; + else + errno = EIO; +errno_set: + rls = -1; + goto out; } /** * ntfs_write_significant_bytes - write the significant bytes of a number - * @dst: destination buffer to write to - * @dst_max: pointer to last byte of destination buffer for bounds checking - * @n: number whose significant bytes to write + * @dst: destination buffer to write to + * @dst_max: pointer to last byte of destination buffer for bounds checking + * @n: number whose significant bytes to write * * Store in @dst, the minimum bytes of the number @n which are required to * identify @n unambiguously as a signed number, taking care not to exceed @@ -1414,47 +1489,52 @@ errno_set: * Return the number of bytes written on success. On error, i.e. the * destination buffer @dst is too small, return -1 with errno set ENOSPC. */ -int ntfs_write_significant_bytes(u8 *dst, const u8 *dst_max, const s64 n) +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; + i = 0; + do + { + if ( dst > dst_max ) + goto err_out; + *dst++ = l & 0xffLL; + l >>= 8; + i++; + } + while ( l != 0LL && l != -1LL ); + j = ( n >> 8 * ( i - 1 ) ) & 0xff; + /* If the sign bit is wrong, we need an extra byte. */ + if ( n < 0LL && j >= 0 ) + { + if ( dst > dst_max ) + goto err_out; + i++; + *dst = ( u8 ) - 1; + } + else if ( n > 0LL && j < 0 ) + { + if ( dst > dst_max ) + goto err_out; + i++; + *dst = 0; + } + return i; err_out: - errno = ENOSPC; - return -1; + errno = ENOSPC; + return -1; } /** * ntfs_mapping_pairs_build - build the mapping pairs array from a runlist - * @vol: ntfs volume (needed for the ntfs version) - * @dst: destination buffer to which to write the mapping pairs array - * @dst_len: size of destination buffer @dst in bytes - * @rl: runlist for which to build the mapping pairs array - * @start_vcn: vcn at which to start the mapping pairs array - * @stop_vcn: first vcn outside destination buffer on success or ENOSPC error + * @vol: ntfs volume (needed for the ntfs version) + * @dst: destination buffer to which to write the mapping pairs array + * @dst_len: size of destination buffer @dst in bytes + * @rl: runlist for which to build the mapping pairs array + * @start_vcn: vcn at which to start the mapping pairs array + * @stop_vcn: first vcn outside destination buffer on success or ENOSPC error * * Create the mapping pairs array from the runlist @rl, starting at vcn * @start_vcn and save the array in @dst. @dst_len is the size of @dst in @@ -1472,155 +1552,162 @@ err_out: * * Return 0 on success. On error, return -1 with errno set to the error code. * The following error codes are defined: - * EINVAL - Run list contains unmapped elements. Make sure to only pass - * fully mapped runlists to this function. - * - @start_vcn is invalid. - * EIO - The runlist is corrupt. - * ENOSPC - The destination buffer is too small. + * EINVAL - Run list contains unmapped elements. Make sure to only pass + * fully mapped runlists to this function. + * - @start_vcn is invalid. + * 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; + /* We know rl->length != 0 already. */ + if ( rl->length < 0 || rl->lcn < LCN_HOLE ) + goto err_out; + delta = start_vcn - rl->vcn; + /* Write length. */ + len_len = ntfs_write_significant_bytes( dst + 1, dst_max, + rl->length - delta ); + if ( len_len < 0 ) + goto size_err; + /* + * If the logical cluster number (lcn) denotes a hole and we + * are on NTFS 3.0+, we don't store it at all, i.e. we need + * zero space. On earlier NTFS versions we just write the lcn + * change. FIXME: Do we need to write the lcn change or just + * the lcn in that case? Not sure as I have never seen this + * case on NT4. - We assume that we just need to write the lcn + * change until someone tells us otherwise... (AIA) + */ + if ( rl->lcn >= 0 || vol->major_ver < 3 ) + { + prev_lcn = rl->lcn; + if ( rl->lcn >= 0 ) + prev_lcn += delta; + /* Write change in lcn. */ + lcn_len = ntfs_write_significant_bytes( dst + 1 + + len_len, dst_max, prev_lcn ); + if ( lcn_len < 0 ) + goto size_err; + } + else + lcn_len = 0; + dst_next = dst + len_len + lcn_len + 1; + if ( dst_next > dst_max ) + goto size_err; + /* Update header byte. */ + *dst = lcn_len << 4 | len_len; + /* Position at next mapping pairs array element. */ + dst = dst_next; + /* Go to next runlist element. */ + rl++; + } + /* Do the full runs. */ + for ( ; rl->length; rl++ ) + { + if ( rl->length < 0 || rl->lcn < LCN_HOLE ) + goto err_out; + /* Write length. */ + len_len = ntfs_write_significant_bytes( dst + 1, dst_max, + rl->length ); + if ( len_len < 0 ) + goto size_err; + /* + * If the logical cluster number (lcn) denotes a hole and we + * are on NTFS 3.0+, we don't store it at all, i.e. we need + * zero space. On earlier NTFS versions we just write the lcn + * change. FIXME: Do we need to write the lcn change or just + * the lcn in that case? Not sure as I have never seen this + * case on NT4. - We assume that we just need to write the lcn + * change until someone tells us otherwise... (AIA) + */ + if ( rl->lcn >= 0 || vol->major_ver < 3 ) + { + /* Write change in lcn. */ + lcn_len = ntfs_write_significant_bytes( dst + 1 + + len_len, dst_max, rl->lcn - prev_lcn ); + if ( lcn_len < 0 ) + goto size_err; + prev_lcn = rl->lcn; + } + else + lcn_len = 0; + dst_next = dst + len_len + lcn_len + 1; + if ( dst_next > dst_max ) + goto size_err; + /* Update header byte. */ + *dst = lcn_len << 4 | len_len; + /* Position at next mapping pairs array element. */ + dst += 1 + len_len + lcn_len; + } + /* Set stop vcn. */ + if ( stop_rl ) + *stop_rl = rl; +ok: + /* Add terminator byte. */ + *dst = 0; out: - return ret; + return ret; size_err: - /* Set stop vcn. */ - if (stop_rl) - *stop_rl = rl; - /* Add terminator byte. */ - *dst = 0; + /* Set stop vcn. */ + if ( stop_rl ) + *stop_rl = rl; + /* Add terminator byte. */ + *dst = 0; nospc_err: - errno = ENOSPC; - goto errno_set; + errno = ENOSPC; + goto errno_set; val_err: - errno = EINVAL; - goto errno_set; + errno = EINVAL; + goto errno_set; err_out: - if (rl->lcn == LCN_RL_NOT_MAPPED) - errno = EINVAL; - else - errno = EIO; + if ( rl->lcn == LCN_RL_NOT_MAPPED ) + errno = EINVAL; + else + errno = EIO; errno_set: - ret = -1; - goto out; + ret = -1; + goto out; } /** * ntfs_rl_truncate - truncate a runlist starting at a specified vcn - * @arl: address of runlist to truncate - * @start_vcn: first vcn which should be cut off + * @arl: address of runlist to truncate + * @start_vcn: first vcn which should be cut off * * Truncate the runlist *@arl starting at vcn @start_vcn as well as the memory * buffer holding the runlist. @@ -1630,131 +1717,144 @@ errno_set: * NOTE: @arl is the address of the runlist. We need the address so we can * modify the pointer to the runlist with the new, reallocated memory buffer. */ -int ntfs_rl_truncate(runlist **arl, const VCN start_vcn) +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:" - " arl: %p *arl: %p", arl, *arl); - return -1; - } - - rl = *arl; - - if (start_vcn < rl->vcn) { - errno = EINVAL; - ntfs_log_perror("Start_vcn lies outside front of runlist"); - return -1; - } - - /* Find the starting vcn in the run list. */ - while (rl->length) { - if (start_vcn < rl[1].vcn) - break; - rl++; - } - - if (!rl->length) { - errno = EIO; - ntfs_log_trace("Truncating already truncated runlist?\n"); - return -1; - } - - /* Truncate the run. */ - rl->length = start_vcn - rl->vcn; - - /* - * If a run was partially truncated, make the following runlist - * element a terminator instead of the truncated runlist - * element itself. - */ - if (rl->length) { - ++rl; - if (!rl->length) - is_end = TRUE; - rl->vcn = start_vcn; - rl->length = 0; - } - rl->lcn = (LCN)LCN_ENOENT; - /** - * Reallocate memory if necessary. - * FIXME: Below code is broken, because runlist allocations must be - * a multiply of 4096. The code caused crashes and corruptions. - */ -/* - if (!is_end) { - size_t new_size = (rl - *arl + 1) * sizeof(runlist_element); - rl = realloc(*arl, new_size); - if (rl) - *arl = rl; - } -*/ - return 0; + if ( !arl || !*arl ) + { + errno = EINVAL; + 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; } /** * ntfs_rl_sparse - check whether runlist have sparse regions or not. - * @rl: runlist to check + * @rl: runlist to check * * Return 1 if have, 0 if not, -1 on error with errno set to the error code. */ -int ntfs_rl_sparse(runlist *rl) +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; } /** * ntfs_rl_get_compressed_size - calculate length of non sparse regions - * @vol: ntfs volume (need for cluster size) - * @rl: runlist to calculate for + * @vol: ntfs volume (need for cluster size) + * @rl: runlist to calculate for * * Return compressed size or -1 on error with errno set to the error code. */ -s64 ntfs_rl_get_compressed_size(ntfs_volume *vol, runlist *rl) +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; } @@ -1762,10 +1862,10 @@ s64 ntfs_rl_get_compressed_size(ntfs_volume *vol, runlist *rl) /** * test_rl_helper */ -#define MKRL(R,V,L,S) \ - (R)->vcn = V; \ - (R)->lcn = L; \ - (R)->length = S; +#define MKRL(R,V,L,S) \ + (R)->vcn = V; \ + (R)->lcn = L; \ + (R)->length = S; /* } */ @@ -1777,48 +1877,53 @@ s64 ntfs_rl_get_compressed_size(ntfs_volume *vol, runlist *rl) * * Returns: */ -static void test_rl_dump_runlist(const runlist_element *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" ); } /** @@ -1830,21 +1935,21 @@ static void test_rl_dump_runlist(const runlist_element *rl) * * Returns: */ -static runlist_element * test_rl_runlists_merge(runlist_element *drl, runlist_element *srl) +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; } /** @@ -1857,23 +1962,25 @@ static runlist_element * test_rl_runlists_merge(runlist_element *drl, runlist_el * * Returns: */ -static int test_rl_read_buffer(const char *file, u8 *buf, int bufsize) +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; } /** @@ -1887,31 +1994,34 @@ static int test_rl_read_buffer(const char *file, u8 *buf, int bufsize) * * Returns: */ -static runlist_element * test_rl_pure_src(BOOL contig, BOOL multi, int vcn, int len) +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; } /** @@ -1928,25 +2038,26 @@ static runlist_element * test_rl_pure_src(BOOL contig, BOOL multi, int vcn, int * * Returns: */ -static void test_rl_pure_test(int test, BOOL contig, BOOL multi, int vcn, int len, runlist_element *file, int size) +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 ); } /** @@ -1958,95 +2069,103 @@ static void test_rl_pure_test(int test, BOOL contig, BOOL multi, int vcn, int le * * Returns: */ -static void test_rl_pure(char *contig, char *multi) +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 ) ); } /** @@ -2056,23 +2175,23 @@ static void test_rl_pure(char *contig, char *multi) * * Returns: */ -static void test_rl_zero(void) +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 ); } /** @@ -2086,29 +2205,29 @@ static void test_rl_zero(void) * * Returns: */ -static void test_rl_frag_combine(ntfs_volume *vol, ATTR_RECORD *attr1, ATTR_RECORD *attr2, ATTR_RECORD *attr3) +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 ); } /** @@ -2119,42 +2238,42 @@ static void test_rl_frag_combine(ntfs_volume *vol, ATTR_RECORD *attr1, ATTR_RECO * * Returns: */ -static void test_rl_frag(char *test) +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); + free( attr1 ); + free( attr2 ); + free( attr3 ); } /** @@ -2166,15 +2285,15 @@ out: * * Returns: */ -int test_rl_main(int argc, char *argv[]) +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..697e074f 100644 --- a/source/libntfs/runlist.h +++ b/source/libntfs/runlist.h @@ -34,56 +34,57 @@ typedef runlist_element runlist; /** * struct _runlist_element - in memory vcn to lcn mapping array element. - * @vcn: starting vcn of the current array element - * @lcn: starting lcn of the current array element - * @length: length in clusters of the current array element + * @vcn: starting vcn of the current array element + * @lcn: starting lcn of the current array element + * @length: length in clusters of the current array element * * The last vcn (in fact the last vcn + 1) is reached when length == 0. * * 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 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_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); +extern int ntfs_rl_truncate( runlist **arl, const VCN start_vcn ); -extern int ntfs_rl_sparse(runlist *rl); -extern s64 ntfs_rl_get_compressed_size(ntfs_volume *vol, runlist *rl); +extern int ntfs_rl_sparse( runlist *rl ); +extern s64 ntfs_rl_get_compressed_size( ntfs_volume *vol, runlist *rl ); #ifdef NTFS_TEST -int test_rl_main(int argc, char *argv[]); +int test_rl_main( int argc, char *argv[] ); #endif #endif /* defined _NTFS_RUNLIST_H */ diff --git a/source/libntfs/security.c b/source/libntfs/security.c index ecf3ca07..20113648 100644 --- a/source/libntfs/security.c +++ b/source/libntfs/security.c @@ -65,8 +65,8 @@ #include "misc.h" /* - * JPA NTFS constants or structs - * should be moved to layout.h + * JPA NTFS constants or structs + * should be moved to layout.h */ #define ALIGN_SDS_BLOCK 0x40000 /* Alignment for a $SDS block */ @@ -74,70 +74,74 @@ #define STUFFSZ 0x4000 /* unitary stuffing size for $SDS */ #define FIRST_SECURITY_ID 0x100 /* Lowest security id */ - /* Mask for attributes which can be forced */ -#define FILE_ATTR_SETTABLE ( FILE_ATTR_READONLY \ - | FILE_ATTR_HIDDEN \ - | FILE_ATTR_SYSTEM \ - | FILE_ATTR_ARCHIVE \ - | FILE_ATTR_TEMPORARY \ - | FILE_ATTR_OFFLINE \ - | FILE_ATTR_NOT_CONTENT_INDEXED ) +/* Mask for attributes which can be forced */ +#define FILE_ATTR_SETTABLE ( FILE_ATTR_READONLY \ + | FILE_ATTR_HIDDEN \ + | FILE_ATTR_SYSTEM \ + | FILE_ATTR_ARCHIVE \ + | FILE_ATTR_TEMPORARY \ + | 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 + * 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) + * null SID (S-1-0-0) */ extern const SID *nullsid; @@ -146,26 +150,27 @@ 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 __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 - * @guid: [IN] guid to check + * @guid: [IN] guid to check * * Return TRUE if @guid is a valid pointer to a GUID and it is the zero GUID * and FALSE otherwise. */ -BOOL ntfs_guid_is_zero(const GUID *guid) +BOOL ntfs_guid_is_zero( const GUID *guid ) { - return (memcmp(guid, zero_guid, sizeof(*zero_guid))); + return ( memcmp( guid, zero_guid, sizeof( *zero_guid ) ) ); } /** * ntfs_guid_to_mbs - convert a GUID to a multi byte string - * @guid: [IN] guid to convert - * @guid_str: [OUT] string in which to return the GUID (optional) + * @guid: [IN] guid to convert + * @guid_str: [OUT] string in which to return the GUID (optional) * * Convert the GUID pointed to by @guid to a multi byte string of the form * "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX". Therefore, @guid_str (if not NULL) @@ -178,39 +183,41 @@ BOOL ntfs_guid_is_zero(const GUID *guid) * On success return the converted string and on failure return NULL with errno * set to the error code. */ -char *ntfs_guid_to_mbs(const GUID *guid, char *guid_str) +char *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; } /** * ntfs_sid_to_mbs_size - determine maximum size for the string of a SID - * @sid: [IN] SID for which to determine the maximum string size + * @sid: [IN] SID for which to determine the maximum string size * * Determine the maximum multi byte string size in bytes which is needed to * store the standard textual representation of the SID pointed to by @sid. @@ -219,48 +226,49 @@ char *ntfs_guid_to_mbs(const GUID *guid, char *guid_str) * On success return the maximum number of bytes needed to store the multi byte * string and on failure return -1 with errno set to the error code. */ -int ntfs_sid_to_mbs_size(const SID *sid) +int 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 ); } /** * ntfs_sid_to_mbs - convert a SID to a multi byte string - * @sid: [IN] SID to convert - * @sid_str: [OUT] string in which to return the SID (optional) - * @sid_str_size: [IN] size in bytes of @sid_str + * @sid: [IN] SID to convert + * @sid_str: [OUT] string in which to return the SID (optional) + * @sid_str_size: [IN] size in bytes of @sid_str * * Convert the SID pointed to by @sid to its standard textual representation. * @sid_str (if not NULL) needs to be able to store at least @@ -268,16 +276,16 @@ int ntfs_sid_to_mbs_size(const SID *sid) * @sid_str if @sid_str is not NULL. * * The standard textual representation of the SID is of the form: - * S-R-I-S-S... + * S-R-I-S-S... * Where: * - The first "S" is the literal character 'S' identifying the following - * digits as a SID. + * digits as a SID. * - R is the revision level of the SID expressed as a sequence of digits - * in decimal. + * in decimal. * - I is the 48-bit identifier_authority, expressed as digits in decimal, - * if I < 2^32, or hexadecimal prefixed by "0x", if I >= 2^32. + * if I < 2^32, or hexadecimal prefixed by "0x", if I >= 2^32. * - S... is one or more sub_authority values, expressed as digits in - * decimal. + * decimal. * * If @sid_str is not NULL it will contain the converted SUID on return. If it * is NULL a string will be allocated and this will be returned. The caller is @@ -286,93 +294,99 @@ int ntfs_sid_to_mbs_size(const SID *sid) * On success return the converted string and on failure return NULL with errno * set to the error code. */ -char *ntfs_sid_to_mbs(const SID *sid, char *sid_str, size_t sid_str_size) +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; + /* + * No need to check @sid if !@sid_str since ntfs_sid_to_mbs_size() will + * check @sid, too. 8 is the minimum SID string size. + */ + if ( sid_str && ( sid_str_size < 8 || !ntfs_sid_is_valid( sid ) ) ) + { + errno = EINVAL; + return NULL; + } + /* Allocate string if not provided. */ + if ( !sid_str ) + { + cnt = ntfs_sid_to_mbs_size( sid ); + if ( cnt < 0 ) + return NULL; + s = ( char* )ntfs_malloc( cnt ); + if ( !s ) + return s; + sid_str = s; + /* So we know we allocated it. */ + sid_str_size = 0; + } + else + { + s = sid_str; + cnt = sid_str_size; + } + /* Start with "S-R-". */ + i = snprintf( s, cnt, "S-%hhu-", ( unsigned char )sid->revision ); + if ( i < 0 || i >= cnt ) + goto err_out; + s += i; + cnt -= i; + /* Add the identifier authority. */ + for ( u = i = 0, j = 40; i < 6; i++, j -= 8 ) + u += ( u64 )sid->identifier_authority.value[i] << j; + if ( !sid->identifier_authority.high_part ) + i = snprintf( s, cnt, "%lu", ( unsigned long )u ); + else + i = snprintf( s, cnt, "0x%llx", ( unsigned long long )u ); + if ( i < 0 || i >= cnt ) + goto err_out; + s += i; + cnt -= i; + /* Finally, add the sub authorities. */ + for ( j = 0; j < sid->sub_authority_count; j++ ) + { + leauth = sid->sub_authority[j]; + i = snprintf( s, cnt, "-%u", ( unsigned int ) + le32_to_cpu( leauth ) ); + if ( i < 0 || i >= cnt ) + goto err_out; + s += i; + cnt -= i; + } + return sid_str; err_out: - if (i >= cnt) - i = EMSGSIZE; - else - i = errno; - if (!sid_str_size) - free(sid_str); - errno = i; - return NULL; + if ( i >= cnt ) + i = EMSGSIZE; + else + i = errno; + if ( !sid_str_size ) + free( sid_str ); + errno = i; + return NULL; } /** * ntfs_generate_guid - generatates a random current guid. - * @guid: [OUT] pointer to a GUID struct to hold the generated guid. + * @guid: [OUT] pointer to a GUID struct to hold the generated guid. * * perhaps not a very good random number generator though... */ -void ntfs_generate_guid(GUID *guid) +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; + } } /** @@ -391,834 +405,913 @@ void ntfs_generate_guid(GUID *guid) * * Return the calculated security hash in little endian. */ -le32 ntfs_security_hash(const SECURITY_DESCRIPTOR_RELATIVE *sd, const u32 len) +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 ); } /* - * Internal read - * copied and pasted from ntfs_fuse_read() and made independent - * of fuse context + * Internal read + * copied and pasted from ntfs_fuse_read() and made independent + * 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; + na = ntfs_attr_open( ni, AT_DATA, stream_name, stream_name_len ); + if ( !na ) + { + res = -errno; + goto exit; + } + if ( ( size_t )offset < ( size_t )na->data_size ) + { + if ( offset + size > ( size_t )na->data_size ) + size = na->data_size - offset; + while ( size ) + { + res = ntfs_attr_pread( na, offset, size, buf ); + if ( ( off_t )res < ( off_t )size ) + ntfs_log_perror( "ntfs_attr_pread partial read " + "(%lld : %lld <> %d)", + ( long long )offset, + ( long long )size, res ); + if ( res <= 0 ) + { + res = -errno; + goto exit; + } + size -= res; + offset += res; + total += res; + } + } + res = total; exit: - if (na) - ntfs_attr_close(na); - return res; + if ( na ) + ntfs_attr_close( na ); + return res; } /* - * Internal write - * copied and pasted from ntfs_fuse_write() and made independent - * of fuse context + * 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; + na = ntfs_attr_open( ni, AT_DATA, stream_name, stream_name_len ); + if ( !na ) + { + res = -errno; + goto exit; + } + while ( size ) + { + res = ntfs_attr_pwrite( na, offset, size, buf ); + if ( res < ( s64 )size ) + ntfs_log_perror( "ntfs_attr_pwrite partial write (%lld: " + "%lld <> %d)", ( long long )offset, + ( long long )size, res ); + if ( res <= 0 ) + { + res = -errno; + goto exit; + } + size -= res; + offset += res; + total += res; + } + res = total; exit: - if (na) - ntfs_attr_close(na); - return res; + if ( na ) + ntfs_attr_close( na ); + return res; } /* - * Get the first entry of current index block - * cut and pasted form ntfs_ie_get_first() in index.c + * Get the first entry of current index block + * cut and pasted form ntfs_ie_get_first() in index.c */ -static INDEX_ENTRY *ntfs_ie_get_first(INDEX_HEADER *ih) +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 ) ); } /* - * Stuff a 256KB block into $SDS before writing descriptors - * into the block. + * Stuff a 256KB block into $SDS before writing descriptors + * into the block. * - * This prevents $SDS from being automatically declared as sparse - * when the second copy of the first security descriptor is written - * 256KB further ahead. + * This prevents $SDS from being automatically declared as sparse + * when the second copy of the first security descriptor is written + * 256KB further ahead. * - * Having $SDS declared as a sparse file is not wrong by itself - * and chkdsk leaves it as a sparse file. It does however complain - * and add a sparse flag (0x0200) into field file_attributes of - * STANDARD_INFORMATION of $Secure. This probably means that a - * sparse attribute (ATTR_IS_SPARSE) is only allowed in sparse - * files (FILE_ATTR_SPARSE_FILE). + * Having $SDS declared as a sparse file is not wrong by itself + * and chkdsk leaves it as a sparse file. It does however complain + * and add a sparse flag (0x0200) into field file_attributes of + * STANDARD_INFORMATION of $Secure. This probably means that a + * sparse attribute (ATTR_IS_SPARSE) is only allowed in sparse + * files (FILE_ATTR_SPARSE_FILE). * - * Windows normally does not convert to sparse attribute or sparse - * file. Stuffing is just a way to get to the same result. + * Windows normally does not convert to sparse attribute or sparse + * file. Stuffing is just a way to get to the same result. */ -static int entersecurity_stuff(ntfs_volume *vol, off_t offs) +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 ); } /* - * Enter a new security descriptor into $Secure (data only) + * Enter a new security descriptor into $Secure (data only) * it has to be written twice with an offset of 256KB * - * Should only be called by entersecurityattr() to ensure consistency + * Should only be called by entersecurityattr() to ensure consistency * - * Returns zero if sucessful + * 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 ); } /* - * Enter a new security descriptor in $Secure (indexes only) + * Enter a new security descriptor in $Secure (indexes only) * - * Should only be called by entersecurityattr() to ensure consistency + * Should only be called by entersecurityattr() to ensure consistency * - * Returns zero if sucessful + * 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 ); } /* - * Enter a new security descriptor in $Secure (data and indexes) - * Returns id of entry, or zero if there is a problem. - * (should not be called for NTFS version < 3.0) + * Enter a new security descriptor in $Secure (data and indexes) + * Returns id of entry, or zero if there is a problem. + * (should not be called for NTFS version < 3.0) * - * important : calls have to be serialized, however no locking is - * needed while fuse is not multithreaded + * important : calls have to be serialized, however no locking is + * 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 ); } /* - * Find a matching security descriptor in $Secure, - * if none, allocate a new id and write the descriptor to storage - * Returns id of entry, or zero if there is a problem. + * Find a matching security descriptor in $Secure, + * if none, allocate a new id and write the descriptor to storage + * Returns id of entry, or zero if there is a problem. * - * important : calls have to be serialized, however no locking is - * needed while fuse is not multithreaded + * important : calls have to be serialized, however no locking is + * 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) - * or, when possible, as an entry in $Secure (for NTFS v3.x) + * Update the security descriptor of a file + * Either as an attribute (complying with pre v3.x NTFS version) + * or, when possible, as an entry in $Secure (for NTFS v3.x) * - * returns 0 if success + * 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 ); } /* - * Upgrade the security descriptor of a file - * This is intended to allow graceful upgrades for files which - * were created in previous versions, with a security attributes - * and no security id. - * + * Upgrade the security descriptor of a file + * This is intended to allow graceful upgrades for files which + * were created in previous versions, with a security attributes + * and no security id. + * * It will allocate a security id and replace the individual - * security attribute by a reference to the global one + * security attribute by a reference to the global one * - * Special files are not upgraded (currently / and files in - * directories /$*) + * Special files are not upgraded (currently / and files in + * directories /$*) * - * Though most code is similar to update_secur_desc() it has - * been kept apart to facilitate the further processing of - * special cases or even to remove it if found dangerous. + * Though most code is similar to update_secur_desc() it has + * been kept apart to facilitate the further processing of + * special cases or even to remove it if found dangerous. * - * returns 0 if success, - * 1 if not upgradable. This is not an error. - * -1 if there is a problem + * returns 0 if success, + * 1 if not upgradable. This is not an error. + * -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 ); } /* - * Optional simplified checking of group membership + * Optional simplified checking of group membership * - * This only takes into account the groups defined in - * /etc/group at initialization time. - * It does not take into account the groups dynamically set by - * setgroups() nor the changes in /etc/group since initialization + * This only takes into account the groups defined in + * /etc/group at initialization time. + * It does not take into account the groups dynamically set by + * setgroups() nor the changes in /etc/group since initialization * - * This optional method could be useful if standard checking - * leads to a performance concern. + * This optional method could be useful if standard checking + * leads to a performance concern. * - * Should not be called for user root, however the group may be root + * Should not be called for user root, however the group may be root * */ -static BOOL staticgroupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid) +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 + * Check whether current thread owner is member of file group * - * Should not be called for user root, however the group may be root + * Should not be called for user root, however the group may be root * * As indicated by Miklos Szeredi : * @@ -1236,1721 +1329,1896 @@ static BOOL staticgroupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid * contains the same data. */ -static BOOL groupmember(struct SECURITY_CONTEXT *scx, uid_t uid, gid_t gid) +static 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 ); } /* - * Cacheing is done two-way : - * - from uid, gid and perm to securid (CACHED_SECURID) - * - from a securid to uid, gid and perm (CACHED_PERMISSIONS) + * Cacheing is done two-way : + * - from uid, gid and perm to securid (CACHED_SECURID) + * - from a securid to uid, gid and perm (CACHED_PERMISSIONS) * - * CACHED_SECURID data is kept in a most-recent-first list - * which should not be too long to be efficient. Its optimal - * size is depends on usage and is hard to determine. + * CACHED_SECURID data is kept in a most-recent-first list + * which should not be too long to be efficient. Its optimal + * size is depends on usage and is hard to determine. * - * CACHED_PERMISSIONS data is kept in a two-level indexed array. It - * is optimal at the expense of storage. Use of a most-recent-first - * list would save memory and provide similar performances for - * standard usage, but not for file servers with too many file - * owners + * CACHED_PERMISSIONS data is kept in a two-level indexed array. It + * is optimal at the expense of storage. Use of a most-recent-first + * list would save memory and provide similar performances for + * standard usage, but not for file servers with too many file + * owners * - * CACHED_PERMISSIONS_LEGACY is a special case for CACHED_PERMISSIONS - * for legacy directories which were not allocated a security_id - * it is organized in a most-recent-first list. + * CACHED_PERMISSIONS_LEGACY is a special case for CACHED_PERMISSIONS + * for legacy directories which were not allocated a security_id + * it is organized in a most-recent-first list. * - * In main caches, data is never invalidated, as the meaning of - * a security_id only changes when user mapping is changed, which - * current implies remounting. However returned entries may be - * overwritten at next update, so data has to be copied elsewhere - * before another cache update is made. - * In legacy cache, data has to be invalidated when protection is - * changed. + * In main caches, data is never invalidated, as the meaning of + * a security_id only changes when user mapping is changed, which + * current implies remounting. However returned entries may be + * overwritten at next update, so data has to be copied elsewhere + * before another cache update is made. + * In legacy cache, data has to be invalidated when protection is + * changed. * - * Though the same data may be found in both list, they - * must be kept separately : the interpretation of ACL - * in both direction are approximations which could be non - * reciprocal for some configuration of the user mapping data + * Though the same data may be found in both list, they + * must be kept separately : the interpretation of ACL + * in both direction are approximations which could be non + * reciprocal for some configuration of the user mapping data * - * During the process of recompiling ntfs-3g from a tgz archive, - * security processing added 7.6% to the cpu time used by ntfs-3g - * and 30% if the cache is disabled. + * During the process of recompiling ntfs-3g from a tgz archive, + * security processing added 7.6% to the cpu time used by ntfs-3g + * 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 ); } /* - * Free memory used by caches - * The only purpose is to facilitate the detection of memory leaks + * Free memory used by caches + * The only purpose is to facilitate the detection of memory leaks */ -static void free_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 ); } /* - * Resize permission cache table - * do not call unless resizing is needed - * - * If allocation fails, the cache size is not updated - * Lack of memory is not considered as an error, the cache is left - * consistent and errno is not set. - */ - -static void resize_cache(struct SECURITY_CONTEXT *scx, - u32 securindex) -{ - struct PERMISSIONS_CACHE *oldcache; - struct PERMISSIONS_CACHE *newcache; - int newcnt; - int oldcnt; - unsigned int index1; - unsigned int i; - - 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; - } - } -} - -/* - * Enter uid, gid and mode into cache, if possible + * Resize permission cache table + * do not call unless resizing is needed * - * returns the updated or created cache entry, - * or NULL if not possible (typically if there is no - * security id associated) + * If allocation fails, the cache size is not updated + * Lack of memory is not considered as an error, the cache is left + * consistent and errno is not set. + */ + +static void resize_cache( struct SECURITY_CONTEXT *scx, + u32 securindex ) +{ + struct PERMISSIONS_CACHE *oldcache; + struct PERMISSIONS_CACHE *newcache; + int newcnt; + int oldcnt; + unsigned int index1; + unsigned int i; + + 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; + } + } +} + +/* + * Enter uid, gid and mode into cache, if possible + * + * returns the updated or created cache entry, + * or NULL if not possible (typically if there is no + * security id associated) */ #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) +static struct CACHED_PERMISSIONS *enter_cache( struct SECURITY_CONTEXT *scx, + 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 ); } /* - * Fetch owner, group and permission of a file, if cached + * Fetch owner, group and permission of a file, if cached * - * Beware : do not use the returned entry after a cache update : - * the cache may be relocated making the returned entry meaningless + * Beware : do not use the returned entry after a cache update : + * the cache may be relocated making the returned entry meaningless * - * returns the cache entry, or NULL if not available + * 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 ); } /* - * Retrieve a security attribute from $Secure + * Retrieve a security attribute from $Secure */ -static char *retrievesecurityattr(ntfs_volume *vol, SII_INDEX_KEY id) +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 ); } /* - * Get the security descriptor associated to a file + * Get the security descriptor associated to a file * - * Either : - * - read the security descriptor attribute (v1.x format) - * - or find the descriptor in $Secure:$SDS (v3.x format) + * Either : + * - read the security descriptor attribute (v1.x format) + * - or find the descriptor in $Secure:$SDS (v3.x format) * - * in both case, sanity checks are done on the attribute and - * the descriptor can be assumed safe + * in both case, sanity checks are done on the attribute and + * the descriptor can be assumed safe * - * The returned descriptor is dynamically allocated and has to be freed + * The returned descriptor is dynamically allocated and has to be freed */ -static char *getsecurityattr(ntfs_volume *vol, ntfs_inode *ni) +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 /* - * Determine which access types to a file are allowed - * according to the relation of current process to the file + * Determine which access types to a file are allowed + * according to the relation of current process to the file * - * Do not call if default_permissions is set + * Do not call if default_permissions is set */ -static int access_check_posix(struct SECURITY_CONTEXT *scx, - struct POSIX_SECURITY *pxdesc, mode_t request, - uid_t uid, gid_t gid) +static int access_check_posix( struct SECURITY_CONTEXT *scx, + struct POSIX_SECURITY *pxdesc, mode_t request, + uid_t uid, gid_t gid ) { - struct POSIX_ACE *pxace; - int userperms; - int groupperms; - int mask; - BOOL somegroup; - 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 ); } /* - * Get permissions to access a file - * Takes into account the relation of user to file (owner, group, ...) - * Do no use as mode of the file - * Do no call if default_permissions is set + * Get permissions to access a file + * Takes into account the relation of user to file (owner, group, ...) + * Do no use as mode of the file + * Do no call if default_permissions is set * - * returns -1 if there is a problem + * 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 */ - 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 ); } /* - * Get a Posix ACL + * Get a Posix ACL * - * returns size or -errno if there is a problem - * if size was too small, no copy is done and errno is not set, - * the caller is expected to issue a new call + * returns size or -errno if there is a problem + * if size was too small, no copy is done and errno is not set, + * the caller is expected to issue a new call */ -int ntfs_get_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - const char *name, char *value, size_t size) +int ntfs_get_posix_acl( struct SECURITY_CONTEXT *scx, ntfs_inode *ni, + 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, ...) - * Do no use as mode of the file + * Get permissions to access a file + * Takes into account the relation of user to file (owner, group, ...) + * Do no use as mode of the file * - * returns -1 if there is a problem + * 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 */ /* - * Get an NTFS ACL + * Get an NTFS ACL * - * Returns size or -errno if there is a problem - * if size was too small, no copy is done and errno is not set, - * the caller is expected to issue a new call + * Returns size or -errno if there is a problem + * if size was too small, no copy is done and errno is not set, + * 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 ); } /* - * Get owner, group and permissions in an stat structure - * returns permissions, or -1 if there is a problem + * Get owner, group and permissions in an stat structure + * 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 /* - * Get the base for a Posix inheritance and - * build an inherited Posix descriptor + * Get the base for a Posix inheritance and + * build an inherited Posix descriptor */ -static struct POSIX_SECURITY *inherit_posix(struct SECURITY_CONTEXT *scx, - ntfs_inode *dir_ni, mode_t mode, BOOL isdir) +static struct POSIX_SECURITY *inherit_posix( struct SECURITY_CONTEXT *scx, + 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 ); } /* - * Allocate a security_id for a file being created - * - * Returns zero if not possible (NTFS v3.x required) - */ - -le32 ntfs_alloc_securid(struct SECURITY_CONTEXT *scx, - uid_t uid, gid_t gid, 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; -#endif - - 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 */ - - 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 */ - - 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); -} - -/* - * Apply Posix inheritance to a newly created file - * (for NTFS 1.x only : no securid) - */ - -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) -{ - 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; - } -#if CACHE_LEGACY_SIZE - /* 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); - } -#endif - free(newattr); - - } 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) -{ -#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; -#endif - - securid = const_cpu_to_le32(0); - -#if !FORCE_FORMAT_v1x - /* 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; - - /* 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() - */ - } - } -#endif - return (securid); -} - -#endif - -/* - * Update ownership and mode of a file, reusing an existing - * security descriptor when possible - * - * Returns zero if successful - */ - -#if POSIXACLS -int ntfs_set_owner_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - uid_t uid, gid_t gid, mode_t mode, - struct POSIX_SECURITY *pxdesc) -#else -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; - - res = 0; - - /* 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; -#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; -#else - 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 (!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); -#else - 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 CACHE_LEGACY_SIZE - /* also invalidate legacy cache */ - if (isdir && !ni->security_id) { - struct CACHED_PERMISSIONS_LEGACY legacy; - - legacy.mft_no = ni->mft_no; -#if POSIXACLS - legacy.variable = wanted.variable; - legacy.varsize = wanted.varsize; -#else - legacy.variable = (void*)NULL; - legacy.varsize = 0; -#endif - 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); -} - -/* - * Check whether user has ownership rights on a file + * Allocate a security_id for a file being created * - * Returns TRUE if allowed - * if not, errno tells why + * Returns zero if not possible (NTFS v3.x required) */ -BOOL ntfs_allowed_as_owner(struct SECURITY_CONTEXT *scx, ntfs_inode *ni) +le32 ntfs_alloc_securid( struct SECURITY_CONTEXT *scx, + uid_t uid, gid_t gid, ntfs_inode *dir_ni, + mode_t mode, BOOL isdir ) { - 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) { -#if OWNERFROMACL - usid = ntfs_acl_owner(oldattr); -#else - const SECURITY_DESCRIPTOR_RELATIVE *phead; - - phead = (const SECURITY_DESCRIPTOR_RELATIVE*) - oldattr; - usid = (const SID*)&oldattr - [le32_to_cpu(phead->owner)]; +#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; #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); + + 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 */ + + 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 */ + + 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 ); +} + +/* + * Apply Posix inheritance to a newly created file + * (for NTFS 1.x only : no securid) + */ + +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 ) +{ + 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; + } +#if CACHE_LEGACY_SIZE + /* 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 ); + } +#endif + free( newattr ); + + } + 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 ) +{ +#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; +#endif + + securid = const_cpu_to_le32( 0 ); + +#if !FORCE_FORMAT_v1x + /* 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; + + /* 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() + */ + } + } +#endif + return ( securid ); +} + +#endif + +/* + * Update ownership and mode of a file, reusing an existing + * security descriptor when possible + * + * Returns zero if successful + */ + +#if POSIXACLS +int ntfs_set_owner_mode( struct SECURITY_CONTEXT *scx, ntfs_inode *ni, + uid_t uid, gid_t gid, mode_t mode, + struct POSIX_SECURITY *pxdesc ) +#else +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; + + res = 0; + + /* 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; +#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; +#else + 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 ( !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 ); +#else + 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 CACHE_LEGACY_SIZE + /* also invalidate legacy cache */ + if ( isdir && !ni->security_id ) + { + struct CACHED_PERMISSIONS_LEGACY legacy; + + legacy.mft_no = ni->mft_no; +#if POSIXACLS + legacy.variable = wanted.variable; + legacy.varsize = wanted.varsize; +#else + legacy.variable = ( void* )NULL; + legacy.varsize = 0; +#endif + 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 ); +} + +/* + * Check whether user has ownership rights on a file + * + * Returns TRUE if allowed + * if not, errno tells why + */ + +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; + + 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 ); +#else + const SECURITY_DESCRIPTOR_RELATIVE *phead; + + 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 ); } #ifdef HAVE_SETXATTR /* extended attributes interface required */ @@ -2958,1089 +3226,1195 @@ BOOL ntfs_allowed_as_owner(struct SECURITY_CONTEXT *scx, ntfs_inode *ni) #if POSIXACLS /* - * Set a new access or default Posix ACL to a file - * (or remove ACL if no input data) - * Validity of input data is checked after merging + * Set a new access or default Posix ACL to a file + * (or remove ACL if no input data) + * Validity of input data is checked after merging * - * Returns 0, or -1 if there is a problem which errno describes + * Returns 0, or -1 if there is a problem which errno describes */ -int ntfs_set_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - const char *name, const char *value, size_t size, - int flags) +int ntfs_set_posix_acl( struct SECURITY_CONTEXT *scx, ntfs_inode *ni, + 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 ); } /* - * Remove a default Posix ACL from a file + * Remove a default Posix ACL from a file * - * Returns 0, or -1 if there is a problem which errno describes + * Returns 0, or -1 if there is a problem which errno describes */ -int ntfs_remove_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - const char *name) +int ntfs_remove_posix_acl( struct SECURITY_CONTEXT *scx, ntfs_inode *ni, + 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 /* - * Set a new NTFS ACL to a file + * Set a new NTFS ACL to a file * - * Returns 0, or -1 if there is a problem + * Returns 0, or -1 if there is a problem */ -int ntfs_set_ntfs_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - const char *value, size_t size, int flags) +int ntfs_set_ntfs_acl( struct SECURITY_CONTEXT *scx, ntfs_inode *ni, + 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 */ /* - * Set new permissions to a file - * Checks user mapping has been defined before request for setting + * Set new permissions to a file + * Checks user mapping has been defined before request for setting * - * rejected if request is not originated by owner or root + * rejected if request is not originated by owner or root * - * returns 0 on success - * -1 on failure, with errno = EIO + * returns 0 on success + * -1 on failure, with errno = EIO */ -int ntfs_set_mode(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, mode_t mode) +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 ); } /* - * Create a default security descriptor for files whose descriptor - * cannot be inherited + * Create a default security descriptor for files whose descriptor + * cannot be inherited */ -int ntfs_sd_add_everyone(ntfs_inode *ni) +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; } /* - * Check whether user can access a file in a specific way + * Check whether user can access a file in a specific way * - * Returns 1 if access is allowed, including user is root or no - * user mapping defined - * 2 if sticky and accesstype is S_IWRITE + S_IEXEC + S_ISVTX - * 0 and sets errno if there is a problem or if access - * is not allowed + * Returns 1 if access is allowed, including user is root or no + * user mapping defined + * 2 if sticky and accesstype is S_IWRITE + S_IEXEC + S_ISVTX + * 0 and sets errno if there is a problem or if access + * is not allowed * - * This is used for Posix ACL and checking creation of DOS file names + * 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 */ /* - * Check whether user can access the parent directory - * of a file in a specific way + * Check whether user can access the parent directory + * of a file in a specific way * - * Returns true if access is allowed, including user is root and - * no user mapping defined - * - * Sets errno if there is a problem or if not allowed + * Returns true if access is allowed, including user is root and + * no user mapping defined * - * This is used for Posix ACL and checking creation of DOS file names + * Sets errno if there is a problem or if not allowed + * + * This is used for Posix ACL and checking creation of DOS file names */ -BOOL old_ntfs_allowed_dir_access(struct SECURITY_CONTEXT *scx, - const char *path, int accesstype) +BOOL old_ntfs_allowed_dir_access( struct SECURITY_CONTEXT *scx, + const char *path, int accesstype ) { - int allow; - char *dirpath; - char *name; - ntfs_inode *ni; - ntfs_inode *dir_ni; - struct stat stbuf; + 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 /* - * Define a new owner/group to a file + * Define a new owner/group to a file * - * returns zero if successful + * 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 ); } /* - * Define new owner/group and mode to a file + * Define new owner/group and mode to a file * - * returns zero if successful + * 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 ); } /* - * Build a security id for a descriptor inherited from - * parent directory the Windows way + * Build a security id for a descriptor inherited from + * 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 ); } /* - * Get an inherited security id + * Get an inherited security id * - * For Windows compatibility, the normal initial permission setting - * may be inherited from the parent directory instead of being - * defined by the creation arguments. + * For Windows compatibility, the normal initial permission setting + * may be inherited from the parent directory instead of being + * defined by the creation arguments. * - * The following creates an inherited id for that purpose. + * The following creates an inherited id for that purpose. * - * Note : the owner and group of parent directory are also - * inherited (which is not the case on Windows) if no user mapping - * is defined. + * Note : the owner and group of parent directory are also + * inherited (which is not the case on Windows) if no user mapping + * is defined. * - * Returns the inherited id, or zero if not possible (eg on NTFS 1.x) + * 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 ); } /* - * Link a group to a member of group + * Link a group to a member of group * - * Returns 0 if OK, -1 (and errno set) if error + * 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 - * the groups dynamically set by setgroups() nor any changes in - * /etc/group into account + * Statically link group to users + * This is based on groups defined in /etc/group and does not take + * the groups dynamically set by setgroups() nor any changes in + * /etc/group into account * - * Only mapped groups and root group are linked to mapped users + * Only mapped groups and root group are linked to mapped users * - * Returns 0 if OK, -1 (and errno set) if error + * Returns 0 if OK, -1 (and errno set) if error * */ -static int link_group_members(struct SECURITY_CONTEXT *scx) +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 ); } /* - * Apply default single user mapping - * returns zero if successful + * Apply default single user mapping + * 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 ); } /* - * Make sure there are no ambiguous mapping - * Ambiguous mapping may lead to undesired configurations and - * we had rather be safe until the consequences are understood + * Make sure there are no ambiguous mapping + * Ambiguous mapping may lead to undesired configurations and + * we had rather be safe until the consequences are understood */ #if 0 /* not activated for now */ -static BOOL check_mapping(const struct MAPPING *usermapping, - const struct MAPPING *groupmapping) +static BOOL check_mapping( const struct MAPPING *usermapping, + const struct MAPPING *groupmapping ) { - const struct MAPPING *mapping1; - const struct MAPPING *mapping2; - BOOL ambiguous; + const struct MAPPING *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 @@ -4048,612 +4422,687 @@ static BOOL check_mapping(const struct MAPPING *usermapping, #if 0 /* not used any more */ /* - * Try and apply default single user mapping - * returns zero if successful + * Try and apply default single user mapping + * returns zero if successful */ -static int ntfs_default_mapping(struct SECURITY_CONTEXT *scx) +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 /* - * Basic read from a user mapping file on another volume + * Basic read from a user mapping file on another volume */ -static int basicread(void *fileid, char *buf, size_t size, off_t offs __attribute__((unused))) +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 + * Read from a user mapping file on current NTFS partition */ -static int localread(void *fileid, char *buf, size_t size, off_t offs) +static int localread( void *fileid, char *buf, size_t size, off_t offs ) { - return (ntfs_local_read((ntfs_inode*)fileid, - AT_UNNAMED, 0, buf, size, offs)); + return ( ntfs_local_read( ( ntfs_inode* )fileid, + AT_UNNAMED, 0, buf, size, offs ) ); } /* - * Build the user mapping - * - according to a mapping file if defined (or default present), - * - or try default single user mapping if possible + * Build the user mapping + * - according to a mapping file if defined (or default present), + * - or try default single user mapping if possible * - * The mapping is specific to a mounted device - * No locking done, mounting assumed non multithreaded + * The mapping is specific to a mounted device + * No locking done, mounting assumed non multithreaded * - * returns zero if mapping is successful - * (failure should not be interpreted as an error) + * returns zero if mapping is successful + * (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 */ /* - * Get the ntfs attribute into an extended attribute - * The attribute is returned according to cpu endianness + * Get the ntfs attribute into an extended attribute + * The attribute is returned according to cpu endianness */ -int ntfs_get_ntfs_attrib(ntfs_inode *ni, char *value, size_t size) +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 ); } /* - * Return the ntfs attribute into an extended attribute - * The attribute is expected according to cpu endianness + * Return the ntfs attribute into an extended attribute + * The attribute is expected according to cpu endianness * - * Returns 0, or -1 if there is a problem + * Returns 0, or -1 if there is a problem */ -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 ) { - 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 */ /* - * Open $Secure once for all - * returns zero if it succeeds - * non-zero if it fails. This is not an error (on NTFS v1.x) + * Open $Secure once for all + * returns zero if it succeeds + * non-zero if it fails. This is not an error (on NTFS v1.x) */ -int ntfs_open_secure(ntfs_volume *vol) +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 ); } /* - * Final cleaning - * Allocated memory is freed to facilitate the detection of memory leaks + * Final cleaning + * Allocated memory is freed to facilitate the detection of memory leaks */ -void ntfs_close_secure(struct SECURITY_CONTEXT *scx) +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 ); } /* - * API for direct access to security descriptors - * based on Win32 API + * API for direct access to security descriptors + * based on Win32 API */ /* - * Selective feeding of a security descriptor into user buffer + * Selective feeding of a security descriptor into user buffer * - * Returns TRUE if successful + * 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 ); } /* - * Merge a new security descriptor into the old one - * and assign to designated file + * Merge a new security descriptor into the old one + * and assign to designated file * - * Returns TRUE if successful + * 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 ); } /* - * Return the security descriptor of a file - * This is intended to be similar to GetFileSecurity() from Win32 - * in order to facilitate the development of portable tools + * Return the security descriptor of a file + * This is intended to be similar to GetFileSecurity() from Win32 + * in order to facilitate the development of portable tools * - * returns zero if unsuccessful (following Win32 conventions) - * -1 if no securid - * the securid if any + * returns zero if unsuccessful (following Win32 conventions) + * -1 if no securid + * the securid if any * * The Win32 API is : * @@ -4667,49 +5116,55 @@ 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 - * in order to facilitate the development of portable tools + * Set the security descriptor of a file or directory + * This is intended to be similar to SetFileSecurity() from Win32 + * in order to facilitate the development of portable tools * - * returns zero if unsuccessful (following Win32 conventions) - * -1 if no securid - * the securid if any + * returns zero if unsuccessful (following Win32 conventions) + * -1 if no securid + * the securid if any * * The Win32 API is : * @@ -4720,65 +5175,72 @@ 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 - * in order to facilitate the development of portable tools + * Return the attributes of a file + * This is intended to be similar to GetFileAttributes() from Win32 + * in order to facilitate the development of portable tools * - * returns -1 if unsuccessful (Win32 : INVALID_FILE_ATTRIBUTES) + * returns -1 if unsuccessful (Win32 : INVALID_FILE_ATTRIBUTES) * * The Win32 API is : * @@ -4787,41 +5249,45 @@ int ntfs_set_file_security(struct SECURITY_API *scapi, * ); */ -int ntfs_get_file_attributes(struct SECURITY_API *scapi, const char *path) +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 - * in order to facilitate the development of portable tools + * Set attributes to a file or directory + * This is intended to be similar to SetFileAttributes() from Win32 + * in order to facilitate the development of portable tools * - * Only a few flags can be set (same list as Win32) + * Only a few flags can be set (same list as Win32) * - * returns zero if unsuccessful (following Win32 conventions) - * nonzero if successful + * returns zero if unsuccessful (following Win32 conventions) + * nonzero if successful * * The Win32 API is : * @@ -4831,352 +5297,401 @@ 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 ); } /* - * read $SDS (for auditing security data) + * read $SDS (for auditing security data) * - * Returns the number or read bytes, or -1 if there is an error + * 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 ); } /* - * read $SII (for auditing security data) + * read $SII (for auditing security data) * - * Returns next entry, or NULL if there is an error + * 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 ); } /* - * read $SDH (for auditing security data) + * read $SDH (for auditing security data) * - * Returns next entry, or NULL if there is an error + * 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 ); } /* - * Get the mapped user SID - * A buffer of 40 bytes has to be supplied + * Get the mapped user SID + * A buffer of 40 bytes has to be supplied * - * returns the size of the SID, or zero and errno set if not found + * returns the size of the SID, or zero and errno set if not found */ -int ntfs_get_usid(struct SECURITY_API *scapi, uid_t uid, char *buf) +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 ); } /* - * Get the mapped group SID - * A buffer of 40 bytes has to be supplied + * Get the mapped group SID + * A buffer of 40 bytes has to be supplied * - * returns the size of the SID, or zero and errno set if not found + * returns the size of the SID, or zero and errno set if not found */ -int ntfs_get_gsid(struct SECURITY_API *scapi, gid_t gid, char *buf) +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 ); } /* - * Get the user mapped to a SID + * Get the user mapped to a SID * - * returns the uid, or -1 if not found + * returns the uid, or -1 if not found */ -int ntfs_get_user(struct SECURITY_API *scapi, const SID *usid) +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 ); } /* - * Get the group mapped to a SID + * Get the group mapped to a SID * - * returns the uid, or -1 if not found + * returns the uid, or -1 if not found */ -int ntfs_get_group(struct SECURITY_API *scapi, const SID *gsid) +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 ); } /* - * Initializations before calling ntfs_get_file_security() - * ntfs_set_file_security() and ntfs_read_directory() + * Initializations before calling ntfs_get_file_security() + * ntfs_set_file_security() and ntfs_read_directory() * - * Only allowed for root + * Only allowed for root * - * Returns an (obscured) struct SECURITY_API* needed for further calls - * NULL if not root (EPERM) or device is mounted (EBUSY) + * Returns an (obscured) struct SECURITY_API* needed for further calls + * 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 ); } /* - * Leaving after ntfs_initialize_file_security() + * Leaving after ntfs_initialize_file_security() * - * Returns FALSE if FAILED + * Returns FALSE if FAILED */ -BOOL ntfs_leave_file_security(struct SECURITY_API *scapi) +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..b4098d96 100644 --- a/source/libntfs/security.h +++ b/source/libntfs/security.h @@ -1,5 +1,5 @@ /* - * security.h - Exports for handling security/ACLs in NTFS. + * security.h - Exports for handling security/ACLs in NTFS. * Originated from the Linux-NTFS project. * * Copyright (c) 2004 Anton Altaparmakov @@ -40,7 +40,7 @@ typedef u32 be32; #if __BYTE_ORDER == __LITTLE_ENDIAN #define const_cpu_to_be16(x) ((((x) & 255L) << 8) + (((x) >> 8) & 255L)) #define const_cpu_to_be32(x) ((((x) & 255L) << 24) + (((x) & 0xff00L) << 8) \ - + (((x) >> 8) & 0xff00L) + (((x) >> 24) & 255L)) + + (((x) >> 8) & 0xff00L) + (((x) >> 24) & 255L)) #else #define const_cpu_to_be16(x) (x) #define const_cpu_to_be32(x) (x) @@ -50,270 +50,284 @@ 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 */ }; /* - * Entry in the permissions cache - * Note : this cache is not organized as a generic cache + * Entry in the permissions cache + * 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 + * 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 + * 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) + * 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 + * 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 + * 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 + * Security context, needed by most security functions */ 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 + * 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_ACE +{ + u16 tag; + u16 perms; + s32 id; } ; -struct POSIX_SECURITY { - mode_t mode; - int acccnt; - int defcnt; - int firstdef; - u16 tagsset; - struct POSIX_ACL acl; +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 + * 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 + * 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 #endif -extern BOOL ntfs_guid_is_zero(const GUID *guid); -extern char *ntfs_guid_to_mbs(const GUID *guid, char *guid_str); +extern BOOL ntfs_guid_is_zero( const GUID *guid ); +extern char *ntfs_guid_to_mbs( const GUID *guid, char *guid_str ); /** * ntfs_sid_is_valid - determine if a SID is valid - * @sid: SID for which to determine if it is valid + * @sid: SID for which to determine if it is valid * * Determine if the SID pointed to by @sid is valid. * * Return TRUE if it is valid and FALSE otherwise. */ -static __inline__ BOOL ntfs_sid_is_valid(const SID *sid) +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 void ntfs_generate_guid(GUID *guid); -extern int ntfs_sd_add_everyone(ntfs_inode *ni); +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 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_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_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 ); #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); +le32 ntfs_alloc_securid( struct SECURITY_CONTEXT *scx, + 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); +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 ); #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); -int ntfs_open_secure(ntfs_volume *vol); -void ntfs_close_secure(struct SECURITY_CONTEXT *scx); +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); -int ntfs_get_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - 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); -int ntfs_remove_posix_acl(struct SECURITY_CONTEXT *scx, ntfs_inode *ni, - const char *name); +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 ); +int ntfs_get_posix_acl( struct SECURITY_CONTEXT *scx, ntfs_inode *ni, + 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 ); +int ntfs_remove_posix_acl( struct SECURITY_CONTEXT *scx, ntfs_inode *ni, + 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_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); - /* - * Security API for direct access to security descriptors - * based on Win32 API + * Security API for direct access to security descriptors + * based on Win32 API */ #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; } ; /* @@ -322,36 +336,36 @@ 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); -BOOL ntfs_leave_file_security(struct SECURITY_API *scx); +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); -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 ntfs_get_group(struct SECURITY_API *scapi, const SID *gsid); +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 ); +int ntfs_get_user( struct SECURITY_API *scapi, const SID *usid ); +int ntfs_get_group( struct SECURITY_API *scapi, const SID *gsid ); #endif /* defined _NTFS_SECURITY_H */ diff --git a/source/libntfs/support.h b/source/libntfs/support.h index 6af4761e..11bdd8c0 100644 --- a/source/libntfs/support.h +++ b/source/libntfs/support.h @@ -33,24 +33,24 @@ /* * Our mailing list. Use this define to prevent typos in email address. */ -#define NTFS_DEV_LIST "ntfs-3g-devel@lists.sf.net" +#define NTFS_DEV_LIST "ntfs-3g-devel@lists.sf.net" /* * Generic macro to convert pointers to values for comparison purposes. */ #ifndef p2n -#define p2n(p) ((ptrdiff_t)((ptrdiff_t*)(p))) +#define p2n(p) ((ptrdiff_t)((ptrdiff_t*)(p))) #endif /* * The classic min and max macros. */ #ifndef min -#define min(a,b) ((a) <= (b) ? (a) : (b)) +#define min(a,b) ((a) <= (b) ? (a) : (b)) #endif #ifndef max -#define max(a,b) ((a) >= (b) ? (a) : (b)) +#define max(a,b) ((a) >= (b) ? (a) : (b)) #endif /* @@ -63,22 +63,22 @@ /* * Simple bit operation macros. NOTE: These are NOT atomic. */ -#define test_bit(bit, var) ((var) & (1 << (bit))) -#define set_bit(bit, var) (var) |= 1 << (bit) -#define clear_bit(bit, var) (var) &= ~(1 << (bit)) +#define test_bit(bit, var) ((var) & (1 << (bit))) +#define set_bit(bit, var) (var) |= 1 << (bit) +#define clear_bit(bit, var) (var) &= ~(1 << (bit)) -#define test_and_set_bit(bit, var) \ -({ \ - const BOOL old_state = test_bit(bit, var); \ - set_bit(bit, var); \ - old_state; \ +#define test_and_set_bit(bit, var) \ +({ \ + const BOOL old_state = test_bit(bit, var); \ + set_bit(bit, var); \ + old_state; \ }) -#define test_and_clear_bit(bit, var) \ -({ \ - const BOOL old_state = test_bit(bit, var); \ - clear_bit(bit, var); \ - old_state; \ +#define test_and_clear_bit(bit, var) \ +({ \ + const BOOL old_state = test_bit(bit, var); \ + clear_bit(bit, var); \ + old_state; \ }) #endif /* defined _NTFS_SUPPORT_H */ diff --git a/source/libntfs/types.h b/source/libntfs/types.h index 3fafe8a7..66b77025 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,16 +119,17 @@ 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) -#define STATUS_ERROR (-1) -#define STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT (-2) -#define STATUS_KEEP_SEARCHING (-3) -#define STATUS_NOT_FOUND (-4) +#define STATUS_OK (0) +#define STATUS_ERROR (-1) +#define STATUS_RESIDENT_ATTRIBUTE_FILLED_MFT (-2) +#define STATUS_KEEP_SEARCHING (-3) +#define STATUS_NOT_FOUND (-4) #endif /* defined _NTFS_TYPES_H */ diff --git a/source/libntfs/unistr.c b/source/libntfs/unistr.c index cc3a1b8d..6ea0392f 100644 --- a/source/libntfs/unistr.c +++ b/source/libntfs/unistr.c @@ -88,153 +88,167 @@ 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 /** * ntfs_names_are_equal - compare two Unicode names for equality - * @s1: name to compare to @s2 - * @s1_len: length in Unicode characters of @s1 - * @s2: name to compare to @s1 - * @s2_len: length in Unicode characters of @s2 - * @ic: ignore case bool - * @upcase: upcase table (only if @ic == IGNORE_CASE) - * @upcase_size: length in Unicode characters of @upcase (if present) + * @s1: name to compare to @s2 + * @s1_len: length in Unicode characters of @s1 + * @s2: name to compare to @s1 + * @s2_len: length in Unicode characters of @s2 + * @ic: ignore case bool + * @upcase: upcase table (only if @ic == IGNORE_CASE) + * @upcase_size: length in Unicode characters of @upcase (if present) * * Compare the names @s1 and @s2 and return TRUE (1) if the names are * 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; } /* * ntfs_names_full_collate() fully collate two Unicode names * - * @name1: first Unicode name to compare - * @name1_len: length of first Unicode name to compare - * @name2: second Unicode name to compare - * @name2_len: length of second Unicode name to compare - * @ic: either CASE_SENSITIVE or IGNORE_CASE - * @upcase: upcase table (ignored if @ic is CASE_SENSITIVE) - * @upcase_len: upcase table size (ignored if @ic is CASE_SENSITIVE) + * @name1: first Unicode name to compare + * @name1_len: length of first Unicode name to compare + * @name2: second Unicode name to compare + * @name2_len: length of second Unicode name to compare + * @ic: either CASE_SENSITIVE or IGNORE_CASE + * @upcase: upcase table (ignored if @ic is CASE_SENSITIVE) + * @upcase_len: upcase table size (ignored if @ic is CASE_SENSITIVE) * * -1 if the first name collates before the second one, * 0 if the names match, * 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; } /** * ntfs_ucsncmp - compare two little endian Unicode strings - * @s1: first string - * @s2: second string - * @n: maximum unicode characters to compare + * @s1: first string + * @s2: second string + * @n: maximum unicode characters to compare * * Compare the first @n characters of the Unicode strings @s1 and @s2, * The strings in little endian format and appropriate le16_to_cpu() @@ -244,37 +258,39 @@ int ntfs_names_full_collate(const ntfschar *name1, const u32 name1_len, * if @s1 (or the first @n Unicode characters thereof) is found, respectively, * to be less than, to match, or be greater than @s2. */ -int ntfs_ucsncmp(const ntfschar *s1, const ntfschar *s2, size_t n) +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; } /** * ntfs_ucsncasecmp - compare two little endian Unicode strings, ignoring case - * @s1: first string - * @s2: second string - * @n: maximum unicode characters to compare - * @upcase: upcase table - * @upcase_size: upcase table size in Unicode characters + * @s1: first string + * @s2: second string + * @n: maximum unicode characters to compare + * @upcase: upcase table + * @upcase_size: upcase table size in Unicode characters * * Compare the first @n characters of the Unicode strings @s1 and @s2, * ignoring case. The strings in little endian format and appropriate @@ -286,37 +302,39 @@ 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; } /** * ntfs_ucsnlen - determine the length of a little endian Unicode string - * @s: pointer to Unicode string - * @maxlen: maximum length of string @s + * @s: pointer to Unicode string + * @maxlen: maximum length of string @s * * Return the number of Unicode characters in the little endian Unicode * string @s up to a maximum of maxlen Unicode characters, not including @@ -325,21 +343,22 @@ int ntfs_ucsncasecmp(const ntfschar *s1, const ntfschar *s2, size_t n, * * This function never looks beyond @s + @maxlen. */ -u32 ntfs_ucsnlen(const ntfschar *s, u32 maxlen) +u32 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; } /** * ntfs_ucsndup - duplicate little endian Unicode string - * @s: pointer to Unicode string - * @maxlen: maximum length of string @s + * @s: pointer to Unicode string + * @maxlen: maximum length of string @s * * Return a pointer to a new little endian Unicode string which is a duplicate * of the string s. Memory for the new string is obtained with ntfs_malloc(3), @@ -353,18 +372,19 @@ u32 ntfs_ucsnlen(const ntfschar *s, u32 maxlen) * Return a pointer to the new little endian Unicode string on success and NULL * on failure with errno set to the error code. */ -ntfschar *ntfs_ucsndup(const ntfschar *s, u32 maxlen) +ntfschar *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 +398,30 @@ 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,11 +434,11 @@ 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 ); } /* @@ -434,379 +454,430 @@ void ntfs_file_value_upcase(FILE_NAME_ATTR *file_name_attr, so this patch fixes the resulting issues for systems which use UTF-8 and for others, specifying the locale in fstab brings them the encoding which they want. - + If no locale is defined or there was a problem with setting one up and whenever nl_langinfo(CODESET) returns a sting starting with "ANSI", use an internal UCS-2LE <-> UTF-8 codeset converter to fix the bug where NTFS-3G does not show any path names which include international characters!!! (and also fails on creating them) as result. - + Author: Bernhard Kaindl Jean-Pierre Andre made it compliant with RFC3629/RFC2781. */ - -/* + +/* * Return the amount of 8-bit elements in UTF-8 needed (without the terminating * null) to store a given UTF-16LE string. * * Return -1 with errno set if string has invalid byte sequence or too long. */ -static int utf16_to_utf8_size(const ntfschar *ins, const int ins_len, int outs_len) +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; + ret = count; out: - return ret; + return ret; fail: - errno = EILSEQ; - goto out; + errno = EILSEQ; + goto out; } /* * ntfs_utf16_to_utf8 - convert a little endian UTF16LE string to an UTF-8 string - * @ins: input utf16 string buffer - * @ins_len: length of input string in utf16 characters - * @outs: on return contains the (allocated) output multibyte string - * @outs_len: length of output buffer in bytes + * @ins: input utf16 string buffer + * @ins_len: length of input string in utf16 characters + * @outs: on return contains the (allocated) output multibyte string + * @outs_len: length of output buffer in bytes * * 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; + + ret = t - *outs; out: - return ret; + return ret; fail: - errno = EILSEQ; - goto out; + errno = EILSEQ; + goto out; } -/* - * Return the amount of 16-bit elements in UTF-16LE needed +/* + * Return the amount of 16-bit elements in UTF-16LE needed * (without the terminating null) to store given UTF-8 string. * * Return -1 with errno set if it's longer than PATH_MAX or string is invalid. * * Note: This does not check whether the input sequence is a valid utf8 string, - * and should be used only in context where such check is made! + * and should be used only in context where such check is made! */ -static int utf8_to_utf16_size(const char *s) +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; + 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; + return ret; fail: - errno = ENAMETOOLONG; - goto out; + errno = ENAMETOOLONG; + goto out; } -/* +/* * This converts one UTF-8 sequence to cpu-endian Unicode value * within range U+0 .. U+10ffff and excluding U+D800 .. U+DFFF * - * Return the number of used utf8 bytes or -1 with errno set + * Return the number of used utf8 bytes or -1 with errno set * if sequence is invalid. */ -static int utf8_to_unicode(u32 *wc, const char *s) +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; - } + } + 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; + errno = EILSEQ; + return -1; } /** * ntfs_utf8_to_utf16 - convert a UTF-8 string to a UTF-16LE string - * @ins: input multibyte string buffer - * @outs: on return contains the (allocated) output utf16 string - * @outs_len: length of output buffer in utf16 characters - * + * @ins: input multibyte string buffer + * @outs: on return contains the (allocated) output utf16 string + * @outs_len: length of output buffer in utf16 characters + * * Return -1 with errno set. */ -static int ntfs_utf8_to_utf16(const char *ins, ntfschar **outs) +static int ntfs_utf8_to_utf16( const char *ins, ntfschar **outs ) { #if defined(__APPLE__) || defined(__DARWIN__) #ifdef ENABLE_NFCONV - char *new_ins = NULL; - if(nfconvert_utf8) { - int new_ins_len; - new_ins_len = ntfs_macosx_normalize_utf8(ins, &new_ins, 1); // Normalize to composed form - if(new_ins_len >= 0) - ins = new_ins; - else - ntfs_log_error("Failed to normalize NTFS string to UTF-8 NFC: %s\n", ins); - } + char *new_ins = NULL; + if ( nfconvert_utf8 ) + { + int new_ins_len; + new_ins_len = ntfs_macosx_normalize_utf8( ins, &new_ins, 1 ); // Normalize to composed form + if ( new_ins_len >= 0 ) + ins = new_ins; + else + ntfs_log_error( "Failed to normalize NTFS string to UTF-8 NFC: %s\n", ins ); + } #endif /* ENABLE_NFCONV */ #endif /* defined(__APPLE__) || defined(__DARWIN__) */ - const char *t = ins; - u32 wc; - 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; + 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; } /** * ntfs_ucstombs - convert a little endian Unicode string to a multibyte string - * @ins: input Unicode string buffer - * @ins_len: length of input string in Unicode characters - * @outs: on return contains the (allocated) output multibyte string - * @outs_len: length of output buffer in bytes + * @ins: input Unicode string buffer + * @ins_len: length of input string in Unicode characters + * @outs: on return contains the (allocated) output multibyte string + * @outs_len: length of output buffer in bytes * * Convert the input little endian, 2-byte Unicode string @ins, of length * @ins_len into the multibyte string format dictated by the current locale. @@ -820,112 +891,121 @@ fail: * * On error, -1 is returned, and errno is set to the error code. The following * error codes can be expected: - * EINVAL Invalid arguments (e.g. @ins or @outs is NULL). - * EILSEQ The input string cannot be represented as a multibyte - * sequence according to the current locale. - * ENAMETOOLONG Destination buffer is too small for input string. - * ENOMEM Not enough memory to allocate destination buffer. + * EINVAL Invalid arguments (e.g. @ins or @outs is NULL). + * EILSEQ The input string cannot be represented as a multibyte + * sequence according to the current locale. + * 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; + /* Now write the NULL character. */ + mbs[o] = '\0'; + if ( *outs != mbs ) + *outs = mbs; + return o; err_out: - if (mbs != *outs) { - int eo = errno; - free(mbs); - errno = eo; - } - return -1; + if ( mbs != *outs ) + { + int eo = errno; + free( mbs ); + errno = eo; + } + return -1; } /** * ntfs_mbstoucs - convert a multibyte string to a little endian Unicode string - * @ins: input multibyte string buffer - * @outs: on return contains the (allocated) output Unicode string + * @ins: input multibyte string buffer + * @outs: on return contains the (allocated) output Unicode string * * Convert the input multibyte string @ins, from the current locale into the * corresponding little endian, 2-byte Unicode string. * - * The function allocates the string and the caller is responsible for calling + * The function allocates the string and the caller is responsible for calling * free(*@outs); when finished with it. * * On success the function returns the number of Unicode characters written to @@ -934,394 +1014,426 @@ err_out: * * On error, -1 is returned, and errno is set to the error code. The following * error codes can be expected: - * EINVAL Invalid arguments (e.g. @ins or @outs is NULL). - * EILSEQ The input string cannot be represented as a Unicode - * string according to the current locale. - * ENAMETOOLONG Destination buffer is too small for input string. - * ENOMEM Not enough memory to allocate destination buffer. + * EINVAL Invalid arguments (e.g. @ins or @outs is NULL). + * EILSEQ The input string cannot be represented as a Unicode + * string according to the current locale. + * ENAMETOOLONG Destination buffer is too small for input string. + * ENOMEM Not enough memory to allocate destination buffer. */ -int ntfs_mbstoucs(const char *ins, ntfschar **outs) +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; + /* Now write the NULL character. */ + ucs[o] = cpu_to_le16( L'\0' ); + *outs = ucs; + return o; err_out: - free(ucs); - return -1; + free( ucs ); + return -1; } /* - * Turn a UTF8 name uppercase + * Turn a UTF8 name uppercase * - * Returns an allocated uppercase name which has to be freed by caller - * or NULL if there is an error (described by errno) + * Returns an allocated uppercase name which has to be freed by caller + * 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 ); } /** * ntfs_upcase_table_build - build the default upcase table for NTFS - * @uc: destination buffer where to store the built table - * @uc_len: size of destination buffer in bytes + * @uc: destination buffer where to store the built table + * @uc_len: size of destination buffer in bytes * * ntfs_upcase_table_build() builds the default upcase table for NTFS and * stores it in the caller supplied buffer @uc of size @uc_len. * * Note, @uc_len must be at least 128kiB in size or bad things will happen! */ -void ntfs_upcase_table_build(ntfschar *uc, u32 uc_len) +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 ); + } } /* - * Build a table for converting to lower case + * Build a table for converting to lower case * - * This is only meaningful when there is a single lower case - * character leading to an upper case one, and currently the - * only exception is the greek letter sigma which has a single - * upper case glyph (code U+03A3), but two lower case glyphs - * (code U+03C3 and U+03C2, the latter to be used at the end - * of a word). In the following implementation the upper case - * sigma will be lowercased as U+03C3. + * This is only meaningful when there is a single lower case + * character leading to an upper case one, and currently the + * only exception is the greek letter sigma which has a single + * upper case glyph (code U+03A3), but two lower case glyphs + * (code U+03C3 and U+03C2, the latter to be used at the end + * of a word). In the following implementation the upper case + * sigma will be lowercased as U+03C3. */ -ntfschar *ntfs_locase_table_build(const ntfschar *uc, u32 uc_cnt) +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; } /** * ntfs_ucsfree - free memory allocated by ntfs_str2ucs() - * @ucs input string to be freed + * @ucs input string to be freed * * Free memory at @ucs and which was allocated by ntfs_str2ucs. * * Return value: none. */ -void ntfs_ucsfree(ntfschar *ucs) +void ntfs_ucsfree( ntfschar *ucs ) { - if (ucs && (ucs != AT_UNNAMED)) - free(ucs); + if ( ucs && ( ucs != AT_UNNAMED ) ) + free( ucs ); } /* - * Check whether a name contains no chars forbidden - * for DOS or Win32 use + * Check whether a name contains no chars forbidden + * for DOS or Win32 use * - * If there is a bad char, errno is set to EINVAL + * If there is a bad char, errno is set to EINVAL */ -BOOL ntfs_forbidden_chars(const ntfschar *name, int len) +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 ); } /* @@ -1329,97 +1441,106 @@ BOOL ntfs_collapsible_chars(ntfs_volume *vol, * Use UTF-8 unless specified otherwise. */ -int ntfs_set_char_encoding(const char *locale) +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 ntfs_macosx_normalize_utf8( const char *utf8_string, char **target, + 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..ee7c3f83 100644 --- a/source/libntfs/unistr.h +++ b/source/libntfs/unistr.h @@ -1,6 +1,6 @@ /* * unistr.h - Exports for Unicode string handling. Originated from the Linux-NTFS - * project. + * project. * * Copyright (c) 2000-2004 Anton Altaparmakov * @@ -26,53 +26,53 @@ #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_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 u32 ntfs_ucsnlen( const ntfschar *s, u32 maxlen ); -extern ntfschar *ntfs_ucsndup(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_mbstoucs(const char *ins, ntfschar **outs); +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); +extern void ntfs_upcase_table_build( ntfschar *uc, u32 uc_len ); +extern ntfschar *ntfs_locase_table_build( const ntfschar *uc, u32 uc_cnt ); -extern ntfschar *ntfs_str2ucs(const char *s, int *len); +extern ntfschar *ntfs_str2ucs( const char *s, int *len ); -extern void ntfs_ucsfree(ntfschar *ucs); +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_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 int ntfs_set_char_encoding(const char *locale); +extern int ntfs_set_char_encoding( const char *locale ); #if defined(__APPLE__) || defined(__DARWIN__) /** @@ -86,17 +86,17 @@ extern int ntfs_set_char_encoding(const char *locale); * normalization form. Since Windows and most other OS:es use the NFC form while Mac OS X * mostly uses NFD, this conversion increases compatibility between Mac applications and * NTFS-3G. - * + * * @param normalize decides whether or not the string functions will do automatic filename * normalization when converting to and from UTF-8. 0 means normalization is disabled, * 1 means it is enabled. * @return -1 if the argument was invalid or an error occurred, 0 if all went well. */ -extern int ntfs_macosx_normalize_filenames(int normalize); +extern int ntfs_macosx_normalize_filenames( int normalize ); /** * Mac OS X only. - * + * * Normalizes the input string "utf8_string" to one of the normalization forms NFD or NFC. * The parameter "composed" decides whether output should be in composed, NFC, form * (composed == 1) or decomposed, NFD, form (composed == 0). @@ -111,7 +111,7 @@ extern int ntfs_macosx_normalize_filenames(int normalize); * @return -1 if the normalization failed for some reason, otherwise the length of the * normalized string stored in target. */ -extern int ntfs_macosx_normalize_utf8(const char *utf8_string, char **target, int composed); +extern int ntfs_macosx_normalize_utf8( const char *utf8_string, char **target, int composed ); #endif /* defined(__APPLE__) || defined(__DARWIN__) */ #endif /* defined _NTFS_UNISTR_H */ diff --git a/source/libntfs/volume.c b/source/libntfs/volume.c index 629ec92c..d10d890f 100644 --- a/source/libntfs/volume.c +++ b/source/libntfs/volume.c @@ -69,51 +69,51 @@ #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"; + "The device '%s' doesn't seem to have a valid NTFS.\n" + "Maybe the wrong device is used? Or the whole disk instead of a\n" + "partition (e.g. /dev/sda, not /dev/sda1)? Or the other way around?\n"; static const char *corrupt_volume_msg = -"NTFS is either inconsistent, or there is a hardware fault, or it's a\n" -"SoftRAID/FakeRAID hardware. In the first case run chkdsk /f on Windows\n" -"then reboot into Windows twice. The usage of the /f parameter is very\n" -"important! If the device is a SoftRAID/FakeRAID then first activate\n" -"it and mount a different device under the /dev/mapper/ directory, (e.g.\n" -"/dev/mapper/nvidia_eahaabcc1). Please see the 'dmraid' documentation\n" -"for more details.\n"; + "NTFS is either inconsistent, or there is a hardware fault, or it's a\n" + "SoftRAID/FakeRAID hardware. In the first case run chkdsk /f on Windows\n" + "then reboot into Windows twice. The usage of the /f parameter is very\n" + "important! If the device is a SoftRAID/FakeRAID then first activate\n" + "it and mount a different device under the /dev/mapper/ directory, (e.g.\n" + "/dev/mapper/nvidia_eahaabcc1). Please see the 'dmraid' documentation\n" + "for more details.\n"; static const char *hibernated_volume_msg = -"The NTFS partition is hibernated. Please resume and shutdown Windows\n" -"properly, or mount the volume read-only with the 'ro' mount option, or\n" -"mount the volume read-write with the 'remove_hiberfile' mount option.\n" -"For example type on the command line:\n" -"\n" -" mount -t ntfs-3g -o remove_hiberfile %s %s\n" -"\n"; + "The NTFS partition is hibernated. Please resume and shutdown Windows\n" + "properly, or mount the volume read-only with the 'ro' mount option, or\n" + "mount the volume read-write with the 'remove_hiberfile' mount option.\n" + "For example type on the command line:\n" + "\n" + " mount -t ntfs-3g -o remove_hiberfile %s %s\n" + "\n"; static const char *unclean_journal_msg = -"Write access is denied because the disk wasn't safely powered\n" -"off and the 'norecover' mount option was specified.\n"; + "Write access is denied because the disk wasn't safely powered\n" + "off and the 'norecover' mount option was specified.\n"; static const char *opened_volume_msg = -"Mount is denied because the NTFS volume is already exclusively opened.\n" -"The volume may be already mounted, or another software may use it which\n" -"could be identified for example by the help of the 'fuser' command.\n"; + "Mount is denied because the NTFS volume is already exclusively opened.\n" + "The volume may be already mounted, or another software may use it which\n" + "could be identified for example by the help of the 'fuser' command.\n"; static const char *fakeraid_msg = -"Either the device is missing or it's powered down, or you have\n" -"SoftRAID hardware and must use an activated, different device under\n" -"/dev/mapper/, (e.g. /dev/mapper/nvidia_eahaabcc1) to mount NTFS.\n" -"Please see the 'dmraid' documentation for help.\n"; + "Either the device is missing or it's powered down, or you have\n" + "SoftRAID hardware and must use an activated, different device under\n" + "/dev/mapper/, (e.g. /dev/mapper/nvidia_eahaabcc1) to mount NTFS.\n" + "Please see the 'dmraid' documentation for help.\n"; static const char *access_denied_msg = -"Please check '%s' and the ntfs-3g binary permissions,\n" -"and the mounting user ID. More explanation is provided at\n" -"http://ntfs-3g.org/support.html#unprivileged\n"; + "Please check '%s' and the ntfs-3g binary permissions,\n" + "and the mounting user ID. More explanation is provided at\n" + "http://ntfs-3g.org/support.html#unprivileged\n"; /** * ntfs_volume_alloc - Create an NTFS volume object and initialise it @@ -122,35 +122,37 @@ static const char *access_denied_msg = * * Returns: */ -ntfs_volume *ntfs_volume_alloc(void) +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) +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) +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) +static void ntfs_error_set( int *err ) { - if (!*err) - *err = errno; + if ( !*err ) + *err = errno; } /** @@ -161,69 +163,71 @@ static void ntfs_error_set(int *err) * * Returns: */ -static int __ntfs_volume_release(ntfs_volume *v) +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) +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 ); + } } /** * ntfs_mft_load - load the $MFT and setup the ntfs volume with it - * @vol: ntfs volume whose $MFT to load + * @vol: ntfs volume whose $MFT to load * * Load $MFT from @vol and setup @vol with it. After calling this function the * volume @vol is ready for use by all read access functions provided by the @@ -231,178 +235,196 @@ static void ntfs_attr_setup_flag(ntfs_inode *ni) * * Return 0 on success and -1 on error with errno set to the error code. */ -static int ntfs_mft_load(ntfs_volume *vol) +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; + + ctx = ntfs_attr_get_search_ctx( vol->mft_ni, NULL ); + if ( !ctx ) + goto error_exit; + + /* Find the $ATTRIBUTE_LIST attribute in $MFT if present. */ + if ( ntfs_attr_lookup( AT_ATTRIBUTE_LIST, AT_UNNAMED, 0, 0, 0, NULL, 0, + ctx ) ) + { + if ( errno != ENOENT ) + { + ntfs_log_error( "$MFT has corrupt attribute list.\n" ); + goto io_error_exit; + } + goto mft_has_no_attr_list; + } + NInoSetAttrList( vol->mft_ni ); + l = ntfs_get_attribute_value_length( ctx->attr ); + if ( l <= 0 || l > 0x40000 ) + { + ntfs_log_error( "$MFT/$ATTR_LIST invalid length (%lld).\n", + ( long long )l ); + goto io_error_exit; + } + vol->mft_ni->attr_list_size = l; + vol->mft_ni->attr_list = ntfs_malloc( l ); + if ( !vol->mft_ni->attr_list ) + goto error_exit; + + l = ntfs_get_attribute_value( vol, ctx->attr, vol->mft_ni->attr_list ); + if ( !l ) + { + ntfs_log_error( "Failed to get value of $MFT/$ATTR_LIST.\n" ); + goto io_error_exit; + } + if ( l != vol->mft_ni->attr_list_size ) + { + ntfs_log_error( "Partial read of $MFT/$ATTR_LIST (%lld != " + "%u).\n", ( long long )l, + vol->mft_ni->attr_list_size ); + goto io_error_exit; + } mft_has_no_attr_list: - 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; + ntfs_attr_setup_flag( vol->mft_ni ); - a = ctx->attr; - /* $MFT must be non-resident. */ - if (!a->non_resident) { - ntfs_log_error("$MFT must be non-resident.\n"); - goto io_error_exit; - } - /* $MFT must be uncompressed and unencrypted. */ - if (a->flags & ATTR_COMPRESSION_MASK || - a->flags & ATTR_IS_ENCRYPTED) { - ntfs_log_error("$MFT must be uncompressed and " - "unencrypted.\n"); - goto io_error_exit; - } - /* - * Decompress the mapping pairs array of this extent and merge - * the result into the existing runlist. No need for locking - * as we have exclusive access to the inode at this time and we - * are a mount in progress task, too. - */ - nrl = ntfs_mapping_pairs_decompress(vol, a, vol->mft_na->rl); - if (!nrl) { - ntfs_log_perror("ntfs_mapping_pairs_decompress() failed"); - goto error_exit; - } - vol->mft_na->rl = nrl; + /* We now have a fully setup ntfs inode for $MFT in vol->mft_ni. */ - /* Get the lowest vcn for the next extent. */ - highest_vcn = sle64_to_cpu(a->highest_vcn); - next_vcn = highest_vcn + 1; + /* 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; - /* Only one extent or error, which we catch below. */ - if (next_vcn <= 0) - break; + 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; - /* 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; + /* 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; + errno = EIO; error_exit: - eo = errno; - if (ctx) - ntfs_attr_put_search_ctx(ctx); - if (vol->mft_na) { - ntfs_attr_close(vol->mft_na); - vol->mft_na = NULL; - } - if (vol->mft_ni) { - ntfs_inode_close(vol->mft_ni); - vol->mft_ni = NULL; - } - errno = eo; - return -1; + eo = errno; + if ( ctx ) + ntfs_attr_put_search_ctx( ctx ); + if ( vol->mft_na ) + { + ntfs_attr_close( vol->mft_na ); + vol->mft_na = NULL; + } + if ( vol->mft_ni ) + { + ntfs_inode_close( vol->mft_ni ); + vol->mft_ni = NULL; + } + errno = eo; + return -1; } /** * ntfs_mftmirr_load - load the $MFTMirr and setup the ntfs volume with it - * @vol: ntfs volume whose $MFTMirr to load + * @vol: ntfs volume whose $MFTMirr to load * * Load $MFTMirr from @vol and setup @vol with it. After calling this function * the volume @vol is ready for use by all write access functions provided by @@ -411,45 +433,49 @@ error_exit: * * Return 0 on success and -1 on error with errno set to the error code. */ -static int ntfs_mftmirr_load(ntfs_volume *vol) +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; + } + + vol->mftmirr_na = ntfs_attr_open( vol->mftmirr_ni, AT_DATA, AT_UNNAMED, 0 ); + if ( !vol->mftmirr_na ) + { + ntfs_log_perror( "Failed to open $MFTMirr/$DATA" ); + goto error_exit; + } + + if ( ntfs_attr_map_runlist( vol->mftmirr_na, 0 ) < 0 ) + { + ntfs_log_perror( "Failed to map runlist of $MFTMirr/$DATA" ); + goto error_exit; + } + + return 0; error_exit: - err = errno; - if (vol->mftmirr_na) { - ntfs_attr_close(vol->mftmirr_na); - vol->mftmirr_na = NULL; - } - ntfs_inode_close(vol->mftmirr_ni); - vol->mftmirr_ni = NULL; - errno = err; - return -1; + err = errno; + if ( vol->mftmirr_na ) + { + ntfs_attr_close( vol->mftmirr_na ); + vol->mftmirr_na = NULL; + } + ntfs_inode_close( vol->mftmirr_ni ); + vol->mftmirr_ni = NULL; + errno = err; + return -1; } /** * ntfs_volume_startup - allocate and setup an ntfs volume - * @dev: device to open - * @flags: optional mount flags + * @dev: device to open + * @flags: optional mount flags * * Load, verify, and parse bootsector; load and setup $MFT and $MFTMirr. After * calling this function, the volume is setup sufficiently to call all read @@ -458,196 +484,206 @@ error_exit: * Return the allocated volume structure on success and NULL on error with * errno set to the error code. */ -ntfs_volume *ntfs_volume_startup(struct ntfs_device *dev, unsigned long flags) +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; + /* 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; + eo = errno; + free( bs ); + if ( vol ) + __ntfs_volume_release( vol ); + errno = eo; + return NULL; } /** * ntfs_volume_check_logfile - check logfile on target volume - * @vol: volume on which to check logfile + * @vol: volume on which to check logfile * * Return 0 on success and -1 on error with errno set error code. */ -static int ntfs_volume_check_logfile(ntfs_volume *vol) +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; } /** @@ -655,57 +691,63 @@ out: * @vol: An ntfs volume obtained from ntfs_mount * * Return: inode Success, hiberfil.sys is valid - * NULL hiberfil.sys doesn't exist or some other error occurred + * NULL hiberfil.sys doesn't exist or some other error occurred */ -static ntfs_inode *ntfs_hiberfile_open(ntfs_volume *vol) +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; - } + inode = MREF( inode ); + ni_hibr = ntfs_inode_open( vol, inode ); + if ( !ni_hibr ) + { + ntfs_log_debug( "Couldn't open inode %lld.\n", ( long long )inode ); + goto out; + } out: - if (ntfs_inode_close(ni_root)) { - ntfs_inode_close(ni_hibr); - ni_hibr = NULL; - } - free(unicode); - return ni_hibr; + if ( ntfs_inode_close( ni_root ) ) + { + ntfs_inode_close( ni_hibr ); + ni_hibr = NULL; + } + free( unicode ); + return ni_hibr; } -#define NTFS_HIBERFILE_HEADER_SIZE 4096 +#define NTFS_HIBERFILE_HEADER_SIZE 4096 /** * ntfs_volume_check_hiberfile - check hiberfil.sys whether Windows is @@ -715,129 +757,141 @@ out: * Return: 0 if Windows isn't hibernated for sure * -1 otherwise and errno is set to the appropriate value */ -int ntfs_volume_check_hiberfile(ntfs_volume *vol, int verbose) +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; + bytes_read = ntfs_attr_pread( na, 0, NTFS_HIBERFILE_HEADER_SIZE, buf ); + if ( bytes_read == -1 ) + { + ntfs_log_perror( "Failed to read hiberfil.sys" ); + goto out; + } + if ( bytes_read < NTFS_HIBERFILE_HEADER_SIZE ) + { + if ( verbose ) + ntfs_log_error( "Hibernated non-system partition, " + "refused to mount.\n" ); + errno = EPERM; + goto out; + } + if ( memcmp( buf, "hibr", 4 ) == 0 ) + { + if ( verbose ) + ntfs_log_error( "Windows is hibernated, refused to mount.\n" ); + errno = EPERM; + goto out; + } + /* All right, all header bytes are zero */ + errno = 0; out: - if (na) - ntfs_attr_close(na); - free(buf); - err = errno; - if (ntfs_inode_close(ni)) - ntfs_error_set(&err); - errno = err; - return errno ? -1 : 0; + if ( na ) + ntfs_attr_close( na ); + free( buf ); + err = errno; + if ( ntfs_inode_close( ni ) ) + ntfs_error_set( &err ); + errno = err; + return errno ? -1 : 0; } /* - * Make sure a LOGGED_UTILITY_STREAM attribute named "$TXF_DATA" - * on the root directory is resident. - * When it is non-resident, the partition cannot be mounted on Vista - * (see http://support.microsoft.com/kb/974729) + * Make sure a LOGGED_UTILITY_STREAM attribute named "$TXF_DATA" + * on the root directory is resident. + * When it is non-resident, the partition cannot be mounted on Vista + * (see http://support.microsoft.com/kb/974729) * - * We take care to avoid this situation, however this can be a - * consequence of having used an older version (including older - * Windows version), so we had better fix it. + * We take care to avoid this situation, however this can be a + * consequence of having used an older version (including older + * Windows version), so we had better fix it. * - * Returns 0 if unneeded or successful - * -1 if there was an error, explained by errno + * Returns 0 if unneeded or successful + * -1 if there was an error, explained by errno */ -static int fix_txf_data(ntfs_volume *vol) +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 ); } /** * ntfs_device_mount - open ntfs volume - * @dev: device to open - * @flags: optional mount flags + * @dev: device to open + * @flags: optional mount flags * * This function mounts an ntfs volume. @dev should describe the device which * to mount as the ntfs volume. @@ -845,7 +899,7 @@ static int fix_txf_data(ntfs_volume *vol) * @flags is an optional second parameter. The same flags are used as for * the mount system call (man 2 mount). Currently only the following flag * is implemented: - * MS_RDONLY - mount volume read-only + * MS_RDONLY - mount volume read-only * * The function opens the device @dev and verifies that it contains a valid * bootsector. Then, it allocates an ntfs_volume structure and initializes @@ -856,409 +910,452 @@ static int fix_txf_data(ntfs_volume *vol) * Return the allocated volume structure on success and NULL on error with * errno set to the error code. */ -ntfs_volume *ntfs_device_mount(struct ntfs_device *dev, unsigned long flags) +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; + /* + * 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; + errno = EIO; error_exit: - eo = errno; - if (ctx) - ntfs_attr_put_search_ctx(ctx); - free(m); - free(m2); - __ntfs_volume_release(vol); - errno = eo; - return NULL; + eo = errno; + if ( ctx ) + ntfs_attr_put_search_ctx( ctx ); + free( m ); + free( m2 ); + __ntfs_volume_release( vol ); + errno = eo; + return NULL; } /* - * Set appropriate flags for showing NTFS metafiles - * or files marked as hidden. - * Not set in ntfs_mount() to avoid breaking existing tools. + * Set appropriate flags for showing NTFS metafiles + * or files marked as hidden. + * 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 ); } /* - * Set ignore case mode + * Set ignore case mode */ -int ntfs_set_ignore_case(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 ); } /** * ntfs_mount - open ntfs volume - * @name: name of device/file to open - * @flags: optional mount flags + * @name: name of device/file to open + * @flags: optional mount flags * * This function mounts an ntfs volume. @name should contain the name of the * device/file to mount as the ntfs volume. @@ -1266,7 +1363,7 @@ int ntfs_set_ignore_case(ntfs_volume *vol) * @flags is an optional second parameter. The same flags are used as for * the mount system call (man 2 mount). Currently only the following flags * is implemented: - * MS_RDONLY - mount volume read-only + * MS_RDONLY - mount volume read-only * * The function opens the device or file @name and verifies that it contains a * valid bootsector. Then, it allocates an ntfs_volume structure and initializes @@ -1280,34 +1377,36 @@ 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 } @@ -1333,19 +1432,20 @@ ntfs_volume *ntfs_mount(const char *name __attribute__((unused)), * function returns success. If it returns an error then nothing has been done * so it is safe to continue using @vol. */ -int ntfs_umount(ntfs_volume *vol, const BOOL force __attribute__((unused))) +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 @@ -1354,11 +1454,11 @@ int ntfs_umount(ntfs_volume *vol, const BOOL force __attribute__((unused))) /** * realpath - If there is no realpath on the system */ -static char *realpath(const char *path, char *resolved_path) +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 @@ -1370,60 +1470,65 @@ static char *realpath(const char *path, char *resolved_path) * * See description of ntfs_check_if_mounted(), below. */ -static int ntfs_mntent_check(const char *file, unsigned long *mnt_flags) +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; + free( real_file ); + free( real_fsname ); + if ( err ) + { + errno = err; + return -1; + } + return 0; } #endif /* HAVE_MNTENT_H */ /** * ntfs_check_if_mounted - check if an ntfs volume is currently mounted - * @file: device file to check - * @mnt_flags: pointer into which to return the ntfs mount flags (see volume.h) + * @file: device file to check + * @mnt_flags: pointer into which to return the ntfs mount flags (see volume.h) * * If the running system does not support the {set,get,end}mntent() calls, * just return 0 and set *@mnt_flags to zero. @@ -1445,20 +1550,20 @@ 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 } /** * ntfs_version_is_supported - check if NTFS version is supported. - * @vol: ntfs volume whose version we're interested in. + * @vol: ntfs volume whose version we're interested in. * * The function checks if the NTFS volume version is known or not. * Version 1.1 and 1.2 are used by Windows NT3.x and NT4. @@ -1469,37 +1574,38 @@ int ntfs_check_if_mounted(const char *file __attribute__((unused)), * Return 0 if NTFS version is supported otherwise -1 with errno set. * * The following error codes are defined: - * EOPNOTSUPP - Unknown NTFS version - * EINVAL - Invalid argument + * EOPNOTSUPP - Unknown NTFS version + * EINVAL - Invalid argument */ -int ntfs_version_is_supported(ntfs_volume *vol) +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; } /** * ntfs_logfile_reset - "empty" $LogFile data attribute value - * @vol: ntfs volume whose $LogFile we intend to reset. + * @vol: ntfs volume whose $LogFile we intend to reset. * * Fill the value of the $LogFile data attribute, i.e. the contents of * the file, with 0xff's, thus marking the journal as empty. @@ -1512,212 +1618,226 @@ int ntfs_version_is_supported(ntfs_volume *vol) * * On error return -1 with errno set to the error code. */ -int ntfs_logfile_reset(ntfs_volume *vol) +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; + } + + ntfs_attr_close( na ); + return ntfs_inode_close( ni ); error_exit: - ntfs_inode_close(ni); - errno = eo; - return -1; + ntfs_inode_close( ni ); + errno = eo; + return -1; } /** * ntfs_volume_write_flags - set the flags of an ntfs volume - * @vol: ntfs volume where we set the volume flags - * @flags: new flags + * @vol: ntfs volume where we set the volume flags + * @flags: new flags * * Set the on-disk volume flags in the mft record of $Volume and * on volume @vol to @flags. * * Return 0 if successful and -1 if not with errno set to the error code. */ -int ntfs_volume_write_flags(ntfs_volume *vol, const le16 flags) +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 */ + ret = 0; /* success */ err_out: - ntfs_attr_put_search_ctx(ctx); - return ret; + ntfs_attr_put_search_ctx( ctx ); + return ret; } -int ntfs_volume_error(int err) +int 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) +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) +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; } /* - * Feed the counts of free clusters and free mft records + * Feed the counts of free clusters and free mft records */ -int ntfs_volume_get_free_space(ntfs_volume *vol) +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..9e4dd108 100644 --- a/source/libntfs/volume.h +++ b/source/libntfs/volume.h @@ -74,28 +74,30 @@ 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); +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,47 +105,48 @@ 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) -#define set_nvol_flag(nv, flag) set_bit(NV_##flag, (nv)->state) -#define clear_nvol_flag(nv, flag) clear_bit(NV_##flag, (nv)->state) +#define test_nvol_flag(nv, flag) test_bit(NV_##flag, (nv)->state) +#define set_nvol_flag(nv, flag) set_bit(NV_##flag, (nv)->state) +#define clear_nvol_flag(nv, flag) clear_bit(NV_##flag, (nv)->state) -#define NVolReadOnly(nv) test_nvol_flag(nv, ReadOnly) -#define NVolSetReadOnly(nv) set_nvol_flag(nv, ReadOnly) -#define NVolClearReadOnly(nv) clear_nvol_flag(nv, ReadOnly) +#define NVolReadOnly(nv) test_nvol_flag(nv, ReadOnly) +#define NVolSetReadOnly(nv) set_nvol_flag(nv, ReadOnly) +#define NVolClearReadOnly(nv) clear_nvol_flag(nv, ReadOnly) -#define NVolCaseSensitive(nv) test_nvol_flag(nv, CaseSensitive) -#define NVolSetCaseSensitive(nv) set_nvol_flag(nv, CaseSensitive) -#define NVolClearCaseSensitive(nv) clear_nvol_flag(nv, CaseSensitive) +#define NVolCaseSensitive(nv) test_nvol_flag(nv, CaseSensitive) +#define NVolSetCaseSensitive(nv) set_nvol_flag(nv, CaseSensitive) +#define NVolClearCaseSensitive(nv) clear_nvol_flag(nv, CaseSensitive) -#define NVolLogFileEmpty(nv) test_nvol_flag(nv, LogFileEmpty) -#define NVolSetLogFileEmpty(nv) set_nvol_flag(nv, LogFileEmpty) -#define NVolClearLogFileEmpty(nv) clear_nvol_flag(nv, LogFileEmpty) +#define NVolLogFileEmpty(nv) test_nvol_flag(nv, LogFileEmpty) +#define NVolSetLogFileEmpty(nv) set_nvol_flag(nv, LogFileEmpty) +#define NVolClearLogFileEmpty(nv) clear_nvol_flag(nv, LogFileEmpty) -#define NVolShowSysFiles(nv) test_nvol_flag(nv, ShowSysFiles) -#define NVolSetShowSysFiles(nv) set_nvol_flag(nv, ShowSysFiles) -#define NVolClearShowSysFiles(nv) clear_nvol_flag(nv, ShowSysFiles) +#define NVolShowSysFiles(nv) test_nvol_flag(nv, ShowSysFiles) +#define NVolSetShowSysFiles(nv) set_nvol_flag(nv, ShowSysFiles) +#define NVolClearShowSysFiles(nv) clear_nvol_flag(nv, ShowSysFiles) -#define NVolShowHidFiles(nv) test_nvol_flag(nv, ShowHidFiles) -#define NVolSetShowHidFiles(nv) set_nvol_flag(nv, ShowHidFiles) -#define NVolClearShowHidFiles(nv) clear_nvol_flag(nv, ShowHidFiles) +#define NVolShowHidFiles(nv) test_nvol_flag(nv, ShowHidFiles) +#define NVolSetShowHidFiles(nv) set_nvol_flag(nv, ShowHidFiles) +#define NVolClearShowHidFiles(nv) clear_nvol_flag(nv, ShowHidFiles) -#define NVolHideDotFiles(nv) test_nvol_flag(nv, HideDotFiles) -#define NVolSetHideDotFiles(nv) set_nvol_flag(nv, HideDotFiles) -#define NVolClearHideDotFiles(nv) clear_nvol_flag(nv, HideDotFiles) +#define NVolHideDotFiles(nv) test_nvol_flag(nv, HideDotFiles) +#define NVolSetHideDotFiles(nv) set_nvol_flag(nv, HideDotFiles) +#define NVolClearHideDotFiles(nv) clear_nvol_flag(nv, HideDotFiles) -#define NVolCompression(nv) test_nvol_flag(nv, Compression) -#define NVolSetCompression(nv) set_nvol_flag(nv, Compression) -#define NVolClearCompression(nv) clear_nvol_flag(nv, Compression) +#define NVolCompression(nv) test_nvol_flag(nv, Compression) +#define NVolSetCompression(nv) set_nvol_flag(nv, Compression) +#define NVolClearCompression(nv) clear_nvol_flag(nv, Compression) /* * NTFS version 1.1 and 1.2 are used by Windows NT4. @@ -163,141 +166,143 @@ 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 }; extern const char *ntfs_home; -extern ntfs_volume *ntfs_volume_alloc(void); +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); +extern ntfs_volume *ntfs_mount( const char *name, unsigned long flags ); +extern int ntfs_umount( ntfs_volume *vol, const BOOL force ); -extern int ntfs_version_is_supported(ntfs_volume *vol); -extern int ntfs_volume_check_hiberfile(ntfs_volume *vol, int verbose); -extern int ntfs_logfile_reset(ntfs_volume *vol); +extern int ntfs_version_is_supported( ntfs_volume *vol ); +extern int ntfs_volume_check_hiberfile( ntfs_volume *vol, int verbose ); +extern int ntfs_logfile_reset( ntfs_volume *vol ); -extern int ntfs_volume_write_flags(ntfs_volume *vol, const le16 flags); +extern int ntfs_volume_write_flags( ntfs_volume *vol, const le16 flags ); -extern int ntfs_volume_error(int err); -extern void ntfs_mount_error(const char *vol, const char *mntpoint, int err); +extern int ntfs_volume_error( int err ); +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_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_locale(void); -extern int ntfs_set_ignore_case(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_locale( void ); +extern int ntfs_set_ignore_case( ntfs_volume *vol ); #endif /* defined _NTFS_VOLUME_H */ diff --git a/source/libwbfs/libwbfs.c b/source/libwbfs/libwbfs.c index 09589b2a..9e11eca9 100644 --- a/source/libwbfs/libwbfs.c +++ b/source/libwbfs/libwbfs.c @@ -15,371 +15,383 @@ wbfs_t wbfs_iso_file; -static int force_mode=0; +static int force_mode = 0; -void wbfs_set_force_mode(int force) +void wbfs_set_force_mode( int force ) { - force_mode = force; + force_mode = force; } -static u8 size_to_shift(u32 size) +static u8 size_to_shift( u32 size ) { - u8 ret = 0; - while(size) - { - ret++; - size>>=1; - } - return ret-1; + u8 ret = 0; + while ( size ) + { + ret++; + size >>= 1; + } + return ret - 1; } #define read_le32_unaligned(x) ((x)[0]|((x)[1]<<8)|((x)[2]<<16)|((x)[3]<<24)) -wbfs_t*wbfs_open_hd(rw_sector_callback_t read_hdsector, - rw_sector_callback_t write_hdsector, - void *callback_data, - int hd_sector_size, int num_hd_sector __attribute((unused)), int reset) +wbfs_t*wbfs_open_hd( rw_sector_callback_t read_hdsector, + rw_sector_callback_t write_hdsector, + void *callback_data, + int hd_sector_size, int num_hd_sector __attribute( ( unused ) ), int reset ) { - int i=num_hd_sector,ret; - u8 *ptr,*tmp_buffer = wbfs_ioalloc(hd_sector_size); - u8 part_table[16*4]; - ret = read_hdsector(callback_data,0,1,tmp_buffer); - if(ret) - return 0; - //find wbfs partition - wbfs_memcpy(part_table,tmp_buffer+0x1be,16*4); - ptr = part_table; - for(i=0;i<4;i++,ptr+=16) - { - u32 part_lba = read_le32_unaligned(ptr+0x8); - wbfs_head_t *head = (wbfs_head_t *)tmp_buffer; - ret = read_hdsector(callback_data,part_lba,1,tmp_buffer); - // verify there is the magic. - if (head->magic == wbfs_htonl(WBFS_MAGIC)) - { - wbfs_t*p = wbfs_open_partition(read_hdsector,write_hdsector, - callback_data,hd_sector_size,0,part_lba,reset); - wbfs_iofree(tmp_buffer); - return p; - } - } - wbfs_iofree(tmp_buffer); - if(reset)// XXX make a empty hd partition.. - { - } + 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; -} -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)); - - wbfs_head_t *head = wbfs_ioalloc(hd_sector_size?hd_sector_size:512); - - //constants, but put here for consistancy - p->wii_sec_sz = 0x8000; - p->wii_sec_sz_s = size_to_shift(0x8000); - p->n_wii_sec = (num_hd_sector/0x8000)*hd_sector_size; - p->n_wii_sec_per_disc = 143432*2;//support for double layers discs.. - p->head = head; - p->part_lba = part_lba; - // init the partition - if (reset) + //find wbfs partition + wbfs_memcpy( part_table, tmp_buffer + 0x1be, 16*4 ); + ptr = part_table; + for ( i = 0; i < 4; i++, ptr += 16 ) + { + u32 part_lba = read_le32_unaligned( ptr + 0x8 ); + wbfs_head_t *head = ( wbfs_head_t * )tmp_buffer; + ret = read_hdsector( callback_data, part_lba, 1, tmp_buffer ); + // verify there is the magic. + if ( head->magic == wbfs_htonl( WBFS_MAGIC ) ) { - u8 sz_s; - wbfs_memset(head,0,hd_sector_size); - head->magic = wbfs_htonl(WBFS_MAGIC); - head->hd_sec_sz_s = size_to_shift(hd_sector_size); - head->n_hd_sec = wbfs_htonl(num_hd_sector); - // choose minimum wblk_sz that fits this partition size - for(sz_s=6;sz_s<11;sz_s++) - { - // ensure that wbfs_sec_sz is big enough to address every blocks using 16 bits - if(p->n_wii_sec <((1U<<16)*(1<wbfs_sec_sz_s = sz_s+p->wii_sec_sz_s; - }else - read_hdsector(callback_data,p->part_lba,1,head); - if (head->magic != wbfs_htonl(WBFS_MAGIC)) - ERROR("bad magic"); - if(!force_mode && hd_sector_size && head->hd_sec_sz_s != size_to_shift(hd_sector_size)) - ERROR("hd sector size doesn't match"); - if(!force_mode && num_hd_sector && head->n_hd_sec != wbfs_htonl(num_hd_sector)) - ERROR("hd num sector doesn't match"); - p->hd_sec_sz = 1<hd_sec_sz_s; - p->hd_sec_sz_s = head->hd_sec_sz_s; - p->n_hd_sec = wbfs_ntohl(head->n_hd_sec); - - p->n_wii_sec = (p->n_hd_sec/p->wii_sec_sz)*(p->hd_sec_sz); - - p->wbfs_sec_sz_s = head->wbfs_sec_sz_s; - p->wbfs_sec_sz = 1<wbfs_sec_sz_s; - p->n_wbfs_sec = p->n_wii_sec >> (p->wbfs_sec_sz_s - p->wii_sec_sz_s); - p->n_wbfs_sec_per_disc = p->n_wii_sec_per_disc >> (p->wbfs_sec_sz_s - p->wii_sec_sz_s); - p->disc_info_sz = ALIGN_LBA(sizeof(wbfs_disc_info_t) + p->n_wbfs_sec_per_disc*2); - - //printf("hd_sector_size %X wii_sector size %X wbfs sector_size %X\n",p->hd_sec_sz,p->wii_sec_sz,p->wbfs_sec_sz); - p->read_hdsector = read_hdsector; - p->write_hdsector = write_hdsector; - p->callback_data = callback_data; - - p->freeblks_lba = (p->wbfs_sec_sz - p->n_wbfs_sec/8)>>p->hd_sec_sz_s; - - if(!reset) - p->freeblks = 0; // will alloc and read only if needed - else - { - // init with all free blocks - p->freeblks = wbfs_ioalloc(ALIGN_LBA(p->n_wbfs_sec/8)); - wbfs_memset(p->freeblks,0xff,p->n_wbfs_sec/8); + 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; } - 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); - wbfs_iofree(head); - return 0; - + } + wbfs_iofree( tmp_buffer ); + if ( reset )// XXX make a empty hd partition.. + { + } + return 0; } - -void wbfs_sync(wbfs_t*p) +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 ) { - // copy back descriptors - if(p->write_hdsector){ - p->write_hdsector(p->callback_data,p->part_lba+0,1, p->head); - - if(p->freeblks) - p->write_hdsector(p->callback_data,p->part_lba+p->freeblks_lba,ALIGN_LBA(p->n_wbfs_sec/8)>>p->hd_sec_sz_s, p->freeblks); - } -} + wbfs_t *p = wbfs_malloc( sizeof( wbfs_t ) ); -void wbfs_close(wbfs_t*p) -{ - wbfs_sync(p); + wbfs_head_t *head = wbfs_ioalloc( hd_sector_size ? hd_sector_size : 512 ); - if(p->n_disc_open) - ERROR("trying to close wbfs while discs still open"); - - wbfs_iofree(p->head); - wbfs_iofree(p->tmp_buffer); - if(p->freeblks) - wbfs_iofree(p->freeblks); - - wbfs_free(p); - -error: - return; -} - -wbfs_disc_t *wbfs_open_disc(wbfs_t* p, u8 *discid) -{ - u32 i; - int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; - wbfs_disc_t *d = 0; - for(i=0;imax_disc;i++) + //constants, but put here for consistancy + p->wii_sec_sz = 0x8000; + p->wii_sec_sz_s = size_to_shift( 0x8000 ); + p->n_wii_sec = ( num_hd_sector / 0x8000 ) * hd_sector_size; + p->n_wii_sec_per_disc = 143432 * 2;//support for double layers discs.. + p->head = head; + p->part_lba = part_lba; + // init the partition + if ( reset ) + { + u8 sz_s; + wbfs_memset( head, 0, hd_sector_size ); + head->magic = wbfs_htonl( WBFS_MAGIC ); + head->hd_sec_sz_s = size_to_shift( hd_sector_size ); + head->n_hd_sec = wbfs_htonl( num_hd_sector ); + // choose minimum wblk_sz that fits this partition size + for ( sz_s = 6; sz_s < 11; sz_s++ ) { - if (p->head->disc_table[i]){ - p->read_hdsector(p->callback_data, - p->part_lba+1+i*disc_info_sz_lba,1,p->tmp_buffer); - if(wbfs_memcmp(discid,p->tmp_buffer,6)==0){ - d = wbfs_malloc(sizeof(*d)); - if(!d) - ERROR("allocating memory"); - d->p = p; - d->i = i; - d->header = wbfs_ioalloc(p->disc_info_sz); - if(!d->header) - ERROR("allocating memory"); - p->read_hdsector(p->callback_data, - p->part_lba+1+i*disc_info_sz_lba, - disc_info_sz_lba,d->header); - p->n_disc_open ++; + // 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; + } + head->wbfs_sec_sz_s = sz_s + p->wii_sec_sz_s; + } + else + read_hdsector( callback_data, p->part_lba, 1, head ); + if ( head->magic != wbfs_htonl( WBFS_MAGIC ) ) + ERROR( "bad magic" ); + if ( !force_mode && hd_sector_size && head->hd_sec_sz_s != size_to_shift( hd_sector_size ) ) + ERROR( "hd sector size doesn't match" ); + if ( !force_mode && num_hd_sector && head->n_hd_sec != wbfs_htonl( num_hd_sector ) ) + ERROR( "hd num sector doesn't match" ); + p->hd_sec_sz = 1 << 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->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->disc_info_sz = ALIGN_LBA( sizeof( wbfs_disc_info_t ) + p->n_wbfs_sec_per_disc * 2 ); + + //printf("hd_sector_size %X wii_sector size %X wbfs sector_size %X\n",p->hd_sec_sz,p->wii_sec_sz,p->wbfs_sec_sz); + p->read_hdsector = read_hdsector; + p->write_hdsector = write_hdsector; + p->callback_data = callback_data; + + p->freeblks_lba = ( p->wbfs_sec_sz - p->n_wbfs_sec / 8 ) >> p->hd_sec_sz_s; + + if ( !reset ) + p->freeblks = 0; // will alloc and read only if needed + else + { + // init with all free blocks + p->freeblks = wbfs_ioalloc( ALIGN_LBA( p->n_wbfs_sec / 8 ) ); + wbfs_memset( p->freeblks, 0xff, p->n_wbfs_sec / 8 ); + } + p->max_disc = ( p->freeblks_lba - 1 ) / ( p->disc_info_sz >> p->hd_sec_sz_s ); + if ( p->max_disc > p->hd_sec_sz - sizeof( wbfs_head_t ) ) + p->max_disc = p->hd_sec_sz - sizeof( wbfs_head_t ); + + p->tmp_buffer = wbfs_ioalloc( p->hd_sec_sz ); + p->n_disc_open = 0; + return p; +error: + wbfs_free( p ); + wbfs_iofree( head ); + return 0; + +} + +void wbfs_sync( wbfs_t*p ) +{ + // copy back descriptors + if ( p->write_hdsector ) + { + p->write_hdsector( p->callback_data, p->part_lba + 0, 1, p->head ); + + if ( p->freeblks ) + p->write_hdsector( p->callback_data, p->part_lba + p->freeblks_lba, ALIGN_LBA( p->n_wbfs_sec / 8 ) >> p->hd_sec_sz_s, p->freeblks ); + } +} + +void wbfs_close( wbfs_t*p ) +{ + wbfs_sync( p ); + + if ( p->n_disc_open ) + ERROR( "trying to close wbfs while discs still open" ); + + wbfs_iofree( p->head ); + wbfs_iofree( p->tmp_buffer ); + if ( p->freeblks ) + wbfs_iofree( p->freeblks ); + + wbfs_free( p ); + +error: + return; +} + +wbfs_disc_t *wbfs_open_disc( wbfs_t* p, u8 *discid ) +{ + u32 i; + int disc_info_sz_lba = p->disc_info_sz >> p->hd_sec_sz_s; + wbfs_disc_t *d = 0; + for ( i = 0; i < p->max_disc; i++ ) + { + if ( p->head->disc_table[i] ) + { + p->read_hdsector( p->callback_data, + p->part_lba + 1 + i*disc_info_sz_lba, 1, p->tmp_buffer ); + if ( wbfs_memcmp( discid, p->tmp_buffer, 6 ) == 0 ) + { + d = wbfs_malloc( sizeof( *d ) ); + if ( !d ) + ERROR( "allocating memory" ); + d->p = p; + d->i = i; + d->header = wbfs_ioalloc( p->disc_info_sz ); + if ( !d->header ) + ERROR( "allocating memory" ); + p->read_hdsector( p->callback_data, + p->part_lba + 1 + i*disc_info_sz_lba, + disc_info_sz_lba, d->header ); + p->n_disc_open ++; // for(i=0;in_wbfs_sec_per_disc;i++) // printf("%d,",wbfs_ntohs(d->header->wlba_table[i])); - return d; - } - } + return d; + } } - return 0; + } + return 0; error: - if(d) - wbfs_iofree(d); - return 0; - + if ( d ) + wbfs_iofree( d ); + return 0; + } -void wbfs_close_disc(wbfs_disc_t*d) +void wbfs_close_disc( wbfs_disc_t*d ) { - d->p->n_disc_open --; - wbfs_iofree(d->header); - wbfs_free(d); + d->p->n_disc_open --; + wbfs_iofree( d->header ); + wbfs_free( d ); } // offset is pointing 32bit words to address the whole dvd, although len is in bytes -int wbfs_disc_read(wbfs_disc_t*d,u32 offset, u32 len, u8 *data) +int wbfs_disc_read( wbfs_disc_t*d, u32 offset, u32 len, u8 *data ) { - if (d->p == &wbfs_iso_file) { - return wbfs_iso_file_read(d, offset, data, len); - } - - wbfs_t *p = d->p; - u16 wlba = offset>>(p->wbfs_sec_sz_s-2); - u32 iwlba_shift = p->wbfs_sec_sz_s - p->hd_sec_sz_s; - u32 lba_mask = (p->wbfs_sec_sz-1)>>(p->hd_sec_sz_s); - u32 lba = (offset>>(p->hd_sec_sz_s-2))&lba_mask; - u32 off = offset&((p->hd_sec_sz>>2)-1); - u16 iwlba = wbfs_ntohs(d->header->wlba_table[wlba]); - u32 len_copied; - int err = 0; - u8 *ptr = data; - if(unlikely(iwlba==0)) - return 1; - if(unlikely(off)){ - off*=4; - err = p->read_hdsector(p->callback_data, - p->part_lba + (iwlba<tmp_buffer); - if(err) - return err; - len_copied = p->hd_sec_sz - off; - if(likely(len < len_copied)) - len_copied = len; - wbfs_memcpy(ptr, p->tmp_buffer + off, len_copied); - len -= len_copied; - ptr += len_copied; - lba++; - if(unlikely(lba>lba_mask && len)){ - lba=0; - iwlba = wbfs_ntohs(d->header->wlba_table[++wlba]); - if(unlikely(iwlba==0)) - return 1; - } - } - while(likely(len>=p->hd_sec_sz)) + if ( d->p == &wbfs_iso_file ) + { + return wbfs_iso_file_read( d, offset, data, len ); + } + + wbfs_t *p = d->p; + u16 wlba = offset >> ( p->wbfs_sec_sz_s - 2 ); + u32 iwlba_shift = p->wbfs_sec_sz_s - p->hd_sec_sz_s; + u32 lba_mask = ( p->wbfs_sec_sz - 1 ) >> ( p->hd_sec_sz_s ); + u32 lba = ( offset >> ( p->hd_sec_sz_s - 2 ) ) & lba_mask; + u32 off = offset & ( ( p->hd_sec_sz >> 2 ) - 1 ); + u16 iwlba = wbfs_ntohs( d->header->wlba_table[wlba] ); + u32 len_copied; + int err = 0; + u8 *ptr = data; + if ( unlikely( iwlba == 0 ) ) + return 1; + if ( unlikely( off ) ) + { + off *= 4; + err = p->read_hdsector( p->callback_data, + p->part_lba + ( iwlba << 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; + wbfs_memcpy( ptr, p->tmp_buffer + off, len_copied ); + len -= len_copied; + ptr += len_copied; + lba++; + if ( unlikely( lba > lba_mask && len ) ) { - u32 nlb = len>>(p->hd_sec_sz_s); - - if(unlikely(lba + nlb > p->wbfs_sec_sz)) // dont cross wbfs sectors.. - nlb = p->wbfs_sec_sz-lba; - err = p->read_hdsector(p->callback_data, - p->part_lba + (iwlba<hd_sec_sz_s; - ptr += nlb<hd_sec_sz_s; - lba += nlb; - if(unlikely(lba>lba_mask && len)){ - lba = 0; - iwlba =wbfs_ntohs(d->header->wlba_table[++wlba]); - if(unlikely(iwlba==0)) - return 1; - } + lba = 0; + iwlba = wbfs_ntohs( d->header->wlba_table[++wlba] ); + if ( unlikely( iwlba == 0 ) ) + return 1; } - if(unlikely(len)){ - err = p->read_hdsector(p->callback_data, - p->part_lba + (iwlba<tmp_buffer); - if(err) - return err; - wbfs_memcpy(ptr, p->tmp_buffer, len); - } - return 0; + } + 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 ) ) + { + 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;imax_disc;i++) - if (p->head->disc_table[i]) - count++; - return count; - + u32 i, count = 0; + 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;jn_wbfs_sec_per_disc;j++) - if(wbfs_ntohs(di->wlba_table[j])) - tot_blk++; - return tot_blk; + 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++; + 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;jn_wbfs_sec_per_disc;j++) - if(wbfs_ntohs(di->wlba_table[j])) { - if (last_blk) *last_blk = j; - tot_blk++; - } - return tot_blk; -} - -u32 wbfs_get_disc_info(wbfs_t*p, u32 index,u8 *header,int header_size,u32 *size)//size in 32 bit -{ - u32 i,count=0; - if (!p) return 1; - int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; - - for(i=0;imax_disc;i++) - if (p->head->disc_table[i]){ - if(count++==index) - { - p->read_hdsector(p->callback_data, - p->part_lba+1+i*disc_info_sz_lba,1,p->tmp_buffer); - if(header_size > (int)p->hd_sec_sz) - header_size = p->hd_sec_sz; - u32 magic = wbfs_ntohl(*(u32*)(p->tmp_buffer+24)); - if(magic!=0x5D1C9EA3){ - p->head->disc_table[i]=0; - return 1; - } - memcpy(header,p->tmp_buffer,header_size); - if(size) - { - u8 *header = wbfs_ioalloc(p->disc_info_sz); - p->read_hdsector(p->callback_data, - p->part_lba+1+i*disc_info_sz_lba,disc_info_sz_lba,header); - u32 sec_used = wbfs_sector_used(p,(wbfs_disc_info_t *)header); - wbfs_iofree(header); - *size = sec_used<<(p->wbfs_sec_sz_s-2); - } - return 0; - } - } - return 1; -} - -static void load_freeblocks(wbfs_t*p) -{ - if(p->freeblks) - return; - // XXX should handle malloc error.. - p->freeblks = wbfs_ioalloc(ALIGN_LBA(p->n_wbfs_sec/8)); - p->read_hdsector(p->callback_data,p->part_lba+p->freeblks_lba,ALIGN_LBA(p->n_wbfs_sec/8)>>p->hd_sec_sz_s, p->freeblks); - -} -u32 wbfs_count_usedblocks(wbfs_t*p) -{ - u32 i,j,count=0; - load_freeblocks(p); - for(i=0;in_wbfs_sec/(8*4);i++) + u32 tot_blk = 0, j; + for ( j = 0; j < p->n_wbfs_sec_per_disc; j++ ) + if ( wbfs_ntohs( di->wlba_table[j] ) ) { - u32 v = wbfs_ntohl(p->freeblks[i]); - if(v == ~0U) - count+=32; - else if(v!=0) - for(j=0;j<32;j++) - if (v & (1<disc_info_sz >> p->hd_sec_sz_s; + + for ( i = 0; i < p->max_disc; i++ ) + if ( p->head->disc_table[i] ) + { + if ( count++ == index ) + { + p->read_hdsector( p->callback_data, + p->part_lba + 1 + i*disc_info_sz_lba, 1, p->tmp_buffer ); + if ( header_size > ( int )p->hd_sec_sz ) + header_size = p->hd_sec_sz; + u32 magic = wbfs_ntohl( *( u32* )( p->tmp_buffer + 24 ) ); + if ( magic != 0x5D1C9EA3 ) + { + p->head->disc_table[i] = 0; + return 1; + } + memcpy( header, p->tmp_buffer, header_size ); + if ( size ) + { + u8 *header = wbfs_ioalloc( p->disc_info_sz ); + p->read_hdsector( p->callback_data, + p->part_lba + 1 + i*disc_info_sz_lba, disc_info_sz_lba, header ); + u32 sec_used = wbfs_sector_used( p, ( wbfs_disc_info_t * )header ); + wbfs_iofree( header ); + *size = sec_used << ( p->wbfs_sec_sz_s - 2 ); + } + return 0; + } + } + return 1; +} + +static void load_freeblocks( wbfs_t*p ) +{ + if ( p->freeblks ) + return; + // XXX should handle malloc error.. + p->freeblks = wbfs_ioalloc( ALIGN_LBA( p->n_wbfs_sec / 8 ) ); + p->read_hdsector( p->callback_data, p->part_lba + p->freeblks_lba, ALIGN_LBA( p->n_wbfs_sec / 8 ) >> p->hd_sec_sz_s, p->freeblks ); + +} +u32 wbfs_count_usedblocks( wbfs_t*p ) +{ + u32 i, j, count = 0; + load_freeblocks( p ); + for ( i = 0; i < p->n_wbfs_sec / ( 8*4 ); i++ ) + { + u32 v = wbfs_ntohl( p->freeblks[i] ); + if ( v == ~0U ) + count += 32; + else if ( v != 0 ) + for ( j = 0; j < 32; j++ ) + if ( v & ( 1 << j ) ) + count++; + } + return count; } @@ -387,373 +399,387 @@ u32 wbfs_count_usedblocks(wbfs_t*p) //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;kn_wbfs_sec/(8*4);i++) + u32 i, j; + for ( i = 0; i < p->n_wbfs_sec / ( 8*4 ); i++ ) + { + u32 v = wbfs_ntohl( p->freeblks[i] ); + if ( v != 0 ) { - u32 v = wbfs_ntohl(p->freeblks[i]); - if(v != 0) + for ( j = 0; j < 32; j++ ) + if ( v & ( 1 << j ) ) { - for(j=0;j<32;j++) - if (v & (1<freeblks[i] = wbfs_htonl(v & ~(1<freeblks[i] = wbfs_htonl( v & ~( 1 << j ) ); + return ( i*32 ) + j + 1; } } - return ~0; + } + 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; - u32 v = wbfs_ntohl(p->freeblks[i]); - p->freeblks[i] = wbfs_htonl(v | 1<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); - wiidisc_t *d = 0; - u8 *used = 0; - wbfs_disc_info_t *info = 0; - u8* copy_buffer = 0; - int retval = -1; - int num_wbfs_sect_to_copy; - u32 last_used; - used = wbfs_malloc(p->n_wii_sec_per_disc); + int i, discn; + u32 tot, cur; + u32 wii_sec_per_wbfs_sect = 1 << ( p->wbfs_sec_sz_s - p->wii_sec_sz_s ); + wiidisc_t *d = 0; + u8 *used = 0; + wbfs_disc_info_t *info = 0; + u8* copy_buffer = 0; + int retval = -1; + int num_wbfs_sect_to_copy; + u32 last_used; + used = wbfs_malloc( p->n_wii_sec_per_disc ); - if(!used) - ERROR("unable to alloc memory"); - // copy_1_1 needs disk usage for layers detection - //if(!copy_1_1) - { - d = wd_open_disc(read_src_wii_disc,callback_data); - if(!d) - ERROR("unable to open wii disc"); - wd_build_disc_usage(d,sel,used); - wd_close_disc(d); - d = 0; - } + if ( !used ) + ERROR( "unable to alloc memory" ); + // copy_1_1 needs disk usage for layers detection + //if(!copy_1_1) + { + d = wd_open_disc( read_src_wii_disc, callback_data ); + if ( !d ) + ERROR( "unable to open wii disc" ); + wd_build_disc_usage( d, sel, used ); + wd_close_disc( d ); + d = 0; + } - for(i=0;imax_disc;i++)// find a free slot. - if(p->head->disc_table[i]==0) - break; - if(i==p->max_disc) - ERROR("no space left on device (table full)"); - p->head->disc_table[i] = 1; - discn = i; - load_freeblocks(p); + for ( i = 0; 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 ); - // build disc info - info = wbfs_ioalloc(p->disc_info_sz); - read_src_wii_disc(callback_data,0,0x100,info->disc_header_copy); + // build disc info + info = wbfs_ioalloc( p->disc_info_sz ); + read_src_wii_disc( callback_data, 0, 0x100, info->disc_header_copy ); - copy_buffer = wbfs_ioalloc(p->wii_sec_sz); - if(!copy_buffer) - ERROR("alloc memory"); - tot=0; - cur=0; - num_wbfs_sect_to_copy = p->n_wbfs_sec_per_disc; - // count total number of sectors to write - last_used = 0; - for(i=0; i (p->n_wbfs_sec_per_disc / 2) ) { - // dual layer - num_wbfs_sect_to_copy = p->n_wbfs_sec_per_disc; - } else { - // single layer - num_wbfs_sect_to_copy = p->n_wbfs_sec_per_disc / 2; - } - tot = num_wbfs_sect_to_copy * wii_sec_per_wbfs_sect; - } - /* - // num of hd sectors to copy could be specified directly - if (copy_1_1 > 1) { - u32 hd_sec_per_wii_sec = p->wii_sec_sz / p->hd_sec_sz; - num_wbfs_sect_to_copy = copy_1_1 / hd_sec_per_wii_sec / wii_sec_per_wbfs_sect; - tot = num_wbfs_sect_to_copy * wii_sec_per_wbfs_sect; - }*/ - int ret = 0; - if(spinner) spinner(0,tot); - for(i=0; iwii_sec_sz ); + if ( !copy_buffer ) + ERROR( "alloc memory" ); + tot = 0; + cur = 0; + num_wbfs_sect_to_copy = p->n_wbfs_sec_per_disc; + // count total number of sectors to write + last_used = 0; + for ( i = 0; i < num_wbfs_sect_to_copy; i++ ) + { + if ( block_used( used, i, wii_sec_per_wbfs_sect ) ) + { + tot += wii_sec_per_wbfs_sect; + last_used = i; + } + } + if ( copy_1_1 ) + { + // detect single or dual layer + if ( ( last_used + 1 ) > ( p->n_wbfs_sec_per_disc / 2 ) ) + { + // dual layer + num_wbfs_sect_to_copy = p->n_wbfs_sec_per_disc; + } + else + { + // single layer + num_wbfs_sect_to_copy = p->n_wbfs_sec_per_disc / 2; + } + tot = num_wbfs_sect_to_copy * wii_sec_per_wbfs_sect; + } + /* + // num of hd sectors to copy could be specified directly + if (copy_1_1 > 1) { + u32 hd_sec_per_wii_sec = p->wii_sec_sz / p->hd_sec_sz; + num_wbfs_sect_to_copy = copy_1_1 / hd_sec_per_wii_sec / wii_sec_per_wbfs_sect; + tot = num_wbfs_sect_to_copy * wii_sec_per_wbfs_sect; + }*/ + int ret = 0; + if ( spinner ) spinner( 0, tot ); + for ( i = 0; i < num_wbfs_sect_to_copy; i++ ) + { + u16 bl = 0; + 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; jwbfs_sec_sz>>2)) + (j*(p->wii_sec_sz>>2)); + bl = alloc_block( p ); + if ( bl == 0xffff ) + ERROR( "no space left on device (disc full)" ); + for ( j = 0; j < wii_sec_per_wbfs_sect; j++ ) + { + 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) { - if (copy_1_1 && i > p->n_wbfs_sec_per_disc / 2) { - // end of dual layer data - if (j > 0) { - info->wlba_table[i] = wbfs_htons(bl); - } - spinner(tot,tot); - break; - } - //ERROR("read error"); - printf("\rWARNING: read (%u) error (%d)\n", offset, ret); - } + ret = read_src_wii_disc( callback_data, offset, p->wii_sec_sz, copy_buffer ); + if ( ret ) + { + if ( copy_1_1 && i > p->n_wbfs_sec_per_disc / 2 ) + { + // end of dual layer data + if ( j > 0 ) + { + info->wlba_table[i] = wbfs_htons( bl ); + } + spinner( tot, tot ); + break; + } + //ERROR("read error"); + printf( "\rWARNING: read (%u) error (%d)\n", offset, ret ); + } - //fix the partition table - if(offset == (0x40000>>2)) - wd_fix_partition_table(d, sel, copy_buffer); - p->write_hdsector(p->callback_data, - p->part_lba+bl*(p->wbfs_sec_sz/p->hd_sec_sz) + j*(p->wii_sec_sz/p->hd_sec_sz), - p->wii_sec_sz/p->hd_sec_sz, copy_buffer); - cur++; - if(spinner) - spinner(cur,tot); - } - } - if (ret) break; - info->wlba_table[i] = wbfs_htons(bl); - 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); - retval = 0; + //fix the partition table + if ( offset == ( 0x40000 >> 2 ) ) + wd_fix_partition_table( d, sel, copy_buffer ); + p->write_hdsector( p->callback_data, + p->part_lba + bl*( p->wbfs_sec_sz / p->hd_sec_sz ) + j*( p->wii_sec_sz / p->hd_sec_sz ), + p->wii_sec_sz / p->hd_sec_sz, copy_buffer ); + cur++; + if ( spinner ) + spinner( cur, tot ); + } + } + if ( ret ) break; + info->wlba_table[i] = wbfs_htons( bl ); + 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 ); + retval = 0; error: - if(d) - wd_close_disc(d); - if(used) - wbfs_free(used); - if(info) - wbfs_iofree(info); - if(copy_buffer) - wbfs_iofree(copy_buffer); - // init with all free blocks + if ( d ) + wd_close_disc( d ); + if ( used ) + wbfs_free( used ); + if ( info ) + wbfs_iofree( info ); + if ( copy_buffer ) + wbfs_iofree( copy_buffer ); + // init with all free blocks - return retval; + return retval; } -u32 wbfs_rm_disc(wbfs_t*p, u8* discid) +u32 wbfs_rm_disc( wbfs_t*p, u8* discid ) { - wbfs_disc_t *d = wbfs_open_disc(p,discid); - int i; - int discn = 0; - int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; - if(!d) - return 1; - load_freeblocks(p); - discn = d->i; - for( i=0; i< p->n_wbfs_sec_per_disc; i++) - { - u32 iwlba = wbfs_ntohs(d->header->wlba_table[i]); - if (iwlba) - free_block(p,iwlba); - } - memset(d->header,0,p->disc_info_sz); - p->write_hdsector(p->callback_data,p->part_lba+1+discn*disc_info_sz_lba,disc_info_sz_lba,d->header); - p->head->disc_table[discn] = 0; - wbfs_close_disc(d); - wbfs_sync(p); - return 0; + wbfs_disc_t *d = wbfs_open_disc( p, discid ); + int i; + int discn = 0; + int disc_info_sz_lba = p->disc_info_sz >> p->hd_sec_sz_s; + if ( !d ) + return 1; + load_freeblocks( p ); + discn = d->i; + for ( i = 0; i < p->n_wbfs_sec_per_disc; i++ ) + { + u32 iwlba = wbfs_ntohs( d->header->wlba_table[i] ); + if ( iwlba ) + free_block( p, iwlba ); + } + memset( d->header, 0, p->disc_info_sz ); + p->write_hdsector( p->callback_data, p->part_lba + 1 + discn*disc_info_sz_lba, disc_info_sz_lba, d->header ); + p->head->disc_table[discn] = 0; + wbfs_close_disc( d ); + wbfs_sync( p ); + return 0; } -u32 wbfs_ren_disc(wbfs_t*p, u8* discid, u8* newname) +u32 wbfs_ren_disc( wbfs_t*p, u8* discid, u8* newname ) { - wbfs_disc_t *d = wbfs_open_disc(p,discid); - int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; + wbfs_disc_t *d = wbfs_open_disc( p, discid ); + int disc_info_sz_lba = p->disc_info_sz >> p->hd_sec_sz_s; - if(!d) - return 1; + if ( !d ) + return 1; - memset(d->header->disc_header_copy+0x20, 0, 0x40); - strncpy((char *) d->header->disc_header_copy+0x20, (char *) newname, 0x39); + memset( d->header->disc_header_copy + 0x20, 0, 0x40 ); + strncpy( ( char * ) d->header->disc_header_copy + 0x20, ( char * ) newname, 0x39 ); - p->write_hdsector(p->callback_data,p->part_lba+1+d->i*disc_info_sz_lba,disc_info_sz_lba,d->header); - wbfs_close_disc(d); - return 0; + p->write_hdsector( p->callback_data, p->part_lba + 1 + d->i*disc_info_sz_lba, disc_info_sz_lba, d->header ); + wbfs_close_disc( d ); + return 0; } -u32 wbfs_rID_disc(wbfs_t*p, u8* discid, u8* newID) +u32 wbfs_rID_disc( wbfs_t*p, u8* discid, u8* newID ) { - wbfs_disc_t *d = wbfs_open_disc(p,discid); - int disc_info_sz_lba = p->disc_info_sz>>p->hd_sec_sz_s; + wbfs_disc_t *d = wbfs_open_disc( p, discid ); + int disc_info_sz_lba = p->disc_info_sz >> p->hd_sec_sz_s; - if(!d) - return 1; + if ( !d ) + return 1; - memset(d->header->disc_header_copy, 0, 0x10); - strncpy((char *) d->header->disc_header_copy, (char *) newID, 0x9); + memset( d->header->disc_header_copy, 0, 0x10 ); + strncpy( ( char * ) d->header->disc_header_copy, ( char * ) newID, 0x9 ); - p->write_hdsector(p->callback_data,p->part_lba+1+d->i*disc_info_sz_lba,disc_info_sz_lba,d->header); - wbfs_close_disc(d); - return 0; + p->write_hdsector( p->callback_data, p->part_lba + 1 + d->i*disc_info_sz_lba, disc_info_sz_lba, d->header ); + wbfs_close_disc( d ); + return 0; } // trim the file-system to its minimum size -u32 wbfs_trim(wbfs_t*p) +u32 wbfs_trim( wbfs_t*p ) { - u32 maxbl; - load_freeblocks(p); - maxbl = alloc_block(p); - p->n_hd_sec = maxbl<<(p->wbfs_sec_sz_s-p->hd_sec_sz_s); - p->head->n_hd_sec = wbfs_htonl(p->n_hd_sec); - // make all block full - memset(p->freeblks,0,p->n_wbfs_sec/8); - wbfs_sync(p); - // os layer will truncate the file. - return maxbl; + u32 maxbl; + load_freeblocks( p ); + maxbl = alloc_block( p ); + p->n_hd_sec = maxbl << ( p->wbfs_sec_sz_s - p->hd_sec_sz_s ); + p->head->n_hd_sec = wbfs_htonl( p->n_hd_sec ); + // make all block full + memset( p->freeblks, 0, p->n_wbfs_sec / 8 ); + wbfs_sync( p ); + // os layer will truncate the file. + return maxbl; } // data extraction -u32 wbfs_extract_disc(wbfs_disc_t*d, rw_sector_callback_t write_dst_wii_sector,void *callback_data,progress_callback_t spinner) +u32 wbfs_extract_disc( wbfs_disc_t*d, rw_sector_callback_t write_dst_wii_sector, void *callback_data, progress_callback_t spinner ) { - wbfs_t *p = d->p; - u8* copy_buffer = 0; - int i; - int src_wbs_nlb=p->wbfs_sec_sz/p->hd_sec_sz; - int dst_wbs_nlb=p->wbfs_sec_sz/p->wii_sec_sz; - copy_buffer = wbfs_ioalloc(p->wbfs_sec_sz); - if(!copy_buffer) - ERROR("alloc memory"); + wbfs_t *p = d->p; + u8* copy_buffer = 0; + int i; + int src_wbs_nlb = p->wbfs_sec_sz / p->hd_sec_sz; + int dst_wbs_nlb = p->wbfs_sec_sz / p->wii_sec_sz; + copy_buffer = wbfs_ioalloc( p->wbfs_sec_sz ); + if ( !copy_buffer ) + ERROR( "alloc memory" ); - for( i=0; i< p->n_wbfs_sec_per_disc; i++) + for ( i = 0; i < p->n_wbfs_sec_per_disc; i++ ) + { + u32 iwlba = wbfs_ntohs( d->header->wlba_table[i] ); + if ( iwlba ) { - u32 iwlba = wbfs_ntohs(d->header->wlba_table[i]); - if (iwlba) - { - - if(spinner) - spinner(i,p->n_wbfs_sec_per_disc); - p->read_hdsector(p->callback_data, p->part_lba + iwlba*src_wbs_nlb, src_wbs_nlb, copy_buffer); - write_dst_wii_sector(callback_data, i*dst_wbs_nlb, dst_wbs_nlb, copy_buffer); - } + + if ( spinner ) + spinner( i, p->n_wbfs_sec_per_disc ); + p->read_hdsector( p->callback_data, p->part_lba + iwlba*src_wbs_nlb, src_wbs_nlb, copy_buffer ); + write_dst_wii_sector( callback_data, i*dst_wbs_nlb, dst_wbs_nlb, copy_buffer ); } - wbfs_iofree(copy_buffer); - return 0; + } + wbfs_iofree( copy_buffer ); + return 0; error: - return 1; + return 1; } float wbfs_estimate_disc ( - wbfs_t *p, read_wiidisc_callback_t read_src_wii_disc, - void *callback_data, - partition_selector_t sel) + wbfs_t *p, read_wiidisc_callback_t read_src_wii_disc, + void *callback_data, + partition_selector_t sel ) { - u8 *b; - int i; - u32 tot; - u32 wii_sec_per_wbfs_sect = 1 << (p->wbfs_sec_sz_s-p->wii_sec_sz_s); - wiidisc_t *d = 0; - u8 *used = 0; - wbfs_disc_info_t *info = 0; + u8 *b; + int i; + u32 tot; + u32 wii_sec_per_wbfs_sect = 1 << ( p->wbfs_sec_sz_s - p->wii_sec_sz_s ); + wiidisc_t *d = 0; + u8 *used = 0; + wbfs_disc_info_t *info = 0; - tot = 0; + tot = 0; - used = wbfs_malloc(p->n_wii_sec_per_disc); - if (!used) - { - ERROR("unable to alloc memory"); - } + used = wbfs_malloc( p->n_wii_sec_per_disc ); + if ( !used ) + { + ERROR( "unable to alloc memory" ); + } - d = wd_open_disc(read_src_wii_disc, callback_data); - if (!d) - { - ERROR("unable to open wii disc"); - } + d = wd_open_disc( read_src_wii_disc, callback_data ); + if ( !d ) + { + ERROR( "unable to open wii disc" ); + } - wd_build_disc_usage(d,sel,used); - wd_close_disc(d); - d = 0; + wd_build_disc_usage( d, sel, used ); + wd_close_disc( d ); + d = 0; - info = wbfs_ioalloc(p->disc_info_sz); - b = (u8 *)info; - read_src_wii_disc(callback_data, 0, 0x100, info->disc_header_copy); + info = wbfs_ioalloc( p->disc_info_sz ); + b = ( u8 * )info; + read_src_wii_disc( callback_data, 0, 0x100, info->disc_header_copy ); - //fprintf(stderr, "estimating %c%c%c%c%c%c %s...\n",b[0], b[1], b[2], b[3], b[4], b[5], b + 0x20); + //fprintf(stderr, "estimating %c%c%c%c%c%c %s...\n",b[0], b[1], b[2], b[3], b[4], b[5], b + 0x20); - for (i = 0; i < p->n_wbfs_sec_per_disc; i++) - { - if (block_used(used, i, wii_sec_per_wbfs_sect)) - { - tot++; - } - } - //memcpy(header, b,0x100); + for ( i = 0; i < p->n_wbfs_sec_per_disc; i++ ) + { + if ( block_used( used, i, wii_sec_per_wbfs_sect ) ) + { + tot++; + } + } + //memcpy(header, b,0x100); error: - if (d) - wd_close_disc(d); + if ( d ) + wd_close_disc( d ); - if (used) - wbfs_free(used); + if ( used ) + wbfs_free( used ); - if (info) - wbfs_iofree(info); + if ( info ) + wbfs_iofree( info ); - return tot * (((p->wbfs_sec_sz*1.0) / p->hd_sec_sz) * 512); + return tot * ( ( ( p->wbfs_sec_sz*1.0 ) / p->hd_sec_sz ) * 512 ); } -u32 wbfs_size_disc(wbfs_t*p,read_wiidisc_callback_t read_src_wii_disc, - void *callback_data,partition_selector_t sel, - u32 *comp_size, u32 *real_size) +u32 wbfs_size_disc( wbfs_t*p, read_wiidisc_callback_t read_src_wii_disc, + void *callback_data, partition_selector_t sel, + u32 *comp_size, u32 *real_size ) { - int i; - u32 tot = 0, last = 0; - u32 wii_sec_per_wbfs_sect = 1<<(p->wbfs_sec_sz_s-p->wii_sec_sz_s); - wiidisc_t *d = 0; - u8 *used = 0; - used = wbfs_malloc(p->n_wii_sec_per_disc); - if(!used) - ERROR("unable to alloc memory"); - d = wd_open_disc(read_src_wii_disc,callback_data); - if(!d) - ERROR("unable to open wii disc"); - wd_build_disc_usage(d,sel,used); - wd_close_disc(d); - d = 0; + int i; + u32 tot = 0, last = 0; + u32 wii_sec_per_wbfs_sect = 1 << ( p->wbfs_sec_sz_s - p->wii_sec_sz_s ); + wiidisc_t *d = 0; + u8 *used = 0; + used = wbfs_malloc( p->n_wii_sec_per_disc ); + if ( !used ) + ERROR( "unable to alloc memory" ); + d = wd_open_disc( read_src_wii_disc, callback_data ); + if ( !d ) + ERROR( "unable to open wii disc" ); + wd_build_disc_usage( d, sel, used ); + wd_close_disc( d ); + d = 0; - // count total number to write for spinner - for(i=0; in_wbfs_sec_per_disc;i++) { - if(block_used(used,i,wii_sec_per_wbfs_sect)) { - tot += wii_sec_per_wbfs_sect; - last = i * wii_sec_per_wbfs_sect; - } - } + // count total number to write for spinner + for ( i = 0; i < p->n_wbfs_sec_per_disc; i++ ) + { + if ( block_used( used, i, wii_sec_per_wbfs_sect ) ) + { + tot += wii_sec_per_wbfs_sect; + last = i * wii_sec_per_wbfs_sect; + } + } error: - if(d) - wd_close_disc(d); - if(used) - wbfs_free(used); + if ( d ) + wd_close_disc( d ); + if ( used ) + wbfs_free( used ); - *comp_size = tot; - *real_size = last; - - return 0; + *comp_size = tot; + *real_size = last; + + return 0; } // offset is pointing 32bit words to address the whole dvd, although len is in bytes @@ -763,58 +789,61 @@ 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; + wiidisc_t *wd = 0; + int ret = 0; - wd = wd_open_disc(read_wiidisc_wbfsdisc, d); - if (!wd) { - ERROR("opening wbfs disc"); - return -1; - } - wd->extracted_size = 0; - *data = wd_extract_file(wd, ONLY_GAME_PARTITION, path); - ret = wd->extracted_size; - if (!*data) { - //ERROR("file not found"); - ret = -1; - } - wd_close_disc(wd); + wd = wd_open_disc( read_wiidisc_wbfsdisc, d ); + if ( !wd ) + { + ERROR( "opening wbfs disc" ); + return -1; + } + wd->extracted_size = 0; + *data = wd_extract_file( wd, ONLY_GAME_PARTITION, path ); + ret = wd->extracted_size; + if ( !*data ) + { + //ERROR("file not found"); + ret = -1; + } + wd_close_disc( wd ); error: - return ret; + 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; - wbfs_t *p = d->p; - int src_wbs_nlb = p->wbfs_sec_sz / p->hd_sec_sz; - int i, ret, last = 0; - for( i=0; i< p->n_wbfs_sec_per_disc; i++) - { - u32 iwlba = wbfs_ntohs(d->header->wlba_table[i]); - if (iwlba) - { - ret = append_fragment(callback_data, - i * src_wbs_nlb, // offset - p->part_lba + iwlba * src_wbs_nlb, // sector - src_wbs_nlb); // count - if (ret) return ret; // error - last = i; - } - } - if (last < p->n_wbfs_sec_per_disc / 2) { - last = p->n_wbfs_sec_per_disc / 2; - } - u32 size = last * src_wbs_nlb; - append_fragment(callback_data, size, 0, 0); // set size - return 0; + if ( !d ) return -1; + wbfs_t *p = d->p; + int src_wbs_nlb = p->wbfs_sec_sz / p->hd_sec_sz; + int i, ret, last = 0; + for ( i = 0; i < p->n_wbfs_sec_per_disc; i++ ) + { + u32 iwlba = wbfs_ntohs( d->header->wlba_table[i] ); + if ( iwlba ) + { + ret = append_fragment( callback_data, + i * src_wbs_nlb, // offset + p->part_lba + iwlba * src_wbs_nlb, // sector + src_wbs_nlb ); // count + if ( ret ) return ret; // error + last = i; + } + } + if ( last < p->n_wbfs_sec_per_disc / 2 ) + { + last = p->n_wbfs_sec_per_disc / 2; + } + u32 size = last * src_wbs_nlb; + append_fragment( callback_data, size, 0, 0 ); // set size + return 0; } // wrapper for reading .iso files using wbfs apis @@ -823,38 +852,41 @@ int wbfs_get_fragments(wbfs_disc_t *d, _frag_append_t append_fragment, void *cal #include // offset is pointing 32bit words to address the whole dvd, although len is in bytes -int wbfs_iso_file_read(wbfs_disc_t*d,u32 offset, u8 *data, u32 len) +int wbfs_iso_file_read( wbfs_disc_t*d, u32 offset, u8 *data, u32 len ) { - if (!d || d->p != &wbfs_iso_file) return -1; - int fd = (int)d->header; - off_t off = ((u64)offset) << 2; - off_t ret_off; - int ret; - ret_off = lseek(fd, off, SEEK_SET); - if (ret_off != off) return -1; - ret = read(fd, data, len); - if (ret != len) return -2; - return 0; + if ( !d || d->p != &wbfs_iso_file ) return -1; + int fd = ( int )d->header; + off_t off = ( ( u64 )offset ) << 2; + off_t ret_off; + int ret; + ret_off = lseek( fd, off, SEEK_SET ); + if ( ret_off != off ) return -1; + ret = read( fd, data, len ); + if ( ret != len ) return -2; + return 0; } -u32 wbfs_disc_sector_used(wbfs_disc_t *d, u32 *num_blk) +u32 wbfs_disc_sector_used( wbfs_disc_t *d, u32 *num_blk ) { - if (d->p == &wbfs_iso_file) { - int fd = (int)d->header; - struct stat st; - if (fstat(fd, &st) == -1) return 0; - if (num_blk) { - *num_blk = (st.st_size >> 9); // in 512 units - } - return st.st_blocks; // in 512 units (can be sparse) - } - u32 last_blk = 0; - u32 ret; - ret = wbfs_sector_used2(d->p, d->header, &last_blk); - if (num_blk) { - *num_blk = last_blk + 1; - } - return ret; + if ( d->p == &wbfs_iso_file ) + { + int fd = ( int )d->header; + struct stat st; + if ( fstat( fd, &st ) == -1 ) return 0; + if ( num_blk ) + { + *num_blk = ( st.st_size >> 9 ); // in 512 units + } + return st.st_blocks; // in 512 units (can be sparse) + } + u32 last_blk = 0; + u32 ret; + ret = wbfs_sector_used2( d->p, d->header, &last_blk ); + if ( num_blk ) + { + *num_blk = last_blk + 1; + } + return ret; } diff --git a/source/libwbfs/libwbfs.h b/source/libwbfs/libwbfs.h index 0bdc502a..7b82d31e 100644 --- a/source/libwbfs/libwbfs.h +++ b/source/libwbfs/libwbfs.h @@ -8,76 +8,77 @@ #include "wiidisc.h" #ifdef __cplusplus - extern "C" { +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 u32 be32_t; + typedef u16 be16_t; -typedef struct wbfs_head -{ + typedef struct wbfs_head + { be32_t magic; // parameters copied in the partition for easy dumping, and bug reports - be32_t n_hd_sec; // total number of hd_sec in this partition + 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 ; + u8 disc_table[0]; // size depends on hd sector size + } __attribute( ( packed ) ) wbfs_head_t ; -typedef struct wbfs_disc_info -{ + typedef struct wbfs_disc_info + { u8 disc_header_copy[0x100]; be16_t wlba_table[0]; -}wbfs_disc_info_t; + } wbfs_disc_info_t; // WBFS first wbfs_sector structure: // // ----------- // | 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 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 -{ + typedef struct wbfs_s + { 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 + u32 n_hd_sec; // the number of hd sector in the wbfs partition /* standard wii sector (0x8000 bytes) */ u32 wii_sec_sz; @@ -106,141 +107,141 @@ typedef struct wbfs_s u32 n_disc_open; -}wbfs_t; + } wbfs_t; -typedef struct wbfs_disc_s -{ + typedef struct wbfs_disc_s + { wbfs_t *p; - wbfs_disc_info_t *header; // pointer to wii header - int i; // disc index in the wbfs header (disc_table) -}wbfs_disc_t; + wbfs_disc_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); + /*! @brief open a MSDOS partitionned harddrive. This tries to find a wbfs partition into the harddrive + @param read_hdsector,write_hdsector: accessors to a harddrive + @hd_sector_size: size of the hd sector. Can be set to zero if the partition in already initialized + @num_hd_sector: number of sectors in this disc. Can be set to zero if the partition in already initialized + @reset: not implemented, This will format the whole harddrive with one wbfs partition that fits the whole disk. + calls wbfs_error() to have textual meaning of errors + @return NULL in case of error + */ + wbfs_t*wbfs_open_hd( rw_sector_callback_t read_hdsector, + rw_sector_callback_t write_hdsector, + void *callback_data, + int hd_sector_size, int num_hd_sector, int reset ); -/*! @brief open a wbfs partition - @param read_hdsector,write_hdsector: accessors to the partition - @hd_sector_size: size of the hd sector. Can be set to zero if the partition in already initialized - @num_hd_sector: number of sectors in this partition. Can be set to zero if the partition in already initialized - @partition_lba: The partitio offset if you provided accessors to the whole disc. - @reset: initialize the partition with an empty wbfs. - calls wbfs_error() to have textual meaning of errors - @return NULL in case of error -*/ -wbfs_t*wbfs_open_partition(rw_sector_callback_t read_hdsector, - rw_sector_callback_t write_hdsector, - void *callback_data, - int hd_sector_size, int num_hd_sector, u32 partition_lba, int reset); + /*! @brief open a wbfs partition + @param read_hdsector,write_hdsector: accessors to the partition + @hd_sector_size: size of the hd sector. Can be set to zero if the partition in already initialized + @num_hd_sector: number of sectors in this partition. Can be set to zero if the partition in already initialized + @partition_lba: The partitio offset if you provided accessors to the whole disc. + @reset: initialize the partition with an empty wbfs. + calls wbfs_error() to have textual meaning of errors + @return NULL in case of error + */ + wbfs_t*wbfs_open_partition( rw_sector_callback_t read_hdsector, + rw_sector_callback_t write_hdsector, + void *callback_data, + int hd_sector_size, int num_hd_sector, u32 partition_lba, int reset ); -/*! @brief close a wbfs partition, and sync the metadatas to the disc */ -void wbfs_close(wbfs_t*); + /*! @brief close a wbfs partition, and sync the metadatas to the disc */ + void wbfs_close( wbfs_t* ); -/*! @brief open a disc inside a wbfs partition use a 6 char discid+vendorid - @return NULL if discid is not present -*/ -wbfs_disc_t *wbfs_open_disc(wbfs_t* p, u8 *diskid); + /*! @brief open a disc inside a wbfs partition use a 6 char discid+vendorid + @return NULL if discid is not present + */ + wbfs_disc_t *wbfs_open_disc( wbfs_t* p, u8 *diskid ); -/*! @brief close a already open disc inside a wbfs partition */ -void wbfs_close_disc(wbfs_disc_t*d); + /*! @brief close a already open disc inside a wbfs partition */ + void wbfs_close_disc( wbfs_disc_t*d ); -u32 wbfs_sector_used(wbfs_t *p,wbfs_disc_info_t *di); -u32 wbfs_sector_used2(wbfs_t *p,wbfs_disc_info_t *di, u32 *last_blk); + u32 wbfs_sector_used( wbfs_t *p, wbfs_disc_info_t *di ); + u32 wbfs_sector_used2( wbfs_t *p, wbfs_disc_info_t *di, u32 *last_blk ); -/*! @brief accessor to the wii disc - @param d: a pointer to already open disc - @param offset: an offset inside the disc, *points 32bit words*, allowing to access 16GB data - @param len: The length of the data to fetch, in *bytes* - */ + /*! @brief accessor to the wii disc + @param d: a pointer to already open disc + @param offset: an offset inside the disc, *points 32bit words*, allowing to access 16GB data + @param len: The length of the data to fetch, in *bytes* + */ // offset is pointing 32bit words to address the whole dvd, although len is in bytes -int wbfs_disc_read(wbfs_disc_t*d,u32 offset, u32 len, u8 *data); + int wbfs_disc_read( wbfs_disc_t*d, u32 offset, u32 len, u8 *data ); -/*! @return the number of discs inside the partition */ -u32 wbfs_count_discs(wbfs_t*p); -/*! get the disc info of ith disc inside the partition. It correspond to the first 0x100 bytes of the wiidvd - http://www.wiibrew.org/wiki/Wiidisc#Header - @param i: index of the disc inside the partition - @param header: pointer to 0x100 bytes to write the header - @size: optional pointer to a 32bit word that will get the size in 32bit words of the DVD taken on the partition. -*/ -u32 wbfs_get_disc_info(wbfs_t*p, u32 i,u8 *header,int header_size,u32 *size); + /*! @return the number of discs inside the partition */ + u32 wbfs_count_discs( wbfs_t*p ); + /*! get the disc info of ith disc inside the partition. It correspond to the first 0x100 bytes of the wiidvd + http://www.wiibrew.org/wiki/Wiidisc#Header + @param i: index of the disc inside the partition + @param header: pointer to 0x100 bytes to write the header + @size: optional pointer to a 32bit word that will get the size in 32bit words of the DVD taken on the partition. + */ + u32 wbfs_get_disc_info( wbfs_t*p, u32 i, u8 *header, int header_size, u32 *size ); -/*! get the number of used block of the partition. - to be multiplied by p->wbfs_sec_sz (use 64bit multiplication) to have the number in bytes -*/ -u32 wbfs_count_usedblocks(wbfs_t*p); + /*! get the number of used block of the partition. + to be multiplied by p->wbfs_sec_sz (use 64bit multiplication) to have the number in bytes + */ + u32 wbfs_count_usedblocks( wbfs_t*p ); -/******************* write access ******************/ + /******************* write access ******************/ -/*! add a wii dvd inside the partition - @param read_src_wii_disc: a callback to access the wii dvd. offsets are in 32bit, len in bytes! - @callback_data: private data passed to the callback - @spinner: a pointer to a function that is regulary called to update a progress bar. - @sel: selects which partitions to copy. - @copy_1_1: makes a 1:1 copy, whenever a game would not use the wii disc format, and some data is hidden outside the filesystem. - */ -u32 wbfs_add_disc(wbfs_t*p,read_wiidisc_callback_t read_src_wii_disc, void *callback_data, - progress_callback_t spinner,partition_selector_t sel,int copy_1_1); + /*! add a wii dvd inside the partition + @param read_src_wii_disc: a callback to access the wii dvd. offsets are in 32bit, len in bytes! + @callback_data: private data passed to the callback + @spinner: a pointer to a function that is regulary called to update a progress bar. + @sel: selects which partitions to copy. + @copy_1_1: makes a 1:1 copy, whenever a game would not use the wii disc format, and some data is hidden outside the filesystem. + */ + u32 wbfs_add_disc( wbfs_t*p, read_wiidisc_callback_t read_src_wii_disc, void *callback_data, + progress_callback_t spinner, partition_selector_t sel, int copy_1_1 ); -/*! remove a wiidvd inside a partition */ -u32 wbfs_rm_disc(wbfs_t*p, u8* discid); + /*! remove a wiidvd inside a partition */ + u32 wbfs_rm_disc( wbfs_t*p, u8* discid ); -/*! rename a game */ -u32 wbfs_ren_disc(wbfs_t*p, u8* discid, u8* newname); + /*! rename a game */ + u32 wbfs_ren_disc( wbfs_t*p, u8* discid, u8* newname ); -/* change ID of a game*/ -u32 wbfs_rID_disc(wbfs_t*p, u8* discid, u8* newID); -/*! trim the file-system to its minimum size - This allows to use wbfs as a wiidisc container - */ -u32 wbfs_trim(wbfs_t*p); + /* change ID of a game*/ + u32 wbfs_rID_disc( wbfs_t*p, u8* discid, u8* newID ); + /*! trim the file-system to its minimum size + This allows to use wbfs as a wiidisc container + */ + u32 wbfs_trim( wbfs_t*p ); -/*! extract a disc from the wbfs, unused sectors are just untouched, allowing descent filesystem to only really usefull space to store the disc. -Even if the filesize is 4.7GB, the disc usage will be less. - */ -u32 wbfs_extract_disc(wbfs_disc_t*d, rw_sector_callback_t write_dst_wii_sector,void *callback_data,progress_callback_t spinner); + /*! extract a disc from the wbfs, unused sectors are just untouched, allowing descent filesystem to only really usefull space to store the disc. + Even if the filesize is 4.7GB, the disc usage will be less. + */ + u32 wbfs_extract_disc( wbfs_disc_t*d, rw_sector_callback_t write_dst_wii_sector, void *callback_data, progress_callback_t spinner ); -/*! extract a file from the wii disc filesystem. - E.G. Allows to extract the opening.bnr to install a game as a system menu channel - */ -int wbfs_extract_file(wbfs_disc_t*d, char *path, void **data); + /*! extract a file from the wii disc filesystem. + E.G. Allows to extract the opening.bnr to install a game as a system menu channel + */ + int wbfs_extract_file( wbfs_disc_t*d, char *path, void **data ); // remove some sanity checks -void wbfs_set_force_mode(int force); + void wbfs_set_force_mode( int force ); -float wbfs_estimate_disc( - wbfs_t *p, read_wiidisc_callback_t read_src_wii_disc, - void *callback_data, - partition_selector_t sel); + float wbfs_estimate_disc( + wbfs_t *p, read_wiidisc_callback_t read_src_wii_disc, + void *callback_data, + partition_selector_t sel ); // compressed and real size -u32 wbfs_size_disc(wbfs_t*p,read_wiidisc_callback_t read_src_wii_disc, - void *callback_data,partition_selector_t sel, - u32 *comp_size, u32 *real_size); + u32 wbfs_size_disc( wbfs_t*p, read_wiidisc_callback_t read_src_wii_disc, + void *callback_data, partition_selector_t sel, + u32 *comp_size, u32 *real_size ); -typedef int (*_frag_append_t)(void *ff, u32 offset, u32 sector, u32 count); -int wbfs_get_fragments(wbfs_disc_t *d, _frag_append_t append_fragment, void *callback_data); + typedef int ( *_frag_append_t )( void *ff, u32 offset, u32 sector, u32 count ); + int wbfs_get_fragments( wbfs_disc_t *d, _frag_append_t append_fragment, void *callback_data ); -extern wbfs_t wbfs_iso_file; -u32 wbfs_disc_sector_used(wbfs_disc_t *d, u32 *num_blk); -int wbfs_iso_file_read(wbfs_disc_t*d,u32 offset, u8 *data, u32 len); + extern wbfs_t wbfs_iso_file; + u32 wbfs_disc_sector_used( wbfs_disc_t *d, u32 *num_blk ); + int wbfs_iso_file_read( wbfs_disc_t*d, u32 offset, u8 *data, u32 len ); #ifdef __cplusplus - } +} #endif /* __cplusplus */ #endif diff --git a/source/libwbfs/libwbfs_os.h b/source/libwbfs/libwbfs_os.h index 45f33464..32cfc2f7 100644 --- a/source/libwbfs/libwbfs_os.h +++ b/source/libwbfs/libwbfs_os.h @@ -6,28 +6,28 @@ #define debug_printf(fmt, ...); #include -#define wbfs_fatal(x) do { printf("\nwbfs panic: %s\n\n",x); while(1); } while(0) -#define wbfs_error(x) do { printf("\nwbfs error: %s\n\n",x); } while(0) +#define wbfs_fatal(x) do { printf("\nwbfs panic: %s\n\n",x); while(1); } while(0) +#define wbfs_error(x) do { printf("\nwbfs error: %s\n\n",x); } while(0) #include #include -#define wbfs_malloc(x) malloc(x) -#define wbfs_free(x) free(x) -#define wbfs_ioalloc(x) memalign(32, ((x) + 31) & ~31) -#define wbfs_iofree(x) free(x) -#define wbfs_be16(x) (*((u16*)(x))) -#define wbfs_be32(x) (*((u32*)(x))) -#define wbfs_ntohl(x) (x) -#define wbfs_htonl(x) (x) -#define wbfs_ntohs(x) (x) -#define wbfs_htons(x) (x) +#define wbfs_malloc(x) malloc(x) +#define wbfs_free(x) free(x) +#define wbfs_ioalloc(x) memalign(32, ((x) + 31) & ~31) +#define wbfs_iofree(x) free(x) +#define wbfs_be16(x) (*((u16*)(x))) +#define wbfs_be32(x) (*((u32*)(x))) +#define wbfs_ntohl(x) (x) +#define wbfs_htonl(x) (x) +#define wbfs_ntohs(x) (x) +#define wbfs_htons(x) (x) #include -#define wbfs_memcmp(x,y,z) memcmp(x,y,z) -#define wbfs_memcpy(x,y,z) memcpy(x,y,z) -#define wbfs_memset(x,y,z) memset(x,y,z) +#define wbfs_memcmp(x,y,z) memcmp(x,y,z) +#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 baf8c871..18acd6f3 100644 --- a/source/libwbfs/rijndael.c +++ b/source/libwbfs/rijndael.c @@ -3,9 +3,9 @@ Written by Mike Scott 21st April 1999 mike@compapp.dcu.ie - Permission for free direct or derivative use is granted subject - to compliance with any conditions that the originators of the - algorithm place on its exploitation. + Permission for free direct or derivative use is granted subject + to compliance with any conditions that the originators of the + algorithm place on its exploitation. */ @@ -28,371 +28,380 @@ /* 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]; -static u8 ptab[256],ltab[256]; +static u8 ptab[256], ltab[256]; static u32 ftable[256]; static u32 rtable[256]; static u32 rco[30]; /* Parameter-dependent data */ -int Nk,Nb,Nr; -u8 fi[24],ri[24]; +int Nk, Nb, Nr; +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; - a<<=1; - a^=b; + 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); - b[0]=fbsub[b[0]]; - b[1]=fbsub[b[1]]; - b[2]=fbsub[b[2]]; - b[3]=fbsub[b[3]]; - return pack(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 ); } -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]); + 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] ); } -static u32 InvMixCol(u32 x) +static u32 InvMixCol( u32 x ) { /* matrix Multiplication */ - u32 y,m; + u32 y, m; u8 b[4]; - m=pack(InCo); - b[3]=product(m,x); - m=ROTL24(m); - b[2]=product(m,x); - m=ROTL24(m); - b[1]=product(m,x); - m=ROTL24(m); - b[0]=product(m,x); - y=pack(b); + m = pack( InCo ); + b[3] = product( m, x ); + m = ROTL24( m ); + b[2] = product( m, x ); + m = ROTL24( m ); + b[1] = product( m, x ); + m = ROTL24( m ); + 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]; + u8 y, b[4]; - /* use 3 as primitive root to generate power and log tables */ + /* use 3 as primitive root to generate power and log tables */ - ltab[0]=0; - ptab[0]=1; ltab[1]=0; - ptab[1]=3; ltab[3]=1; - for (i=2;i<256;i++) + ltab[0] = 0; + ptab[0] = 1; ltab[1] = 0; + ptab[1] = 3; ltab[3] = 1; + for ( i = 2; i < 256; i++ ) { - ptab[i]=ptab[i-1]^xtime(ptab[i-1]); - ltab[ptab[i]]=i; - } - - /* affine transformation:- each bit is xored with itself shifted one bit */ - - fbsub[0]=0x63; - rbsub[0x63]=0; - for (i=1;i<256;i++) - { - y=ByteSub((u8)i); - fbsub[i]=y; rbsub[y]=i; + ptab[i] = ptab[i-1] ^ xtime( ptab[i-1] ); + ltab[ptab[i]] = i; } - for (i=0,y=1;i<30;i++) + /* affine transformation:- each bit is xored with itself shifted one bit */ + + fbsub[0] = 0x63; + rbsub[0x63] = 0; + for ( i = 1; i < 256; i++ ) { - rco[i]=y; - y=xtime(y); + y = ByteSub( ( u8 )i ); + fbsub[i] = y; rbsub[y] = i; } - /* calculate forward and reverse tables */ - for (i=0;i<256;i++) + for ( i = 0, y = 1; i < 30; i++ ) { - y=fbsub[i]; - b[3]=y^xtime(y); b[2]=y; - b[1]=y; b[0]=xtime(y); - ftable[i]=pack(b); + rco[i] = y; + y = xtime( y ); + } - 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); + /* calculate forward and reverse tables */ + for ( i = 0; i < 256; i++ ) + { + y = fbsub[i]; + b[3] = y ^ xtime( y ); b[2] = y; + b[1] = y; b[0] = xtime( y ); + 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 ); } } -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 */ - /* Key Scheduler. Create expanded encryption key */ - int i,j,k,m,N; - int C1,C2,C3; + /* currently nb,bk = 4, 6 or 8 */ + /* key comes as 4*Nk bytes */ + /* Key Scheduler. Create expanded encryption key */ + int i, j, k, m, N; + int C1, C2, C3; u32 CipherKey[8]; - - Nb=nb; Nk=nk; - /* Nr is number of rounds */ - if (Nb>=Nk) Nr=6+Nb; - else Nr=6+Nk; + Nb = nb; Nk = nk; - C1=1; - if (Nb<8) { C2=2; C3=3; } - else { C2=3; C3=4; } + /* Nr is number of rounds */ + if ( Nb >= Nk ) Nr = 6 + Nb; + else Nr = 6 + Nk; - /* pre-calculate forward and reverse increments */ - for (m=j=0;j>8)])^ - ROTL16(ftable[(u8)(x[fi[m+1]]>>16)])^ - ROTL24(ftable[x[fi[m+2]]>>24]); + /* 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] ); } - t=x; x=y; y=t; /* swap pointers */ + t = x; x = y; y = t; /* swap pointers */ } -/* Last Round - unroll if possible */ - for (m=j=0;j>8)])^ - ROTL16((u32)fbsub[(u8)(x[fi[m+1]]>>16)])^ - ROTL24((u32)fbsub[x[fi[m+2]]>>24]); - } - for (i=j=0;i> 8 )] ) ^ + ROTL16( ( 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 ) { - 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; + int i, j, k, m; + u32 a[8], b[8], *x, *y, *t; - for (i=j=0;i>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>8)])^ - ROTL16((u32)rbsub[(u8)(x[ri[m+1]]>>16)])^ - ROTL24((u32)rbsub[x[ri[m+2]]>>24]); - } - for (i=j=0;i> 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 ) { - 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) { - gentables(); - gkey(4, 4,(char*) key); +void aes_set_key( u8 *key ) +{ + gentables(); + gkey( 4, 4, ( char* ) key ); } // CBC mode decryption -void aes_decrypt(u8 *iv, u8 *inbuf, u8 *outbuf, unsigned long long len) { - u8 block[16]; - unsigned int blockno = 0, i; +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); + //printf("aes_decrypt(%p, %p, %p, %lld)\n", iv, inbuf, outbuf, len); - for (blockno = 0; blockno <= (len / sizeof(block)); blockno++) { - unsigned int fraction; - if (blockno == (len / sizeof(block))) { // last block - fraction = len % sizeof(block); - if (fraction == 0) break; - memset(block, 0, sizeof(block)); - } else fraction = 16; + for ( blockno = 0; blockno <= ( len / sizeof( block ) ); blockno++ ) + { + unsigned int fraction; + if ( blockno == ( len / sizeof( block ) ) ) // last 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); - u8 *ctext_ptr; - 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]; - // debug_printf("Block %d output: ", blockno); - // hexdump(outbuf + blockno*sizeof(block), 16); - } + // debug_printf("block %d: fraction = %d\n", blockno, fraction); + 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 ); + + 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) { - u8 block[16]; - unsigned int blockno = 0, i; +// CBC mode encryption +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); + // debug_printf("aes_decrypt(%p, %p, %p, %lld)\n", iv, inbuf, outbuf, len); - for (blockno = 0; blockno <= (len / sizeof(block)); blockno++) { - unsigned int fraction; - if (blockno == (len / sizeof(block))) { // last block - fraction = len % sizeof(block); - if (fraction == 0) break; - memset(block, 0, sizeof(block)); - } else fraction = 16; + for ( blockno = 0; blockno <= ( len / sizeof( block ) ); blockno++ ) + { + unsigned int fraction; + if ( blockno == ( len / sizeof( block ) ) ) // last 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); - - 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)); - // debug_printf("Block %d output: ", blockno); - // hexdump(outbuf + blockno*sizeof(block), 16); - } + // debug_printf("block %d: fraction = %d\n", blockno, fraction); + memcpy( block, inbuf + blockno * sizeof( block ), fraction ); + + 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 ) ); + // 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 ce1c38d4..19ecfecd 100644 --- a/source/libwbfs/wiidisc.c +++ b/source/libwbfs/wiidisc.c @@ -5,349 +5,368 @@ #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 iv[16]; + 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_cbc_dec(common_key, iv, tik + 0x01bf, 16, title_key); - aes_decrypt(iv, tik + 0x01bf,title_key,16); + wbfs_memset( iv, 0, sizeof iv ); + wbfs_memcpy( iv, tik + 0x01dc, 8 ); + aes_set_key( common_key ); + //_aes_cbc_dec(common_key, iv, tik + 0x01bf, 16, title_key); + 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){ - int ret=0; - if(len==0) - return ; - ret = d->read(d->fp,offset,len,data); - if(ret) - wbfs_fatal("error reading disc"); - } - if(d->sector_usage_table) + if ( data ) + { + int ret = 0; + if ( len == 0 ) + return ; + ret = d->read( d->fp, offset, len, data ); + if ( ret ) + wbfs_fatal( "error reading disc" ); + } + if ( d->sector_usage_table ) + { + u32 blockno = offset >> 13; + do { - u32 blockno = offset>>13; - do - { - d->sector_usage_table[blockno]=1; - blockno+=1; - if(len>0x8000) - len-=0x8000; - }while(len>0x8000); + d->sector_usage_table[blockno] = 1; + blockno += 1; + if ( len > 0x8000 ) + len -= 0x8000; } + while ( len > 0x8000 ); + } } -static void partition_raw_read(wiidisc_t *d,u32 offset, u8 *data, u32 len) +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); + u8*raw = d->tmp_buffer; + u8 iv[16]; + u32 offset; + if ( d->sector_usage_table ) + d->sector_usage_table[d->partition_block+blockno] = 1; + offset = d->partition_data_offset + ( ( 0x8000 >> 2 ) * blockno ); + partition_raw_read( d, offset, raw, 0x8000 ); - // decrypt data - memcpy(iv, raw + 0x3d0, 16); - aes_set_key(d->disc_key); - aes_decrypt(iv, raw + 0x400,block,0x7c00); + // decrypt data + memcpy( iv, raw + 0x3d0, 16 ); + aes_set_key( d->disc_key ); + aes_decrypt( iv, raw + 0x400, block, 0x7c00 ); } -static void partition_read(wiidisc_t *d,u32 offset, u8 *data, u32 len,int fake) +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; + u8 *block = d->tmp_buffer2; + u32 offset_in_block; + u32 len_in_block; + if ( fake && d->sector_usage_table == 0 ) + return; - while(len) { - offset_in_block = offset % (0x7c00>>2); - len_in_block = 0x7c00 - (offset_in_block<<2); - if (len_in_block > len) - len_in_block = len; - if(!fake){ - partition_read_block(d,offset / (0x7c00>>2), block); - wbfs_memcpy(data, block + (offset_in_block<<2), len_in_block); - }else - d->sector_usage_table[d->partition_block+(offset/(0x7c00>>2))]=1; - data += len_in_block; - offset += len_in_block>>2; - len -= len_in_block; - } -} - - -static u32 do_fst(wiidisc_t *d,u8 *fst, const char *names, u32 i) -{ - u32 offset; - u32 size; - const char *name; - u32 j; - - name = names + (_be32(fst + 12*i) & 0x00ffffff); - size = _be32(fst + 12*i + 8); - - if (i == 0) { - for (j = 1; j < size && !d->extracted_buffer; ){ - j = do_fst(d,fst, names, j); - } - return size; - } - //printf("name %s\n",name); - - if (fst[12*i]) { - - for (j = i + 1; j < size && !d->extracted_buffer; ) - j = do_fst(d,fst, names, j); - - return size; - } else { - offset = _be32(fst + 12*i + 4); - if(d->extract_pathname && strcasecmp(name, d->extract_pathname)==0) - { - d->extracted_buffer = wbfs_ioalloc(size); - d->extracted_size = size; - partition_read(d,offset, d->extracted_buffer, size,0); - }else - partition_read(d,offset, 0, size,1); - return i + 1; - } -} - -static void do_files(wiidisc_t*d) -{ - u8 *b = wbfs_ioalloc(0x480); // XXX: determine actual header size - u32 dol_offset; - u32 fst_offset; - u32 fst_size; - u32 apl_offset; - u32 apl_size; - u8 *apl_header = wbfs_ioalloc(0x20); - u8 *fst; - u32 n_files; - partition_read(d,0, b, 0x480,0); - - dol_offset = _be32(b + 0x0420); - fst_offset = _be32(b + 0x0424); - fst_size = _be32(b + 0x0428)<<2; - - apl_offset = 0x2440>>2; - partition_read(d,apl_offset, apl_header, 0x20,0); - apl_size = 0x20 + _be32(apl_header + 0x14) + _be32(apl_header + 0x18); - // fake read dol and partition - 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) { - fst = wbfs_ioalloc(fst_size); - if (fst == 0) - wbfs_fatal("malloc fst"); - partition_read(d,fst_offset, fst, fst_size,0); - n_files = _be32(fst + 8); - - if (d->extract_pathname && *d->extract_pathname == 0) { - // if empty pathname requested return fst - d->extracted_buffer = fst; - d->extracted_size = fst_size; - d->extract_pathname = NULL; - // skip do_fst if only fst requested - n_files = 0; - } - - if (12*n_files <= fst_size ) { - if (n_files > 1) - do_fst(d,fst, (char *)fst + 12*n_files, 0); - } - } - wbfs_iofree(b); - wbfs_iofree(apl_header); - if (fst != d->extracted_buffer) - wbfs_iofree(fst); -} - -static void do_partition(wiidisc_t*d) -{ - u8 *tik = wbfs_ioalloc(0x2a4); - u8 *b = wbfs_ioalloc(0x1c); - u64 tmd_offset; - u32 tmd_size; - u8 *tmd; - u64 cert_offset; - u32 cert_size; - u8 *cert; - u64 h3_offset; - - // read ticket, and read some offsets and sizes - partition_raw_read(d,0, tik, 0x2a4); - partition_raw_read(d,0x2a4>>2, b, 0x1c); - - tmd_size = _be32(b); - tmd_offset = _be32(b + 4); - cert_size = _be32(b + 8); - cert_offset = _be32(b + 0x0c); - h3_offset = _be32(b + 0x10); - d->partition_data_offset = _be32(b + 0x14); - d->partition_block = (d->partition_raw_offset+d->partition_data_offset)>>13; - tmd = wbfs_ioalloc(tmd_size); - if (tmd == 0) - wbfs_fatal("malloc tmd"); - partition_raw_read(d,tmd_offset, tmd, tmd_size); - - cert = wbfs_ioalloc(cert_size); - if (cert == 0) - wbfs_fatal("malloc cert"); - partition_raw_read(d,cert_offset, cert, cert_size); - - - _decrypt_title_key(tik, d->disc_key); - - partition_raw_read(d,h3_offset, 0, 0x18000); - wbfs_iofree(b); - wbfs_iofree(tik); - wbfs_iofree(cert); - wbfs_iofree(tmd); - - do_files(d); - -} -static int test_parition_skip(u32 partition_type,partition_selector_t part_sel) -{ - switch(part_sel) + while ( len ) + { + offset_in_block = offset % ( 0x7c00 >> 2 ); + len_in_block = 0x7c00 - ( offset_in_block << 2 ); + if ( len_in_block > len ) + len_in_block = len; + if ( !fake ) { + partition_read_block( d, offset / ( 0x7c00 >> 2 ), block ); + wbfs_memcpy( data, block + ( offset_in_block << 2 ), len_in_block ); + } + else + d->sector_usage_table[d->partition_block+( offset/( 0x7c00>>2 ) )] = 1; + data += len_in_block; + offset += len_in_block >> 2; + len -= len_in_block; + } +} + + +static u32 do_fst( wiidisc_t *d, u8 *fst, const char *names, u32 i ) +{ + u32 offset; + u32 size; + const char *name; + u32 j; + + name = names + ( _be32( fst + 12 * i ) & 0x00ffffff ); + size = _be32( fst + 12 * i + 8 ); + + if ( i == 0 ) + { + for ( j = 1; j < size && !d->extracted_buffer; ) + { + j = do_fst( d, fst, names, j ); + } + return size; + } + //printf("name %s\n",name); + + if ( fst[12*i] ) + { + + for ( j = i + 1; j < size && !d->extracted_buffer; ) + j = do_fst( d, fst, names, j ); + + return size; + } + else + { + offset = _be32( fst + 12 * i + 4 ); + if ( d->extract_pathname && strcasecmp( name, d->extract_pathname ) == 0 ) + { + d->extracted_buffer = wbfs_ioalloc( size ); + d->extracted_size = size; + partition_read( d, offset, d->extracted_buffer, size, 0 ); + } + else + partition_read( d, offset, 0, size, 1 ); + return i + 1; + } +} + +static void do_files( wiidisc_t*d ) +{ + u8 *b = wbfs_ioalloc( 0x480 ); // XXX: determine actual header size + u32 dol_offset; + u32 fst_offset; + u32 fst_size; + u32 apl_offset; + u32 apl_size; + u8 *apl_header = wbfs_ioalloc( 0x20 ); + u8 *fst; + u32 n_files; + partition_read( d, 0, b, 0x480, 0 ); + + dol_offset = _be32( b + 0x0420 ); + fst_offset = _be32( b + 0x0424 ); + fst_size = _be32( b + 0x0428 ) << 2; + + apl_offset = 0x2440 >> 2; + partition_read( d, apl_offset, apl_header, 0x20, 0 ); + apl_size = 0x20 + _be32( apl_header + 0x14 ) + _be32( apl_header + 0x18 ); + // fake read dol and partition + 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 ) + { + fst = wbfs_ioalloc( fst_size ); + if ( fst == 0 ) + wbfs_fatal( "malloc fst" ); + partition_read( d, fst_offset, fst, fst_size, 0 ); + n_files = _be32( fst + 8 ); + + if ( d->extract_pathname && *d->extract_pathname == 0 ) + { + // if empty pathname requested return fst + d->extracted_buffer = fst; + d->extracted_size = fst_size; + d->extract_pathname = NULL; + // skip do_fst if only fst requested + n_files = 0; + } + + if ( 12*n_files <= fst_size ) + { + if ( n_files > 1 ) + do_fst( d, fst, ( char * )fst + 12*n_files, 0 ); + } + } + wbfs_iofree( b ); + wbfs_iofree( apl_header ); + if ( fst != d->extracted_buffer ) + wbfs_iofree( fst ); +} + +static void do_partition( wiidisc_t*d ) +{ + u8 *tik = wbfs_ioalloc( 0x2a4 ); + u8 *b = wbfs_ioalloc( 0x1c ); + u64 tmd_offset; + u32 tmd_size; + u8 *tmd; + u64 cert_offset; + u32 cert_size; + u8 *cert; + u64 h3_offset; + + // read ticket, and read some offsets and sizes + partition_raw_read( d, 0, tik, 0x2a4 ); + partition_raw_read( d, 0x2a4 >> 2, b, 0x1c ); + + tmd_size = _be32( b ); + tmd_offset = _be32( b + 4 ); + cert_size = _be32( b + 8 ); + cert_offset = _be32( b + 0x0c ); + h3_offset = _be32( b + 0x10 ); + d->partition_data_offset = _be32( b + 0x14 ); + d->partition_block = ( d->partition_raw_offset + d->partition_data_offset ) >> 13; + tmd = wbfs_ioalloc( tmd_size ); + if ( tmd == 0 ) + wbfs_fatal( "malloc tmd" ); + partition_raw_read( d, tmd_offset, tmd, tmd_size ); + + cert = wbfs_ioalloc( cert_size ); + if ( cert == 0 ) + wbfs_fatal( "malloc cert" ); + partition_raw_read( d, cert_offset, cert, cert_size ); + + + _decrypt_title_key( tik, d->disc_key ); + + partition_raw_read( d, h3_offset, 0, 0x18000 ); + wbfs_iofree( b ); + wbfs_iofree( tik ); + wbfs_iofree( cert ); + wbfs_iofree( tmd ); + + do_files( d ); + +} +static int test_parition_skip( u32 partition_type, partition_selector_t part_sel ) +{ + switch ( part_sel ) + { case ALL_PARTITIONS: - return 0; + 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); - } -} -static void do_disc(wiidisc_t*d) + return ( partition_type != part_sel ); + } +} +static void do_disc( wiidisc_t*d ) { - u8 *b = wbfs_ioalloc(0x100); - u64 partition_offset[32]; // XXX: don't know the real maximum - u64 partition_type[32]; // XXX: don't know the real maximum - u32 n_partitions; - u32 magic; - u32 i; - disc_read(d,0, b, 0x100); - magic=_be32(b+24); - if(magic!=0x5D1C9EA3){ - wbfs_error("not a wii disc"); - return ; - } - disc_read(d,0x40000>>2, b, 0x100); - n_partitions = _be32(b); - disc_read(d,_be32(b + 4), b, 0x100); - for (i = 0; i < n_partitions; i++){ - partition_offset[i] = _be32(b + 8 * i); - partition_type[i] = _be32(b + 8 * i+4); - } - for (i = 0; i < n_partitions; i++) { - d->partition_raw_offset = partition_offset[i]; - if(!test_parition_skip(partition_type[i],d->part_sel)) - do_partition(d); - } - wbfs_iofree(b); + u8 *b = wbfs_ioalloc( 0x100 ); + u64 partition_offset[32]; // XXX: don't know the real maximum + u64 partition_type[32]; // XXX: don't know the real maximum + u32 n_partitions; + u32 magic; + u32 i; + disc_read( d, 0, b, 0x100 ); + magic = _be32( b + 24 ); + if ( magic != 0x5D1C9EA3 ) + { + wbfs_error( "not a wii disc" ); + return ; + } + disc_read( d, 0x40000 >> 2, b, 0x100 ); + n_partitions = _be32( b ); + disc_read( d, _be32( b + 4 ), b, 0x100 ); + for ( i = 0; i < n_partitions; i++ ) + { + partition_offset[i] = _be32( b + 8 * i ); + partition_type[i] = _be32( b + 8 * i + 4 ); + } + for ( i = 0; i < n_partitions; i++ ) + { + d->partition_raw_offset = partition_offset[i]; + if ( !test_parition_skip( partition_type[i], d->part_sel ) ) + do_partition( d ); + } + wbfs_iofree( b ); } -wiidisc_t *wd_open_disc(read_wiidisc_callback_t read,void*fp) +wiidisc_t *wd_open_disc( read_wiidisc_callback_t read, void*fp ) { - wiidisc_t *d = wbfs_malloc(sizeof(wiidisc_t)); - if(!d) - return 0; - wbfs_memset(d,0,sizeof(wiidisc_t)); - d->read = read; - d->fp = fp; - d->part_sel = ALL_PARTITIONS; - d->tmp_buffer = wbfs_ioalloc(0x8000); - d->tmp_buffer2 = wbfs_malloc(0x8000); + wiidisc_t *d = wbfs_malloc( sizeof( wiidisc_t ) ); + if ( !d ) + return 0; + wbfs_memset( d, 0, sizeof( wiidisc_t ) ); + d->read = read; + d->fp = fp; + d->part_sel = ALL_PARTITIONS; + d->tmp_buffer = wbfs_ioalloc( 0x8000 ); + d->tmp_buffer2 = wbfs_malloc( 0x8000 ); - return d; + 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); - wbfs_free(d); + wbfs_iofree( d->tmp_buffer ); + wbfs_free( d->tmp_buffer2 ); + wbfs_free( d ); } // returns a buffer allocated with wbfs_ioalloc() or NULL if not found of alloc error -// XXX pathname not implemented. files are extracted by their name. +// XXX pathname not implemented. files are extracted by their name. // first file found with that name is returned. -u8 * wd_extract_file(wiidisc_t *d, partition_selector_t partition_type, char *pathname) +u8 * wd_extract_file( wiidisc_t *d, partition_selector_t partition_type, char *pathname ) { - u8 *retval = 0; - d->extract_pathname = pathname; - d->extracted_buffer = 0; - d->part_sel = partition_type; - do_disc(d); - d->extract_pathname = 0; - d->part_sel = ALL_PARTITIONS; - retval = d->extracted_buffer; - d->extracted_buffer = 0; - return retval; + u8 *retval = 0; + d->extract_pathname = pathname; + d->extracted_buffer = 0; + d->part_sel = partition_type; + do_disc( d ); + d->extract_pathname = 0; + d->part_sel = ALL_PARTITIONS; + retval = d->extracted_buffer; + d->extracted_buffer = 0; + return retval; } -void wd_build_disc_usage(wiidisc_t *d, partition_selector_t selector, u8* usage_table) +void wd_build_disc_usage( wiidisc_t *d, partition_selector_t selector, u8* usage_table ) { - d->sector_usage_table = usage_table; - wbfs_memset(usage_table,0,143432*2); - d->part_sel = selector; - do_disc(d); - d->part_sel = ALL_PARTITIONS; - d->sector_usage_table = 0; + d->sector_usage_table = usage_table; + wbfs_memset( usage_table, 0, 143432*2 ); + d->part_sel = selector; + do_disc( d ); + d->part_sel = ALL_PARTITIONS; + d->sector_usage_table = 0; } -void wd_fix_partition_table(wiidisc_t *d, partition_selector_t selector, u8* partition_table) +void wd_fix_partition_table( wiidisc_t *d, partition_selector_t selector, u8* partition_table ) { - u8 *b = partition_table; - u32 partition_offset; - u32 partition_type; - u32 n_partitions,i,j; - u32 *b32; - if(selector == ALL_PARTITIONS) - return; - n_partitions = _be32(b); - if(_be32(b + 4)-(0x40000>>2) >0x50) - wbfs_fatal("cannot modify this partition table. Please report the bug."); - - b += (_be32(b + 4)-(0x40000>>2))*4; - j=0; - for (i = 0; i < n_partitions; i++){ - partition_offset = _be32(b + 8 * i); - partition_type = _be32(b + 8 * i+4); - if(!test_parition_skip(partition_type,selector)) - { - b32 = (u32*)(b + 8 * j); - b32[0] = wbfs_htonl(partition_offset); - b32[1] = wbfs_htonl(partition_type); - j++; - } + u8 *b = partition_table; + u32 partition_offset; + u32 partition_type; + u32 n_partitions, i, j; + u32 *b32; + if ( selector == ALL_PARTITIONS ) + return; + n_partitions = _be32( b ); + if ( _be32( b + 4 ) - ( 0x40000 >> 2 ) > 0x50 ) + wbfs_fatal( "cannot modify this partition table. Please report the bug." ); + + b += ( _be32( b + 4 ) - ( 0x40000 >> 2 ) ) * 4; + j = 0; + for ( i = 0; i < n_partitions; i++ ) + { + partition_offset = _be32( b + 8 * i ); + partition_type = _be32( b + 8 * i + 4 ); + if ( !test_parition_skip( partition_type, selector ) ) + { + b32 = ( u32* )( b + 8 * j ); + b32[0] = wbfs_htonl( partition_offset ); + b32[1] = wbfs_htonl( partition_type ); + j++; } - b32 = (u32*)(partition_table); - *b32 = wbfs_htonl(j); + } + b32 = ( u32* )( partition_table ); + *b32 = wbfs_htonl( j ); } diff --git a/source/libwbfs/wiidisc.h b/source/libwbfs/wiidisc.h index ba285208..2ea61724 100644 --- a/source/libwbfs/wiidisc.h +++ b/source/libwbfs/wiidisc.h @@ -4,65 +4,67 @@ #include "libwbfs_os.h" // this file is provided by the project wanting to compile libwbfs and wiidisc #ifdef __cplusplus - extern "C" { +extern "C" +{ #endif /* __cplusplus */ #if 0 //removes extra automatic indentation by editors - } +} #endif // callback definition. Return 1 on fatal error (callback is supposed to make retries until no hopes..) // offset points 32bit words, count counts bytes -typedef int (*read_wiidisc_callback_t)(void*fp,u32 offset,u32 count,void*iobuf); +typedef 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; + 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; - - u8 *tmp_buffer; - u8 *tmp_buffer2; - u8 disc_key[16]; - int dont_decrypt; + // everything points 32bit words. + u32 disc_raw_offset; + u32 partition_raw_offset; + u32 partition_data_offset; + u32 partition_data_size; + u32 partition_block; - partition_selector_t part_sel; + u8 *tmp_buffer; + u8 *tmp_buffer2; + u8 disc_key[16]; + int dont_decrypt; - char *extract_pathname; - u8 *extracted_buffer; - int extracted_size; -}wiidisc_t; + partition_selector_t part_sel; -wiidisc_t *wd_open_disc(read_wiidisc_callback_t read,void*fp); -void wd_close_disc(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); +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); +void wd_fix_partition_table( wiidisc_t *d, partition_selector_t selector, u8* partition_table ); #if 0 { #endif #ifdef __cplusplus - } +} #endif /* __cplusplus */ #endif diff --git a/source/libwiigui/Text.cpp b/source/libwiigui/Text.cpp index 246a661a..c942ccdd 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,30 @@ Text::Text(const char * t, int s, GXColor c) FirstLineOffset = 0; wText = NULL; - if(!text) + 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); + 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,29 +40,29 @@ Text::Text(const wchar_t * t, int s, GXColor c) FirstLineOffset = 0; wText = NULL; - if(!t) + 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) + if ( wText ) delete wText; wText = NULL; @@ -70,28 +70,28 @@ Text::~Text() ClearDynamicText(); } -void Text::SetText(const char * t) +void Text::SetText( const char * t ) { - wchar_t * tmp = charToWideChar(t); - if(!tmp) + wchar_t * tmp = charToWideChar( t ); + if ( !tmp ) return; - if(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; @@ -99,54 +99,54 @@ void Text::SetText(const char * t) CalcLineOffsets(); } -void Text::SetText(const wchar_t * t) +void Text::SetText( const wchar_t * t ) { - if(!t) + if ( !t ) return; - if(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) - line = 0; - else if(line > (int) TextLines.size()-1) - line = TextLines.size()-1; + if ( line < 0 ) + line = 0; + 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) + 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 +155,7 @@ void Text::SetTextPos(int pos) FillRows(); - while((int) textDyn.size() < linestodraw && curLineStart > 0) + while ( ( int ) textDyn.size() < linestodraw && curLineStart > 0 ) { PreviousLine(); } @@ -166,34 +166,34 @@ 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) + if ( TextLines.size() == 0 ) return 0; - if(ind < 0) + if ( ind < 0 ) return TextLines[0].LineOffset; - if(ind >= (int) TextLines.size()-1) + 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) + if ( filling || textDyn.size() == 0 ) return NULL; - if(ind < 0) + if ( ind < 0 ) return textDyn[0]; - if(ind >= (int) textDyn.size()) + if ( ind >= ( int ) textDyn.size() ) return textDyn[textDyn.size()-1]; return textDyn[ind]; @@ -207,7 +207,7 @@ void Text::Refresh() void Text::NextLine() { - if(!wText || (curLineStart+1 > ((int) TextLines.size()-linestodraw))) + if ( !wText || ( curLineStart + 1 > ( ( int ) TextLines.size() - linestodraw ) ) ) return; ++curLineStart; @@ -217,7 +217,7 @@ void Text::NextLine() void Text::PreviousLine() { - if(!wText || curLineStart-1 < 0) + if ( !wText || curLineStart - 1 < 0 ) return; --curLineStart; @@ -227,25 +227,25 @@ void Text::PreviousLine() void Text::FillRows() { - if(!wText) + 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 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,7 +257,7 @@ void Text::FillRows() void Text::CalcLineOffsets() { - if(!wText) + if ( !wText ) return; TextLines.clear(); @@ -274,35 +274,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.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; + TmpLine.LineOffset = ch + 1; } - else if(origTxt[ch] == '\n') + else if ( origTxt[ch] == '\n' ) { - TmpLine.CharCount = ch-TmpLine.LineOffset; + 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; + TmpLine.LineOffset = ch + 1; } - else if(origTxt[ch] == ' ') + else if ( origTxt[ch] == ' ' ) { lastSpace = ch; lastSpaceIndex = i; @@ -312,39 +312,39 @@ void Text::CalcLineOffsets() i++; } - TmpLine.CharCount = ch-TmpLine.LineOffset; + 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) + if ( textDyn.size() == 0 ) return; - if(!this->IsVisible()) - return; + if ( !this->IsVisible() ) + return; - GXColor c = color; - c.a = this->GetAlpha(); + GXColor c = color; + c.a = this->GetAlpha(); - int newSize = size*GetScale(); + int newSize = size * GetScale(); - if(newSize != currentSize) - { - currentSize = newSize; + 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/gui.h b/source/libwiigui/gui.h index 289dab6a..96bafcf6 100644 --- a/source/libwiigui/gui.h +++ b/source/libwiigui/gui.h @@ -48,196 +48,197 @@ extern FreeTypeGX *fontSystem; -#define SCROLL_INITIAL_DELAY 20 -#define SCROLL_LOOP_DELAY 3 -#define PAGESIZE 9 +#define SCROLL_INITIAL_DELAY 20 +#define SCROLL_LOOP_DELAY 3 +#define PAGESIZE 9 #define FILEBROWSERSIZE 8 -#define MAX_OPTIONS 170 +#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; +typedef struct _paddata +{ + 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 -#define EFFECT_SLIDE_BOTTOM 2 -#define EFFECT_SLIDE_RIGHT 4 -#define EFFECT_SLIDE_LEFT 8 -#define EFFECT_SLIDE_IN 16 -#define EFFECT_SLIDE_OUT 32 -#define EFFECT_FADE 64 -#define EFFECT_SCALE 128 -#define EFFECT_COLOR_TRANSITION 256 +#define EFFECT_SLIDE_TOP 1 +#define EFFECT_SLIDE_BOTTOM 2 +#define EFFECT_SLIDE_RIGHT 4 +#define EFFECT_SLIDE_LEFT 8 +#define EFFECT_SLIDE_IN 16 +#define EFFECT_SLIDE_OUT 32 +#define EFFECT_FADE 64 +#define EFFECT_SCALE 128 +#define EFFECT_COLOR_TRANSITION 256 #define EFFECT_PULSE 512 #define EFFECT_ROCK_VERTICLE 1024 #define EFFECT_GOROUND 2048 -#define MAX_SND_VOICES 16 +#define MAX_SND_VOICES 16 class GuiSoundDecoder; class GuiSound { - public: - //!Constructor - //!\param s Pointer to the sound data - //!\param l Length of sound data - //!\param v Sound volume (0-100) - //!\param r RAW PCM Sound, when no decoder is found then try to play as raw-pcm - //!\param a true--> Pointer to the sound data is allocated with new u8[...] - //!\ GuiSound will be destroy the buffer if it no more needed - //!\ false-> sound data buffer has to live just as long as GuiSound - GuiSound(const u8 *s, int l, int v=100, bool r=true, bool a=false); - //!Constructor - //!\param p Path to the sound data - //!\param v Sound volume (0-100) - GuiSound(const char *p, int v=100); - //!Load - stop playing and load the new sound data - //! if load not failed replace the current with new sound data - //! otherwise the current date will not changed - //!\params same as by Constructors - //!\return true ok / false = failed - bool Load(const u8 *s, int l, bool r=false, bool a=false); - bool Load(const char *p); - //!Destructor - ~GuiSound(); + public: + //!Constructor + //!\param s Pointer to the sound data + //!\param l Length of sound data + //!\param v Sound volume (0-100) + //!\param r RAW PCM Sound, when no decoder is found then try to play as raw-pcm + //!\param a true--> Pointer to the sound data is allocated with new u8[...] + //!\ GuiSound will be destroy the buffer if it no more needed + //!\ false-> sound data buffer has to live just as long as GuiSound + GuiSound( const u8 *s, int l, int v = 100, bool r = true, bool a = false ); + //!Constructor + //!\param p Path to the sound data + //!\param v Sound volume (0-100) + GuiSound( const char *p, int v = 100 ); + //!Load - stop playing and load the new sound data + //! if load not failed replace the current with new sound data + //! otherwise the current date will not changed + //!\params same as by Constructors + //!\return true ok / false = failed + bool Load( const u8 *s, int l, bool r = false, bool a = false ); + bool Load( const char *p ); + //!Destructor + ~GuiSound(); - //!Start sound playback - void Play(); - //!Stop sound playback - void Stop(); - //!Pause sound playback - void Pause(); - //!Resume sound playback - void Resume(); - //!Checks if the sound is currently playing - //!\return true if sound is playing, false otherwise - bool IsPlaying(); - //!Set sound volume - //!\param v Sound volume (0-100) - void SetVolume(int v); - //!Set the sound to loop playback (only applies to OGG) - //!\param l Loop (true to loop) - void SetLoop(bool l); - //!Get the playing time in ms for that moment (only applies to OGG) - protected: - s32 voice; // used asnd-voice - u8 *play_buffer[3]; // trpple-playbuffer - int buffer_nr; // current playbuffer - int buffer_pos; // current idx to write in buffer - bool buffer_ready; // buffer is filled and ready - bool buffer_eof; // no mor datas - will stop playing - bool loop; // play looped - s32 volume; // volume - GuiSoundDecoder *decoder; + //!Start sound playback + void Play(); + //!Stop sound playback + void Stop(); + //!Pause sound playback + void Pause(); + //!Resume sound playback + void Resume(); + //!Checks if the sound is currently playing + //!\return true if sound is playing, false otherwise + bool IsPlaying(); + //!Set sound volume + //!\param v Sound volume (0-100) + void SetVolume( int v ); + //!Set the sound to loop playback (only applies to OGG) + //!\param l Loop (true to loop) + void SetLoop( bool l ); + //!Get the playing time in ms for that moment (only applies to OGG) + protected: + s32 voice; // used asnd-voice + u8 *play_buffer[3]; // trpple-playbuffer + int buffer_nr; // current playbuffer + int buffer_pos; // current idx to write in buffer + bool buffer_ready; // buffer is filled and ready + bool buffer_eof; // no mor datas - will stop playing + bool loop; // play looped + s32 volume; // volume + GuiSoundDecoder *decoder; - void DecoderCallback(); - void PlayerCallback(); - friend void *GuiSoundDecoderThread(void *args); - friend void GuiSoundPlayerCallback(s32 Voice); + void DecoderCallback(); + void PlayerCallback(); + friend void *GuiSoundDecoderThread( void *args ); + friend void GuiSoundPlayerCallback( s32 Voice ); }; //!Menu input trigger management. Determine if action is neccessary based on input data by comparing controller input data to a specific trigger element. class GuiTrigger { - public: - //!Constructor - GuiTrigger(); - //!Destructor - ~GuiTrigger(); - //!Sets a simple trigger. Requires: element is selected, and trigger button is pressed - //!\param ch Controller channel number - //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately - //!\param gcbtns GameCube controller trigger button(s) - void SetSimpleTrigger(s32 ch, u32 wiibtns, u16 gcbtns); - //!Sets a held trigger. Requires: element is selected, and trigger button is pressed - //!\param ch Controller channel number - //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately - //!\param gcbtns GameCube controller trigger button(s) - void SetHeldTrigger(s32 ch, u32 wiibtns, u16 gcbtns); - //!Sets a button-only trigger. Requires: Trigger button is pressed - //!\param ch Controller channel number - //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately - //!\param gcbtns GameCube controller trigger button(s) - void SetButtonOnlyTrigger(s32 ch, u32 wiibtns, u16 gcbtns); - //!Sets a button-only trigger. Requires: trigger button is pressed and parent window of element is in focus - //!\param ch Controller channel number - //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately - //!\param gcbtns GameCube controller trigger button(s) - void SetButtonOnlyInFocusTrigger(s32 ch, u32 wiibtns, u16 gcbtns); - //!Get X/Y value from Wii Joystick (classic, nunchuk) input - //!\param right Controller stick (left = 0, right = 1) - //!\param axis Controller stick axis (x-axis = 0, y-axis = 1) - //!\return Stick value - s8 WPAD_Stick(u8 right, int axis); - //!Move menu selection left (via pad/joystick). Allows scroll delay and button overriding - //!\return true if selection should be moved left, false otherwise - bool Left(); - //!Move menu selection right (via pad/joystick). Allows scroll delay and button overriding - //!\return true if selection should be moved right, false otherwise - bool Right(); - //!Move menu selection up (via pad/joystick). Allows scroll delay and button overriding - //!\return true if selection should be moved up, false otherwise - bool Up(); - //!Move menu selection down (via pad/joystick). Allows scroll delay and button overriding - //!\return true if selection should be moved down, false otherwise - bool Down(); + public: + //!Constructor + GuiTrigger(); + //!Destructor + ~GuiTrigger(); + //!Sets a simple trigger. Requires: element is selected, and trigger button is pressed + //!\param ch Controller channel number + //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately + //!\param gcbtns GameCube controller trigger button(s) + void SetSimpleTrigger( s32 ch, u32 wiibtns, u16 gcbtns ); + //!Sets a held trigger. Requires: element is selected, and trigger button is pressed + //!\param ch Controller channel number + //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately + //!\param gcbtns GameCube controller trigger button(s) + void SetHeldTrigger( s32 ch, u32 wiibtns, u16 gcbtns ); + //!Sets a button-only trigger. Requires: Trigger button is pressed + //!\param ch Controller channel number + //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately + //!\param gcbtns GameCube controller trigger button(s) + void SetButtonOnlyTrigger( s32 ch, u32 wiibtns, u16 gcbtns ); + //!Sets a button-only trigger. Requires: trigger button is pressed and parent window of element is in focus + //!\param ch Controller channel number + //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately + //!\param gcbtns GameCube controller trigger button(s) + void SetButtonOnlyInFocusTrigger( s32 ch, u32 wiibtns, u16 gcbtns ); + //!Get X/Y value from Wii Joystick (classic, nunchuk) input + //!\param right Controller stick (left = 0, right = 1) + //!\param axis Controller stick axis (x-axis = 0, y-axis = 1) + //!\return Stick value + s8 WPAD_Stick( u8 right, int axis ); + //!Move menu selection left (via pad/joystick). Allows scroll delay and button overriding + //!\return true if selection should be moved left, false otherwise + bool Left(); + //!Move menu selection right (via pad/joystick). Allows scroll delay and button overriding + //!\return true if selection should be moved right, false otherwise + bool Right(); + //!Move menu selection up (via pad/joystick). Allows scroll delay and button overriding + //!\return true if selection should be moved up, false otherwise + bool Up(); + //!Move menu selection down (via pad/joystick). Allows scroll delay and button overriding + //!\return true if selection should be moved down, false otherwise + bool Down(); - u8 type; //!< trigger type (TRIGGER_SIMPLE, TRIGGER_HELD, TRIGGER_BUTTON_ONLY, TRIGGER_BUTTON_ONLY_IN_FOCUS) - s32 chan; //!< Trigger controller channel (0-3, -1 for all) - WPADData wpad; //!< Wii controller trigger data - PADData pad; //!< GameCube controller trigger data + u8 type; //!< trigger type (TRIGGER_SIMPLE, TRIGGER_HELD, TRIGGER_BUTTON_ONLY, TRIGGER_BUTTON_ONLY_IN_FOCUS) + s32 chan; //!< Trigger controller channel (0-3, -1 for all) + WPADData wpad; //!< Wii controller trigger data + PADData pad; //!< GameCube controller trigger data }; extern GuiTrigger userInput[4]; @@ -245,123 +246,123 @@ extern GuiTrigger userInput[4]; //!Primary GUI class. Most other classes inherit from this class. class GuiElement { - public: - //!Constructor - GuiElement(); - //!Destructor - ~GuiElement(); - //!Set the element's parent - //!\param e Pointer to parent element - void SetParent(GuiElement * e); - //!Gets the element's parent - //!\return Pointer to parent element - GuiElement * GetParent(); - //!Gets the current leftmost coordinate of the element - //!Considers horizontal alignment, x offset, width, and parent element's GetLeft() / GetWidth() values - //!\return left coordinate - int GetLeft(); - //!Gets the current topmost coordinate of the element - //!Considers vertical alignment, y offset, height, and parent element's GetTop() / GetHeight() values - //!\return top coordinate - int GetTop(); - //!Sets the minimum y offset of the element - //!\param y Y offset - void SetMinY(int y); - //!Gets the minimum y offset of the element - //!\return Minimum Y offset - int GetMinY(); - //!Sets the maximum y offset of the element - //!\param y Y offset - void SetMaxY(int y); - //!Gets the maximum y offset of the element - //!\return Maximum Y offset - int GetMaxY(); - //!Sets the minimum x offset of the element - //!\param x X offset - void SetMinX(int x); - //!Gets the minimum x offset of the element - //!\return Minimum X offset - int GetMinX(); - //!Sets the maximum x offset of the element - //!\param x X offset - void SetMaxX(int x); - //!Gets the maximum x offset of the element - //!\return Maximum X offset - int GetMaxX(); - //!Gets the current width of the element. Does not currently consider the scale - //!\return width - int GetWidth(); - //!Gets the height of the element. Does not currently consider the scale - //!\return height - int GetHeight(); - //!Sets the size (width/height) of the element - //!\param w Width of element - //!\param h Height of element - void SetSize(int w, int h); - //!Checks whether or not the element is visible - //!\return true if visible, false otherwise - bool IsVisible(); - //!Checks whether or not the element is selectable - //!\return true if selectable, false otherwise - bool IsSelectable(); - //!Checks whether or not the element is clickable - //!\return true if clickable, false otherwise - bool IsClickable(); - //!Checks whether or not the element is holdable - //!\return true if holdable, false otherwise - bool IsHoldable(); - //!Sets whether or not the element is selectable - //!\param s Selectable - void SetSelectable(bool s); - //!Sets whether or not the element is clickable - //!\param c Clickable - void SetClickable(bool c); - //!Sets whether or not the element is holdable - //!\param c Holdable - void SetHoldable(bool d); - //!Gets the element's current state - //!\return state - int GetState(); - //!Gets the controller channel that last changed the element's state - //!\return Channel number (0-3, -1 = no channel) - int GetStateChan(); - //!Sets the element's alpha value - //!\param a alpha value - void SetAlpha(int a); - //!Gets the element's alpha value - //!Considers alpha, alphaDyn, and the parent element's GetAlpha() value - //!\return alpha - int GetAlpha(); - //!Gets the element's AngleDyn value - //!\return alpha - float GetAngleDyn(); - //!Sets the element's scale - //!\param s scale (1 is 100%) - void SetScale(float s); - //!Gets the element's current scale - //!Considers scale, scaleDyn, and the parent element's GetScale() value - virtual float GetScale(); - //!Set a new GuiTrigger for the element - //!\param t Pointer to GuiTrigger - void SetTrigger(GuiTrigger * t); - //!\overload - //!\param i Index of trigger array to set - //!\param t Pointer to GuiTrigger - void SetTrigger(u8 i, GuiTrigger * t); - //!Remove GuiTrigger for the element - //!\param i Index of trigger array to set - void RemoveTrigger(u8 i); - //!Checks whether rumble was requested by the element - //!\return true is rumble was requested, false otherwise - bool Rumble(); - //!Sets whether or not the element is requesting a rumble event - //!\param r true if requesting rumble, false if not - void SetRumble(bool r); - //!Set an effect for the element - //!\param e Effect to enable - //!\param a Amount of the effect (usage varies on effect) - //!\param t Target amount of the effect (usage varies on effect) - void SetEffect(int e, int a, int t=0); + public: + //!Constructor + GuiElement(); + //!Destructor + ~GuiElement(); + //!Set the element's parent + //!\param e Pointer to parent element + void SetParent( GuiElement * e ); + //!Gets the element's parent + //!\return Pointer to parent element + GuiElement * GetParent(); + //!Gets the current leftmost coordinate of the element + //!Considers horizontal alignment, x offset, width, and parent element's GetLeft() / GetWidth() values + //!\return left coordinate + int GetLeft(); + //!Gets the current topmost coordinate of the element + //!Considers vertical alignment, y offset, height, and parent element's GetTop() / GetHeight() values + //!\return top coordinate + int GetTop(); + //!Sets the minimum y offset of the element + //!\param y Y offset + void SetMinY( int y ); + //!Gets the minimum y offset of the element + //!\return Minimum Y offset + int GetMinY(); + //!Sets the maximum y offset of the element + //!\param y Y offset + void SetMaxY( int y ); + //!Gets the maximum y offset of the element + //!\return Maximum Y offset + int GetMaxY(); + //!Sets the minimum x offset of the element + //!\param x X offset + void SetMinX( int x ); + //!Gets the minimum x offset of the element + //!\return Minimum X offset + int GetMinX(); + //!Sets the maximum x offset of the element + //!\param x X offset + void SetMaxX( int x ); + //!Gets the maximum x offset of the element + //!\return Maximum X offset + int GetMaxX(); + //!Gets the current width of the element. Does not currently consider the scale + //!\return width + int GetWidth(); + //!Gets the height of the element. Does not currently consider the scale + //!\return height + int GetHeight(); + //!Sets the size (width/height) of the element + //!\param w Width of element + //!\param h Height of element + void SetSize( int w, int h ); + //!Checks whether or not the element is visible + //!\return true if visible, false otherwise + bool IsVisible(); + //!Checks whether or not the element is selectable + //!\return true if selectable, false otherwise + bool IsSelectable(); + //!Checks whether or not the element is clickable + //!\return true if clickable, false otherwise + bool IsClickable(); + //!Checks whether or not the element is holdable + //!\return true if holdable, false otherwise + bool IsHoldable(); + //!Sets whether or not the element is selectable + //!\param s Selectable + void SetSelectable( bool s ); + //!Sets whether or not the element is clickable + //!\param c Clickable + void SetClickable( bool c ); + //!Sets whether or not the element is holdable + //!\param c Holdable + void SetHoldable( bool d ); + //!Gets the element's current state + //!\return state + int GetState(); + //!Gets the controller channel that last changed the element's state + //!\return Channel number (0-3, -1 = no channel) + int GetStateChan(); + //!Sets the element's alpha value + //!\param a alpha value + void SetAlpha( int a ); + //!Gets the element's alpha value + //!Considers alpha, alphaDyn, and the parent element's GetAlpha() value + //!\return alpha + int GetAlpha(); + //!Gets the element's AngleDyn value + //!\return alpha + float GetAngleDyn(); + //!Sets the element's scale + //!\param s scale (1 is 100%) + void SetScale( float s ); + //!Gets the element's current scale + //!Considers scale, scaleDyn, and the parent element's GetScale() value + virtual float GetScale(); + //!Set a new GuiTrigger for the element + //!\param t Pointer to GuiTrigger + void SetTrigger( GuiTrigger * t ); + //!\overload + //!\param i Index of trigger array to set + //!\param t Pointer to GuiTrigger + void SetTrigger( u8 i, GuiTrigger * t ); + //!Remove GuiTrigger for the element + //!\param i Index of trigger array to set + void RemoveTrigger( u8 i ); + //!Checks whether rumble was requested by the element + //!\return true is rumble was requested, false otherwise + bool Rumble(); + //!Sets whether or not the element is requesting a rumble event + //!\param r true if requesting rumble, false if not + void SetRumble( bool r ); + //!Set an effect for the element + //!\param e Effect to enable + //!\param a Amount of the effect (usage varies on effect) + //!\param t Target amount of the effect (usage varies on effect) + void SetEffect( int e, int a, int t = 0 ); //!This SetEffect is for EFFECT_GOROUND only //!\param e Effect to enable //!\param speed is for Circlespeed @@ -371,426 +372,426 @@ class GuiElement //!\param anglespeedset Set the speed of Angle rotating make 1 for same speed as Circlespeed //! or 0.5 for half the speed of the circlingspeed. Turn Anglecircling off by 0 to this param. //!\param center_x x co-ordinate of the center of circle. - //!\param center_y y co-ordinate of the center of circle. - void SetEffect(int e, int speed, f32 circles, int r, f32 startdegree, f32 anglespeedset, int center_x, int center_y); - //!Gets the frequency from the above effect - //!\return element frequency - float GetFrequency(); - //!Sets an effect to be enabled on wiimote cursor over - //!\param e Effect to enable - //!\param a Amount of the effect (usage varies on effect) - //!\param t Target amount of the effect (usage varies on effect) - void SetEffectOnOver(int e, int a, int t=0); - //!Shortcut to SetEffectOnOver(EFFECT_SCALE, 4, 110) - void SetEffectGrow(); - //!Stops the current element effect - void StopEffect(); - //!Gets the current element effects - //!\return element effects - int GetEffect(); - //!Gets the current element on over effects - //!\return element on over effects - int GetEffectOnOver(); - //!Checks whether the specified coordinates are within the element's boundaries - //!\param x X coordinate - //!\param y Y coordinate - //!\return true if contained within, false otherwise - bool IsInside(int x, int y); - //!Sets the element's position - //!\param x X coordinate - //!\param y Y coordinate - void SetPosition(int x, int y, int z = 0); - //!Updates the element's effects (dynamic values) - //!Called by Draw(), used for animation purposes - void UpdateEffects(); - //!Sets a function to called after after Update() - //!Callback function can be used to response to changes in the state of the element, and/or update the element's attributes - void SetUpdateCallback(UpdateCallback u); - //!Checks whether the element is in focus - //!\return true if element is in focus, false otherwise - int IsFocused(); - //!Sets the element's visibility - //!\param v Visibility (true = visible) - virtual void SetVisible(bool v); - //!Sets the element's focus - //!\param f Focus (true = in focus) - virtual void SetFocus(int f); - //!Sets the element's state - //!\param s State (STATE_DEFAULT, STATE_SELECTED, STATE_CLICKED, STATE_DISABLED) - //!\param c Controller channel (0-3, -1 = none) - virtual void SetState(int s, int c = -1); - //!Resets the element's state to STATE_DEFAULT - virtual void ResetState(); - //!Gets whether or not the element is in STATE_SELECTED - //!\return true if selected, false otherwise - virtual int GetSelected(); - //!Sets the element's alignment respective to its parent element - //!\param hor Horizontal alignment (ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTRE) - //!\param vert Vertical alignment (ALIGN_TOP, ALIGN_BOTTOM, ALIGN_MIDDLE) - virtual void SetAlignment(int hor, int vert); - //!Called constantly to allow the element to respond to the current input data - //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD - virtual void Update(GuiTrigger * t); - //!Called constantly to redraw the element - virtual void Draw(); - virtual void DrawTooltip(); - protected: - void Lock(); - void Unlock(); -// static mutex_t mutex; - static mutex_t _lock_mutex; - lwp_t _lock_thread; - u16 _lock_count; - lwpq_t _lock_queue; - friend class SimpleLock; + //!\param center_y y co-ordinate of the center of circle. + void SetEffect( int e, int speed, f32 circles, int r, f32 startdegree, f32 anglespeedset, int center_x, int center_y ); + //!Gets the frequency from the above effect + //!\return element frequency + float GetFrequency(); + //!Sets an effect to be enabled on wiimote cursor over + //!\param e Effect to enable + //!\param a Amount of the effect (usage varies on effect) + //!\param t Target amount of the effect (usage varies on effect) + void SetEffectOnOver( int e, int a, int t = 0 ); + //!Shortcut to SetEffectOnOver(EFFECT_SCALE, 4, 110) + void SetEffectGrow(); + //!Stops the current element effect + void StopEffect(); + //!Gets the current element effects + //!\return element effects + int GetEffect(); + //!Gets the current element on over effects + //!\return element on over effects + int GetEffectOnOver(); + //!Checks whether the specified coordinates are within the element's boundaries + //!\param x X coordinate + //!\param y Y coordinate + //!\return true if contained within, false otherwise + bool IsInside( int x, int y ); + //!Sets the element's position + //!\param x X coordinate + //!\param y Y coordinate + void SetPosition( int x, int y, int z = 0 ); + //!Updates the element's effects (dynamic values) + //!Called by Draw(), used for animation purposes + void UpdateEffects(); + //!Sets a function to called after after Update() + //!Callback function can be used to response to changes in the state of the element, and/or update the element's attributes + void SetUpdateCallback( UpdateCallback u ); + //!Checks whether the element is in focus + //!\return true if element is in focus, false otherwise + int IsFocused(); + //!Sets the element's visibility + //!\param v Visibility (true = visible) + virtual void SetVisible( bool v ); + //!Sets the element's focus + //!\param f Focus (true = in focus) + virtual void SetFocus( int f ); + //!Sets the element's state + //!\param s State (STATE_DEFAULT, STATE_SELECTED, STATE_CLICKED, STATE_DISABLED) + //!\param c Controller channel (0-3, -1 = none) + virtual void SetState( int s, int c = -1 ); + //!Resets the element's state to STATE_DEFAULT + virtual void ResetState(); + //!Gets whether or not the element is in STATE_SELECTED + //!\return true if selected, false otherwise + virtual int GetSelected(); + //!Sets the element's alignment respective to its parent element + //!\param hor Horizontal alignment (ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTRE) + //!\param vert Vertical alignment (ALIGN_TOP, ALIGN_BOTTOM, ALIGN_MIDDLE) + virtual void SetAlignment( int hor, int vert ); + //!Called constantly to allow the element to respond to the current input data + //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD + virtual void Update( GuiTrigger * t ); + //!Called constantly to redraw the element + virtual void Draw(); + virtual void DrawTooltip(); + protected: + void Lock(); + void Unlock(); +// static mutex_t mutex; + static mutex_t _lock_mutex; + lwp_t _lock_thread; + u16 _lock_count; + lwpq_t _lock_queue; + friend class SimpleLock; //int position2; //! B Scrollbariable - bool visible; //!< Visibility of the element. If false, Draw() is skipped - int focus; //!< Element focus (-1 = focus disabled, 0 = not focused, 1 = focused) - int dontsetfocus; //! _elements; //!< Contains all elements within the GuiWindow + public: + //!Constructor + GuiWindow(); + //!\overload + //!\param w Width of window + //!\param h Height of window + GuiWindow( int w, int h ); + //!Destructor + ~GuiWindow(); + //!Appends a GuiElement to the GuiWindow + //!\param e The GuiElement to append. If it is already in the GuiWindow, it is removed first + void Append( GuiElement* e ); + //!Inserts a GuiElement into the GuiWindow at the specified index + //!\param e The GuiElement to insert. If it is already in the GuiWindow, it is removed first + //!\param i Index in which to insert the element + void Insert( GuiElement* e, u32 i ); + //!Removes the specified GuiElement from the GuiWindow + //!\param e GuiElement to be removed + void Remove( GuiElement* e ); + //!Removes all GuiElements + void RemoveAll(); + //!Returns the GuiElement at the specified index + //!\param index The index of the element + //!\return A pointer to the element at the index, NULL on error (eg: out of bounds) + GuiElement* GetGuiElementAt( u32 index ) const; + //!Returns the size of the list of elements + //!\return The size of the current element list + u32 GetSize(); + //!Sets the visibility of the window + //!\param v visibility (true = visible) + void SetVisible( bool v ); + //!Resets the window's state to STATE_DEFAULT + void ResetState(); + //!Sets the window's state + //!\param s State + void SetState( int s ); + //!Gets the index of the GuiElement inside the window that is currently selected + //!\return index of selected GuiElement + int GetSelected(); + //!Sets the window focus + //!\param f Focus + void SetFocus( int f ); + //!Change the focus to the specified element + //!This is intended for the primary GuiWindow only + //!\param e GuiElement that should have focus + void ChangeFocus( GuiElement * e ); + //!Changes window focus to the next focusable window or element + //!If no element is in focus, changes focus to the first available element + //!If B or 1 button is pressed, changes focus to the next available element + //!This is intended for the primary GuiWindow only + //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD + void ToggleFocus( GuiTrigger * t ); + //!Moves the selected element to the element to the left or right + //!\param d Direction to move (-1 = left, 1 = right) + void MoveSelectionHor( int d ); + //!Moves the selected element to the element above or below + //!\param d Direction to move (-1 = up, 1 = down) + void MoveSelectionVert( int d ); + //!Draws all the elements in this GuiWindow + void Draw(); + void DrawTooltip(); + //!Updates the window and all elements contains within + //!Allows the GuiWindow and all elements to respond to the input data specified + //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD + void Update( GuiTrigger * t ); + protected: + std::vector _elements; //!< Contains all elements within the GuiWindow }; //!Converts image data into GX-useable RGBA8. Currently designed for use only with PNG files class GuiImageData { - public: - //!Constructor - //!Converts the image data to RGBA8 - expects PNG format - //!\param i Image data - GuiImageData(const u8 * i); - GuiImageData(const char * imgPath, const u8 * buffer); - GuiImageData(const u8 * img, int imgSize); - GuiImageData(const char *path, const char *file, const u8 * buffer, bool force_widescreen=false, const u8 * wbuffer=NULL); - //!Destructor - ~GuiImageData(); - //!Gets a pointer to the image data - //!\return pointer to image data - u8 * GetImage(); - //!Gets the image width - //!\return image width - int GetWidth(); - //!Gets the image height - //!\return image height - int GetHeight(); - //!LoadJpeg file - void LoadJpeg(const u8 *img, int imgSize); - //!RawTo4x4RGBA - void RawTo4x4RGBA(const unsigned char *src, void *dst, const unsigned int width, const unsigned int height); - //!Sets the image to grayscale - void SetGrayscale(void); - protected: - u8 * data; //!< Image data - int height; //!< Height of image - int width; //!< Width of image + public: + //!Constructor + //!Converts the image data to RGBA8 - expects PNG format + //!\param i Image data + GuiImageData( const u8 * i ); + GuiImageData( const char * imgPath, const u8 * buffer ); + GuiImageData( const u8 * img, int imgSize ); + GuiImageData( const char *path, const char *file, const u8 * buffer, bool force_widescreen = false, const u8 * wbuffer = NULL ); + //!Destructor + ~GuiImageData(); + //!Gets a pointer to the image data + //!\return pointer to image data + u8 * GetImage(); + //!Gets the image width + //!\return image width + int GetWidth(); + //!Gets the image height + //!\return image height + int GetHeight(); + //!LoadJpeg file + void LoadJpeg( const u8 *img, int imgSize ); + //!RawTo4x4RGBA + void RawTo4x4RGBA( const unsigned char *src, void *dst, const unsigned int width, const unsigned int height ); + //!Sets the image to grayscale + void SetGrayscale( void ); + protected: + u8 * data; //!< Image data + int height; //!< Height of image + int width; //!< Width of image }; //!Display, manage, and manipulate images in the GUI class GuiImage : public GuiElement { - public: - //!Constructor - GuiImage(); - //!\overload - //!\param img Pointer to GuiImageData element - GuiImage(GuiImageData * img); - //!\overload - //!Sets up a new image from the image data specified - //!\param img - //!\param w Image width - //!\param h Image height - GuiImage(u8 * img, int w, int h); - //!\overload - //!Creates an image filled with the specified color - //!\param w Image width - //!\param h Image height - //!\param c Image color - GuiImage(int w, int h, GXColor c); - //! Copy Constructor - GuiImage(GuiImage &srcimage); - GuiImage(GuiImage *srcimage); - //! = operator for copying images - GuiImage &operator=(GuiImage &srcimage); - //!Destructor - ~GuiImage(); - //!Sets the image rotation angle for drawing - //!\param a Angle (in degrees) - void SetAngle(float a); - //!Gets the image rotation angle for drawing - float GetAngle(); - //!Sets the number of times to draw the image horizontally - //!\param t Number of times to draw the image - void SetTile(int t); - // true set horizontal scale to 0.8 //added - void SetWidescreen(bool w); - //!Constantly called to draw the image - void Draw(); - //!Gets the image data - //!\return pointer to image data - u8 * GetImage(); - //!Sets up a new image using the GuiImageData object specified - //!\param img Pointer to GuiImageData object - void SetImage(GuiImageData * img); - //!\overload - //!\param img Pointer to image data - //!\param w Width - //!\param h Height - void SetImage(u8 * img, int w, int h); - //!Gets the pixel color at the specified coordinates of the image - //!\param x X coordinate - //!\param y Y coordinate - GXColor GetPixel(int x, int y); - //!Sets the pixel color at the specified coordinates of the image - //!\param x X coordinate - //!\param y Y coordinate - //!\param color Pixel color - void SetPixel(int x, int y, GXColor color); - //!Sets the image to grayscale - void SetGrayscale(void); - //!Set/disable the use of parentelement angle (default true) - void SetParentAngle(bool a); - //!Directly modifies the image data to create a color-striped effect - //!Alters the RGB values by the specified amount - //!\param s Amount to increment/decrement the RGB values in the image - void ColorStripe(int s); - //!Sets a stripe effect on the image, overlaying alpha blended rectangles - //!Does not alter the image data - //!\param s Alpha amount to draw over the image - void SetStripe(int s); - s32 z; - void SetSkew(int XX1, int YY1,int XX2, int YY2,int XX3, int YY3,int XX4, int YY4); - void SetSkew(int *skew /* int skew[8] */ ); - int xx1; - int yy1; - int xx2; - int yy2; - int xx3; - int yy3; - int xx4; - int yy4; - int rxx1; - int ryy1; - int rxx2; - int ryy2; - int rxx3; - int ryy3; - int rxx4; - int ryy4; - protected: - int imgType; //!< Type of image data (IMAGE_TEXTURE, IMAGE_COLOR, IMAGE_DATA) - u8 * image; //!< Poiner to image data. May be shared with GuiImageData data - f32 imageangle; //!< Angle to draw the image - int tile; //!< Number of times to draw (tile) the image horizontally - int stripe; //!< Alpha value (0-255) to apply a stripe effect to the texture - short widescreen; //added - bool parentangle; + public: + //!Constructor + GuiImage(); + //!\overload + //!\param img Pointer to GuiImageData element + GuiImage( GuiImageData * img ); + //!\overload + //!Sets up a new image from the image data specified + //!\param img + //!\param w Image width + //!\param h Image height + GuiImage( u8 * img, int w, int h ); + //!\overload + //!Creates an image filled with the specified color + //!\param w Image width + //!\param h Image height + //!\param c Image color + GuiImage( int w, int h, GXColor c ); + //! Copy Constructor + GuiImage( GuiImage &srcimage ); + GuiImage( GuiImage *srcimage ); + //! = operator for copying images + GuiImage &operator=( GuiImage &srcimage ); + //!Destructor + ~GuiImage(); + //!Sets the image rotation angle for drawing + //!\param a Angle (in degrees) + void SetAngle( float a ); + //!Gets the image rotation angle for drawing + float GetAngle(); + //!Sets the number of times to draw the image horizontally + //!\param t Number of times to draw the image + void SetTile( int t ); + // true set horizontal scale to 0.8 //added + void SetWidescreen( bool w ); + //!Constantly called to draw the image + void Draw(); + //!Gets the image data + //!\return pointer to image data + u8 * GetImage(); + //!Sets up a new image using the GuiImageData object specified + //!\param img Pointer to GuiImageData object + void SetImage( GuiImageData * img ); + //!\overload + //!\param img Pointer to image data + //!\param w Width + //!\param h Height + void SetImage( u8 * img, int w, int h ); + //!Gets the pixel color at the specified coordinates of the image + //!\param x X coordinate + //!\param y Y coordinate + GXColor GetPixel( int x, int y ); + //!Sets the pixel color at the specified coordinates of the image + //!\param x X coordinate + //!\param y Y coordinate + //!\param color Pixel color + void SetPixel( int x, int y, GXColor color ); + //!Sets the image to grayscale + void SetGrayscale( void ); + //!Set/disable the use of parentelement angle (default true) + void SetParentAngle( bool a ); + //!Directly modifies the image data to create a color-striped effect + //!Alters the RGB values by the specified amount + //!\param s Amount to increment/decrement the RGB values in the image + void ColorStripe( int s ); + //!Sets a stripe effect on the image, overlaying alpha blended rectangles + //!Does not alter the image data + //!\param s Alpha amount to draw over the image + void SetStripe( int s ); + s32 z; + void SetSkew( int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, int XX4, int YY4 ); + void SetSkew( int *skew /* int skew[8] */ ); + int xx1; + int yy1; + int xx2; + int yy2; + int xx3; + int yy3; + int xx4; + int yy4; + int rxx1; + int ryy1; + int rxx2; + int ryy2; + int rxx3; + int ryy3; + int rxx4; + int ryy4; + protected: + int imgType; //!< Type of image data (IMAGE_TEXTURE, IMAGE_COLOR, IMAGE_DATA) + u8 * image; //!< Poiner to image data. May be shared with GuiImageData data + f32 imageangle; //!< Angle to draw the image + int tile; //!< Number of times to draw (tile) the image horizontally + int stripe; //!< Alpha value (0-255) to apply a stripe effect to the texture + short widescreen; //added + bool parentangle; }; //!Display, manage, and manipulate text in the GUI class GuiText : public GuiElement { - public: - //!Constructor - //!\param t Text - //!\param s Font size - //!\param c Font color - GuiText(const char * t, int s, GXColor c); - //!\overload - //!\param t Text - //!\param s Font size - //!\param c Font color - 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); - //!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))); - //!Sets up preset values to be used by GuiText(t) - //!Useful when printing multiple text elements, all with the same attributes set - //!\param sz Font size - //!\param c Font color - //!\param w Maximum width of texture image (for text wrapping) - //!\param wrap Wrapmode when w>0 - //!\param s Font style - //!\param h Text alignment (horizontal) - //!\param v Text alignment (vertical) - static void SetPresets(int sz, GXColor c, int w, u16 s, int h, int v); - //!Sets the font size - //!\param s Font size - void SetFontSize(int s); - //!Sets the maximum width of the drawn texture image - //!If the text exceeds this, it is wrapped to the next line - //!\param w Maximum width - //!\param m WrapMode - void SetMaxWidth(int w = 0, int m = WRAP); - //!Sets the font color - //!\param c Font color - void SetColor(GXColor c); - //!Sets the FreeTypeGX style attributes - //!\param s Style attributes - //!\param m Style-Mask attributes - void SetStyle(u16 s); - //!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); - //!Set PassChar - void SetPassChar(wchar_t p); - //!Sets the font - //!\param f Font - void SetFont(FreeTypeGX *f); - //!Get the original text as char + public: + //!Constructor + //!\param t Text + //!\param s Font size + //!\param c Font color + 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 ); + //!\overload + //!\Assumes SetPresets() has been called to setup preferred text attributes + //!\param t Text + GuiText( const char * t ); + //!Destructor + ~GuiText(); + //!Sets the text of the GuiText element + //!\param t Text + 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 + //!\param c Font color + //!\param w Maximum width of texture image (for text wrapping) + //!\param wrap Wrapmode when w>0 + //!\param s Font style + //!\param h Text alignment (horizontal) + //!\param v Text alignment (vertical) + static void SetPresets( int sz, GXColor c, int w, u16 s, int h, int v ); + //!Sets the font size + //!\param s Font size + void SetFontSize( int s ); + //!Sets the maximum width of the drawn texture image + //!If the text exceeds this, it is wrapped to the next line + //!\param w Maximum width + //!\param m WrapMode + void SetMaxWidth( int w = 0, int m = WRAP ); + //!Sets the font color + //!\param c Font color + void SetColor( GXColor c ); + //!Sets the FreeTypeGX style attributes + //!\param s Style attributes + //!\param m Style-Mask attributes + void SetStyle( u16 s ); + //!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 ); + //!Set PassChar + void SetPassChar( wchar_t p ); + //!Sets the font + //!\param f Font + 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); - //!Get the max textwidth + //!Get the Horizontal Size of Text + int GetTextWidth(); + int GetTextWidth( int ind ); + //!Get the max textwidth int GetTextMaxWidth(); - //!Gets the total line number - virtual int GetLinesCount() { return 1; }; - //!Get fontsize - int GetFontSize() { return size; }; - //!Set max lines to draw - 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); }; - //!Change the font - //!\param font bufferblock - //!\param font filesize - bool SetFont(const u8 *font, const u32 filesize); - //!Constantly called to draw the text - void Draw(); - protected: + //!Gets the total line number + virtual int GetLinesCount() { return 1; }; + //!Get fontsize + int GetFontSize() { return size; }; + //!Set max lines to draw + 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 ); }; + //!Change the font + //!\param font bufferblock + //!\param font filesize + bool SetFont( const u8 *font, const u32 filesize ); + //!Constantly called to draw the text + void Draw(); + protected: //!Clear the dynamic text void ClearDynamicText(); //!Create a dynamic dotted text if the text is too long @@ -802,391 +803,393 @@ class GuiText : public GuiElement wchar_t *text; std::vector textDyn; - int wrapMode; //!< Wrapping toggle - int textScrollPos; //!< Current starting index of text string for scrolling - int textScrollInitialDelay; //!< Delay to wait before starting to scroll - int textScrollDelay; //!< Scrolling speed - int size; //!< Font size - int maxWidth; //!< Maximum width of the generated text object (for text wrapping) - u16 style; //!< FreeTypeGX style attributes - GXColor color; //!< Font color - FreeTypeGX *font; - int textWidth; - int currentSize; - int linestodraw; - wchar_t passChar; - bool widescreen; + int wrapMode; //!< Wrapping toggle + int textScrollPos; //!< Current starting index of text string for scrolling + int textScrollInitialDelay; //!< Delay to wait before starting to scroll + int textScrollDelay; //!< Scrolling speed + int size; //!< Font size + int maxWidth; //!< Maximum width of the generated text object (for text wrapping) + u16 style; //!< FreeTypeGX style attributes + GXColor color; //!< Font color + FreeTypeGX *font; + int textWidth; + int currentSize; + int linestodraw; + wchar_t passChar; + bool widescreen; }; //!Display, manage, and manipulate tooltips in the GUI. class GuiTooltip : public GuiElement { - public: - //!Constructor - //!\param t Text - GuiTooltip(const char *t, int Alpha=255); + public: + //!Constructor + //!\param t Text + GuiTooltip( const char *t, int Alpha = 255 ); - //!Destructor - ~ GuiTooltip(); + //!Destructor + ~ GuiTooltip(); - //!Gets the element's current scale - //!Considers scale, scaleDyn, and the parent element's GetScale() value - float GetScale(); - //!Sets the text of the GuiTooltip element - //!\param t Text - void SetText(const char * t); - void SetWidescreen(bool w); // timely a dummy - //!Constantly called to draw the GuiButton - void Draw(); + //!Gets the element's current scale + //!Considers scale, scaleDyn, and the parent element's GetScale() value + float GetScale(); + //!Sets the text of the GuiTooltip element + //!\param t Text + void SetText( const char * t ); + void SetWidescreen( bool w ); // timely a dummy + //!Constantly called to draw the GuiButton + void Draw(); - protected: - GuiImage leftImage; //!< Tooltip left-image - GuiImage tileImage; //!< Tooltip tile-image - GuiImage rightImage; //!< Tooltip right-image - GuiText *text; + protected: + GuiImage leftImage; //!< Tooltip left-image + GuiImage tileImage; //!< Tooltip tile-image + GuiImage rightImage; //!< Tooltip right-image + GuiText *text; }; //!Display, manage, and manipulate buttons in the GUI. Buttons can have images, icons, text, and sound set (all of which are optional) class GuiButton : public GuiElement { - public: - //!Constructor - //!\param w Width - //!\param h Height - GuiButton(int w, int h); - //!\param img is the button GuiImage. it uses the height & width of this image for the button - //!\param imgOver is the button's over GuiImage - //!\param hor is horizontal alingment of the button - //!\param vert is verticle alignment of the button - //!\param x is xposition of the button - //!\param y is yposition of the button - //!\param trig is a GuiTrigger to assign to this button - //!\param sndOver is a GuiSound used for soundOnOver for this button - //!\param sndClick is a GuiSound used for clickSound of this button - //!\param grow sets effect grow for this button. 1 for yes ;0 for no - GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow); - //!\param same as all the parameters for the above button plus the following - //!\param tt is a GuiTooltip assigned to this button - //!\param ttx and tty are the xPOS and yPOS for this tooltip in relationship to the button - //!\param h_align and v_align are horizontal and verticle alignment for the tooltip in relationship to the button - GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow, GuiTooltip* tt, int ttx, int tty, int h_align, int v_align); - //!Destructor - ~GuiButton(); - //!Sets the button's image - //!\param i Pointer to GuiImage object - void SetImage(GuiImage* i); - //!Sets the button's image on over - //!\param i Pointer to GuiImage object - void SetImageOver(GuiImage* i); - //!Sets the button's image on hold - //!\param i Pointer to GuiImage object - void SetAngle(float a); - void SetImageHold(GuiImage* i); - //!Sets the button's image on click - //!\param i Pointer to GuiImage object - void SetImageClick(GuiImage* i); - //!Sets the button's icon - //!\param i Pointer to GuiImage object - void SetIcon(GuiImage* i); - //!Sets the button's icon on over - //!\param i Pointer to GuiImage object - void SetIconOver(GuiImage* i); - //!Sets the button's icon on hold - //!\param i Pointer to GuiImage object - void SetIconHold(GuiImage* i); - //!Sets the button's icon on click - //!\param i Pointer to GuiImage object - void SetIconClick(GuiImage* i); - //!Sets the button's label - //!\param t Pointer to GuiText object - //!\param n Index of label to set (optional, default is 0) - void SetLabel(GuiText* t, int n = 0); - //!Sets the button's label on over (eg: different colored text) - //!\param t Pointer to GuiText object - //!\param n Index of label to set (optional, default is 0) - void SetLabelOver(GuiText* t, int n = 0); - //!Sets the button's label on hold - //!\param t Pointer to GuiText object - //!\param n Index of label to set (optional, default is 0) - void SetLabelHold(GuiText* t, int n = 0); - //!Sets the button's label on click - //!\param t Pointer to GuiText object - //!\param n Index of label to set (optional, default is 0) - void SetLabelClick(GuiText* t, int n = 0); - //!Sets the sound to play on over - //!\param s Pointer to GuiSound object - void SetSoundOver(GuiSound * s); - //!Sets the sound to play on hold - //!\param s Pointer to GuiSound object - void SetSoundHold(GuiSound * s); - //!Sets the sound to play on click - //!\param s Pointer to GuiSound object - void SetSoundClick(GuiSound * s); - //!\param reset the soundover to NULL - void RemoveSoundOver(); - //!\param reset the soundclick to NULL - void RemoveSoundClick(); - //!Constantly called to draw the GuiButtons ToolTip - //!Sets the button's Tooltip on over - //!\param tt Pointer to GuiElement object, x & y Positioning, h & v Align - void SetToolTip(GuiTooltip* tt, int x, int y, int h=ALIGN_RIGHT, int v=ALIGN_TOP); + public: + //!Constructor + //!\param w Width + //!\param h Height + GuiButton( int w, int h ); + //!\param img is the button GuiImage. it uses the height & width of this image for the button + //!\param imgOver is the button's over GuiImage + //!\param hor is horizontal alingment of the button + //!\param vert is verticle alignment of the button + //!\param x is xposition of the button + //!\param y is yposition of the button + //!\param trig is a GuiTrigger to assign to this button + //!\param sndOver is a GuiSound used for soundOnOver for this button + //!\param sndClick is a GuiSound used for clickSound of this button + //!\param grow sets effect grow for this button. 1 for yes ;0 for no + GuiButton( GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow ); + //!\param same as all the parameters for the above button plus the following + //!\param tt is a GuiTooltip assigned to this button + //!\param ttx and tty are the xPOS and yPOS for this tooltip in relationship to the button + //!\param h_align and v_align are horizontal and verticle alignment for the tooltip in relationship to the button + GuiButton( GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow, GuiTooltip* tt, int ttx, int tty, int h_align, int v_align ); + //!Destructor + ~GuiButton(); + //!Sets the button's image + //!\param i Pointer to GuiImage object + void SetImage( GuiImage* i ); + //!Sets the button's image on over + //!\param i Pointer to GuiImage object + void SetImageOver( GuiImage* i ); + //!Sets the button's image on hold + //!\param i Pointer to GuiImage object + void SetAngle( float a ); + void SetImageHold( GuiImage* i ); + //!Sets the button's image on click + //!\param i Pointer to GuiImage object + void SetImageClick( GuiImage* i ); + //!Sets the button's icon + //!\param i Pointer to GuiImage object + void SetIcon( GuiImage* i ); + //!Sets the button's icon on over + //!\param i Pointer to GuiImage object + void SetIconOver( GuiImage* i ); + //!Sets the button's icon on hold + //!\param i Pointer to GuiImage object + void SetIconHold( GuiImage* i ); + //!Sets the button's icon on click + //!\param i Pointer to GuiImage object + void SetIconClick( GuiImage* i ); + //!Sets the button's label + //!\param t Pointer to GuiText object + //!\param n Index of label to set (optional, default is 0) + void SetLabel( GuiText* t, int n = 0 ); + //!Sets the button's label on over (eg: different colored text) + //!\param t Pointer to GuiText object + //!\param n Index of label to set (optional, default is 0) + void SetLabelOver( GuiText* t, int n = 0 ); + //!Sets the button's label on hold + //!\param t Pointer to GuiText object + //!\param n Index of label to set (optional, default is 0) + void SetLabelHold( GuiText* t, int n = 0 ); + //!Sets the button's label on click + //!\param t Pointer to GuiText object + //!\param n Index of label to set (optional, default is 0) + void SetLabelClick( GuiText* t, int n = 0 ); + //!Sets the sound to play on over + //!\param s Pointer to GuiSound object + void SetSoundOver( GuiSound * s ); + //!Sets the sound to play on hold + //!\param s Pointer to GuiSound object + void SetSoundHold( GuiSound * s ); + //!Sets the sound to play on click + //!\param s Pointer to GuiSound object + void SetSoundClick( GuiSound * s ); + //!\param reset the soundover to NULL + void RemoveSoundOver(); + //!\param reset the soundclick to NULL + void RemoveSoundClick(); + //!Constantly called to draw the GuiButtons ToolTip + //!Sets the button's Tooltip on over + //!\param tt Pointer to GuiElement object, x & y Positioning, h & v Align + void SetToolTip( GuiTooltip* tt, int x, int y, int h = ALIGN_RIGHT, int v = ALIGN_TOP ); - void RemoveToolTip(); - //!Constantly called to draw the GuiButton - void Draw(); - void DrawTooltip(); - //!Constantly called to allow the GuiButton to respond to updated input data - //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD - void Update(GuiTrigger * t); - //!Deactivate/Activate pointing on Games while B scrolling - void ScrollIsOn(int f); - void SetSkew(int XX1, int YY1,int XX2, int YY2,int XX3, int YY3,int XX4, int YY4); - void SetSkew(int *skew /* int skew[8] */ ); - protected: - GuiImage * image; //!< Button image (default) - GuiImage * imageOver; //!< Button image for STATE_SELECTED - GuiImage * imageHold; //!< Button image for STATE_HELD - GuiImage * imageClick; //!< Button image for STATE_CLICKED - GuiImage * icon; //!< Button icon (drawn after button image) - GuiImage * iconOver; //!< Button icon for STATE_SELECTED - GuiImage * iconHold; //!< Button icon for STATE_HELD - GuiImage * iconClick; //!< Button icon for STATE_CLICKED - GuiTooltip *toolTip; - time_t time1, time2;//!< Tooltip timeconstants - GuiText * label[3]; //!< Label(s) to display (default) - GuiText * labelOver[3]; //!< Label(s) to display for STATE_SELECTED - GuiText * labelHold[3]; //!< Label(s) to display for STATE_HELD - GuiText * labelClick[3]; //!< Label(s) to display for STATE_CLICKED - GuiSound * soundOver; //!< Sound to play for STATE_SELECTED - GuiSound * soundHold; //!< Sound to play for STATE_HELD - GuiSound * soundClick; //!< Sound to play for STATE_CLICKED + void RemoveToolTip(); + //!Constantly called to draw the GuiButton + void Draw(); + void DrawTooltip(); + //!Constantly called to allow the GuiButton to respond to updated input data + //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD + void Update( GuiTrigger * t ); + //!Deactivate/Activate pointing on Games while B scrolling + void ScrollIsOn( int f ); + void SetSkew( int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, int XX4, int YY4 ); + void SetSkew( int *skew /* int skew[8] */ ); + protected: + GuiImage * image; //!< Button image (default) + GuiImage * imageOver; //!< Button image for STATE_SELECTED + GuiImage * imageHold; //!< Button image for STATE_HELD + GuiImage * imageClick; //!< Button image for STATE_CLICKED + GuiImage * icon; //!< Button icon (drawn after button image) + GuiImage * iconOver; //!< Button icon for STATE_SELECTED + GuiImage * iconHold; //!< Button icon for STATE_HELD + GuiImage * iconClick; //!< Button icon for STATE_CLICKED + GuiTooltip *toolTip; + time_t time1, time2;//!< Tooltip timeconstants + GuiText * label[3]; //!< Label(s) to display (default) + GuiText * labelOver[3]; //!< Label(s) to display for STATE_SELECTED + GuiText * labelHold[3]; //!< Label(s) to display for STATE_HELD + GuiText * labelClick[3]; //!< Label(s) to display for STATE_CLICKED + GuiSound * soundOver; //!< Sound to play for STATE_SELECTED + GuiSound * soundHold; //!< Sound to play for STATE_HELD + GuiSound * soundClick; //!< Sound to play for STATE_CLICKED }; -typedef struct _keytype { - char ch, chShift, chalt, chalt2; +typedef struct _keytype +{ + char ch, chShift, chalt, chalt2; } Key; //!On-screen keyboard class GuiKeyboard : public GuiWindow { - public: - GuiKeyboard(char * t, u32 m, int min, int lang); - ~GuiKeyboard(); - void Update(GuiTrigger * t); - char kbtextstr[256]; - protected: - u32 kbtextmaxlen; - Key keys[4][11]; - int shift; - int caps; - int alt; - int alt2; - GuiText * kbText; - GuiImage * keyTextboxImg; - GuiText * keyCapsText; - GuiImage * keyCapsImg; - GuiImage * keyCapsOverImg; - GuiButton * keyCaps; - GuiText * keyAltText; - GuiImage * keyAltImg; - GuiImage * keyAltOverImg; - GuiButton * keyAlt; - GuiText * keyAlt2Text; - GuiImage * keyAlt2Img; - GuiImage * keyAlt2OverImg; - GuiButton * keyAlt2; - GuiText * keyShiftText; - GuiImage * keyShiftImg; - GuiImage * keyShiftOverImg; - GuiButton * keyShift; - GuiText * keyBackText; - GuiImage * keyBackImg; - GuiImage * keyBackOverImg; - GuiButton * keyBack; - GuiText * keyClearText; - GuiImage * keyClearImg; - GuiImage * keyClearOverImg; - GuiButton * keyClear; - GuiImage * keySpaceImg; - GuiImage * keySpaceOverImg; - GuiButton * keySpace; - GuiButton * keyBtn[4][11]; - GuiImage * keyImg[4][11]; - GuiImage * keyImgOver[4][11]; - GuiText * keyTxt[4][11]; - GuiImageData * keyTextbox; - GuiImageData * key; - GuiImageData * keyOver; - GuiImageData * keyMedium; - GuiImageData * keyMediumOver; - GuiImageData * keyLarge; - GuiImageData * keyLargeOver; - GuiSound * keySoundOver; - GuiSound * keySoundClick; - GuiTrigger * trigA; - GuiTrigger * trigB; + public: + GuiKeyboard( char * t, u32 m, int min, int lang ); + ~GuiKeyboard(); + void Update( GuiTrigger * t ); + char kbtextstr[256]; + protected: + u32 kbtextmaxlen; + Key keys[4][11]; + int shift; + int caps; + int alt; + int alt2; + GuiText * kbText; + GuiImage * keyTextboxImg; + GuiText * keyCapsText; + GuiImage * keyCapsImg; + GuiImage * keyCapsOverImg; + GuiButton * keyCaps; + GuiText * keyAltText; + GuiImage * keyAltImg; + GuiImage * keyAltOverImg; + GuiButton * keyAlt; + GuiText * keyAlt2Text; + GuiImage * keyAlt2Img; + GuiImage * keyAlt2OverImg; + GuiButton * keyAlt2; + GuiText * keyShiftText; + GuiImage * keyShiftImg; + GuiImage * keyShiftOverImg; + GuiButton * keyShift; + GuiText * keyBackText; + GuiImage * keyBackImg; + GuiImage * keyBackOverImg; + GuiButton * keyBack; + GuiText * keyClearText; + GuiImage * keyClearImg; + GuiImage * keyClearOverImg; + GuiButton * keyClear; + GuiImage * keySpaceImg; + GuiImage * keySpaceOverImg; + GuiButton * keySpace; + GuiButton * keyBtn[4][11]; + GuiImage * keyImg[4][11]; + GuiImage * keyImgOver[4][11]; + GuiText * keyTxt[4][11]; + GuiImageData * keyTextbox; + GuiImageData * key; + GuiImageData * keyOver; + GuiImageData * keyMedium; + GuiImageData * keyMediumOver; + GuiImageData * keyLarge; + GuiImageData * keyLargeOver; + GuiSound * keySoundOver; + GuiSound * keySoundClick; + GuiTrigger * trigA; + GuiTrigger * trigB; }; //!On-screen keyboard class GuiNumpad : public GuiWindow { - public: - GuiNumpad(char * t, u32 max); - ~GuiNumpad(); - void Update(GuiTrigger * t); - char kbtextstr[256]; - protected: - u32 kbtextmaxlen; - char keys[11]; - GuiText * kbText; - GuiImage * keyTextboxImg; + public: + GuiNumpad( char * t, u32 max ); + ~GuiNumpad(); + void Update( GuiTrigger * t ); + char kbtextstr[256]; + protected: + u32 kbtextmaxlen; + char keys[11]; + GuiText * kbText; + GuiImage * keyTextboxImg; - GuiText * keyBackText; - GuiImage * keyBackImg; - GuiImage * keyBackOverImg; - GuiButton * keyBack; - GuiText * keyClearText; - GuiImage * keyClearImg; - GuiImage * keyClearOverImg; - GuiButton * keyClear; - GuiButton * keyBtn[11]; - GuiImage * keyImg[11]; - GuiImage * keyImgOver[11]; - GuiText * keyTxt[11]; - GuiImageData * keyTextbox; - GuiImageData * keyMedium; - GuiImageData * keyMediumOver; - GuiSound * keySoundOver; - GuiSound * keySoundClick; - GuiTrigger * trigA; - GuiTrigger * trigB; + GuiText * keyBackText; + GuiImage * keyBackImg; + GuiImage * keyBackOverImg; + GuiButton * keyBack; + GuiText * keyClearText; + GuiImage * keyClearImg; + GuiImage * keyClearOverImg; + GuiButton * keyClear; + GuiButton * keyBtn[11]; + GuiImage * keyImg[11]; + GuiImage * keyImgOver[11]; + GuiText * keyTxt[11]; + GuiImageData * keyTextbox; + GuiImageData * keyMedium; + GuiImageData * keyMediumOver; + GuiSound * keySoundOver; + GuiSound * keySoundClick; + GuiTrigger * trigA; + GuiTrigger * trigB; }; -typedef struct _optionlist { - int length; - char name[MAX_OPTIONS][60]; - char value[MAX_OPTIONS][30]; +typedef struct _optionlist +{ + int length; + char name[MAX_OPTIONS][60]; + char value[MAX_OPTIONS][30]; } OptionList; //!Display a list of menu options class GuiOptionBrowser : public GuiElement { - public: - GuiOptionBrowser(int w, int h, OptionList * l, const u8 *imagebg, int scrollbar); - GuiOptionBrowser(int w, int h, OptionList * l, const char * themePath, const u8 *imagebg, int scrollbar, int start); - ~GuiOptionBrowser(); - void SetCol2Position(int x); - int FindMenuItem(int c, int d); - int GetClickedOption(); - int GetSelectedOption(); - void ResetState(); - void SetFocus(int f); - void Draw(); - void TriggerUpdate(); - void Update(GuiTrigger * t); - GuiText * optionVal[PAGESIZE]; - protected: - int selectedItem; - int listOffset; - bool listChanged; - OptionList * options; - int optionIndex[PAGESIZE]; - GuiButton * optionBtn[PAGESIZE]; - GuiText * optionTxt[PAGESIZE]; - GuiImage * optionBg[PAGESIZE]; + public: + GuiOptionBrowser( int w, int h, OptionList * l, const u8 *imagebg, int scrollbar ); + GuiOptionBrowser( int w, int h, OptionList * l, const char * themePath, const u8 *imagebg, int scrollbar, int start ); + ~GuiOptionBrowser(); + void SetCol2Position( int x ); + int FindMenuItem( int c, int d ); + int GetClickedOption(); + int GetSelectedOption(); + void ResetState(); + void SetFocus( int f ); + void Draw(); + void TriggerUpdate(); + void Update( GuiTrigger * t ); + GuiText * optionVal[PAGESIZE]; + protected: + int selectedItem; + int listOffset; + bool listChanged; + OptionList * options; + int optionIndex[PAGESIZE]; + GuiButton * optionBtn[PAGESIZE]; + GuiText * optionTxt[PAGESIZE]; + GuiImage * optionBg[PAGESIZE]; - GuiButton * arrowUpBtn; - GuiButton * arrowDownBtn; - GuiButton * scrollbarBoxBtn; + GuiButton * arrowUpBtn; + GuiButton * arrowDownBtn; + GuiButton * scrollbarBoxBtn; - GuiImage * bgOptionsImg; - GuiImage * bgOptionsOverImg; - GuiImage * scrollbarImg; - GuiImage * arrowDownImg; - GuiImage * arrowDownOverImg; - GuiImage * arrowUpImg; - GuiImage * arrowUpOverImg; - GuiImage * scrollbarBoxImg; - GuiImage * scrollbarBoxOverImg; + GuiImage * bgOptionsImg; + GuiImage * bgOptionsOverImg; + GuiImage * scrollbarImg; + GuiImage * arrowDownImg; + GuiImage * arrowDownOverImg; + GuiImage * arrowUpImg; + GuiImage * arrowUpOverImg; + GuiImage * scrollbarBoxImg; + GuiImage * scrollbarBoxOverImg; - GuiImageData * bgOptions; - GuiImageData * bgOptionsOver; - GuiImageData * bgOptionsEntry; - GuiImageData * scrollbar; - GuiImageData * arrowDown; - GuiImageData * arrowDownOver; - GuiImageData * arrowUp; - GuiImageData * arrowUpOver; - GuiImageData * scrollbarBox; - GuiImageData * scrollbarBoxOver; + GuiImageData * bgOptions; + GuiImageData * bgOptionsOver; + GuiImageData * bgOptionsEntry; + GuiImageData * scrollbar; + GuiImageData * arrowDown; + GuiImageData * arrowDownOver; + GuiImageData * arrowUp; + GuiImageData * arrowUpOver; + GuiImageData * scrollbarBox; + GuiImageData * scrollbarBoxOver; - GuiSound * btnSoundOver; - GuiSound * btnSoundClick; - GuiTrigger * trigA; - GuiTrigger * trigB; - GuiTrigger * trigHeldA; + GuiSound * btnSoundOver; + GuiSound * btnSoundClick; + GuiTrigger * trigA; + GuiTrigger * trigB; + GuiTrigger * trigHeldA; }; //!Display a list of files class GuiFileBrowser : public GuiElement { - public: - GuiFileBrowser(int w, int h); - ~GuiFileBrowser(); - void DisableTriggerUpdate(bool set); - void ResetState(); - void SetFocus(int f); - void Draw(); - void TriggerUpdate(); - void Update(GuiTrigger * t); - GuiButton * fileList[PAGESIZE]; - protected: - int selectedItem; - bool listChanged; - bool triggerdisabled; + public: + GuiFileBrowser( int w, int h ); + ~GuiFileBrowser(); + void DisableTriggerUpdate( bool set ); + void ResetState(); + void SetFocus( int f ); + void Draw(); + void TriggerUpdate(); + void Update( GuiTrigger * t ); + GuiButton * fileList[PAGESIZE]; + protected: + int selectedItem; + bool listChanged; + bool triggerdisabled; - GuiText * fileListText[PAGESIZE]; - GuiText * fileListTextOver[PAGESIZE]; - GuiImage * fileListBg[PAGESIZE]; - //GuiImage * fileListArchives[PAGESIZE]; - //GuiImage * fileListDefault[PAGESIZE]; - GuiImage * fileListFolder[PAGESIZE]; - //GuiImage * fileListGFX[PAGESIZE]; - //GuiImage * fileListPLS[PAGESIZE]; - //GuiImage * fileListSFX[PAGESIZE]; - //GuiImage * fileListTXT[PAGESIZE]; - //GuiImage * fileListXML[PAGESIZE]; + GuiText * fileListText[PAGESIZE]; + GuiText * fileListTextOver[PAGESIZE]; + GuiImage * fileListBg[PAGESIZE]; + //GuiImage * fileListArchives[PAGESIZE]; + //GuiImage * fileListDefault[PAGESIZE]; + GuiImage * fileListFolder[PAGESIZE]; + //GuiImage * fileListGFX[PAGESIZE]; + //GuiImage * fileListPLS[PAGESIZE]; + //GuiImage * fileListSFX[PAGESIZE]; + //GuiImage * fileListTXT[PAGESIZE]; + //GuiImage * fileListXML[PAGESIZE]; - GuiButton * arrowUpBtn; - GuiButton * arrowDownBtn; - GuiButton * scrollbarBoxBtn; + GuiButton * arrowUpBtn; + GuiButton * arrowDownBtn; + GuiButton * scrollbarBoxBtn; - GuiImage * bgFileSelectionImg; - GuiImage * scrollbarImg; - GuiImage * arrowDownImg; - GuiImage * arrowUpImg; - GuiImage * scrollbarBoxImg; + GuiImage * bgFileSelectionImg; + GuiImage * scrollbarImg; + GuiImage * arrowDownImg; + GuiImage * arrowUpImg; + GuiImage * scrollbarBoxImg; - GuiImageData * bgFileSelection; - GuiImageData * bgFileSelectionEntry; + GuiImageData * bgFileSelection; + GuiImageData * bgFileSelectionEntry; //GuiImageData * fileArchives; - //GuiImageData * fileDefault; - GuiImageData * fileFolder; + //GuiImageData * fileDefault; + GuiImageData * fileFolder; //GuiImageData * fileGFX; - //GuiImageData * filePLS; - //GuiImageData * fileSFX; + //GuiImageData * filePLS; + //GuiImageData * fileSFX; //GuiImageData * fileTXT; //GuiImageData * fileXML; - GuiImageData * scrollbar; - GuiImageData * arrowDown; - GuiImageData * arrowUp; - GuiImageData * scrollbarBox; + GuiImageData * scrollbar; + GuiImageData * arrowDown; + GuiImageData * arrowUp; + GuiImageData * scrollbarBox; - GuiSound * btnSoundOver; - GuiSound * btnSoundClick; - GuiTrigger * trigA; - GuiTrigger * trigHeldA; + GuiSound * btnSoundOver; + GuiSound * btnSoundClick; + GuiTrigger * trigA; + GuiTrigger * trigHeldA; }; #endif diff --git a/source/libwiigui/gui_bgm.cpp b/source/libwiigui/gui_bgm.cpp index 9c7ae641..d5547f4c 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,27 +18,27 @@ 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) + 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; } @@ -46,92 +46,92 @@ void GuiBGM::SetLoop(int l) 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; 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) + if ( ret ) Play(); return ret; } -bool GuiBGM::ParsePath(const char * folderpath) +bool GuiBGM::ParsePath( const char * folderpath ) { ClearList(); - if(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) + if ( strcmp( LoadedFilename, filename ) == 0 ) currentPlaying = counter; counter++; @@ -139,32 +139,32 @@ bool GuiBGM::ParsePath(const char * folderpath) } } - 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) + 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,16 +173,16 @@ void GuiBGM::ClearList() bool GuiBGM::PlayNext() { - if(!currentPath) + if ( !currentPath ) return false; currentPlaying++; - if(currentPlaying >= (int) PlayList.size()) + 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)) + if ( !GuiSound::Load( Settings.ogg_path ) ) return false; Play(); @@ -192,16 +192,16 @@ bool GuiBGM::PlayNext() bool GuiBGM::PlayPrevious() { - if(!currentPath) + 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)) + if ( !GuiSound::Load( Settings.ogg_path ) ) return false; Play(); @@ -211,22 +211,22 @@ bool GuiBGM::PlayPrevious() bool GuiBGM::PlayRandom() { - if(!currentPath) + if ( !currentPath ) return false; - srand (time(NULL)); + srand ( time( NULL ) ); currentPlaying = rand() % PlayList.size(); //just in case - if(currentPlaying < 0) - currentPlaying = PlayList.size()-1; - else if(currentPlaying >= (int) PlayList.size()) + if ( currentPlaying < 0 ) + currentPlaying = PlayList.size() - 1; + 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)) + if ( !GuiSound::Load( Settings.ogg_path ) ) return false; Play(); @@ -236,13 +236,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 f1731fb9..5a458d3a 100644 --- a/source/libwiigui/gui_bgm.h +++ b/source/libwiigui/gui_bgm.h @@ -21,19 +21,19 @@ enum 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 40ee15c8..70f9a1c9 100644 --- a/source/libwiigui/gui_button.cpp +++ b/source/libwiigui/gui_button.cpp @@ -16,130 +16,132 @@ static int scrollison; * Constructor for the GuiButton class. */ -GuiButton::GuiButton(int w, int h) +GuiButton::GuiButton( int w, int h ) { - width = w; - height = h; - image = NULL; - imageOver = NULL; - imageHold = NULL; - imageClick = NULL; - icon = NULL; - iconOver = NULL; - iconHold = NULL; - iconClick = NULL; - toolTip = NULL; + width = w; + height = h; + image = NULL; + imageOver = NULL; + imageHold = NULL; + imageClick = NULL; + icon = NULL; + iconOver = NULL; + iconHold = NULL; + iconClick = NULL; + toolTip = NULL; - for(int i=0; i < 3; i++) - { - label[i] = NULL; - labelOver[i] = NULL; - labelHold[i] = NULL; - labelClick[i] = NULL; - } + for ( int i = 0; i < 3; i++ ) + { + label[i] = NULL; + labelOver[i] = NULL; + labelHold[i] = NULL; + labelClick[i] = NULL; + } - soundOver = NULL; - soundHold = NULL; - soundClick = NULL; - selectable = true; - holdable = false; - clickable = true; - - time1 = time2 = 0; + soundOver = NULL; + soundHold = NULL; + soundClick = NULL; + selectable = true; + holdable = false; + clickable = true; + + time1 = time2 = 0; } -GuiButton::GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow) +GuiButton::GuiButton( GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow ) { - width = img->GetWidth(); - height = img->GetHeight(); - image = img; - image->SetParent(this); - imageOver = imgOver; - if(imageOver) imageOver->SetParent(this); - imageHold = NULL; - imageClick = NULL; - icon = NULL; - iconOver = NULL; - iconHold = NULL; - iconClick = NULL; - toolTip = NULL; - alignmentHor = hor; - alignmentVert = vert; - xoffset = x; - yoffset = y; - trigger[0] = trig; + width = img->GetWidth(); + height = img->GetHeight(); + image = img; + image->SetParent( this ); + imageOver = imgOver; + if ( imageOver ) imageOver->SetParent( this ); + imageHold = NULL; + imageClick = NULL; + icon = NULL; + iconOver = NULL; + iconHold = NULL; + iconClick = NULL; + toolTip = NULL; + alignmentHor = hor; + alignmentVert = vert; + xoffset = x; + yoffset = y; + trigger[0] = trig; - for(int i=0; i < 3; i++) - { - label[i] = NULL; - labelOver[i] = NULL; - labelHold[i] = NULL; - labelClick[i] = NULL; - } + for ( int i = 0; i < 3; i++ ) + { + label[i] = NULL; + labelOver[i] = NULL; + labelHold[i] = NULL; + labelClick[i] = NULL; + } - soundOver = sndOver; - soundHold = NULL; - soundClick = sndClick; - selectable = true; - holdable = false; - clickable = true; + soundOver = sndOver; + soundHold = NULL; + soundClick = sndClick; + selectable = true; + holdable = false; + clickable = true; - if (grow==1){ - effectsOver |= EFFECT_SCALE; - effectAmountOver = 4; - effectTargetOver = 110; - } - time1 = time2 = 0; + if ( grow == 1 ) + { + effectsOver |= EFFECT_SCALE; + effectAmountOver = 4; + effectTargetOver = 110; + } + time1 = time2 = 0; } -GuiButton::GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow, GuiTooltip* tt, int ttx, int tty, int h_align, int v_align) +GuiButton::GuiButton( GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow, GuiTooltip* tt, int ttx, int tty, int h_align, int v_align ) { - width = img->GetWidth(); - height = img->GetHeight(); - image = img; - image->SetParent(this); - imageOver = imgOver; - if(imageOver) imageOver->SetParent(this); - imageHold = NULL; - imageClick = NULL; - icon = NULL; - iconOver = NULL; - iconHold = NULL; - iconClick = NULL; - toolTip = NULL; - alignmentHor = hor; - alignmentVert = vert; - xoffset = x; - yoffset = y; - trigger[0] = trig; + width = img->GetWidth(); + height = img->GetHeight(); + image = img; + image->SetParent( this ); + imageOver = imgOver; + if ( imageOver ) imageOver->SetParent( this ); + imageHold = NULL; + imageClick = NULL; + icon = NULL; + iconOver = NULL; + iconHold = NULL; + iconClick = NULL; + toolTip = NULL; + alignmentHor = hor; + alignmentVert = vert; + xoffset = x; + yoffset = y; + trigger[0] = trig; - for(int i=0; i < 3; i++) - { - label[i] = NULL; - labelOver[i] = NULL; - labelHold[i] = NULL; - labelClick[i] = NULL; - } + for ( int i = 0; i < 3; i++ ) + { + label[i] = NULL; + labelOver[i] = NULL; + labelHold[i] = NULL; + labelClick[i] = NULL; + } - soundOver = sndOver; - soundHold = NULL; - soundClick = sndClick; - selectable = true; - holdable = false; - clickable = true; + soundOver = sndOver; + soundHold = NULL; + soundClick = sndClick; + selectable = true; + holdable = false; + clickable = true; - if (grow==1) { - effectsOver |= EFFECT_SCALE; - effectAmountOver = 4; - effectTargetOver = 110; - } + if ( grow == 1 ) + { + effectsOver |= EFFECT_SCALE; + effectAmountOver = 4; + effectTargetOver = 110; + } - toolTip = tt; - toolTip->SetParent(this); - toolTip->SetAlignment(h_align, v_align); - toolTip->SetPosition(ttx,tty); + toolTip = tt; + toolTip->SetParent( this ); + toolTip->SetAlignment( h_align, v_align ); + toolTip->SetPosition( ttx, tty ); - time1 = time2 = 0; + time1 = time2 = 0; } /** @@ -149,142 +151,142 @@ GuiButton::~GuiButton() { } -void GuiButton::SetImage(GuiImage* img) +void GuiButton::SetImage( GuiImage* img ) { - LOCK(this); - image = img; - if(img) img->SetParent(this); + LOCK( this ); + image = img; + if ( img ) img->SetParent( this ); } -void GuiButton::SetImageOver(GuiImage* img) +void GuiButton::SetImageOver( GuiImage* img ) { - LOCK(this); - imageOver = img; - if(img) img->SetParent(this); + LOCK( this ); + imageOver = img; + if ( img ) img->SetParent( this ); } -void GuiButton::SetImageHold(GuiImage* img) +void GuiButton::SetImageHold( GuiImage* img ) { - LOCK(this); - imageHold = img; - if(img) img->SetParent(this); + LOCK( this ); + imageHold = img; + if ( img ) img->SetParent( this ); } -void GuiButton::SetImageClick(GuiImage* img) +void GuiButton::SetImageClick( GuiImage* img ) { - LOCK(this); - imageClick = img; - if(img) img->SetParent(this); + LOCK( this ); + imageClick = img; + if ( img ) img->SetParent( this ); } -void GuiButton::SetIcon(GuiImage* img) +void GuiButton::SetIcon( GuiImage* img ) { - LOCK(this); - icon = img; - if(img) img->SetParent(this); + LOCK( this ); + icon = img; + if ( img ) img->SetParent( this ); } -void GuiButton::SetIconOver(GuiImage* img) +void GuiButton::SetIconOver( GuiImage* img ) { - LOCK(this); - iconOver = img; - if(img) img->SetParent(this); + LOCK( this ); + iconOver = img; + if ( img ) img->SetParent( this ); } -void GuiButton::SetIconHold(GuiImage* img) +void GuiButton::SetIconHold( GuiImage* img ) { - LOCK(this); - iconHold = img; - if(img) img->SetParent(this); + LOCK( this ); + iconHold = img; + if ( img ) img->SetParent( this ); } -void GuiButton::SetIconClick(GuiImage* img) +void GuiButton::SetIconClick( GuiImage* img ) { - LOCK(this); - iconClick = img; - if(img) img->SetParent(this); + LOCK( this ); + iconClick = img; + 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); + LOCK( this ); + label[n] = txt; + 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); + LOCK( this ); + labelOver[n] = txt; + 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); + LOCK( this ); + labelHold[n] = txt; + 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); + LOCK( this ); + labelClick[n] = txt; + if ( txt ) txt->SetParent( this ); } -void GuiButton::SetSoundOver(GuiSound * snd) +void GuiButton::SetSoundOver( GuiSound * snd ) { - LOCK(this); - soundOver = snd; + LOCK( this ); + soundOver = snd; } -void GuiButton::SetSoundHold(GuiSound * snd) +void GuiButton::SetSoundHold( GuiSound * snd ) { - LOCK(this); - soundHold = snd; + LOCK( this ); + soundHold = snd; } -void GuiButton::SetSoundClick(GuiSound * snd) +void GuiButton::SetSoundClick( GuiSound * snd ) { - LOCK(this); - soundClick = 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) - { - toolTip = tt; - toolTip->SetParent(this); - toolTip->SetAlignment(h_align, v_align); - toolTip->SetPosition(x,y); + LOCK( this ); + if ( tt ) + { + toolTip = tt; + toolTip->SetParent( this ); + toolTip->SetAlignment( h_align, v_align ); + toolTip->SetPosition( x, y ); - } + } } void GuiButton::RemoveToolTip() { - LOCK(this); - toolTip = NULL; + LOCK( this ); + toolTip = NULL; } void GuiButton::RemoveSoundOver() { - LOCK(this); - soundOver = NULL; + LOCK( this ); + soundOver = NULL; } void GuiButton::RemoveSoundClick() { - LOCK(this); - soundClick = NULL; + LOCK( this ); + soundClick = NULL; } -void GuiButton::SetSkew(int XX1, int YY1,int XX2, int YY2,int XX3, int YY3,int XX4, int YY4) -{ - if(image) - { - image->xx1 = XX1; - image->yy1 = YY1; - image->xx2 = XX2; - image->yy2 = YY2; - image->xx3 = XX3; - image->yy3 = YY3; - image->xx4 = XX4; - image->yy4 = YY4; - } +void GuiButton::SetSkew( int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, int XX4, int YY4 ) +{ + if ( image ) + { + image->xx1 = XX1; + image->yy1 = YY1; + image->xx2 = XX2; + image->yy2 = YY2; + image->xx3 = XX3; + image->yy3 = YY3; + image->xx4 = XX4; + image->yy4 = YY4; + } } -void GuiButton::SetSkew(int *skew) -{ - if(image) - image->SetSkew(skew); +void GuiButton::SetSkew( int *skew ) +{ + if ( image ) + image->SetSkew( skew ); } @@ -293,235 +295,236 @@ void GuiButton::SetSkew(int *skew) */ void GuiButton::Draw() { - LOCK(this); - if(!this->IsVisible()) - return; + LOCK( this ); + if ( !this->IsVisible() ) + return; - // draw image - if((state == STATE_SELECTED || state == STATE_HELD) && imageOver) - imageOver->Draw(); - else if(image) - image->Draw(); - // draw icon - if((state == STATE_SELECTED || state == STATE_HELD) && iconOver) - iconOver->Draw(); - else if(icon) - icon->Draw(); - // draw text - for(int i=0; i<3; i++) - { - if((state == STATE_SELECTED || state == STATE_HELD) && labelOver[i]) - labelOver[i]->Draw(); - else if(label[i]) - label[i]->Draw(); - } + // draw image + if ( ( state == STATE_SELECTED || state == STATE_HELD ) && imageOver ) + imageOver->Draw(); + else if ( image ) + image->Draw(); + // draw icon + if ( ( state == STATE_SELECTED || state == STATE_HELD ) && iconOver ) + iconOver->Draw(); + else if ( icon ) + icon->Draw(); + // draw text + for ( int i = 0; i < 3; i++ ) + { + if ( ( state == STATE_SELECTED || state == STATE_HELD ) && labelOver[i] ) + labelOver[i]->Draw(); + else if ( label[i] ) + label[i]->Draw(); + } - this->UpdateEffects(); + this->UpdateEffects(); } void GuiButton::DrawTooltip() { - LOCK(this); - if(this->IsVisible() && state == STATE_SELECTED && toolTip) - { - if (time2 == 0) - { - time(&time1); - time2 = time1; - } - if(time1 != 0) // timer läuft - time(&time1); - - if(time1 == 0 || difftime(time1, time2) >= 2) - { - if(time1 != 0) // timer gerade abgelaufen - toolTip->SetEffect(EFFECT_FADE, 20); - time1 = 0; - toolTip->Draw(); - return; + LOCK( this ); + if ( this->IsVisible() && state == STATE_SELECTED && toolTip ) + { + if ( time2 == 0 ) + { + time( &time1 ); + time2 = time1; } - } - else - { - if(time2 != 0 && time1 == 0) // timer abgelaufen, gerade DESELECT - if(toolTip) toolTip->SetEffect(EFFECT_FADE, -20); - time2 = 0; - } - if(toolTip && toolTip->GetEffect()) - toolTip->Draw(); + if ( time1 != 0 ) // timer läuft + time( &time1 ); + + if ( time1 == 0 || difftime( time1, time2 ) >= 2 ) + { + if ( time1 != 0 ) // timer gerade abgelaufen + toolTip->SetEffect( EFFECT_FADE, 20 ); + time1 = 0; + toolTip->Draw(); + return; + } + } + else + { + if ( time2 != 0 && time1 == 0 ) // timer abgelaufen, gerade DESELECT + if ( toolTip ) toolTip->SetEffect( EFFECT_FADE, -20 ); + time2 = 0; + } + if ( toolTip && toolTip->GetEffect() ) + toolTip->Draw(); } -void GuiButton::ScrollIsOn(int f) +void GuiButton::ScrollIsOn( int f ) { - LOCK(this); + 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) - return; + LOCK( this ); + if ( !this->IsVisible() || state == STATE_CLICKED || state == STATE_DISABLED || !t ) + return; + else if ( parentElement && parentElement->GetState() == STATE_DISABLED ) + return; - #ifdef HW_RVL - // cursor - if(t->wpad.ir.valid) - { - if(this->IsInside(t->wpad.ir.x, t->wpad.ir.y)) - { - if(state == STATE_DEFAULT) // we weren't on the button before! - { - if(scrollison == 0) { - this->SetState(STATE_SELECTED, t->chan); - } +#ifdef HW_RVL + // cursor + if ( t->wpad.ir.valid ) + { + if ( this->IsInside( t->wpad.ir.x, t->wpad.ir.y ) ) + { + if ( state == STATE_DEFAULT ) // we weren't on the button before! + { + if ( scrollison == 0 ) + { + this->SetState( STATE_SELECTED, t->chan ); + } - if(this->Rumble() && scrollison == 0) - rumbleRequest[t->chan] = 1; + if ( this->Rumble() && scrollison == 0 ) + rumbleRequest[t->chan] = 1; - if(soundOver && scrollison == 0) - soundOver->Play(); + if ( soundOver && scrollison == 0 ) + soundOver->Play(); - if(effectsOver && !effects && scrollison == 0) - { - // initiate effects - effects = effectsOver; - effectAmount = effectAmountOver; - effectTarget = effectTargetOver; - } - } - } - else - { - if(state == STATE_SELECTED && (stateChan == t->chan || stateChan == -1)) - this->ResetState(); + if ( effectsOver && !effects && scrollison == 0 ) + { + // initiate effects + effects = effectsOver; + effectAmount = effectAmountOver; + effectTarget = effectTargetOver; + } + } + } + else + { + if ( state == STATE_SELECTED && ( stateChan == t->chan || stateChan == -1 ) ) + this->ResetState(); - if(effectTarget == effectTargetOver && effectAmount == effectAmountOver) - { - // initiate effects (in reverse) - effects = effectsOver; - effectAmount = -effectAmountOver; - effectTarget = 100; - } - } - } - #else - - if(state == STATE_SELECTED && (stateChan == t->chan || stateChan == -1)) - this->ResetState(); + if ( effectTarget == effectTargetOver && effectAmount == effectAmountOver ) + { + // initiate effects (in reverse) + effects = effectsOver; + effectAmount = -effectAmountOver; + effectTarget = 100; + } + } + } +#else - if(effectTarget == effectTargetOver && effectAmount == effectAmountOver) - { - // initiate effects (in reverse) - effects = effectsOver; - effectAmount = -effectAmountOver; - effectTarget = 100; - } - - - #endif + if ( state == STATE_SELECTED && ( stateChan == t->chan || stateChan == -1 ) ) + this->ResetState(); - // button triggers - if(this->IsClickable() && scrollison == 0) - { - s32 wm_btns, wm_btns_trig, cc_btns, cc_btns_trig; - for(int i=0; i<6; i++) - { - if(trigger[i] && (trigger[i]->chan == -1 || trigger[i]->chan == t->chan)) - { - // higher 16 bits only (wiimote) - wm_btns = t->wpad.btns_d << 16; - wm_btns_trig = trigger[i]->wpad.btns_d << 16; + if ( effectTarget == effectTargetOver && effectAmount == effectAmountOver ) + { + // initiate effects (in reverse) + effects = effectsOver; + effectAmount = -effectAmountOver; + effectTarget = 100; + } - // lower 16 bits only (classic controller) - 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->chan == stateChan || stateChan == -1) - { - if(state == STATE_SELECTED) - { - this->SetState(STATE_CLICKED, t->chan); +#endif - if(soundClick) - soundClick->Play(); - } - else if(trigger[i]->type == TRIGGER_BUTTON_ONLY) - { - this->SetState(STATE_CLICKED, t->chan); - if(soundClick) - soundClick->Play(); - } - else if(trigger[i]->type == TRIGGER_BUTTON_ONLY_IN_FOCUS && - parentElement->IsFocused()) - { - this->SetState(STATE_CLICKED, t->chan); - if(soundClick) - soundClick->Play(); - } - } - } - } - } - } + // button triggers + if ( this->IsClickable() && scrollison == 0 ) + { + s32 wm_btns, wm_btns_trig, cc_btns, cc_btns_trig; + for ( int i = 0; i < 6; i++ ) + { + if ( trigger[i] && ( trigger[i]->chan == -1 || trigger[i]->chan == t->chan ) ) + { + // higher 16 bits only (wiimote) + wm_btns = t->wpad.btns_d << 16; + wm_btns_trig = trigger[i]->wpad.btns_d << 16; - if(this->IsHoldable()) - { - bool held = false; - s32 wm_btns, wm_btns_h, wm_btns_trig, cc_btns, cc_btns_h, cc_btns_trig; + // lower 16 bits only (classic controller) + cc_btns = t->wpad.btns_d >> 16; + cc_btns_trig = trigger[i]->wpad.btns_d >> 16; - for(int i=0; i<6; i++) - { - if(trigger[i] && (trigger[i]->chan == -1 || trigger[i]->chan == t->chan)) - { - // higher 16 bits only (wiimote) - wm_btns = t->wpad.btns_d << 16; - wm_btns_h = t->wpad.btns_h << 16; - wm_btns_trig = trigger[i]->wpad.btns_h << 16; + if ( + ( ( t->wpad.btns_d > 0 && + wm_btns == wm_btns_trig ) || + ( cc_btns == cc_btns_trig && t->wpad.exp.type == EXP_CLASSIC ) ) || + ( t->pad.btns_d == trigger[i]->pad.btns_d && t->pad.btns_d > 0 ) ) + { + if ( t->chan == stateChan || stateChan == -1 ) + { + if ( state == STATE_SELECTED ) + { + this->SetState( STATE_CLICKED, t->chan ); - // lower 16 bits only (classic controller) - cc_btns = t->wpad.btns_d >> 16; - cc_btns_h = t->wpad.btns_h >> 16; - cc_btns_trig = trigger[i]->wpad.btns_h >> 16; + if ( soundClick ) + soundClick->Play(); + } + else if ( trigger[i]->type == TRIGGER_BUTTON_ONLY ) + { + this->SetState( STATE_CLICKED, t->chan ); + if ( soundClick ) + soundClick->Play(); + } + else if ( trigger[i]->type == TRIGGER_BUTTON_ONLY_IN_FOCUS && + parentElement->IsFocused() ) + { + this->SetState( STATE_CLICKED, t->chan ); + if ( soundClick ) + soundClick->Play(); + } + } + } + } + } + } - 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 ( this->IsHoldable() ) + { + bool held = false; + s32 wm_btns, wm_btns_h, wm_btns_trig, cc_btns, cc_btns_h, cc_btns_trig; - if( - ((t->wpad.btns_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; - } + for ( int i = 0; i < 6; i++ ) + { + if ( trigger[i] && ( trigger[i]->chan == -1 || trigger[i]->chan == t->chan ) ) + { + // higher 16 bits only (wiimote) + wm_btns = t->wpad.btns_d << 16; + wm_btns_h = t->wpad.btns_h << 16; + wm_btns_trig = trigger[i]->wpad.btns_h << 16; - if(!held && state == STATE_HELD && stateChan == t->chan) - { - this->ResetState(); - } - else if(held && state == STATE_CLICKED && stateChan == t->chan) - { - this->SetState(STATE_HELD, t->chan); - } - } - } - } + // lower 16 bits only (classic controller) + cc_btns = t->wpad.btns_d >> 16; + cc_btns_h = t->wpad.btns_h >> 16; + cc_btns_trig = trigger[i]->wpad.btns_h >> 16; - if(updateCB) - updateCB(this); + if ( + ( ( t->wpad.btns_d > 0 && + wm_btns == wm_btns_trig ) || + ( cc_btns == cc_btns_trig && t->wpad.exp.type == EXP_CLASSIC ) ) || + ( t->pad.btns_d == trigger[i]->pad.btns_h && t->pad.btns_d > 0 ) ) + { + if ( trigger[i]->type == TRIGGER_HELD && state == STATE_SELECTED && + ( t->chan == stateChan || stateChan == -1 ) ) + this->SetState( STATE_CLICKED, t->chan ); + } + + if ( + ( ( t->wpad.btns_h > 0 && + wm_btns_h == wm_btns_trig ) || + ( cc_btns_h == cc_btns_trig && t->wpad.exp.type == EXP_CLASSIC ) ) || + ( t->pad.btns_h == trigger[i]->pad.btns_h && t->pad.btns_h > 0 ) ) + { + if ( trigger[i]->type == TRIGGER_HELD ) + held = true; + } + + if ( !held && state == STATE_HELD && stateChan == t->chan ) + { + this->ResetState(); + } + else if ( held && state == STATE_CLICKED && stateChan == t->chan ) + { + this->SetState( STATE_HELD, t->chan ); + } + } + } + } + + if ( updateCB ) + updateCB( this ); } diff --git a/source/libwiigui/gui_customoptionbrowser.cpp b/source/libwiigui/gui_customoptionbrowser.cpp index c3858bb7..38388464 100644 --- a/source/libwiigui/gui_customoptionbrowser.cpp +++ b/source/libwiigui/gui_customoptionbrowser.cpp @@ -17,256 +17,256 @@ #define GAMESELECTSIZE 30 -#define OPTION_LIST_PADDING PAGESIZE +#define OPTION_LIST_PADDING PAGESIZE -customOptionList::customOptionList(int Size) +customOptionList::customOptionList( int Size ) { - name = value = NULL; - size = 0; - SetSize(Size==0 ? PAGESIZE : Size); - length = Size; - changed = false; + name = value = NULL; + size = 0; + SetSize( Size == 0 ? PAGESIZE : Size ); + length = Size; + changed = false; } customOptionList::~customOptionList() { - for (int i = 0; i < size; i++) - { - free(name[i]); - free(value[i]); - } - delete [] name; - delete [] value; + for ( int i = 0; i < size; i++ ) + { + free( name[i] ); + free( value[i] ); + } + delete [] name; + delete [] value; } -void customOptionList::SetLength(int Length) //set number of lines +void customOptionList::SetLength( int Length ) //set number of lines { - if(Length < 0 || Length == length) return; - - if(Length > size) - SetSize(Length + OPTION_LIST_PADDING); - if(Length < length) - { - for (int i = Length; i < length; i++) - { - free(name[i]); // clear unused - name[i] = NULL; - free(value[i]); - value[i] = NULL; - } - } - length = Length; - changed = true; -} -void customOptionList::SetSize(int Size) //set number of lines -{ - if(Size < 0 || Size == size) return; - - if(Size > size) - { - char **newName = new char *[Size]; - char **newValue = new char *[Size]; - int i; - for (i = 0; i < size; i++) - { - newName[i] = name[i]; // copy - newValue[i] = value[i]; - } - for (; i < Size; i++) - { - newName[i] = NULL; // fill rest with NULL - newValue[i] = NULL; - } - delete [] name; - name = newName; // set new - delete [] value; - value = newValue; - size = Size; - } -} -void customOptionList::SetName(int i, const char *format, ...) -{ - if(i >= length) SetLength(i+1); + if ( Length < 0 || Length == length ) return; - if(i >= 0 && i < length) - { - if(name[i]) free(name[i]); - name[i] = 0; - va_list va; - va_start(va, format); - vasprintf(&name[i], format, va); - va_end(va); - changed = true; - } - //gprintf("customOptionList::SetName( %d, %s )\n", i, name[i] ); + if ( Length > size ) + SetSize( Length + OPTION_LIST_PADDING ); + if ( Length < length ) + { + for ( int i = Length; i < length; i++ ) + { + free( name[i] ); // clear unused + name[i] = NULL; + free( value[i] ); + value[i] = NULL; + } + } + length = Length; + changed = true; } -void customOptionList::SetValue(int i, const char *format, ...) +void customOptionList::SetSize( int Size ) //set number of lines { - if(i >= length) SetLength(i+1); + if ( Size < 0 || Size == size ) return; - if(i >= 0 && i < length) - { - char *tmp=0; - va_list va; - va_start(va, format); - vasprintf(&tmp, format, va); - va_end(va); - - if(tmp) - { - if(value[i] && !strcmp(tmp, value[i])) - free(tmp); - else - { - free(value[i]); - value[i] = tmp; - changed = true; - } - } - } - //gprintf("customOptionList::SetValue( %d, %s )\n", i, value[i] ); + if ( Size > size ) + { + char **newName = new char *[Size]; + char **newValue = new char *[Size]; + int i; + for ( i = 0; i < size; i++ ) + { + newName[i] = name[i]; // copy + newValue[i] = value[i]; + } + for ( ; i < Size; i++ ) + { + newName[i] = NULL; // fill rest with NULL + newValue[i] = NULL; + } + delete [] name; + name = newName; // set new + delete [] value; + value = newValue; + size = Size; + } } -void customOptionList::Clear(bool OnlyValue/*=false*/) +void customOptionList::SetName( int i, const char *format, ... ) { - for (int i = 0; i < size; i++) - { - if(!OnlyValue) - { - free(name[i]); - name[i] = NULL; - } - free(value[i]); - value[i] = NULL; - } - changed = true; + if ( i >= length ) SetLength( i + 1 ); + + if ( i >= 0 && i < length ) + { + if ( name[i] ) free( name[i] ); + name[i] = 0; + va_list va; + va_start( va, format ); + vasprintf( &name[i], format, va ); + va_end( va ); + changed = true; + } + //gprintf("customOptionList::SetName( %d, %s )\n", i, name[i] ); +} +void customOptionList::SetValue( int i, const char *format, ... ) +{ + if ( i >= length ) SetLength( i + 1 ); + + if ( i >= 0 && i < length ) + { + char *tmp = 0; + va_list va; + va_start( va, format ); + vasprintf( &tmp, format, va ); + va_end( va ); + + if ( tmp ) + { + if ( value[i] && !strcmp( tmp, value[i] ) ) + free( tmp ); + else + { + free( value[i] ); + value[i] = tmp; + changed = true; + } + } + } + //gprintf("customOptionList::SetValue( %d, %s )\n", i, value[i] ); +} +void customOptionList::Clear( bool OnlyValue/*=false*/ ) +{ + for ( int i = 0; i < size; i++ ) + { + if ( !OnlyValue ) + { + free( name[i] ); + name[i] = NULL; + } + free( value[i] ); + value[i] = NULL; + } + changed = true; } /** * Constructor for the GuiCustomOptionBrowser class. */ -GuiCustomOptionBrowser::GuiCustomOptionBrowser(int w, int h, customOptionList * l, const char *themePath, const char *custombg, const u8 *imagebg, int scrollon,int col2) +GuiCustomOptionBrowser::GuiCustomOptionBrowser( int w, int h, customOptionList * l, const char *themePath, const char *custombg, const u8 *imagebg, int scrollon, int col2 ) { - width = w; - height = h; - options = l; - size = PAGESIZE; - scrollbaron = scrollon; - selectable = true; - listOffset = this->FindMenuItem(-1, 1); - selectedItem = 0; - focus = 1; // allow focus - coL2 = col2; - char imgPath[100]; + width = w; + height = h; + options = l; + size = PAGESIZE; + scrollbaron = scrollon; + selectable = true; + listOffset = this->FindMenuItem( -1, 1 ); + selectedItem = 0; + focus = 1; // allow focus + coL2 = col2; + char imgPath[100]; - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - trigHeldA = new GuiTrigger; - trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A, PAD_BUTTON_A); - btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigHeldA = new GuiTrigger; + trigHeldA->SetHeldTrigger( -1, WPAD_BUTTON_A, PAD_BUTTON_A ); + btnSoundClick = new GuiSound( button_click_pcm, button_click_pcm_size, Settings.sfxvolume ); - snprintf(imgPath, sizeof(imgPath), "%s%s", themePath, custombg); - bgOptions = new GuiImageData(imgPath, imagebg); + snprintf( imgPath, sizeof( imgPath ), "%s%s", themePath, custombg ); + bgOptions = new GuiImageData( imgPath, imagebg ); - bgOptionsImg = new GuiImage(bgOptions); - bgOptionsImg->SetParent(this); - bgOptionsImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + bgOptionsImg = new GuiImage( bgOptions ); + bgOptionsImg->SetParent( this ); + bgOptionsImg->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - snprintf(imgPath, sizeof(imgPath), "%sbg_options_entry.png", themePath); - bgOptionsEntry = new GuiImageData(imgPath, bg_options_entry_png); + snprintf( imgPath, sizeof( imgPath ), "%sbg_options_entry.png", themePath ); + bgOptionsEntry = new GuiImageData( imgPath, bg_options_entry_png ); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar.png", themePath); - scrollbar = new GuiImageData(imgPath, scrollbar_png); - scrollbarImg = new GuiImage(scrollbar); - scrollbarImg->SetParent(this); - scrollbarImg->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); - scrollbarImg->SetPosition(0, 4); + snprintf( imgPath, sizeof( imgPath ), "%sscrollbar.png", themePath ); + scrollbar = new GuiImageData( imgPath, scrollbar_png ); + scrollbarImg = new GuiImage( scrollbar ); + scrollbarImg->SetParent( this ); + scrollbarImg->SetAlignment( ALIGN_RIGHT, ALIGN_TOP ); + scrollbarImg->SetPosition( 0, 4 ); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowdown.png", themePath); - arrowDown = new GuiImageData(imgPath, scrollbar_arrowdown_png); - arrowDownImg = new GuiImage(arrowDown); - arrowDownOver = new GuiImageData(imgPath, scrollbar_arrowdown_png); - arrowDownOverImg = new GuiImage(arrowDownOver); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", themePath); - arrowUp = new GuiImageData(imgPath, scrollbar_arrowup_png); - arrowUpImg = new GuiImage(arrowUp); - arrowUpOver = new GuiImageData(imgPath, scrollbar_arrowup_png); - arrowUpOverImg = new GuiImage(arrowUpOver); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_box.png", themePath); - scrollbarBox = new GuiImageData(imgPath, scrollbar_box_png); - scrollbarBoxImg = new GuiImage(scrollbarBox); - scrollbarBoxOver = new GuiImageData(imgPath, scrollbar_box_png); - scrollbarBoxOverImg = new GuiImage(scrollbarBoxOver); + snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_arrowdown.png", themePath ); + arrowDown = new GuiImageData( imgPath, scrollbar_arrowdown_png ); + arrowDownImg = new GuiImage( arrowDown ); + arrowDownOver = new GuiImageData( imgPath, scrollbar_arrowdown_png ); + arrowDownOverImg = new GuiImage( arrowDownOver ); + snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_arrowup.png", themePath ); + arrowUp = new GuiImageData( imgPath, scrollbar_arrowup_png ); + arrowUpImg = new GuiImage( arrowUp ); + arrowUpOver = new GuiImageData( imgPath, scrollbar_arrowup_png ); + arrowUpOverImg = new GuiImage( arrowUpOver ); + snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_box.png", themePath ); + scrollbarBox = new GuiImageData( imgPath, scrollbar_box_png ); + scrollbarBoxImg = new GuiImage( scrollbarBox ); + scrollbarBoxOver = new GuiImageData( imgPath, scrollbar_box_png ); + scrollbarBoxOverImg = new GuiImage( scrollbarBoxOver ); - arrowUpBtn = new GuiButton(arrowUpImg->GetWidth(), arrowUpImg->GetHeight()); - arrowUpBtn->SetParent(this); - arrowUpBtn->SetImage(arrowUpImg); - arrowUpBtn->SetImageOver(arrowUpOverImg); - arrowUpBtn->SetImageHold(arrowUpOverImg); - arrowUpBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - arrowUpBtn->SetPosition(width/2-18+7,-18); - arrowUpBtn->SetSelectable(false); - arrowUpBtn->SetTrigger(trigA); - arrowUpBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowUpBtn->SetSoundClick(btnSoundClick); + arrowUpBtn = new GuiButton( arrowUpImg->GetWidth(), arrowUpImg->GetHeight() ); + arrowUpBtn->SetParent( this ); + arrowUpBtn->SetImage( arrowUpImg ); + arrowUpBtn->SetImageOver( arrowUpOverImg ); + arrowUpBtn->SetImageHold( arrowUpOverImg ); + arrowUpBtn->SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + arrowUpBtn->SetPosition( width / 2 - 18 + 7, -18 ); + arrowUpBtn->SetSelectable( false ); + arrowUpBtn->SetTrigger( trigA ); + arrowUpBtn->SetEffectOnOver( EFFECT_SCALE, 50, 130 ); + arrowUpBtn->SetSoundClick( btnSoundClick ); - arrowDownBtn = new GuiButton(arrowDownImg->GetWidth(), arrowDownImg->GetHeight()); - arrowDownBtn->SetParent(this); - arrowDownBtn->SetImage(arrowDownImg); - arrowDownBtn->SetImageOver(arrowDownOverImg); - arrowDownBtn->SetImageHold(arrowDownOverImg); - arrowDownBtn->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - arrowDownBtn->SetPosition(width/2-18+7,18); - arrowDownBtn->SetSelectable(false); - arrowDownBtn->SetTrigger(trigA); - arrowDownBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowDownBtn->SetSoundClick(btnSoundClick); + arrowDownBtn = new GuiButton( arrowDownImg->GetWidth(), arrowDownImg->GetHeight() ); + arrowDownBtn->SetParent( this ); + arrowDownBtn->SetImage( arrowDownImg ); + arrowDownBtn->SetImageOver( arrowDownOverImg ); + arrowDownBtn->SetImageHold( arrowDownOverImg ); + arrowDownBtn->SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); + arrowDownBtn->SetPosition( width / 2 - 18 + 7, 18 ); + arrowDownBtn->SetSelectable( false ); + arrowDownBtn->SetTrigger( trigA ); + arrowDownBtn->SetEffectOnOver( EFFECT_SCALE, 50, 130 ); + arrowDownBtn->SetSoundClick( btnSoundClick ); - scrollbarBoxBtn = new GuiButton(scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight()); - scrollbarBoxBtn->SetParent(this); - scrollbarBoxBtn->SetImage(scrollbarBoxImg); - scrollbarBoxBtn->SetImageOver(scrollbarBoxOverImg); - scrollbarBoxBtn->SetImageHold(scrollbarBoxOverImg); - scrollbarBoxBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - scrollbarBoxBtn->SetSelectable(false); - scrollbarBoxBtn->SetEffectOnOver(EFFECT_SCALE, 50, 120); - scrollbarBoxBtn->SetMinY(0); - scrollbarBoxBtn->SetMaxY(height-30); - scrollbarBoxBtn->SetHoldable(true); - scrollbarBoxBtn->SetTrigger(trigHeldA); + scrollbarBoxBtn = new GuiButton( scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight() ); + scrollbarBoxBtn->SetParent( this ); + scrollbarBoxBtn->SetImage( scrollbarBoxImg ); + scrollbarBoxBtn->SetImageOver( scrollbarBoxOverImg ); + scrollbarBoxBtn->SetImageHold( scrollbarBoxOverImg ); + scrollbarBoxBtn->SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + scrollbarBoxBtn->SetSelectable( false ); + scrollbarBoxBtn->SetEffectOnOver( EFFECT_SCALE, 50, 120 ); + scrollbarBoxBtn->SetMinY( 0 ); + scrollbarBoxBtn->SetMaxY( height - 30 ); + scrollbarBoxBtn->SetHoldable( true ); + scrollbarBoxBtn->SetTrigger( trigHeldA ); - optionIndex = new int[size]; - optionVal = new GuiText * [size]; - optionValOver = new GuiText * [size]; - optionBtn = new GuiButton * [size]; - optionTxt = new GuiText * [size]; - optionBg = new GuiImage * [size]; + optionIndex = new int[size]; + optionVal = new GuiText * [size]; + optionValOver = new GuiText * [size]; + optionBtn = new GuiButton * [size]; + optionTxt = new GuiText * [size]; + optionBg = new GuiImage * [size]; - for(int i=0; i < size; i++) - { - optionTxt[i] = new GuiText(options->GetName(i), 20, THEME.settingstext); - optionTxt[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - optionTxt[i]->SetPosition(24,0); - optionTxt[i]->SetMaxWidth(bgOptionsImg->GetWidth() - (coL2+24), DOTTED); + for ( int i = 0; i < size; i++ ) + { + optionTxt[i] = new GuiText( options->GetName( i ), 20, THEME.settingstext ); + optionTxt[i]->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + optionTxt[i]->SetPosition( 24, 0 ); + optionTxt[i]->SetMaxWidth( bgOptionsImg->GetWidth() - ( coL2 + 24 ), 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(); + } + UpdateListEntries(); } /** @@ -274,121 +274,121 @@ GuiCustomOptionBrowser::GuiCustomOptionBrowser(int w, int h, customOptionList * */ GuiCustomOptionBrowser::~GuiCustomOptionBrowser() { - delete arrowUpBtn; - delete arrowDownBtn; - delete scrollbarBoxBtn; - delete scrollbarImg; - delete arrowDownImg; - delete arrowDownOverImg; - delete arrowUpImg; - delete arrowUpOverImg; - delete scrollbarBoxImg; - delete scrollbarBoxOverImg; - delete scrollbar; - delete arrowDown; - delete arrowDownOver; - delete arrowUp; - delete arrowUpOver; - delete scrollbarBox; - delete scrollbarBoxOver; + delete arrowUpBtn; + delete arrowDownBtn; + delete scrollbarBoxBtn; + delete scrollbarImg; + delete arrowDownImg; + delete arrowDownOverImg; + delete arrowUpImg; + delete arrowUpOverImg; + delete scrollbarBoxImg; + delete scrollbarBoxOverImg; + delete scrollbar; + delete arrowDown; + delete arrowDownOver; + delete arrowUp; + delete arrowUpOver; + delete scrollbarBox; + delete scrollbarBoxOver; - delete bgOptionsImg; - delete bgOptions; - delete bgOptionsEntry; + delete bgOptionsImg; + delete bgOptions; + delete bgOptionsEntry; - delete trigA; - delete trigHeldA; - delete btnSoundClick; + delete trigA; + delete trigHeldA; + delete btnSoundClick; - for(int i = 0; i < size; i++) - { - delete optionTxt[i]; - delete optionVal[i]; - delete optionValOver[i]; - delete optionBg[i]; - delete optionBtn[i]; - } - delete [] optionIndex; - delete [] optionVal; - delete [] optionValOver; - delete [] optionBtn; - delete [] optionTxt; - delete [] optionBg; + for ( int i = 0; i < size; i++ ) + { + delete optionTxt[i]; + delete optionVal[i]; + delete optionValOver[i]; + delete optionBg[i]; + delete optionBtn[i]; + } + delete [] optionIndex; + delete [] optionVal; + delete [] optionValOver; + delete [] optionBtn; + delete [] optionTxt; + delete [] optionBg; } -void GuiCustomOptionBrowser::SetFocus(int f) +void GuiCustomOptionBrowser::SetFocus( int f ) { - LOCK(this); - focus = f; + LOCK( this ); + focus = f; - for(int i = 0; i < size; i++) - optionBtn[i]->ResetState(); + for ( int i = 0; i < size; i++ ) + optionBtn[i]->ResetState(); - if(f == 1) - optionBtn[selectedItem]->SetState(STATE_SELECTED); + if ( f == 1 ) + optionBtn[selectedItem]->SetState( STATE_SELECTED ); } void GuiCustomOptionBrowser::ResetState() { - LOCK(this); - if(state != STATE_DISABLED) - { - state = STATE_DEFAULT; - stateChan = -1; - } + LOCK( this ); + if ( state != STATE_DISABLED ) + { + state = STATE_DEFAULT; + stateChan = -1; + } - for(int i = 0; i < size; i++) - { - optionBtn[i]->ResetState(); - } + for ( int i = 0; i < size; i++ ) + { + optionBtn[i]->ResetState(); + } } int GuiCustomOptionBrowser::GetClickedOption() { - int found = -1; - for(int i = 0; i < size; i++) - { - if(optionBtn[i]->GetState() == STATE_CLICKED) - { - optionBtn[i]->SetState(STATE_SELECTED); - found = optionIndex[i]; - break; - } - } - return found; + int found = -1; + for ( int i = 0; i < size; i++ ) + { + if ( optionBtn[i]->GetState() == STATE_CLICKED ) + { + optionBtn[i]->SetState( STATE_SELECTED ); + found = optionIndex[i]; + break; + } + } + return found; } int GuiCustomOptionBrowser::GetSelectedOption() { - int found = -1; - for(int i = 0; i < size; i++) - { - if(optionBtn[i]->GetState() == STATE_SELECTED) - { - found = optionIndex[i]; - break; - } - } - return found; + int found = -1; + for ( int i = 0; i < size; i++ ) + { + if ( optionBtn[i]->GetState() == STATE_SELECTED ) + { + found = optionIndex[i]; + break; + } + } + return found; } -void GuiCustomOptionBrowser::SetClickable(bool enable) +void GuiCustomOptionBrowser::SetClickable( bool enable ) { - for(int i = 0; i < size; i++) - { - optionBtn[i]->SetClickable(enable); - } + for ( int i = 0; i < size; i++ ) + { + optionBtn[i]->SetClickable( enable ); + } } -void GuiCustomOptionBrowser::SetScrollbar(int enable) +void GuiCustomOptionBrowser::SetScrollbar( int enable ) { - scrollbaron = enable; + scrollbaron = enable; } -void GuiCustomOptionBrowser::SetOffset(int optionnumber) +void GuiCustomOptionBrowser::SetOffset( int optionnumber ) { - listOffset = optionnumber; - selectedItem = optionnumber; + listOffset = optionnumber; + selectedItem = optionnumber; } /**************************************************************************** @@ -397,17 +397,17 @@ 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; + int nextItem = currentItem + direction; - if(nextItem < 0 || nextItem >= options->GetLength()) - return -1; + if ( nextItem < 0 || nextItem >= options->GetLength() ) + return -1; - if(strlen(options->GetName(nextItem)) > 0) - return nextItem; - else - return FindMenuItem(nextItem, direction); + if ( strlen( options->GetName( nextItem ) ) > 0 ) + return nextItem; + else + return FindMenuItem( nextItem, direction ); } /** @@ -415,276 +415,287 @@ int GuiCustomOptionBrowser::FindMenuItem(int currentItem, int direction) */ void GuiCustomOptionBrowser::Draw() { - LOCK(this); - if(!this->IsVisible()) - return; + LOCK( this ); + if ( !this->IsVisible() ) + return; - bgOptionsImg->Draw(); + bgOptionsImg->Draw(); - int next = listOffset; + int next = listOffset; - for(int i=0; i < size; i++) - { - if(next >= 0) - { - optionBtn[i]->Draw(); - next = this->FindMenuItem(next, 1); - } - else - break; - } + for ( int i = 0; i < size; i++ ) + { + if ( next >= 0 ) + { + optionBtn[i]->Draw(); + next = this->FindMenuItem( next, 1 ); + } + else + break; + } - if(scrollbaron == 1) { - scrollbarImg->Draw(); - arrowUpBtn->Draw(); - arrowDownBtn->Draw(); - scrollbarBoxBtn->Draw(); - } - this->UpdateEffects(); + if ( scrollbaron == 1 ) + { + scrollbarImg->Draw(); + arrowUpBtn->Draw(); + arrowDownBtn->Draw(); + scrollbarBoxBtn->Draw(); + } + this->UpdateEffects(); } void GuiCustomOptionBrowser::UpdateListEntries() { - scrollbaron = options->GetLength() > size; - if(listOffset<0) listOffset = this->FindMenuItem(-1, 1); - int next = listOffset; + scrollbaron = options->GetLength() > size; + if ( listOffset < 0 ) listOffset = this->FindMenuItem( -1, 1 ); + int next = listOffset; - int maxNameWidth = 0; - for(int i=0; i < size; i++) - { - if(next >= 0) - { - if(optionBtn[i]->GetState() == STATE_DISABLED) - { - optionBtn[i]->SetVisible(true); - optionBtn[i]->SetState(STATE_DEFAULT); - } + int maxNameWidth = 0; + for ( int i = 0; i < size; i++ ) + { + if ( next >= 0 ) + { + if ( optionBtn[i]->GetState() == STATE_DISABLED ) + { + optionBtn[i]->SetVisible( true ); + optionBtn[i]->SetState( STATE_DEFAULT ); + } - optionTxt[i]->SetText(options->GetName(next)); - if(maxNameWidth < optionTxt[i]->GetTextWidth()) - maxNameWidth = optionTxt[i]->GetTextWidth(); - optionVal[i]->SetText(options->GetValue(next)); - optionValOver[i]->SetText(options->GetValue(next)); + optionTxt[i]->SetText( options->GetName( next ) ); + if ( maxNameWidth < optionTxt[i]->GetTextWidth() ) + maxNameWidth = optionTxt[i]->GetTextWidth(); + optionVal[i]->SetText( options->GetValue( next ) ); + optionValOver[i]->SetText( options->GetValue( next ) ); - optionIndex[i] = next; - next = this->FindMenuItem(next, 1); - } - else - { - optionBtn[i]->SetVisible(false); - optionBtn[i]->SetState(STATE_DISABLED); - } - } - if(coL2 < (24+maxNameWidth+16)) - coL2 = 24+maxNameWidth+16; - for(int i=0; i < size; i++) - { - if(optionBtn[i]->GetState() != STATE_DISABLED) - { - optionVal[i]->SetPosition(coL2,0); - optionVal[i]->SetMaxWidth(bgOptionsImg->GetWidth() - (coL2+24), DOTTED); + optionIndex[i] = next; + next = this->FindMenuItem( next, 1 ); + } + else + { + optionBtn[i]->SetVisible( false ); + optionBtn[i]->SetState( STATE_DISABLED ); + } + } + if ( coL2 < ( 24 + maxNameWidth + 16 ) ) + coL2 = 24 + maxNameWidth + 16; + for ( int i = 0; i < size; i++ ) + { + if ( optionBtn[i]->GetState() != STATE_DISABLED ) + { + optionVal[i]->SetPosition( coL2, 0 ); + optionVal[i]->SetMaxWidth( bgOptionsImg->GetWidth() - ( coL2 + 24 ), 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(); + LOCK( this ); + int next, prev, lang = options->GetLength(); - if(state == STATE_DISABLED || !t) - return; + if ( state == STATE_DISABLED || !t ) + return; - if(options->IsChanged()) { - coL2 = 0; - UpdateListEntries(); - } - int old_listOffset = listOffset; + if ( options->IsChanged() ) + { + coL2 = 0; + UpdateListEntries(); + } + int old_listOffset = listOffset; - if (scrollbaron == 1) - { - // update the location of the scroll box based on the position in the option list - arrowUpBtn->Update(t); - arrowDownBtn->Update(t); - scrollbarBoxBtn->Update(t); - } + if ( scrollbaron == 1 ) + { + // update the location of the scroll box based on the position in the option list + arrowUpBtn->Update( t ); + arrowDownBtn->Update( t ); + scrollbarBoxBtn->Update( t ); + } - next = listOffset; + next = listOffset; - u32 buttonshold = ButtonsHold(); + u32 buttonshold = ButtonsHold(); - if(buttonshold != WPAD_BUTTON_UP && buttonshold != WPAD_BUTTON_DOWN) { - for(int i=0; i < size; i++) - { - if(next >= 0) - next = this->FindMenuItem(next, 1); + if ( buttonshold != WPAD_BUTTON_UP && buttonshold != WPAD_BUTTON_DOWN ) + { + for ( int i = 0; i < size; i++ ) + { + if ( next >= 0 ) + next = this->FindMenuItem( next, 1 ); - if(focus) - { - if(i != selectedItem && optionBtn[i]->GetState() == STATE_SELECTED) { - optionBtn[i]->ResetState(); - } else if(i == selectedItem && optionBtn[i]->GetState() == STATE_DEFAULT) { - optionBtn[selectedItem]->SetState(STATE_SELECTED); - } - } + if ( focus ) + { + if ( i != selectedItem && optionBtn[i]->GetState() == STATE_SELECTED ) + { + optionBtn[i]->ResetState(); + } + else if ( i == selectedItem && optionBtn[i]->GetState() == STATE_DEFAULT ) + { + optionBtn[selectedItem]->SetState( STATE_SELECTED ); + } + } - optionBtn[i]->Update(t); + optionBtn[i]->Update( t ); - if(optionBtn[i]->GetState() == STATE_SELECTED) - { - selectedItem = i; - } - } - } + if ( optionBtn[i]->GetState() == STATE_SELECTED ) + { + selectedItem = i; + } + } + } - // pad/joystick navigation - if(!focus) - return; // skip navigation + // pad/joystick navigation + if ( !focus ) + return; // skip navigation - if(t->Down()) - { - next = this->FindMenuItem(optionIndex[selectedItem], 1); + if ( t->Down() ) + { + next = this->FindMenuItem( optionIndex[selectedItem], 1 ); - if(next >= 0) - { - if(selectedItem == size-1) - { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - } - else if(optionBtn[selectedItem+1]->IsVisible()) - { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } - } - } - else if(t->Up()) - { - prev = this->FindMenuItem(optionIndex[selectedItem], -1); + if ( next >= 0 ) + { + if ( selectedItem == size - 1 ) + { + // move list down by 1 + listOffset = this->FindMenuItem( listOffset, 1 ); + } + else if ( optionBtn[selectedItem+1]->IsVisible() ) + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + selectedItem++; + } + } + } + else if ( t->Up() ) + { + prev = this->FindMenuItem( optionIndex[selectedItem], -1 ); - if(prev >= 0) - { - if(selectedItem == 0) - { - // move list up by 1 - listOffset = prev; - } - else - { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } - } - } + if ( prev >= 0 ) + { + if ( selectedItem == 0 ) + { + // move list up by 1 + listOffset = prev; + } + else + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + selectedItem--; + } + } + } - if (scrollbaron == 1) - { - if (arrowDownBtn->GetState() == STATE_CLICKED || - arrowDownBtn->GetState() == STATE_HELD) - { + if ( scrollbaron == 1 ) + { + if ( arrowDownBtn->GetState() == STATE_CLICKED || + arrowDownBtn->GetState() == STATE_HELD ) + { - next = this->FindMenuItem(optionIndex[selectedItem], 1); + next = this->FindMenuItem( optionIndex[selectedItem], 1 ); - if(next >= 0) - { - if(selectedItem == size-1) - { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - } - else if(optionBtn[selectedItem+1]->IsVisible()) - { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } - scrollbarBoxBtn->Draw(); - usleep(35000); - } - if (buttonshold != WPAD_BUTTON_A) { - arrowDownBtn->ResetState(); - } - } - else if(arrowUpBtn->GetState() == STATE_CLICKED || - arrowUpBtn->GetState() == STATE_HELD) - { - prev = this->FindMenuItem(optionIndex[selectedItem], -1); + if ( next >= 0 ) + { + if ( selectedItem == size - 1 ) + { + // move list down by 1 + listOffset = this->FindMenuItem( listOffset, 1 ); + } + else if ( optionBtn[selectedItem+1]->IsVisible() ) + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + selectedItem++; + } + scrollbarBoxBtn->Draw(); + usleep( 35000 ); + } + if ( buttonshold != WPAD_BUTTON_A ) + { + arrowDownBtn->ResetState(); + } + } + else if ( arrowUpBtn->GetState() == STATE_CLICKED || + arrowUpBtn->GetState() == STATE_HELD ) + { + prev = this->FindMenuItem( optionIndex[selectedItem], -1 ); - if(prev >= 0) - { - if(selectedItem == 0) - { - // move list up by 1 - listOffset = prev; - } - else - { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } - scrollbarBoxBtn->Draw(); - usleep(35000); - } - if (buttonshold != WPAD_BUTTON_A) { - arrowUpBtn->ResetState(); - } - } + if ( prev >= 0 ) + { + if ( selectedItem == 0 ) + { + // move list up by 1 + listOffset = prev; + } + else + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + selectedItem--; + } + scrollbarBoxBtn->Draw(); + usleep( 35000 ); + } + if ( buttonshold != WPAD_BUTTON_A ) + { + arrowUpBtn->ResetState(); + } + } - if(scrollbarBoxBtn->GetState() == STATE_HELD && - scrollbarBoxBtn->GetStateChan() == t->chan && - t->wpad.ir.valid && options->GetLength() > size) - { - scrollbarBoxBtn->SetPosition(width/2-18+7,0); + if ( scrollbarBoxBtn->GetState() == STATE_HELD && + scrollbarBoxBtn->GetStateChan() == t->chan && + t->wpad.ir.valid && options->GetLength() > size ) + { + scrollbarBoxBtn->SetPosition( width / 2 - 18 + 7, 0 ); - int position = t->wpad.ir.y - 50 - scrollbarBoxBtn->GetTop(); + int position = t->wpad.ir.y - 50 - scrollbarBoxBtn->GetTop(); - listOffset = (position * lang)/180 - selectedItem; + listOffset = ( position * lang ) / 180 - selectedItem; - if(listOffset <= 0) { - listOffset = 0; - selectedItem = 0; - } else if(listOffset+size >= lang) { - listOffset = lang-size; - selectedItem = size-1; - } - } - int positionbar = 237*(listOffset + selectedItem) / lang; + if ( listOffset <= 0 ) + { + listOffset = 0; + selectedItem = 0; + } + else if ( listOffset + size >= lang ) + { + listOffset = lang - size; + selectedItem = size - 1; + } + } + int positionbar = 237 * ( listOffset + selectedItem ) / lang; - if(positionbar > 216) - positionbar = 216; - scrollbarBoxBtn->SetPosition(width/2-18+7, positionbar+8); + if ( positionbar > 216 ) + positionbar = 216; + scrollbarBoxBtn->SetPosition( width / 2 - 18 + 7, positionbar + 8 ); - if(t->Right()) - { - if(listOffset < lang && lang > size) - { - listOffset =listOffset+ size; - if(listOffset+size >= lang) - listOffset = lang-size; - } - } - else if(t->Left()) - { - if(listOffset > 0) - { - listOffset =listOffset- size; - if(listOffset < 0) - listOffset = 0; - } - } - } + if ( t->Right() ) + { + if ( listOffset < lang && lang > size ) + { + listOffset = listOffset + size; + if ( listOffset + size >= lang ) + listOffset = lang - size; + } + } + else if ( t->Left() ) + { + if ( listOffset > 0 ) + { + listOffset = listOffset - size; + if ( listOffset < 0 ) + listOffset = 0; + } + } + } - if(old_listOffset != listOffset) - UpdateListEntries(); + if ( old_listOffset != listOffset ) + UpdateListEntries(); - if(updateCB) - updateCB(this); + if ( updateCB ) + updateCB( this ); } diff --git a/source/libwiigui/gui_customoptionbrowser.h b/source/libwiigui/gui_customoptionbrowser.h index 8bc8d176..8bab4d77 100644 --- a/source/libwiigui/gui_customoptionbrowser.h +++ b/source/libwiigui/gui_customoptionbrowser.h @@ -1,94 +1,95 @@ #include "gui.h" -class customOptionList { - public: - customOptionList(int Size); - ~customOptionList(); - void SetLength(int Length); - void SetName(int i, const char *format, ...) __attribute__((format (printf, 3, 4))); - const char *GetName(int i) - { - if(i >= 0 && i < length && name[i]) - return name[i]; - else - return ""; - } - void SetValue(int i, const char *format, ...) __attribute__((format (printf, 3, 4))); - const char *GetValue(int i) - { - if(i >= 0 && i < length && value[i]) - return value[i]; - else - return ""; - } - void Clear(bool OnlyValue=false); - int GetLength() { return length; } - bool IsChanged() { bool ret = changed; changed = false; return ret;} - private: - void SetSize(int Size); - int size; - char ** name; - char ** value; - int length; - bool changed; +class customOptionList +{ + public: + customOptionList( int Size ); + ~customOptionList(); + void SetLength( int Length ); + void SetName( int i, const char *format, ... ) __attribute__( ( format ( printf, 3, 4 ) ) ); + const char *GetName( int i ) + { + if ( i >= 0 && i < length && name[i] ) + return name[i]; + else + return ""; + } + void SetValue( int i, const char *format, ... ) __attribute__( ( format ( printf, 3, 4 ) ) ); + const char *GetValue( int i ) + { + if ( i >= 0 && i < length && value[i] ) + return value[i]; + else + return ""; + } + void Clear( bool OnlyValue = false ); + int GetLength() { return length; } + bool IsChanged() { bool ret = changed; changed = false; return ret;} + private: + void SetSize( int Size ); + int size; + char ** name; + char ** value; + int length; + bool changed; }; //!Display a list of menu options class GuiCustomOptionBrowser : public GuiElement { - public: - GuiCustomOptionBrowser(int w, int h, customOptionList * l, const char * themePath, const char *custombg, const u8 *imagebg, int scrollbar, int col2); - ~GuiCustomOptionBrowser(); - int FindMenuItem(int c, int d); - int GetClickedOption(); - int GetSelectedOption(); - void SetClickable(bool enable); - void SetScrollbar(int enable); - void SetOffset(int optionnumber); - void ResetState(); - void SetFocus(int f); - void Draw(); - void Update(GuiTrigger * t); - protected: - void UpdateListEntries(); - int selectedItem; - int listOffset; - int size; - int coL2; - int scrollbaron; + public: + GuiCustomOptionBrowser( int w, int h, customOptionList * l, const char * themePath, const char *custombg, const u8 *imagebg, int scrollbar, int col2 ); + ~GuiCustomOptionBrowser(); + int FindMenuItem( int c, int d ); + int GetClickedOption(); + int GetSelectedOption(); + void SetClickable( bool enable ); + void SetScrollbar( int enable ); + void SetOffset( int optionnumber ); + void ResetState(); + void SetFocus( int f ); + void Draw(); + void Update( GuiTrigger * t ); + protected: + void UpdateListEntries(); + int selectedItem; + int listOffset; + int size; + int coL2; + int scrollbaron; - customOptionList * options; - int * optionIndex; - GuiButton ** optionBtn; - GuiText ** optionTxt; - GuiText ** optionVal; - GuiText ** optionValOver; - GuiImage ** optionBg; + customOptionList * options; + int * optionIndex; + GuiButton ** optionBtn; + GuiText ** optionTxt; + GuiText ** optionVal; + GuiText ** optionValOver; + GuiImage ** optionBg; - GuiButton * arrowUpBtn; - GuiButton * arrowDownBtn; - GuiButton * scrollbarBoxBtn; + GuiButton * arrowUpBtn; + GuiButton * arrowDownBtn; + GuiButton * scrollbarBoxBtn; - GuiImage * bgOptionsImg; - GuiImage * scrollbarImg; - GuiImage * arrowDownImg; - GuiImage * arrowDownOverImg; - GuiImage * arrowUpImg; - GuiImage * arrowUpOverImg; - GuiImage * scrollbarBoxImg; - GuiImage * scrollbarBoxOverImg; + GuiImage * bgOptionsImg; + GuiImage * scrollbarImg; + GuiImage * arrowDownImg; + GuiImage * arrowDownOverImg; + GuiImage * arrowUpImg; + GuiImage * arrowUpOverImg; + GuiImage * scrollbarBoxImg; + GuiImage * scrollbarBoxOverImg; - GuiImageData * bgOptions; - GuiImageData * bgOptionsEntry; - GuiImageData * scrollbar; - GuiImageData * arrowDown; - GuiImageData * arrowDownOver; - GuiImageData * arrowUp; - GuiImageData * arrowUpOver; - GuiImageData * scrollbarBox; - GuiImageData * scrollbarBoxOver; + GuiImageData * bgOptions; + GuiImageData * bgOptionsEntry; + GuiImageData * scrollbar; + GuiImageData * arrowDown; + GuiImageData * arrowDownOver; + GuiImageData * arrowUp; + GuiImageData * arrowUpOver; + GuiImageData * scrollbarBox; + GuiImageData * scrollbarBoxOver; - GuiSound * btnSoundClick; - GuiTrigger * trigA; - GuiTrigger * trigHeldA; + GuiSound * btnSoundClick; + GuiTrigger * trigA; + GuiTrigger * trigHeldA; }; diff --git a/source/libwiigui/gui_diskcover.cpp b/source/libwiigui/gui_diskcover.cpp index 7e40c1cb..dbc916a4 100644 --- a/source/libwiigui/gui_diskcover.cpp +++ b/source/libwiigui/gui_diskcover.cpp @@ -3,76 +3,76 @@ GuiDiskCover::GuiDiskCover() { - deg_beta=0.0; - eff_step=0; -// spin_angle = 0; - spin_speedup = 1.0; - spin_up = false; + deg_beta = 0.0; + eff_step = 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_speedup = 1.0; - spin_up = false; + deg_beta = 0.0; + eff_step = 0; +// spin_angle = 0; + spin_speedup = 1.0; + spin_up = false; } GuiDiskCover::~GuiDiskCover() { } -void GuiDiskCover::SetBeta(f32 beta) +void GuiDiskCover::SetBeta( f32 beta ) { - deg_beta=beta; + deg_beta = beta; } -void GuiDiskCover::SetBetaRotateEffect(f32 beta, u16 step) +void GuiDiskCover::SetBetaRotateEffect( f32 beta, u16 step ) { - eff_beta = beta/(f32)step; - eff_step = step; + eff_beta = beta / ( f32 )step; + eff_step = step; } bool GuiDiskCover::GetBetaRotateEffect() { - return eff_step != 0; + return eff_step != 0; } -void GuiDiskCover::SetSpin(bool Up) +void GuiDiskCover::SetSpin( bool Up ) { - spin_up = 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; - 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); + LOCK( this ); + if ( !image || !this->IsVisible() ) + return; + float currScale = this->GetScale(); +// Menu_DrawDiskCoverShadow(this->GetLeft(), this->GetTop(), 190, width, height, 40, image, imageangle, deg_beta, widescreen ? currScale*0.8 : currScale, currScale, this->GetAlpha(), true); + Menu_DrawDiskCover( this->GetLeft(), this->GetTop(), 50, width, height, 55, image, imageangle, deg_beta, widescreen ? currScale*0.8 : currScale, currScale, 64, true ); + Menu_DrawDiskCover( this->GetLeft(), this->GetTop(), 50, width, height, 55, image, imageangle, deg_beta, widescreen ? currScale*0.8 : currScale, currScale, this->GetAlpha(), false ); - if(eff_step) - { - deg_beta += eff_beta; - eff_step--; - } - GuiImage::imageangle += spin_speedup; - while(GuiImage::imageangle >= 360.0) GuiImage::imageangle -= 360.0; - - if(spin_up) - { - if (spin_speedup < 11) // speed up - spin_speedup += 0.20; - } - else - { - if (spin_speedup > 1) - spin_speedup -=0.05; //slow down - } - - this->UpdateEffects(); + if ( eff_step ) + { + deg_beta += eff_beta; + eff_step--; + } + GuiImage::imageangle += spin_speedup; + while ( GuiImage::imageangle >= 360.0 ) GuiImage::imageangle -= 360.0; + + if ( spin_up ) + { + if ( spin_speedup < 11 ) // speed up + spin_speedup += 0.20; + } + else + { + if ( spin_speedup > 1 ) + spin_speedup -= 0.05; //slow down + } + + this->UpdateEffects(); } diff --git a/source/libwiigui/gui_diskcover.h b/source/libwiigui/gui_diskcover.h index 09ad7fe8..426007e4 100644 --- a/source/libwiigui/gui_diskcover.h +++ b/source/libwiigui/gui_diskcover.h @@ -6,24 +6,24 @@ class GuiDiskCover : public GuiImage { -public: - GuiDiskCover(); - GuiDiskCover(GuiImageData * img); - ~GuiDiskCover(); - void SetBeta(f32 beta); - void SetBetaRotateEffect(f32 beta, u16 Step); - bool GetBetaRotateEffect(); - - void SetSpin(bool Up); - void Draw(); -private: - f32 deg_beta; - f32 eff_beta; - u16 eff_step; - -// f32 spin_angle; - f32 spin_speedup; - bool spin_up; + public: + GuiDiskCover(); + GuiDiskCover( GuiImageData * img ); + ~GuiDiskCover(); + void SetBeta( f32 beta ); + void SetBetaRotateEffect( f32 beta, u16 Step ); + bool GetBetaRotateEffect(); + + void SetSpin( bool Up ); + void Draw(); + private: + f32 deg_beta; + f32 eff_beta; + u16 eff_step; + +// f32 spin_angle; + f32 spin_speedup; + bool spin_up; }; diff --git a/source/libwiigui/gui_element.cpp b/source/libwiigui/gui_element.cpp index e566ea3a..0056409d 100644 --- a/source/libwiigui/gui_element.cpp +++ b/source/libwiigui/gui_element.cpp @@ -17,60 +17,60 @@ mutex_t GuiElement::_lock_mutex = LWP_MUTEX_NULL; GuiElement::GuiElement() { - xoffset = 0; - yoffset = 0; - zoffset = 0; - xmin = 0; - xmax = 0; - ymin = 0; - ymax = 0; - width = 0; - height = 0; - alpha = 255; - scale = 1; - state = STATE_DEFAULT; - stateChan = -1; - trigger[0] = NULL; - trigger[1] = NULL; - trigger[2] = NULL; - trigger[3] = NULL; - trigger[4] = NULL; - trigger[5] = NULL; - parentElement = NULL; - rumble = true; - selectable = false; - clickable = false; - holdable = false; - visible = true; - focus = -1; // cannot be focused - updateCB = NULL; - yoffsetDyn = 0; - xoffsetDyn = 0; - yoffsetDynFloat = 0; - alphaDyn = -1; - scaleDyn = 1; - effects = 0; - effectAmount = 0; - effectTarget = 0; - effectsOver = 0; - effectAmountOver = 0; - effectTargetOver = 0; - frequency = 0.0f; - changervar = 0; - degree = -90.0f; - circleamount = 360.0f; - Radius = 150; - angleDyn = 0.0f; - anglespeed = 0.0f; + xoffset = 0; + yoffset = 0; + zoffset = 0; + xmin = 0; + xmax = 0; + ymin = 0; + ymax = 0; + width = 0; + height = 0; + alpha = 255; + scale = 1; + state = STATE_DEFAULT; + stateChan = -1; + trigger[0] = NULL; + trigger[1] = NULL; + trigger[2] = NULL; + trigger[3] = NULL; + trigger[4] = NULL; + trigger[5] = NULL; + parentElement = NULL; + rumble = true; + selectable = false; + clickable = false; + holdable = false; + visible = true; + focus = -1; // cannot be focused + updateCB = NULL; + yoffsetDyn = 0; + xoffsetDyn = 0; + yoffsetDynFloat = 0; + alphaDyn = -1; + scaleDyn = 1; + effects = 0; + effectAmount = 0; + effectTarget = 0; + effectsOver = 0; + effectAmountOver = 0; + effectTargetOver = 0; + frequency = 0.0f; + changervar = 0; + degree = -90.0f; + circleamount = 360.0f; + Radius = 150; + angleDyn = 0.0f; + anglespeed = 0.0f; - // default alignment - align to top left - alignmentVert = ALIGN_TOP; - alignmentHor = ALIGN_LEFT; -// 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; + // 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; } @@ -79,18 +79,18 @@ GuiElement::GuiElement() */ GuiElement::~GuiElement() { -// LWP_MutexDestroy(mutex); +// LWP_MutexDestroy(mutex); } -void GuiElement::SetParent(GuiElement * e) +void GuiElement::SetParent( GuiElement * e ) { - LOCK(this); - parentElement = e; + LOCK( this ); + parentElement = e; } GuiElement * GuiElement::GetParent() { - return parentElement; + return parentElement; } /** * Get the left position of the GuiElement. @@ -99,32 +99,32 @@ GuiElement * GuiElement::GetParent() */ int GuiElement::GetLeft() { - int x = 0; - int pWidth = 0; - int pLeft = 0; + int x = 0; + int pWidth = 0; + int pLeft = 0; - if(parentElement) - { - pWidth = parentElement->GetWidth(); - pLeft = parentElement->GetLeft(); - } + if ( parentElement ) + { + pWidth = parentElement->GetWidth(); + pLeft = parentElement->GetLeft(); + } - if(effects & (EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND | EFFECT_ROCK_VERTICLE)) - pLeft += xoffsetDyn; + if ( effects & ( EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND | EFFECT_ROCK_VERTICLE ) ) + pLeft += xoffsetDyn; - switch(alignmentHor) - { - case ALIGN_LEFT: - x = pLeft; - break; - case ALIGN_CENTRE: - x = pLeft + (pWidth/2) - (width/2); - break; - case ALIGN_RIGHT: - x = pLeft + pWidth - width; - break; - } - return x + xoffset; + switch ( alignmentHor ) + { + case ALIGN_LEFT: + x = pLeft; + break; + case ALIGN_CENTRE: + x = pLeft + ( pWidth / 2 ) - ( width / 2 ); + break; + case ALIGN_RIGHT: + x = pLeft + pWidth - width; + break; + } + return x + xoffset; } /** @@ -134,77 +134,77 @@ int GuiElement::GetLeft() */ int GuiElement::GetTop() { - int y = 0; - int pHeight = 0; - int pTop = 0; + int y = 0; + int pHeight = 0; + int pTop = 0; - if(parentElement) - { - pHeight = parentElement->GetHeight(); - pTop = parentElement->GetTop(); - } + if ( parentElement ) + { + pHeight = parentElement->GetHeight(); + pTop = parentElement->GetTop(); + } - if(effects & (EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND | EFFECT_ROCK_VERTICLE)) - pTop += yoffsetDyn; + if ( effects & ( EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND | EFFECT_ROCK_VERTICLE ) ) + pTop += yoffsetDyn; - switch(alignmentVert) - { - case ALIGN_TOP: - y = pTop; - break; - case ALIGN_MIDDLE: - y = pTop + (pHeight/2) - (height/2); - break; - case ALIGN_BOTTOM: - y = pTop + pHeight - height; - break; - } - return y + yoffset; + switch ( alignmentVert ) + { + case ALIGN_TOP: + y = pTop; + break; + case ALIGN_MIDDLE: + y = pTop + ( pHeight / 2 ) - ( height / 2 ); + break; + case ALIGN_BOTTOM: + y = pTop + pHeight - height; + break; + } + return y + yoffset; } -void GuiElement::SetMinX(int x) +void GuiElement::SetMinX( int x ) { - LOCK(this); - xmin = x; + LOCK( this ); + xmin = x; } int GuiElement::GetMinX() { - return xmin; + return xmin; } -void GuiElement::SetMaxX(int x) +void GuiElement::SetMaxX( int x ) { - LOCK(this); - xmax = x; + LOCK( this ); + xmax = x; } int GuiElement::GetMaxX() { - return xmax; + return xmax; } -void GuiElement::SetMinY(int y) +void GuiElement::SetMinY( int y ) { - LOCK(this); - ymin = y; + LOCK( this ); + ymin = y; } int GuiElement::GetMinY() { - return ymin; + return ymin; } -void GuiElement::SetMaxY(int y) +void GuiElement::SetMaxY( int y ) { - LOCK(this); - ymax = y; + LOCK( this ); + ymax = y; } int GuiElement::GetMaxY() { - return ymax; + return ymax; } /** @@ -214,7 +214,7 @@ int GuiElement::GetMaxY() */ int GuiElement::GetWidth() { - return width; + return width; } /** @@ -224,7 +224,7 @@ int GuiElement::GetWidth() */ int GuiElement::GetHeight() { - return height; + return height; } /** @@ -234,12 +234,12 @@ int GuiElement::GetHeight() * @see SetWidth() * @see SetHeight() */ -void GuiElement::SetSize(int w, int h) +void GuiElement::SetSize( int w, int h ) { - LOCK(this); + LOCK( this ); - width = w; - height = h; + width = w; + height = h; } /** @@ -249,7 +249,7 @@ void GuiElement::SetSize(int w, int h) */ bool GuiElement::IsVisible() { - return visible; + return visible; } /** @@ -257,479 +257,500 @@ 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; + LOCK( this ); + visible = v; } -void GuiElement::SetAlpha(int a) +void GuiElement::SetAlpha( int a ) { - LOCK(this); - alpha = a; + LOCK( this ); + alpha = a; } int GuiElement::GetAlpha() { - int a; + int a; - if(alphaDyn >= 0) - a = alphaDyn; - else - a = alpha; + if ( alphaDyn >= 0 ) + a = alphaDyn; + else + a = alpha; - if(parentElement) - a *= parentElement->GetAlpha()/255.0; + if ( parentElement ) + a *= parentElement->GetAlpha() / 255.0; - return a; + return a; } float GuiElement::GetAngleDyn() { float 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; + LOCK( this ); + scale = s; } float GuiElement::GetScale() { - float s = scale * scaleDyn; + float s = scale * scaleDyn; - if(parentElement) - s *= parentElement->GetScale(); + if ( parentElement ) + s *= parentElement->GetScale(); - return s; + return s; } int GuiElement::GetState() { - return state; + return state; } int GuiElement::GetStateChan() { - return stateChan; + return stateChan; } -void GuiElement::SetState(int s, int c) +void GuiElement::SetState( int s, int c ) { - LOCK(this); - state = s; - stateChan = c; + LOCK( this ); + state = s; + stateChan = c; } void GuiElement::ResetState() { - LOCK(this); - if(state != STATE_DISABLED) - { - state = STATE_DEFAULT; - stateChan = -1; - } + LOCK( this ); + if ( state != STATE_DISABLED ) + { + state = STATE_DEFAULT; + stateChan = -1; + } } -void GuiElement::SetClickable(bool c) +void GuiElement::SetClickable( bool c ) { - LOCK(this); - clickable = c; + LOCK( this ); + clickable = c; } -void GuiElement::SetSelectable(bool s) +void GuiElement::SetSelectable( bool s ) { - LOCK(this); - selectable = s; + LOCK( this ); + selectable = s; } -void GuiElement::SetHoldable(bool d) +void GuiElement::SetHoldable( bool d ) { - LOCK(this); - holdable = d; + LOCK( this ); + holdable = d; } bool GuiElement::IsSelectable() { - if(state == STATE_DISABLED || state == STATE_CLICKED) - return false; - else - return selectable; + if ( state == STATE_DISABLED || state == STATE_CLICKED ) + return false; + else + return selectable; } bool GuiElement::IsClickable() { - if(state == STATE_DISABLED || - state == STATE_CLICKED || - state == STATE_HELD) - return false; - else - return clickable; + if ( state == STATE_DISABLED || + state == STATE_CLICKED || + state == STATE_HELD ) + return false; + else + return clickable; } bool GuiElement::IsHoldable() { - if(state == STATE_DISABLED) - return false; - else - return holdable; + if ( state == STATE_DISABLED ) + return false; + else + return holdable; } -void GuiElement::SetFocus(int f) +void GuiElement::SetFocus( int f ) { - LOCK(this); - focus = f; + LOCK( this ); + focus = f; } int GuiElement::IsFocused() { - return focus; + return focus; } -void GuiElement::SetTrigger(GuiTrigger * t) +void GuiElement::SetTrigger( GuiTrigger * t ) { - LOCK(this); - if(!trigger[0]) - trigger[0] = t; - else if(!trigger[1]) - trigger[1] = t; - else if(!trigger[2]) - trigger[2] = t; - else if(!trigger[3]) - trigger[3] = t; - else if(!trigger[4]) - trigger[4] = t; - else if(!trigger[5]) - trigger[5] = t; - else // both were assigned, so we'll just overwrite the first one - trigger[0] = t; + LOCK( this ); + if ( !trigger[0] ) + trigger[0] = t; + else if ( !trigger[1] ) + trigger[1] = t; + else if ( !trigger[2] ) + trigger[2] = t; + else if ( !trigger[3] ) + trigger[3] = t; + else if ( !trigger[4] ) + trigger[4] = t; + else if ( !trigger[5] ) + trigger[5] = t; + else // both were assigned, so we'll just overwrite the first one + trigger[0] = t; } -void GuiElement::SetTrigger(u8 i, GuiTrigger * t) +void GuiElement::SetTrigger( u8 i, GuiTrigger * t ) { - LOCK(this); - trigger[i] = t; + LOCK( this ); + trigger[i] = t; } -void GuiElement::RemoveTrigger(u8 i) +void GuiElement::RemoveTrigger( u8 i ) { - LOCK(this); - trigger[i] = NULL; + LOCK( this ); + trigger[i] = NULL; } bool GuiElement::Rumble() { - return rumble; + return rumble; } -void GuiElement::SetRumble(bool r) +void GuiElement::SetRumble( bool r ) { - LOCK(this); - rumble = r; + LOCK( this ); + rumble = r; } int GuiElement::GetEffect() { - LOCK(this); - return effects; -} - + LOCK( this ); + return effects; +} + int GuiElement::GetEffectOnOver() { - LOCK(this); - return effectsOver; + LOCK( this ); + return effectsOver; } float GuiElement::GetFrequency() { - LOCK(this); - return frequency; + LOCK( this ); + return frequency; } -void GuiElement::SetEffect(int eff, int speed, f32 circles, int r, f32 startdegree, f32 anglespeedset, int center_x, int center_y) { +void GuiElement::SetEffect( int eff, int speed, f32 circles, int r, f32 startdegree, f32 anglespeedset, int center_x, int center_y ) +{ - if(eff & EFFECT_GOROUND) { + if ( eff & EFFECT_GOROUND ) + { xoffsetDyn = 0; //!position of circle in x yoffsetDyn = 0; //!position of circle in y Radius = r; //!radius of the circle degree = startdegree; //!for example -90 (°) to start at top of circle circleamount = circles; //!circleamoutn in degrees for example 360 for 1 circle angleDyn = 0.0f; //!this is used by the code to calc the angle - anglespeed = anglespeedset; //!This is anglespeed depending on circle speed 1 is same speed and 0.5 half speed - temp_xoffset = center_x; //!position of center in x - temp_yoffset = center_y; //!position of center in y + anglespeed = anglespeedset; //!This is anglespeed depending on circle speed 1 is same speed and 0.5 half speed + temp_xoffset = center_x; //!position of center in x + temp_yoffset = center_y; //!position of center in y } effects |= eff; effectAmount = speed; //!Circlespeed } -void GuiElement::SetEffect(int eff, int amount, int target) +void GuiElement::SetEffect( int eff, int amount, int target ) { - LOCK(this); - if(eff & EFFECT_SLIDE_IN) - { - // these calculations overcompensate a little - if(eff & EFFECT_SLIDE_TOP) - yoffsetDyn = -screenheight; - else if(eff & EFFECT_SLIDE_LEFT) - xoffsetDyn = -screenwidth; - else if(eff & EFFECT_SLIDE_BOTTOM) - yoffsetDyn = screenheight; - else if(eff & EFFECT_SLIDE_RIGHT) - xoffsetDyn = screenwidth; - } + LOCK( this ); + if ( eff & EFFECT_SLIDE_IN ) + { + // these calculations overcompensate a little + if ( eff & EFFECT_SLIDE_TOP ) + yoffsetDyn = -screenheight; + else if ( eff & EFFECT_SLIDE_LEFT ) + xoffsetDyn = -screenwidth; + else if ( eff & EFFECT_SLIDE_BOTTOM ) + yoffsetDyn = screenheight; + else if ( eff & EFFECT_SLIDE_RIGHT ) + xoffsetDyn = screenwidth; + } - if(eff & EFFECT_FADE && amount > 0) - { - alphaDyn = 0; - } - else if(eff & EFFECT_FADE && amount < 0) - { - alphaDyn = alpha; + if ( eff & EFFECT_FADE && amount > 0 ) + { + alphaDyn = 0; + } + else if ( eff & EFFECT_FADE && amount < 0 ) + { + alphaDyn = alpha; - } else if(eff & EFFECT_ROCK_VERTICLE) { - changervar = 0; + } + else if ( eff & EFFECT_ROCK_VERTICLE ) + { + changervar = 0; yoffsetDyn = 0; yoffsetDynFloat = 0.0; - } + } - effects |= eff; - effectAmount = amount; - effectTarget = target; + effects |= eff; + effectAmount = amount; + effectTarget = target; } -void GuiElement::SetEffectOnOver(int eff, int amount, int target) +void GuiElement::SetEffectOnOver( int eff, int amount, int target ) { - LOCK(this); - effectsOver |= eff; - effectAmountOver = amount; - effectTargetOver = target; + LOCK( this ); + effectsOver |= eff; + effectAmountOver = amount; + effectTargetOver = target; } void GuiElement::SetEffectGrow() { - SetEffectOnOver(EFFECT_SCALE, 4, 110); + SetEffectOnOver( EFFECT_SCALE, 4, 110 ); } void GuiElement::StopEffect() { - xoffsetDyn = 0; - yoffsetDyn = 0; - effects = 0; - effectsOver = 0; - effectAmount = 0; - effectAmountOver = 0; - effectTarget = 0; - effectTargetOver = 0; - scaleDyn = 1; - frequency = 0.0f; - changervar = 0; - //angleDyn = 0.0f; - anglespeed = 0.0f; + xoffsetDyn = 0; + yoffsetDyn = 0; + effects = 0; + effectsOver = 0; + effectAmount = 0; + effectAmountOver = 0; + effectTarget = 0; + effectTargetOver = 0; + scaleDyn = 1; + frequency = 0.0f; + changervar = 0; + //angleDyn = 0.0f; + anglespeed = 0.0f; } void GuiElement::UpdateEffects() { - LOCK(this); + LOCK( this ); - if(effects & (EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND)) - { - if(effects & EFFECT_SLIDE_IN) - { - if(effects & EFFECT_SLIDE_LEFT) - { - xoffsetDyn += effectAmount; + if ( effects & ( EFFECT_SLIDE_IN | EFFECT_SLIDE_OUT | EFFECT_GOROUND ) ) + { + if ( effects & EFFECT_SLIDE_IN ) + { + if ( effects & EFFECT_SLIDE_LEFT ) + { + xoffsetDyn += effectAmount; - if(xoffsetDyn >= 0) - { - xoffsetDyn = 0; - effects = 0; - } - } - else if(effects & EFFECT_SLIDE_RIGHT) - { - xoffsetDyn -= effectAmount; + if ( xoffsetDyn >= 0 ) + { + xoffsetDyn = 0; + effects = 0; + } + } + else if ( effects & EFFECT_SLIDE_RIGHT ) + { + xoffsetDyn -= effectAmount; - if(xoffsetDyn <= 0) - { - xoffsetDyn = 0; - effects = 0; - } - } - else if(effects & EFFECT_SLIDE_TOP) - { - yoffsetDyn += effectAmount; + if ( xoffsetDyn <= 0 ) + { + xoffsetDyn = 0; + effects = 0; + } + } + else if ( effects & EFFECT_SLIDE_TOP ) + { + yoffsetDyn += effectAmount; - if(yoffsetDyn >= 0) - { - yoffsetDyn = 0; - effects = 0; - } - } - else if(effects & EFFECT_SLIDE_BOTTOM) - { - yoffsetDyn -= effectAmount; + if ( yoffsetDyn >= 0 ) + { + yoffsetDyn = 0; + effects = 0; + } + } + else if ( effects & EFFECT_SLIDE_BOTTOM ) + { + yoffsetDyn -= effectAmount; - if(yoffsetDyn <= 0) - { - yoffsetDyn = 0; - effects = 0; - } - } - } - else - { - if(effects & EFFECT_SLIDE_LEFT) - { - xoffsetDyn -= effectAmount; + if ( yoffsetDyn <= 0 ) + { + yoffsetDyn = 0; + effects = 0; + } + } + } + else + { + if ( effects & EFFECT_SLIDE_LEFT ) + { + xoffsetDyn -= effectAmount; - if(xoffsetDyn <= -screenwidth) - effects = 0; // shut off effect - } - else if(effects & EFFECT_SLIDE_RIGHT) - { - xoffsetDyn += effectAmount; + if ( xoffsetDyn <= -screenwidth ) + effects = 0; // shut off effect + } + else if ( effects & EFFECT_SLIDE_RIGHT ) + { + xoffsetDyn += effectAmount; - if(xoffsetDyn >= screenwidth) - effects = 0; // shut off effect - } - else if(effects & EFFECT_SLIDE_TOP) - { - yoffsetDyn -= effectAmount; + if ( xoffsetDyn >= screenwidth ) + effects = 0; // shut off effect + } + else if ( effects & EFFECT_SLIDE_TOP ) + { + yoffsetDyn -= effectAmount; - if(yoffsetDyn <= -screenheight) - effects = 0; // shut off effect - } - else if(effects & EFFECT_SLIDE_BOTTOM) - { - yoffsetDyn += effectAmount; + if ( yoffsetDyn <= -screenheight ) + effects = 0; // shut off effect + } + else if ( effects & EFFECT_SLIDE_BOTTOM ) + { + yoffsetDyn += effectAmount; - if(yoffsetDyn >= screenheight) - effects = 0; // shut off effect - } - } - } - - if(effects & EFFECT_GOROUND) { - //!< check out gui.h for info - xoffset = temp_xoffset; - yoffset = temp_yoffset; - if(fabs(frequency) < circleamount) { - angleDyn = (frequency+degree+90.0f) * anglespeed; - xoffsetDyn = (int) lround(((f32) Radius)*cos((frequency+degree)*PI/180.0f)); - yoffsetDyn = (int) lround(((f32) Radius)*sin((frequency+degree)*PI/180.0f)); - frequency += ((f32) effectAmount)*0.01f; - } else { - f32 temp_frequency = ((effectAmount<0)?-1.0f:1.0f)*circleamount; - angleDyn = (temp_frequency+degree+90.0f) * anglespeed; - xoffsetDyn = (int) lround(((f32) Radius)*cos((temp_frequency+degree)*PI/180.0f)); - yoffsetDyn = (int) lround(((f32) Radius)*sin((temp_frequency+degree)*PI/180.0f)); - xoffset += xoffsetDyn; - yoffset += yoffsetDyn; - effects ^= EFFECT_GOROUND; - frequency = 0.0f; - } + if ( yoffsetDyn >= screenheight ) + effects = 0; // shut off effect + } + } } - if(effects & EFFECT_ROCK_VERTICLE) { + if ( effects & EFFECT_GOROUND ) + { + //!< check out gui.h for info + xoffset = temp_xoffset; + yoffset = temp_yoffset; + if ( fabs( frequency ) < circleamount ) + { + angleDyn = ( frequency + degree + 90.0f ) * anglespeed; + xoffsetDyn = ( int ) lround( ( ( f32 ) Radius ) * cos( ( frequency + degree ) * PI / 180.0f ) ); + yoffsetDyn = ( int ) lround( ( ( f32 ) Radius ) * sin( ( frequency + degree ) * PI / 180.0f ) ); + frequency += ( ( f32 ) effectAmount ) * 0.01f; + } + else + { + f32 temp_frequency = ( ( effectAmount < 0 ) ? -1.0f : 1.0f ) * circleamount; + angleDyn = ( temp_frequency + degree + 90.0f ) * anglespeed; + xoffsetDyn = ( int ) lround( ( ( f32 ) Radius ) * cos( ( temp_frequency + degree ) * PI / 180.0f ) ); + yoffsetDyn = ( int ) lround( ( ( f32 ) Radius ) * sin( ( temp_frequency + degree ) * PI / 180.0f ) ); + xoffset += xoffsetDyn; + yoffset += yoffsetDyn; + effects ^= EFFECT_GOROUND; + frequency = 0.0f; + } + } + + if ( effects & EFFECT_ROCK_VERTICLE ) + { //move up to 10pixel above 0 - if(changervar == 0 && yoffsetDynFloat < 11.0) { - yoffsetDynFloat += (effectAmount*0.01); - } else if(yoffsetDynFloat > 10.0) { + if ( changervar == 0 && yoffsetDynFloat < 11.0 ) + { + yoffsetDynFloat += ( effectAmount * 0.01 ); + } + else if ( yoffsetDynFloat > 10.0 ) + { changervar = 1; } //move down till 10pixel under 0 - if(changervar == 1 && yoffsetDynFloat > -11.0) { - yoffsetDynFloat -= (effectAmount*0.01); - } else if(yoffsetDynFloat < -10.0) { + if ( changervar == 1 && yoffsetDynFloat > -11.0 ) + { + yoffsetDynFloat -= ( effectAmount * 0.01 ); + } + else if ( yoffsetDynFloat < -10.0 ) + { changervar = 0; } - yoffsetDyn = (int)(yoffsetDynFloat); + yoffsetDyn = ( int )( yoffsetDynFloat ); } - if(effects & EFFECT_FADE) - { - alphaDyn += effectAmount; + if ( effects & EFFECT_FADE ) + { + alphaDyn += effectAmount; - if(effectAmount < 0 && alphaDyn <= 0) - { - alphaDyn = 0; - effects = 0; // shut off effect - } - else if(effectAmount > 0 && alphaDyn >= alpha) - { - alphaDyn = alpha; - effects = 0; // shut off effect - } - } - if(effects & EFFECT_SCALE) - { - scaleDyn += effectAmount/100.0; + if ( effectAmount < 0 && alphaDyn <= 0 ) + { + alphaDyn = 0; + effects = 0; // shut off effect + } + else if ( effectAmount > 0 && alphaDyn >= alpha ) + { + alphaDyn = alpha; + effects = 0; // shut off effect + } + } + if ( effects & EFFECT_SCALE ) + { + scaleDyn += effectAmount / 100.0; - if((effectAmount < 0 && scaleDyn <= effectTarget/100.0) - || (effectAmount > 0 && scaleDyn >= effectTarget/100.0)) - { - scaleDyn = effectTarget/100.0; - effects = 0; // shut off effect - } - } - if(effects & EFFECT_PULSE) - { - int percent = 10; //go down from target by this + if ( ( effectAmount < 0 && scaleDyn <= effectTarget / 100.0 ) + || ( effectAmount > 0 && scaleDyn >= effectTarget / 100.0 ) ) + { + scaleDyn = effectTarget / 100.0; + effects = 0; // shut off effect + } + } + if ( effects & EFFECT_PULSE ) + { + int percent = 10; //go down from target by this - if((scaleDyn <= (effectTarget*0.01)) && (!changervar)) { - scaleDyn += (effectAmount*0.001); - } else if(scaleDyn > (effectTarget*0.01)) { + if ( ( scaleDyn <= ( effectTarget*0.01 ) ) && ( !changervar ) ) + { + scaleDyn += ( effectAmount * 0.001 ); + } + else if ( scaleDyn > ( effectTarget*0.01 ) ) + { changervar = 1; - } - if((scaleDyn >= ((effectTarget-percent)*0.01)) && (changervar)) { - scaleDyn -= (effectAmount*0.001); - } else if(scaleDyn < ((effectTarget-percent)*0.01)) { + } + if ( ( scaleDyn >= ( ( effectTarget - percent )*0.01 ) ) && ( changervar ) ) + { + scaleDyn -= ( effectAmount * 0.001 ); + } + 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); + LOCK( this ); + if ( updateCB ) + updateCB( this ); } -void GuiElement::SetUpdateCallback(UpdateCallback u) +void GuiElement::SetUpdateCallback( UpdateCallback u ) { - LOCK(this); - updateCB = 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; - yoffset = yoff; - zoffset = zoff; + LOCK( this ); + xoffset = xoff; + yoffset = yoff; + zoffset = zoff; } -void GuiElement::SetAlignment(int hor, int vert) +void GuiElement::SetAlignment( int hor, int vert ) { - LOCK(this); - alignmentHor = hor; - alignmentVert = vert; + LOCK( this ); + alignmentHor = hor; + alignmentVert = vert; } int GuiElement::GetSelected() { - return -1; + return -1; } /** @@ -751,69 +772,69 @@ void GuiElement::DrawTooltip() * @param[in] x X position in pixel. * @param[in] y Y position in pixel. */ -bool GuiElement::IsInside(int x, int y) +bool GuiElement::IsInside( int x, int y ) { - if(x > this->GetLeft() && x < (this->GetLeft()+width) - && y > this->GetTop() && y < (this->GetTop()+height)) - return true; - return false; + 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(_lock_mutex); +// LWP_MutexLock(mutex); + for ( ;; ) // loop while element is locked by self + { + LWP_MutexLock( _lock_mutex ); - if(_lock_thread == LWP_THREAD_NULL) // element is not locked - { - _lock_thread = LWP_GetSelf(); // mark as locked - _lock_count = 1; // set count of lock to 1 - LWP_MutexUnlock(_lock_mutex); - return; - } - else if(_lock_thread == LWP_GetSelf()) // thread is locked by my self - { - _lock_count++; // inc count of locks; - LWP_MutexUnlock(_lock_mutex); - return; - } - else // otherwise the element is locked by an other thread - { - if(_lock_queue == LWP_TQUEUE_NULL) // no queue - meens it is the first access to the locked element - LWP_InitQueue(&_lock_queue); // init queue - LWP_MutexUnlock(_lock_mutex); - LWP_ThreadSleep(_lock_queue); // and sleep - // try lock again; - } - } + if ( _lock_thread == LWP_THREAD_NULL ) // element is not locked + { + _lock_thread = LWP_GetSelf(); // mark as locked + _lock_count = 1; // set count of lock to 1 + LWP_MutexUnlock( _lock_mutex ); + return; + } + else if ( _lock_thread == LWP_GetSelf() ) // thread is locked by my self + { + _lock_count++; // inc count of locks; + LWP_MutexUnlock( _lock_mutex ); + return; + } + else // otherwise the element is locked by an other thread + { + if ( _lock_queue == LWP_TQUEUE_NULL ) // no queue - meens it is the first access to the locked element + LWP_InitQueue( &_lock_queue ); // init queue + LWP_MutexUnlock( _lock_mutex ); + LWP_ThreadSleep( _lock_queue ); // and sleep + // try lock again; + } + } } void GuiElement::Unlock() { -// LWP_MutexUnlock(mutex); - LWP_MutexLock(_lock_mutex); - // only the thread was locked this element, can call unlock - if(_lock_thread == LWP_GetSelf()) // but we check it here – safe is safe - { - if(--_lock_count == 0) // dec count of locks and check if it last lock; - { - _lock_thread = LWP_THREAD_NULL; // mark as unlocked - if(_lock_queue != LWP_TQUEUE_NULL) // has a queue - { - LWP_CloseQueue(_lock_queue); // close the queue and wake all waited threads - _lock_queue = LWP_TQUEUE_NULL; - } - } - } - LWP_MutexUnlock(_lock_mutex); +// LWP_MutexUnlock(mutex); + LWP_MutexLock( _lock_mutex ); + // only the thread was locked this element, can call unlock + if ( _lock_thread == LWP_GetSelf() ) // but we check it here – safe is safe + { + if ( --_lock_count == 0 ) // dec count of locks and check if it last lock; + { + _lock_thread = LWP_THREAD_NULL; // mark as unlocked + if ( _lock_queue != LWP_TQUEUE_NULL ) // has a queue + { + LWP_CloseQueue( _lock_queue ); // close the queue and wake all waited threads + _lock_queue = LWP_TQUEUE_NULL; + } + } + } + LWP_MutexUnlock( _lock_mutex ); } -SimpleLock::SimpleLock(GuiElement *e) : element(e) +SimpleLock::SimpleLock( GuiElement *e ) : element( e ) { - element->Lock(); + element->Lock(); } SimpleLock::~SimpleLock() { - element->Unlock(); + element->Unlock(); } diff --git a/source/libwiigui/gui_filebrowser.cpp b/source/libwiigui/gui_filebrowser.cpp index 42a6595f..e453c4a9 100644 --- a/source/libwiigui/gui_filebrowser.cpp +++ b/source/libwiigui/gui_filebrowser.cpp @@ -15,128 +15,128 @@ /** * Constructor for the GuiFileBrowser class. */ -GuiFileBrowser::GuiFileBrowser(int w, int h) +GuiFileBrowser::GuiFileBrowser( int w, int h ) { - width = w; - height = h; - selectedItem = 0; - selectable = true; - listChanged = true; // trigger an initial list update - triggerdisabled = false; // trigger disable - focus = 0; // allow focus + width = w; + height = h; + selectedItem = 0; + selectable = true; + listChanged = true; // trigger an initial list update + triggerdisabled = false; // trigger disable + focus = 0; // allow focus - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); - trigHeldA = new GuiTrigger; - trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigHeldA = new GuiTrigger; + trigHeldA->SetHeldTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); - btnSoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + btnSoundOver = new GuiSound( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + btnSoundClick = new GuiSound( button_click_pcm, button_click_pcm_size, Settings.sfxvolume ); - char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbg_browser.png", CFG.theme_path); - bgFileSelection = new GuiImageData(imgPath, bg_browser_png); - bgFileSelectionImg = new GuiImage(bgFileSelection); - bgFileSelectionImg->SetParent(this); - bgFileSelectionImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + char imgPath[100]; + snprintf( imgPath, sizeof( imgPath ), "%sbg_browser.png", CFG.theme_path ); + bgFileSelection = new GuiImageData( imgPath, bg_browser_png ); + bgFileSelectionImg = new GuiImage( bgFileSelection ); + bgFileSelectionImg->SetParent( this ); + bgFileSelectionImg->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - snprintf(imgPath, sizeof(imgPath), "%sbg_browser_selection.png", CFG.theme_path); - bgFileSelectionEntry = new GuiImageData(imgPath, bg_browser_selection_png); -// 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", CFG.theme_path); - scrollbar = new GuiImageData(imgPath, scrollbar_png); - scrollbarImg = new GuiImage(scrollbar); - scrollbarImg->SetParent(this); - scrollbarImg->SetAlignment(ALIGN_RIGHT, ALIGN_TOP); - scrollbarImg->SetPosition(0, 2); - scrollbarImg->SetSkew(0,0,0,0,0,-30,0,-30); + snprintf( imgPath, sizeof( imgPath ), "%sbg_browser_selection.png", CFG.theme_path ); + bgFileSelectionEntry = new GuiImageData( imgPath, bg_browser_selection_png ); +// fileArchives = new GuiImageData(icon_archives_png); +// fileDefault = new GuiImageData(icon_default_png); + fileFolder = new GuiImageData( icon_folder_png ); +// 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_arrowdown.png", CFG.theme_path); - arrowDown = new GuiImageData(imgPath, scrollbar_arrowdown_png); - arrowDownImg = new GuiImage(arrowDown); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", CFG.theme_path); - arrowUp = new GuiImageData(imgPath, scrollbar_arrowup_png); - arrowUpImg = new GuiImage(arrowUp); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_box.png", CFG.theme_path); - scrollbarBox = new GuiImageData(imgPath, scrollbar_box_png); - scrollbarBoxImg = new GuiImage(scrollbarBox); + snprintf( imgPath, sizeof( imgPath ), "%sscrollbar.png", CFG.theme_path ); + scrollbar = new GuiImageData( imgPath, scrollbar_png ); + scrollbarImg = new GuiImage( scrollbar ); + scrollbarImg->SetParent( this ); + scrollbarImg->SetAlignment( ALIGN_RIGHT, ALIGN_TOP ); + scrollbarImg->SetPosition( 0, 2 ); + scrollbarImg->SetSkew( 0, 0, 0, 0, 0, -30, 0, -30 ); - 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); + snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_arrowdown.png", CFG.theme_path ); + arrowDown = new GuiImageData( imgPath, scrollbar_arrowdown_png ); + arrowDownImg = new GuiImage( arrowDown ); + snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_arrowup.png", CFG.theme_path ); + arrowUp = new GuiImageData( imgPath, scrollbar_arrowup_png ); + arrowUpImg = new GuiImage( arrowUp ); + snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_box.png", CFG.theme_path ); + scrollbarBox = new GuiImageData( imgPath, scrollbar_box_png ); + scrollbarBoxImg = new GuiImage( scrollbarBox ); - 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); + 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 ); - 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); + 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 ); - for(int i=0; iSetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - fileListText[i]->SetPosition(5,0); - fileListText[i]->SetMaxWidth(bgFileSelectionImg->GetWidth() - (arrowDownImg->GetWidth()+20), DOTTED); + 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 ); - 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); + 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 ); - fileListBg[i] = new GuiImage(bgFileSelectionEntry); - //fileListArchives[i] = new GuiImage(fileArchives); - //fileListDefault[i] = new GuiImage(fileDefault); - fileListFolder[i] = new GuiImage(fileFolder); - //fileListGFX[i] = new GuiImage(fileGFX); - //fileListPLS[i] = new GuiImage(filePLS); - //fileListSFX[i] = new GuiImage(fileSFX); - //fileListTXT[i] = new GuiImage(fileTXT); - //fileListXML[i] = new GuiImage(fileXML); - fileList[i] = new GuiButton(350,30); - fileList[i]->SetParent(this); - fileList[i]->SetLabel(fileListText[i]); - fileList[i]->SetLabelOver(fileListTextOver[i]); - fileList[i]->SetImageOver(fileListBg[i]); - fileList[i]->SetPosition(2,30*i+3); - fileList[i]->SetTrigger(trigA); - fileList[i]->SetRumble(false); - fileList[i]->SetSoundClick(btnSoundClick); - } + 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 ); + //fileListArchives[i] = new GuiImage(fileArchives); + //fileListDefault[i] = new GuiImage(fileDefault); + fileListFolder[i] = new GuiImage( fileFolder ); + //fileListGFX[i] = new GuiImage(fileGFX); + //fileListPLS[i] = new GuiImage(filePLS); + //fileListSFX[i] = new GuiImage(fileSFX); + //fileListTXT[i] = new GuiImage(fileTXT); + //fileListXML[i] = new GuiImage(fileXML); + fileList[i] = new GuiButton( 350, 30 ); + fileList[i]->SetParent( this ); + fileList[i]->SetLabel( fileListText[i] ); + fileList[i]->SetLabelOver( fileListTextOver[i] ); + fileList[i]->SetImageOver( fileListBg[i] ); + fileList[i]->SetPosition( 2, 30*i + 3 ); + fileList[i]->SetTrigger( trigA ); + fileList[i]->SetRumble( false ); + fileList[i]->SetSoundClick( btnSoundClick ); + } } /** @@ -144,88 +144,88 @@ GuiFileBrowser::GuiFileBrowser(int w, int h) */ GuiFileBrowser::~GuiFileBrowser() { - delete arrowUpBtn; - delete arrowDownBtn; - delete scrollbarBoxBtn; + delete arrowUpBtn; + delete arrowDownBtn; + delete scrollbarBoxBtn; - delete bgFileSelectionImg; - delete scrollbarImg; - delete arrowDownImg; - delete arrowUpImg; - delete scrollbarBoxImg; + delete bgFileSelectionImg; + delete scrollbarImg; + delete arrowDownImg; + delete arrowUpImg; + delete scrollbarBoxImg; - delete bgFileSelection; - delete bgFileSelectionEntry; - //delete fileArchives; - //delete fileDefault; - delete fileFolder; - //delete fileGFX; - //delete filePLS; - //delete fileSFX; - //delete fileTXT; - //delete fileXML; - delete scrollbar; - delete arrowDown; - delete arrowUp; - delete scrollbarBox; + delete bgFileSelection; + delete bgFileSelectionEntry; + //delete fileArchives; + //delete fileDefault; + delete fileFolder; + //delete fileGFX; + //delete filePLS; + //delete fileSFX; + //delete fileTXT; + //delete fileXML; + delete scrollbar; + delete arrowDown; + delete arrowUp; + delete scrollbarBox; - delete btnSoundOver; - delete btnSoundClick; - delete trigHeldA; - delete trigA; + delete btnSoundOver; + delete btnSoundClick; + delete trigHeldA; + delete trigA; - for(int i=0; iResetState(); + for ( int i = 0; 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; + LOCK( this ); + triggerdisabled = set; } void GuiFileBrowser::ResetState() { - LOCK(this); - state = STATE_DEFAULT; - stateChan = -1; - selectedItem = 0; + LOCK( this ); + state = STATE_DEFAULT; + stateChan = -1; + selectedItem = 0; - for(int i=0; iResetState(); - } + for ( int i = 0; i < FILEBROWSERSIZE; i++ ) + { + fileList[i]->ResetState(); + } } void GuiFileBrowser::TriggerUpdate() { - LOCK(this); - listChanged = true; + LOCK( this ); + listChanged = true; } /** @@ -233,183 +233,183 @@ void GuiFileBrowser::TriggerUpdate() */ void GuiFileBrowser::Draw() { - LOCK(this); - if(!this->IsVisible()) - return; + LOCK( this ); + if ( !this->IsVisible() ) + return; - bgFileSelectionImg->Draw(); + bgFileSelectionImg->Draw(); - for(int i=0; iDraw(); - } + for ( int i = 0; i < FILEBROWSERSIZE; i++ ) + { + fileList[i]->Draw(); + } - scrollbarImg->Draw(); - arrowUpBtn->Draw(); - arrowDownBtn->Draw(); - scrollbarBoxBtn->Draw(); + scrollbarImg->Draw(); + arrowUpBtn->Draw(); + arrowDownBtn->Draw(); + scrollbarBoxBtn->Draw(); - this->UpdateEffects(); + this->UpdateEffects(); } -void GuiFileBrowser::Update(GuiTrigger * t) +void GuiFileBrowser::Update( GuiTrigger * t ) { - LOCK(this); - if(state == STATE_DISABLED || !t || triggerdisabled) - return; + LOCK( this ); + if ( state == STATE_DISABLED || !t || triggerdisabled ) + return; - int position = 0; - int positionWiimote = 0; + int position = 0; + int positionWiimote = 0; - arrowUpBtn->Update(t); - arrowDownBtn->Update(t); - scrollbarBoxBtn->Update(t); + arrowUpBtn->Update( t ); + arrowDownBtn->Update( t ); + scrollbarBoxBtn->Update( t ); - // move the file listing to respond to wiimote cursor movement - if(scrollbarBoxBtn->GetState() == STATE_HELD && - scrollbarBoxBtn->GetStateChan() == t->chan && - t->wpad.ir.valid && - browser->browserList.size() > FILEBROWSERSIZE - ) - { - scrollbarBoxBtn->SetPosition(20,-10); - positionWiimote = t->wpad.ir.y - 60 - scrollbarBoxBtn->GetTop(); + // move the file listing to respond to wiimote cursor movement + if ( scrollbarBoxBtn->GetState() == STATE_HELD && + scrollbarBoxBtn->GetStateChan() == t->chan && + t->wpad.ir.valid && + browser->browserList.size() > FILEBROWSERSIZE + ) + { + scrollbarBoxBtn->SetPosition( 20, -10 ); + positionWiimote = t->wpad.ir.y - 60 - scrollbarBoxBtn->GetTop(); - if(positionWiimote < scrollbarBoxBtn->GetMinY()) - positionWiimote = scrollbarBoxBtn->GetMinY(); - else if(positionWiimote > scrollbarBoxBtn->GetMaxY()) - positionWiimote = scrollbarBoxBtn->GetMaxY(); + if ( positionWiimote < scrollbarBoxBtn->GetMinY() ) + positionWiimote = scrollbarBoxBtn->GetMinY(); + else if ( positionWiimote > scrollbarBoxBtn->GetMaxY() ) + positionWiimote = scrollbarBoxBtn->GetMaxY(); - browser->pageIndex = (positionWiimote * browser->browserList.size())/136.0 - selectedItem; + browser->pageIndex = ( positionWiimote * browser->browserList.size() ) / 136.0 - selectedItem; - if(browser->pageIndex <= 0) - { - browser->pageIndex = 0; - } - else if(browser->pageIndex+FILEBROWSERSIZE >= (int)browser->browserList.size()) - { - browser->pageIndex = browser->browserList.size()-FILEBROWSERSIZE; - } - listChanged = true; - focus = false; - + if ( browser->pageIndex <= 0 ) + { + browser->pageIndex = 0; + } + else if ( browser->pageIndex + FILEBROWSERSIZE >= ( int )browser->browserList.size() ) + { + browser->pageIndex = browser->browserList.size() - FILEBROWSERSIZE; + } + listChanged = true; + focus = false; - } - if(arrowDownBtn->GetState() == STATE_HELD && arrowDownBtn->GetStateChan() == t->chan) - { - t->wpad.btns_h |= WPAD_BUTTON_DOWN; - if(!this->IsFocused()) - ((GuiWindow *)this->GetParent())->ChangeFocus(this); - - } - else if(arrowUpBtn->GetState() == STATE_HELD && arrowUpBtn->GetStateChan() == t->chan) - { - t->wpad.btns_h |= WPAD_BUTTON_UP; - if(!this->IsFocused()) - ((GuiWindow *)this->GetParent())->ChangeFocus(this); - - } + } -/* // pad/joystick navigation - if(!focus) - { - goto endNavigation; // skip navigation - listChanged = false; - } -*/ - if(t->Right()) - { - if(browser->pageIndex < (int)browser->browserList.size() && browser->browserList.size() > FILEBROWSERSIZE) - { - browser->pageIndex += FILEBROWSERSIZE; - if(browser->pageIndex+FILEBROWSERSIZE >= (int)browser->browserList.size()) - browser->pageIndex = browser->browserList.size()-FILEBROWSERSIZE; - listChanged = true; - } - } - else if(t->Left()) - { - if(browser->pageIndex > 0) - { - browser->pageIndex -= FILEBROWSERSIZE; - if(browser->pageIndex < 0) - browser->pageIndex = 0; - listChanged = true; - } - } - else if(t->Down()) - { - if(browser->pageIndex + selectedItem + 1 < (int)browser->browserList.size()) - { - if(selectedItem == FILEBROWSERSIZE-1) - { - // move list down by 1 - browser->pageIndex++; - listChanged = true; - } - else if(fileList[selectedItem+1]->IsVisible()) - { - fileList[selectedItem]->ResetState(); - fileList[++selectedItem]->SetState(STATE_SELECTED, t->chan); - } - } - } - else if(t->Up()) - { - if(selectedItem == 0 && browser->pageIndex + selectedItem > 0) - { - // move list up by 1 - browser->pageIndex--; - listChanged = true; - } - else if(selectedItem > 0) - { - fileList[selectedItem]->ResetState(); - fileList[--selectedItem]->SetState(STATE_SELECTED, t->chan); - } - } + if ( arrowDownBtn->GetState() == STATE_HELD && arrowDownBtn->GetStateChan() == t->chan ) + { + t->wpad.btns_h |= WPAD_BUTTON_DOWN; + if ( !this->IsFocused() ) + ( ( GuiWindow * )this->GetParent() )->ChangeFocus( this ); - //endNavigation: + } + 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 ); - for(int i=0; ipageIndex+i < (int)browser->browserList.size()) - { - if(fileList[i]->GetState() == STATE_DISABLED) - fileList[i]->SetState(STATE_DEFAULT); + } - if(fileList[i]->GetState() == STATE_SELECTED) - haveselected = true; + /* // pad/joystick navigation + if(!focus) + { + goto endNavigation; // skip navigation + listChanged = false; + } + */ + if ( t->Right() ) + { + if ( browser->pageIndex < ( int )browser->browserList.size() && browser->browserList.size() > FILEBROWSERSIZE ) + { + browser->pageIndex += FILEBROWSERSIZE; + if ( browser->pageIndex + FILEBROWSERSIZE >= ( int )browser->browserList.size() ) + browser->pageIndex = browser->browserList.size() - FILEBROWSERSIZE; + listChanged = true; + } + } + else if ( t->Left() ) + { + if ( browser->pageIndex > 0 ) + { + browser->pageIndex -= FILEBROWSERSIZE; + if ( browser->pageIndex < 0 ) + browser->pageIndex = 0; + listChanged = true; + } + } + else if ( t->Down() ) + { + if ( browser->pageIndex + selectedItem + 1 < ( int )browser->browserList.size() ) + { + if ( selectedItem == FILEBROWSERSIZE - 1 ) + { + // move list down by 1 + browser->pageIndex++; + listChanged = true; + } + else if ( fileList[selectedItem+1]->IsVisible() ) + { + fileList[selectedItem]->ResetState(); + fileList[++selectedItem]->SetState( STATE_SELECTED, t->chan ); + } + } + } + else if ( t->Up() ) + { + if ( selectedItem == 0 && browser->pageIndex + selectedItem > 0 ) + { + // move list up by 1 + browser->pageIndex--; + listChanged = true; + } + else if ( selectedItem > 0 ) + { + fileList[selectedItem]->ResetState(); + fileList[--selectedItem]->SetState( STATE_SELECTED, t->chan ); + } + } - fileList[i]->SetVisible(true); + //endNavigation: - fileListText[i]->SetText(browser->browserList[browser->pageIndex+i].displayname); - fileListTextOver[i]->SetText(browser->browserList[browser->pageIndex+i].displayname); + for ( int i = 0; i < FILEBROWSERSIZE; i++ ) + { + if ( listChanged ) + { + bool haveselected = false; + if ( browser->pageIndex + i < ( int )browser->browserList.size() ) + { + if ( fileList[i]->GetState() == STATE_DISABLED ) + fileList[i]->SetState( STATE_DEFAULT ); - if(browser->browserList[browser->pageIndex+i].isdir) // directory - { - fileList[i]->SetIcon(fileListFolder[i]); - fileListText[i]->SetPosition(30,0); - fileListTextOver[i]->SetPosition(30,0); - } - else - { - /* - char *fileext = strrchr(browserList[browser.pageIndex+i].displayname, '.'); - fileListText[i]->SetPosition(32,0); - fileListTextOver[i]->SetPosition(32,0); - if(fileext) - { + if ( fileList[i]->GetState() == STATE_SELECTED ) + haveselected = true; + + fileList[i]->SetVisible( true ); + + fileListText[i]->SetText( browser->browserList[browser->pageIndex+i].displayname ); + fileListTextOver[i]->SetText( browser->browserList[browser->pageIndex+i].displayname ); + + if ( browser->browserList[browser->pageIndex+i].isdir ) // directory + { + fileList[i]->SetIcon( fileListFolder[i] ); + fileListText[i]->SetPosition( 30, 0 ); + fileListTextOver[i]->SetPosition( 30, 0 ); + } + else + { + /* + char *fileext = strrchr(browserList[browser.pageIndex+i].displayname, '.'); + fileListText[i]->SetPosition(32,0); + fileListTextOver[i]->SetPosition(32,0); + if(fileext) + { if(!strcasecmp(fileext, ".png") || !strcasecmp(fileext, ".jpg") || !strcasecmp(fileext, ".jpeg") || - !strcasecmp(fileext, ".gif") || !strcasecmp(fileext, ".tga") || !strcasecmp(fileext, ".tpl") || - !strcasecmp(fileext, ".bmp")) { + !strcasecmp(fileext, ".gif") || !strcasecmp(fileext, ".tga") || !strcasecmp(fileext, ".tpl") || + !strcasecmp(fileext, ".bmp")) { fileList[i]->SetIcon(fileListGFX[i]); } else if(!strcasecmp(fileext, ".mp3") || !strcasecmp(fileext, ".ogg") || !strcasecmp(fileext, ".flac") || - !strcasecmp(fileext, ".mpc") || !strcasecmp(fileext, ".m4a") || !strcasecmp(fileext, ".wav")) { + !strcasecmp(fileext, ".mpc") || !strcasecmp(fileext, ".m4a") || !strcasecmp(fileext, ".wav")) { fileList[i]->SetIcon(fileListSFX[i]); } else if(!strcasecmp(fileext, ".pls") || !strcasecmp(fileext, ".m3u")) { fileList[i]->SetIcon(fileListPLS[i]); @@ -418,68 +418,68 @@ void GuiFileBrowser::Update(GuiTrigger * t) } else if(!strcasecmp(fileext, ".xml")) { fileList[i]->SetIcon(fileListXML[i]); } else if(!strcasecmp(fileext, ".rar") || !strcasecmp(fileext, ".zip") || - !strcasecmp(fileext, ".gz") || !strcasecmp(fileext, ".7z")) { + !strcasecmp(fileext, ".gz") || !strcasecmp(fileext, ".7z")) { fileList[i]->SetIcon(fileListArchives[i]); } else { fileList[i]->SetIcon(fileListDefault[i]); } - } else { + } else { fileList[i]->SetIcon(fileListDefault[i]); - } - */ - fileList[i]->SetIcon(NULL); - fileListText[i]->SetPosition(10,0); - fileListTextOver[i]->SetPosition(10,0); - } - } - else - { - fileList[i]->SetVisible(false); - fileList[i]->SetState(STATE_DISABLED); - } - if(!haveselected && browser->pageIndex < (int)browser->browserList.size()) - fileList[i]->SetState(STATE_SELECTED, t->chan); + } + */ + fileList[i]->SetIcon( NULL ); + fileListText[i]->SetPosition( 10, 0 ); + fileListTextOver[i]->SetPosition( 10, 0 ); + } + } + else + { + fileList[i]->SetVisible( false ); + fileList[i]->SetState( STATE_DISABLED ); + } + if ( !haveselected && browser->pageIndex < ( int )browser->browserList.size() ) + fileList[i]->SetState( STATE_SELECTED, t->chan ); - } + } - if(i != selectedItem && fileList[i]->GetState() == STATE_SELECTED) - fileList[i]->ResetState(); - else if(focus && i == selectedItem && fileList[i]->GetState() == STATE_DEFAULT) - fileList[selectedItem]->SetState(STATE_SELECTED, t->chan); + if ( i != selectedItem && fileList[i]->GetState() == STATE_SELECTED ) + fileList[i]->ResetState(); + else if ( focus && i == selectedItem && fileList[i]->GetState() == STATE_DEFAULT ) + fileList[selectedItem]->SetState( STATE_SELECTED, t->chan ); - int currChan = t->chan; + int currChan = t->chan; - if(t->wpad.ir.valid && !fileList[i]->IsInside(t->wpad.ir.x, t->wpad.ir.y)) - t->chan = -1; + if ( t->wpad.ir.valid && !fileList[i]->IsInside( t->wpad.ir.x, t->wpad.ir.y ) ) + t->chan = -1; - fileList[i]->Update(t); - t->chan = currChan; + fileList[i]->Update( t ); + t->chan = currChan; - if(fileList[i]->GetState() == STATE_SELECTED) - { - selectedItem = i; - } - } + if ( fileList[i]->GetState() == STATE_SELECTED ) + { + selectedItem = i; + } + } - // update the location of the scroll box based on the position in the file list - if(positionWiimote > 0) - { - position = positionWiimote; // follow wiimote cursor - } - else - { - position = 136*(browser->pageIndex + FILEBROWSERSIZE/2.0) / (browser->browserList.size()*1.0); + // update the location of the scroll box based on the position in the file list + if ( positionWiimote > 0 ) + { + position = positionWiimote; // follow wiimote cursor + } + else + { + position = 136 * ( browser->pageIndex + FILEBROWSERSIZE / 2.0 ) / ( browser->browserList.size() * 1.0 ); - if(browser->pageIndex/(FILEBROWSERSIZE/2.0) < 1) - position = -10; - else if((browser->pageIndex+FILEBROWSERSIZE)/(FILEBROWSERSIZE*1.0) >= (browser->browserList.size())/(FILEBROWSERSIZE*1.0)) - position = 156; - } + if ( browser->pageIndex / ( FILEBROWSERSIZE / 2.0 ) < 1 ) + position = -10; + else if ( ( browser->pageIndex + FILEBROWSERSIZE ) / ( FILEBROWSERSIZE*1.0 ) >= ( browser->browserList.size() ) / ( FILEBROWSERSIZE*1.0 ) ) + position = 156; + } - scrollbarBoxBtn->SetPosition(12,position+26); + scrollbarBoxBtn->SetPosition( 12, position + 26 ); - listChanged = false; + listChanged = false; - if(updateCB) - updateCB(this); + if ( updateCB ) + updateCB( this ); } diff --git a/source/libwiigui/gui_gamebrowser.cpp b/source/libwiigui/gui_gamebrowser.cpp index 1d66fe67..cc4ce8bb 100644 --- a/source/libwiigui/gui_gamebrowser.cpp +++ b/source/libwiigui/gui_gamebrowser.cpp @@ -24,141 +24,141 @@ 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; - selectable = true; - listOffset = MAX(0,MIN(offset,(gameList.size()-pagesize))); - selectedItem = selected - offset; - focus = 1; // allow focus - char imgPath[100]; + width = w; + height = h; + pagesize = THEME.pagesize; + scrollbaron = ( gameList.size() > pagesize ) ? 1 : 0; + selectable = true; + listOffset = MAX( 0, MIN( offset, ( gameList.size() - pagesize ) ) ); + selectedItem = selected - offset; + focus = 1; // allow focus + char imgPath[100]; - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); trigHeldA = new GuiTrigger; - trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A, PAD_BUTTON_A); - btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + trigHeldA->SetHeldTrigger( -1, WPAD_BUTTON_A, PAD_BUTTON_A ); + btnSoundClick = new GuiSound( button_click_pcm, button_click_pcm_size, Settings.sfxvolume ); - snprintf(imgPath, sizeof(imgPath), "%sbg_options.png", themePath); - bgGames = new GuiImageData(imgPath, imagebg); + snprintf( imgPath, sizeof( imgPath ), "%sbg_options.png", themePath ); + bgGames = new GuiImageData( imgPath, imagebg ); - snprintf(imgPath, sizeof(imgPath), "%snew.png", themePath); - newGames = new GuiImageData(imgPath, new_png); + snprintf( imgPath, sizeof( imgPath ), "%snew.png", themePath ); + newGames = new GuiImageData( imgPath, new_png ); - bgGameImg = new GuiImage(bgGames); - bgGameImg->SetParent(this); - bgGameImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - - maxTextWidth = bgGameImg->GetWidth() - 24 - 4; + bgGameImg = new GuiImage( bgGames ); + bgGameImg->SetParent( this ); + bgGameImg->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - snprintf(imgPath, sizeof(imgPath), "%sbg_options_entry.png", themePath); - bgGamesEntry = new GuiImageData(imgPath, bg_options_entry_png); + maxTextWidth = bgGameImg->GetWidth() - 24 - 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 ), "%sbg_options_entry.png", themePath ); + bgGamesEntry = new GuiImageData( imgPath, bg_options_entry_png ); - maxTextWidth -= scrollbarImg->GetWidth() + 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); + maxTextWidth -= scrollbarImg->GetWidth() + 4; - 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); + 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 ); - 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); + 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 ); - 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); + 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 ); - gameIndex = new int[pagesize]; - game = new GuiButton * [pagesize]; - gameTxt = new GuiText * [pagesize]; - gameTxtOver = new GuiText * [pagesize]; - gameBg = new GuiImage * [pagesize]; - newImg = new GuiImage * [pagesize]; + 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 ); - 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); + gameIndex = new int[pagesize]; + game = new GuiButton * [pagesize]; + gameTxt = new GuiText * [pagesize]; + gameTxtOver = new GuiText * [pagesize]; + gameBg = new GuiImage * [pagesize]; + newImg = new GuiImage * [pagesize]; + + for ( int i = 0; i < pagesize; i++ ) + { + gameTxt[i] = new GuiText( get_title( gameList[i] ), 20, THEME.gametext ); + gameTxt[i]->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + gameTxt[i]->SetPosition( 24, 0 ); + gameTxt[i]->SetMaxWidth( maxTextWidth, 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; - } - UpdateListEntries(); + gameIndex[i] = i; + } + UpdateListEntries(); } /** @@ -166,109 +166,109 @@ GuiGameBrowser::GuiGameBrowser(int w, int h, const char *themePath, const u8 *im */ GuiGameBrowser::~GuiGameBrowser() { - delete arrowUpBtn; - delete arrowDownBtn; - delete scrollbarBoxBtn; - delete scrollbarImg; - delete arrowDownImg; - delete arrowDownOverImg; - delete arrowUpImg; - delete arrowUpOverImg; - delete scrollbarBoxImg; - delete scrollbarBoxOverImg; - delete scrollbar; - delete arrowDown; - delete arrowDownOver; - delete arrowUp; - delete arrowUpOver; - delete scrollbarBox; - delete scrollbarBoxOver; - delete bgGameImg; - delete bgGames; - delete bgGamesEntry; - delete newGames; + delete arrowUpBtn; + delete arrowDownBtn; + delete scrollbarBoxBtn; + delete scrollbarImg; + delete arrowDownImg; + delete arrowDownOverImg; + delete arrowUpImg; + delete arrowUpOverImg; + delete scrollbarBoxImg; + delete scrollbarBoxOverImg; + delete scrollbar; + delete arrowDown; + delete arrowDownOver; + delete arrowUp; + delete arrowUpOver; + delete scrollbarBox; + delete scrollbarBoxOver; + delete bgGameImg; + delete bgGames; + delete bgGamesEntry; + delete newGames; - delete trigA; - delete trigHeldA; - delete btnSoundClick; + delete trigA; + delete trigHeldA; + delete btnSoundClick; - for(int i=0; iResetState(); + for ( int i = 0; 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) - { - state = STATE_DEFAULT; - stateChan = -1; - } + LOCK( this ); + if ( state != STATE_DISABLED ) + { + state = STATE_DEFAULT; + stateChan = -1; + } - for(int i=0; iResetState(); - } + for ( int i = 0; i < pagesize; i++ ) + { + game[i]->ResetState(); + } } int GuiGameBrowser::GetOffset() { - return listOffset; + return listOffset; } int GuiGameBrowser::GetClickedOption() { - int found = -1; - for(int i=0; iGetState() == STATE_CLICKED) - { - game[i]->SetState(STATE_SELECTED); - found = gameIndex[i]; - break; - } - } - return found; + int found = -1; + for ( int i = 0; i < pagesize; i++ ) + { + if ( game[i]->GetState() == STATE_CLICKED ) + { + game[i]->SetState( STATE_SELECTED ); + found = gameIndex[i]; + break; + } + } + return found; } int GuiGameBrowser::GetSelectedOption() { - int found = -1; - for(int i=0; iGetState() == STATE_SELECTED) - { - game[i]->SetState(STATE_SELECTED); - found = gameIndex[i]; - break; - } - } - return found; + int found = -1; + for ( int i = 0; i < pagesize; i++ ) + { + if ( game[i]->GetState() == STATE_SELECTED ) + { + game[i]->SetState( STATE_SELECTED ); + found = gameIndex[i]; + break; + } + } + return found; } /**************************************************************************** @@ -277,17 +277,17 @@ 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; + 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) - return nextItem; - else - return FindMenuItem(nextItem, direction); + if ( strlen( get_title( gameList[nextItem] ) ) > 0 ) + return nextItem; + else + return FindMenuItem( nextItem, direction ); } /** @@ -295,342 +295,349 @@ int GuiGameBrowser::FindMenuItem(int currentItem, int direction) */ void GuiGameBrowser::Draw() { - LOCK(this); - if(!this->IsVisible() || !gameList.size()) - return; + LOCK( this ); + if ( !this->IsVisible() || !gameList.size() ) + return; - bgGameImg->Draw(); + bgGameImg->Draw(); - int next = listOffset; + int next = listOffset; - for(int i=0; i= 0) - { - game[i]->Draw(); - next = this->FindMenuItem(next, 1); - } - else - break; - } + for ( int i = 0; i < pagesize; i++ ) + { + if ( next >= 0 ) + { + game[i]->Draw(); + next = this->FindMenuItem( next, 1 ); + } + else + break; + } - if(scrollbaron == 1) { - scrollbarImg->Draw(); - arrowUpBtn->Draw(); - arrowDownBtn->Draw(); - scrollbarBoxBtn->Draw(); - } - this->UpdateEffects(); + if ( scrollbaron == 1 ) + { + scrollbarImg->Draw(); + arrowUpBtn->Draw(); + arrowDownBtn->Draw(); + scrollbarBoxBtn->Draw(); + } + this->UpdateEffects(); } void GuiGameBrowser::UpdateListEntries() { - int next = listOffset; - for(int i=0; i= 0) - { - if(game[i]->GetState() == STATE_DISABLED) - { - game[i]->SetVisible(true); - game[i]->SetState(STATE_DEFAULT); - } - gameTxt[i]->SetText(get_title(gameList[next])); - gameTxt[i]->SetPosition(24, 0); - gameTxtOver[i]->SetText(get_title(gameList[next])); - gameTxtOver[i]->SetPosition(24, 0); + int next = listOffset; + for ( int i = 0; i < pagesize; i++ ) + { + if ( next >= 0 ) + { + if ( game[i]->GetState() == STATE_DISABLED ) + { + game[i]->SetVisible( true ); + game[i]->SetState( STATE_DEFAULT ); + } + gameTxt[i]->SetText( get_title( gameList[next] ) ); + gameTxt[i]->SetPosition( 24, 0 ); + gameTxtOver[i]->SetText( get_title( gameList[next] ) ); + gameTxtOver[i]->SetPosition( 24, 0 ); - if (Settings.marknewtitles) { - bool isNew = NewTitles::Instance()->IsNew(gameList[next]->id); - if (isNew) { - gameTxt[i]->SetMaxWidth(maxTextWidth - (newGames->GetWidth() + 1), DOTTED); - gameTxtOver[i]->SetMaxWidth(maxTextWidth - (newGames->GetWidth() + 1), SCROLL_HORIZONTAL); - } else { - gameTxt[i]->SetMaxWidth(maxTextWidth, DOTTED); - gameTxtOver[i]->SetMaxWidth(maxTextWidth, SCROLL_HORIZONTAL); - } - newImg[i]->SetVisible(isNew); - } + if ( Settings.marknewtitles ) + { + 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 ); + } + else + { + gameTxt[i]->SetMaxWidth( maxTextWidth, DOTTED ); + gameTxtOver[i]->SetMaxWidth( maxTextWidth, SCROLL_HORIZONTAL ); + } + newImg[i]->SetVisible( isNew ); + } - gameIndex[i] = next; - next = this->FindMenuItem(next, 1); - } - else - { - game[i]->SetVisible(false); - game[i]->SetState(STATE_DISABLED); - } - } + gameIndex[i] = next; + next = this->FindMenuItem( next, 1 ); + } + else + { + game[i]->SetVisible( false ); + game[i]->SetState( STATE_DISABLED ); + } + } } -void GuiGameBrowser::Update(GuiTrigger * t) +void GuiGameBrowser::Update( GuiTrigger * t ) { - LOCK(this); - if(state == STATE_DISABLED || !t || !gameList.size()) - return; + LOCK( this ); + if ( state == STATE_DISABLED || !t || !gameList.size() ) + return; - int next, prev; - int old_listOffset = listOffset; - static int position2; - // scrolldelay affects how fast the list scrolls - // when the arrows are clicked - float scrolldelay = 3.5; + int next, prev; + int old_listOffset = listOffset; + static int position2; + // scrolldelay affects how fast the list scrolls + // when the arrows are clicked + float scrolldelay = 3.5; - if (scrollbaron == 1) { - // update the location of the scroll box based on the position in the option list - arrowUpBtn->Update(t); - arrowDownBtn->Update(t); - scrollbarBoxBtn->Update(t); - } + if ( scrollbaron == 1 ) + { + // update the location of the scroll box based on the position in the option list + arrowUpBtn->Update( t ); + arrowDownBtn->Update( t ); + scrollbarBoxBtn->Update( t ); + } - next = listOffset; + next = listOffset; u32 buttonshold = ButtonsHold(); - if(buttonshold != WPAD_BUTTON_UP && buttonshold != WPAD_BUTTON_DOWN) { + if ( buttonshold != WPAD_BUTTON_UP && buttonshold != WPAD_BUTTON_DOWN ) + { - for(int i=0; i= 0) - 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; } } } - // pad and joystick navigation - if(!focus || !gameList.size()) - return; // skip navigation + // pad and joystick 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(selectedItem == pagesize-1) - { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - } - else if(game[selectedItem+1]->IsVisible()) - { - game[selectedItem]->ResetState(); - game[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } -// scrollbarBoxBtn->Draw(); - usleep(10000 * scrolldelay); - } - if (!(ButtonsHold() & WPAD_BUTTON_A)) - arrowDownBtn->ResetState(); - } - else if(t->Up() || arrowUpBtn->GetState() == STATE_CLICKED || arrowUpBtn->GetState() == STATE_HELD) //up - { - prev = this->FindMenuItem(gameIndex[selectedItem], -1); + if ( next >= 0 ) + { + if ( selectedItem == pagesize - 1 ) + { + // move list down by 1 + listOffset = this->FindMenuItem( listOffset, 1 ); + } + else if ( game[selectedItem+1]->IsVisible() ) + { + game[selectedItem]->ResetState(); + game[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + selectedItem++; + } +// scrollbarBoxBtn->Draw(); + usleep( 10000 * scrolldelay ); + } + if ( !( ButtonsHold() & WPAD_BUTTON_A ) ) + arrowDownBtn->ResetState(); + } + else if ( t->Up() || arrowUpBtn->GetState() == STATE_CLICKED || arrowUpBtn->GetState() == STATE_HELD ) //up + { + prev = this->FindMenuItem( gameIndex[selectedItem], -1 ); - if(prev >= 0) - { - if(selectedItem == 0) - { - // move list up by 1 - listOffset = prev; - } - else - { - game[selectedItem]->ResetState(); - game[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } -// scrollbarBoxBtn->Draw(); - usleep(10000 * scrolldelay); - } - if (!(ButtonsHold() & WPAD_BUTTON_A)) - arrowUpBtn->ResetState(); - } - int position1 = t->wpad.ir.y; + if ( prev >= 0 ) + { + if ( selectedItem == 0 ) + { + // move list up by 1 + listOffset = prev; + } + else + { + game[selectedItem]->ResetState(); + game[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + selectedItem--; + } +// scrollbarBoxBtn->Draw(); + usleep( 10000 * scrolldelay ); + } + if ( !( ButtonsHold() & WPAD_BUTTON_A ) ) + arrowUpBtn->ResetState(); + } + int position1 = t->wpad.ir.y; - if (position2 == 0 && position1 > 0) - { - position2 = position1; - } + if ( position2 == 0 && position1 > 0 ) + { + position2 = position1; + } - if ((buttonshold & WPAD_BUTTON_B) && position1 > 0) - { - scrollbarBoxBtn->ScrollIsOn(1); - if (position2 > position1) - { + if ( ( buttonshold & WPAD_BUTTON_B ) && position1 > 0 ) + { + scrollbarBoxBtn->ScrollIsOn( 1 ); + if ( position2 > position1 ) + { - prev = this->FindMenuItem(gameIndex[selectedItem], -1); + prev = this->FindMenuItem( gameIndex[selectedItem], -1 ); - if(prev >= 0) - { - if(selectedItem == 0) - { - // move list up by 1 - listOffset = prev; - } - else - { - game[selectedItem]->ResetState(); - game[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } -// scrollbarBoxBtn->Draw(); - usleep(10000 * scrolldelay); - } - } - else if (position2 < position1) - { - next = this->FindMenuItem(gameIndex[selectedItem], 1); + if ( prev >= 0 ) + { + if ( selectedItem == 0 ) + { + // move list up by 1 + listOffset = prev; + } + else + { + game[selectedItem]->ResetState(); + game[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + selectedItem--; + } +// scrollbarBoxBtn->Draw(); + usleep( 10000 * scrolldelay ); + } + } + else if ( position2 < position1 ) + { + next = this->FindMenuItem( gameIndex[selectedItem], 1 ); - if(next >= 0) - { - if(selectedItem == pagesize-1) - { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - } - else if(game[selectedItem+1]->IsVisible()) - { - game[selectedItem]->ResetState(); - game[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } -// scrollbarBoxBtn->Draw(); - usleep(10000 * scrolldelay); - } - } + if ( next >= 0 ) + { + if ( selectedItem == pagesize - 1 ) + { + // move list down by 1 + listOffset = this->FindMenuItem( listOffset, 1 ); + } + else if ( game[selectedItem+1]->IsVisible() ) + { + game[selectedItem]->ResetState(); + game[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + selectedItem++; + } +// scrollbarBoxBtn->Draw(); + usleep( 10000 * scrolldelay ); + } + } - } - else if(!(buttonshold & WPAD_BUTTON_B)) - { - scrollbarBoxBtn->ScrollIsOn(0); - position2 = 0; - } + } + else if ( !( buttonshold & WPAD_BUTTON_B ) ) + { + scrollbarBoxBtn->ScrollIsOn( 0 ); + position2 = 0; + } - if(scrollbarBoxBtn->GetState() == STATE_HELD && scrollbarBoxBtn->GetStateChan() == t->chan && t->wpad.ir.valid && gameList.size() > pagesize) - { - // allow dragging of scrollbar box - scrollbarBoxBtn->SetPosition(width/2-18+7,0); - int position = t->wpad.ir.y - 32 - scrollbarBoxBtn->GetTop(); + if ( scrollbarBoxBtn->GetState() == STATE_HELD && scrollbarBoxBtn->GetStateChan() == t->chan && t->wpad.ir.valid && gameList.size() > pagesize ) + { + // allow dragging of scrollbar box + 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) - { - listOffset = 0; - selectedItem = 0; - } - else if(listOffset+pagesize >= gameList.size()) - { - listOffset = gameList.size() - pagesize; - selectedItem = pagesize-1; - } + if ( listOffset <= 0 ) + { + listOffset = 0; + selectedItem = 0; + } + 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(listOffset < gameList.size() && gameList.size() > pagesize) - { - listOffset =listOffset+ pagesize; - if(listOffset+pagesize >= gameList.size()) - listOffset = gameList.size()-pagesize; - } - } - else if(t->Left()) - { - if(listOffset > 0) - { - listOffset =listOffset- pagesize; - if(listOffset < 0) - listOffset = 0; - } - } + if ( t->Right() ) //skip pagesize # of games if right is pressed + { + if ( listOffset < gameList.size() && gameList.size() > pagesize ) + { + listOffset = listOffset + pagesize; + if ( listOffset + pagesize >= gameList.size() ) + listOffset = gameList.size() - pagesize; + } + } + else if ( t->Left() ) + { + if ( listOffset > 0 ) + { + listOffset = listOffset - pagesize; + if ( listOffset < 0 ) + listOffset = 0; + } + } - } - else - { - if(t->Down()) //if there isn't a scrollbar and down is pressed - { - next = this->FindMenuItem(gameIndex[selectedItem], 1); + } + else + { + if ( t->Down() ) //if there isn't a scrollbar and down is pressed + { + next = this->FindMenuItem( gameIndex[selectedItem], 1 ); - if(next >= 0) - { - if(selectedItem == pagesize-1) - { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - } - else if(game[selectedItem+1]->IsVisible()) - { - game[selectedItem]->ResetState(); - game[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } - } - } - else if(t->Up()) //up - { - prev = this->FindMenuItem(gameIndex[selectedItem], -1); + if ( next >= 0 ) + { + if ( selectedItem == pagesize - 1 ) + { + // move list down by 1 + listOffset = this->FindMenuItem( listOffset, 1 ); + } + else if ( game[selectedItem+1]->IsVisible() ) + { + game[selectedItem]->ResetState(); + game[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + selectedItem++; + } + } + } + else if ( t->Up() ) //up + { + prev = this->FindMenuItem( gameIndex[selectedItem], -1 ); - if(prev >= 0) - { - if(selectedItem == 0) - { - // move list up by 1 - listOffset = prev; - } - else - { - game[selectedItem]->ResetState(); - game[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } - } - } - } + if ( prev >= 0 ) + { + if ( selectedItem == 0 ) + { + // move list up by 1 + listOffset = prev; + } + else + { + game[selectedItem]->ResetState(); + game[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + selectedItem--; + } + } + } + } - if(old_listOffset != listOffset) - UpdateListEntries(); + if ( old_listOffset != listOffset ) + UpdateListEntries(); - if(updateCB) - updateCB(this); + if ( updateCB ) + updateCB( this ); } void GuiGameBrowser::Reload() { - LOCK(this); - scrollbaron = (gameList.size() > pagesize) ? 1 : 0; - selectedItem = 0; - listOffset = 0; - focus = 1; - UpdateListEntries(); + LOCK( this ); + scrollbaron = ( gameList.size() > pagesize ) ? 1 : 0; + selectedItem = 0; + listOffset = 0; + focus = 1; + UpdateListEntries(); - for(int i=0; iResetState(); + 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 33ab1069..ee7b9f6e 100644 --- a/source/libwiigui/gui_gamebrowser.h +++ b/source/libwiigui/gui_gamebrowser.h @@ -1,4 +1,4 @@ -#ifndef _GUIGAMEBROWSER_H_ +#ifndef _GUIGAMEBROWSER_H_ #define _GUIGAMEBROWSER_H_ #include "gui.h" @@ -6,60 +6,60 @@ class GuiGameBrowser : public GuiElement { - public: - 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 GetClickedOption(); - int GetSelectedOption(); - void ResetState(); - void SetFocus(int f); - void Draw(); - void Update(GuiTrigger * t); - int GetOffset(); - void Reload(); - //GuiText * optionVal[PAGESIZE]; - protected: - void UpdateListEntries(); - int selectedItem; - int listOffset; - int scrollbaron; - int pagesize; - int maxTextWidth; + public: + 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 GetClickedOption(); + int GetSelectedOption(); + void ResetState(); + void SetFocus( int f ); + void Draw(); + void Update( GuiTrigger * t ); + int GetOffset(); + void Reload(); + //GuiText * optionVal[PAGESIZE]; + protected: + void UpdateListEntries(); + int selectedItem; + int listOffset; + int scrollbaron; + int pagesize; + int maxTextWidth; - int * gameIndex; - GuiButton ** game; - GuiText ** gameTxt; - GuiText ** gameTxtOver; - GuiImage ** gameBg; - GuiImage ** newImg; + int * gameIndex; + GuiButton ** game; + GuiText ** gameTxt; + GuiText ** gameTxtOver; + GuiImage ** gameBg; + GuiImage ** newImg; - GuiButton * arrowUpBtn; - GuiButton * arrowDownBtn; - GuiButton * scrollbarBoxBtn; + GuiButton * arrowUpBtn; + GuiButton * arrowDownBtn; + GuiButton * scrollbarBoxBtn; - GuiImage * bgGameImg; - GuiImage * scrollbarImg; - GuiImage * arrowDownImg; - GuiImage * arrowDownOverImg; - GuiImage * arrowUpImg; - GuiImage * arrowUpOverImg; - GuiImage * scrollbarBoxImg; - GuiImage * scrollbarBoxOverImg; + GuiImage * bgGameImg; + GuiImage * scrollbarImg; + GuiImage * arrowDownImg; + GuiImage * arrowDownOverImg; + GuiImage * arrowUpImg; + GuiImage * arrowUpOverImg; + GuiImage * scrollbarBoxImg; + GuiImage * scrollbarBoxOverImg; - GuiImageData * bgGames; - GuiImageData * bgGamesEntry; - GuiImageData * newGames; - GuiImageData * scrollbar; - GuiImageData * arrowDown; - GuiImageData * arrowDownOver; - GuiImageData * arrowUp; - GuiImageData * arrowUpOver; - GuiImageData * scrollbarBox; - GuiImageData * scrollbarBoxOver; + GuiImageData * bgGames; + GuiImageData * bgGamesEntry; + GuiImageData * newGames; + GuiImageData * scrollbar; + GuiImageData * arrowDown; + GuiImageData * arrowDownOver; + GuiImageData * arrowUp; + GuiImageData * arrowUpOver; + GuiImageData * scrollbarBox; + GuiImageData * scrollbarBoxOver; - GuiSound * btnSoundClick; - GuiTrigger * trigA; - GuiTrigger * trigHeldA; + GuiSound * btnSoundClick; + GuiTrigger * trigA; + GuiTrigger * trigHeldA; }; #endif diff --git a/source/libwiigui/gui_gamecarousel.cpp b/source/libwiigui/gui_gamecarousel.cpp index 4439ae75..8bd014e3 100644 --- a/source/libwiigui/gui_gamecarousel.cpp +++ b/source/libwiigui/gui_gamecarousel.cpp @@ -21,131 +21,131 @@ #include #include -#define SCALE 0.8f -#define DEG_OFFSET 7 -#define RADIUS 780 -#define IN_SPEED 175 -#define SHIFT_SPEED 75 -#define SPEED_STEP 4 -#define SPEED_LIMIT 250 +#define SCALE 0.8f +#define DEG_OFFSET 7 +#define RADIUS 780 +#define IN_SPEED 175 +#define SHIFT_SPEED 75 +#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; - return 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; - listOffset = 0; - selectable = true; - selectedItem = -1; - focus = 1; // allow focus - clickedItem = -1; - - speed = 0; - char imgPath[100]; + width = w; + height = h; + pagesize = ( gameList.size() < 11 ) ? gameList.size() : 11; + listOffset = 0; + selectable = true; + selectedItem = -1; + focus = 1; // allow focus + clickedItem = -1; - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - trigL = new GuiTrigger; - trigL->SetButtonOnlyTrigger(-1, WPAD_BUTTON_LEFT | WPAD_CLASSIC_BUTTON_LEFT, PAD_BUTTON_LEFT); - trigR = new GuiTrigger; - trigR->SetButtonOnlyTrigger(-1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT); - trigPlus = new GuiTrigger; - trigPlus->SetButtonOnlyTrigger(-1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0); - trigMinus = new GuiTrigger; - trigMinus->SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0); + speed = 0; + char imgPath[100]; - btnSoundClick = new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - btnSoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigL = new GuiTrigger; + trigL->SetButtonOnlyTrigger( -1, WPAD_BUTTON_LEFT | WPAD_CLASSIC_BUTTON_LEFT, PAD_BUTTON_LEFT ); + trigR = new GuiTrigger; + trigR->SetButtonOnlyTrigger( -1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT ); + trigPlus = new GuiTrigger; + trigPlus->SetButtonOnlyTrigger( -1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0 ); + trigMinus = new GuiTrigger; + trigMinus->SetButtonOnlyTrigger( -1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0 ); - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", CFG.theme_path); - imgLeft = new GuiImageData(imgPath, startgame_arrow_left_png); - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", CFG.theme_path); - imgRight = new GuiImageData(imgPath, startgame_arrow_right_png); + 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); + snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_left.png", CFG.theme_path ); + imgLeft = new GuiImageData( imgPath, startgame_arrow_left_png ); + snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_right.png", CFG.theme_path ); + imgRight = new GuiImageData( imgPath, startgame_arrow_right_png ); - btnLeftImg = new GuiImage(imgLeft); - if (Settings.wsprompt == yes) - btnLeftImg->SetWidescreen(CFG.widescreen); - btnLeft = new GuiButton(imgLeft->GetWidth(), imgLeft->GetHeight()); - btnLeft->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - btnLeft->SetPosition(20, btnHeight); - btnLeft->SetParent(this); - btnLeft->SetImage(btnLeftImg); - btnLeft->SetSoundOver(btnSoundOver); - btnLeft->SetTrigger(trigA); - btnLeft->SetTrigger(trigL); - btnLeft->SetTrigger(trigMinus); - btnLeft->SetEffectGrow(); + int btnHeight = ( int ) lround( sqrt( RADIUS * RADIUS - 90000 ) - RADIUS - 50 ); - btnRightImg = new GuiImage(imgRight); - if (Settings.wsprompt == yes) - btnRightImg->SetWidescreen(CFG.widescreen); - btnRight = new GuiButton(imgRight->GetWidth(), imgRight->GetHeight()); - btnRight->SetParent(this); - btnRight->SetAlignment(ALIGN_RIGHT, ALIGN_MIDDLE); - btnRight->SetPosition(-20, btnHeight); - btnRight->SetImage(btnRightImg); - btnRight->SetSoundOver(btnSoundOver); - btnRight->SetTrigger(trigA); - btnRight->SetTrigger(trigR); - btnRight->SetTrigger(trigPlus); - btnRight->SetEffectGrow(); - - gamename = new GuiText(" ", 18, THEME.info); - gamename->SetParent(this); - gamename->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - gamename->SetPosition(0, 330); - gamename->SetMaxWidth(280, DOTTED); + btnLeftImg = new GuiImage( imgLeft ); + if ( Settings.wsprompt == yes ) + btnLeftImg->SetWidescreen( CFG.widescreen ); + btnLeft = new GuiButton( imgLeft->GetWidth(), imgLeft->GetHeight() ); + btnLeft->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + btnLeft->SetPosition( 20, btnHeight ); + btnLeft->SetParent( this ); + btnLeft->SetImage( btnLeftImg ); + btnLeft->SetSoundOver( btnSoundOver ); + btnLeft->SetTrigger( trigA ); + btnLeft->SetTrigger( trigL ); + btnLeft->SetTrigger( trigMinus ); + btnLeft->SetEffectGrow(); - gameIndex = new int[pagesize]; - game = new GuiButton * [pagesize]; - coverImg = new GuiImageAsync * [pagesize]; + btnRightImg = new GuiImage( imgRight ); + if ( Settings.wsprompt == yes ) + btnRightImg->SetWidescreen( CFG.widescreen ); + btnRight = new GuiButton( imgRight->GetWidth(), imgRight->GetHeight() ); + btnRight->SetParent( this ); + btnRight->SetAlignment( ALIGN_RIGHT, ALIGN_MIDDLE ); + btnRight->SetPosition( -20, btnHeight ); + btnRight->SetImage( btnRightImg ); + btnRight->SetSoundOver( btnSoundOver ); + btnRight->SetTrigger( trigA ); + btnRight->SetTrigger( trigR ); + btnRight->SetTrigger( trigPlus ); + btnRight->SetEffectGrow(); - for(int i=0; i < pagesize; i++) - { - //------------------------ - // Index - //------------------------ - gameIndex[i] = GetGameIndex(i, listOffset, gameList.size()); + gamename = new GuiText( " ", 18, THEME.info ); + gamename->SetParent( this ); + gamename->SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + gamename->SetPosition( 0, 330 ); + gamename->SetMaxWidth( 280, DOTTED ); - //------------------------ - // Image - //------------------------ - coverImg[i] = new(std::nothrow) GuiImageAsync(GameCarouselLoadCoverImage, gameList[gameIndex[i]], sizeof(struct discHdr), &noCover); - if(coverImg[i]) - coverImg[i]->SetWidescreen(CFG.widescreen); + gameIndex = new int[pagesize]; + game = new GuiButton * [pagesize]; + coverImg = new GuiImageAsync * [pagesize]; - //------------------------ - // GameButton - //------------------------ + for ( int i = 0; i < pagesize; i++ ) + { + //------------------------ + // Index + //------------------------ + gameIndex[i] = GetGameIndex( i, listOffset, gameList.size() ); - 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); - } + //------------------------ + // Image + //------------------------ + coverImg[i] = new( std::nothrow ) GuiImageAsync( GameCarouselLoadCoverImage, gameList[gameIndex[i]], sizeof( struct discHdr ), &noCover ); + if ( coverImg[i] ) + coverImg[i]->SetWidescreen( CFG.widescreen ); + + //------------------------ + // GameButton + //------------------------ + + game[i] = new GuiButton( 122, 244 ); + game[i]->SetParent( this ); + game[i]->SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); + game[i]->SetPosition( 0, 740 ); + game[i]->SetImage( coverImg[i] ); + game[i]->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 ); + } } @@ -154,98 +154,101 @@ noCover(nocover_png) */ GuiGameCarousel::~GuiGameCarousel() { - delete imgRight; - delete imgLeft; - delete btnLeftImg; - delete btnRightImg; - delete btnRight; - delete btnLeft; + delete imgRight; + delete imgLeft; + delete btnLeftImg; + delete btnRightImg; + delete btnRight; + delete btnLeft; - delete trigA; - delete trigL; - delete trigR; - delete trigPlus; - delete trigMinus; - delete btnSoundClick; - delete btnSoundOver; + delete trigA; + delete trigL; + delete trigR; + delete trigPlus; + delete trigMinus; + delete btnSoundClick; + delete btnSoundOver; delete gamename; - for(int i=0; iResetState(); + for ( int i = 0; 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) { - state = STATE_DEFAULT; - stateChan = -1; - } + LOCK( this ); + if ( state != STATE_DISABLED ) + { + state = STATE_DEFAULT; + stateChan = -1; + } - for(int i=0; iResetState(); - } + for ( int i = 0; i < pagesize; i++ ) + { + game[i]->ResetState(); + } } int GuiGameCarousel::GetOffset() { - LOCK(this); - return listOffset; + LOCK( this ); + return listOffset; } int GuiGameCarousel::GetClickedOption() { - LOCK(this); - int found = -1; - if (clickedItem>=0) - { - game[clickedItem]->SetState(STATE_SELECTED); - found = gameIndex[clickedItem]; - clickedItem=-1; - } - return found; + LOCK( this ); + int found = -1; + if ( clickedItem >= 0 ) + { + game[clickedItem]->SetState( STATE_SELECTED ); + found = gameIndex[clickedItem]; + clickedItem = -1; + } + return found; } int GuiGameCarousel::GetSelectedOption() { - LOCK(this); - int found = -1; - for(int i=0; iGetState() == STATE_SELECTED) - { - game[i]->SetState(STATE_SELECTED); - found = gameIndex[i]; - break; - } - } - return found; + LOCK( this ); + int found = -1; + for ( int i = 0; i < pagesize; i++ ) + { + if ( game[i]->GetState() == STATE_SELECTED ) + { + game[i]->SetState( STATE_SELECTED ); + found = gameIndex[i]; + break; + } + } + return found; } /** @@ -253,204 +256,204 @@ int GuiGameCarousel::GetSelectedOption() */ void GuiGameCarousel::Draw() { - LOCK(this); - if(!this->IsVisible() || !gameList.size()) - return; + LOCK( this ); + if ( !this->IsVisible() || !gameList.size() ) + return; - for(int i=0; iDraw(); - + for ( int i = 0; i < pagesize; i++ ) + game[i]->Draw(); - gamename->Draw(); - 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; iDrawTooltip(); + gamename->Draw(); - this->UpdateEffects(); + 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(); + + this->UpdateEffects(); } -void GuiGameCarousel::Update(GuiTrigger * t) +void GuiGameCarousel::Update( GuiTrigger * t ) { - LOCK(this); - if(state == STATE_DISABLED || !t || !gameList.size()) - return; + LOCK( this ); + if ( state == STATE_DISABLED || !t || !gameList.size() ) + return; - btnRight->Update(t); - btnLeft->Update(t); - - if(game[0]->GetEffect() & EFFECT_GOROUND || game[pagesize-1]->GetEffect() & EFFECT_GOROUND) - { - return; // skip when rotate - } - - // find selected + clicked - int selectedItem_old = selectedItem; - selectedItem = -1; - clickedItem = -1; - for(int i=pagesize-1; i>=0; i--) - { - game[i]->Update(t); - if(game[i]->GetState() == STATE_SELECTED) - { - selectedItem = i; - } - if(game[i]->GetState() == STATE_CLICKED) - { - clickedItem = i; - } + btnRight->Update( t ); + btnLeft->Update( t ); - } + if ( game[0]->GetEffect() & EFFECT_GOROUND || game[pagesize-1]->GetEffect() & EFFECT_GOROUND ) + { + return; // skip when rotate + } - /// OnOver-Effect + GameText + Tooltop - if(selectedItem_old != selectedItem) - { - if(selectedItem>=0) - { - game[selectedItem]->SetEffect(EFFECT_SCALE, 1, 130); - char *gameTitle = get_title(gameList[gameIndex[selectedItem]]); - gamename->SetText(gameTitle); - } - else - gamename->SetText((char*)NULL); - if(selectedItem_old>=0) - game[selectedItem_old]->SetEffect(EFFECT_SCALE, -1, 100); - } - // navigation - if(focus && gameList.size()>6) - { + // find selected + clicked + int selectedItem_old = selectedItem; + selectedItem = -1; + clickedItem = -1; + for ( int i = pagesize - 1; i >= 0; i-- ) + { + game[i]->Update( t ); + if ( game[i]->GetState() == STATE_SELECTED ) + { + selectedItem = i; + } + if ( game[i]->GetState() == STATE_CLICKED ) + { + clickedItem = i; + } - int newspeed = 0; - // Left/Right Navigation - if (btnLeft->GetState() == STATE_CLICKED) - { - WPAD_ScanPads(); - u16 buttons = 0; - for(int i=0; i<4; i++) - buttons |= WPAD_ButtonsHeld(i); - if(!((buttons & WPAD_BUTTON_A) || (buttons & WPAD_BUTTON_MINUS) || t->Left())) - { - btnLeft->ResetState(); - return; - } + } - if (Settings.xflip==sysmenu || Settings.xflip==yes || Settings.xflip==disk3d) - newspeed = SHIFT_SPEED; - else - newspeed = -SHIFT_SPEED; - } - else if(btnRight->GetState() == STATE_CLICKED) - { - WPAD_ScanPads(); - u16 buttons = 0; - for(int i=0; i<4; i++) - buttons |= WPAD_ButtonsHeld(i); - if(!((buttons & WPAD_BUTTON_A) || (buttons & WPAD_BUTTON_PLUS) || t->Right())) - { - btnRight->ResetState(); - return; - } - if (Settings.xflip==sysmenu ||Settings.xflip==yes || Settings.xflip==disk3d) - newspeed = -SHIFT_SPEED; - else - newspeed = SHIFT_SPEED; - } - if(newspeed) - { - if(speed==0) - speed = newspeed; - else if(speed>0) - { - if((speed+=SPEED_STEP) > SPEED_LIMIT) - speed = SPEED_LIMIT; - } - else - { - if((speed-=SPEED_STEP) < -SPEED_LIMIT) - speed = -SPEED_LIMIT; - } - } - else - speed = 0; + /// OnOver-Effect + GameText + Tooltop + if ( selectedItem_old != selectedItem ) + { + if ( selectedItem >= 0 ) + { + game[selectedItem]->SetEffect( EFFECT_SCALE, 1, 130 ); + char *gameTitle = get_title( gameList[gameIndex[selectedItem]] ); + gamename->SetText( gameTitle ); + } + else + gamename->SetText( ( char* )NULL ); + if ( selectedItem_old >= 0 ) + game[selectedItem_old]->SetEffect( EFFECT_SCALE, -1, 100 ); + } + // navigation + if ( focus && gameList.size() > 6 ) + { + + int newspeed = 0; + // Left/Right Navigation + if ( btnLeft->GetState() == STATE_CLICKED ) + { + WPAD_ScanPads(); + u16 buttons = 0; + for ( int i = 0; i < 4; i++ ) + buttons |= WPAD_ButtonsHeld( i ); + if ( !( ( buttons & WPAD_BUTTON_A ) || ( buttons & WPAD_BUTTON_MINUS ) || t->Left() ) ) + { + btnLeft->ResetState(); + return; + } + + if ( Settings.xflip == sysmenu || Settings.xflip == yes || Settings.xflip == disk3d ) + newspeed = SHIFT_SPEED; + else + newspeed = -SHIFT_SPEED; + } + else if ( btnRight->GetState() == STATE_CLICKED ) + { + WPAD_ScanPads(); + u16 buttons = 0; + for ( int i = 0; i < 4; i++ ) + buttons |= WPAD_ButtonsHeld( i ); + if ( !( ( buttons & WPAD_BUTTON_A ) || ( buttons & WPAD_BUTTON_PLUS ) || t->Right() ) ) + { + btnRight->ResetState(); + return; + } + if ( Settings.xflip == sysmenu || Settings.xflip == yes || Settings.xflip == disk3d ) + newspeed = -SHIFT_SPEED; + else + newspeed = SHIFT_SPEED; + } + if ( newspeed ) + { + if ( speed == 0 ) + speed = newspeed; + else if ( speed > 0 ) + { + if ( ( speed += SPEED_STEP ) > SPEED_LIMIT ) + speed = SPEED_LIMIT; + } + else + { + if ( ( speed -= SPEED_STEP ) < -SPEED_LIMIT ) + speed = -SPEED_LIMIT; + } + } + else + speed = 0; - if(speed > 0) // rotate right - { - GuiButton *tmpButton; - 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]; - - // Move all Page-Entries one step right - for (int i=pagesize-1; i>=1; i--) - { - coverImg[i] = coverImg[i-1]; - game[i] = game[i-1]; - gameIndex[i] = gameIndex[i-1]; - } - // set saved Button & gameIndex to right - gameIndex[0] = listOffset; - coverImg[0] = new GuiImageAsync(GameCarouselLoadCoverImage, gameList[gameIndex[0]], sizeof(struct discHdr), &noCover); - coverImg[0] ->SetWidescreen(CFG.widescreen); + if ( speed > 0 ) // rotate right + { + GuiButton *tmpButton; + 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]; - game[0] = tmpButton; - game[0] ->SetImage(coverImg[0]); + // Move all Page-Entries one step right + for ( int i = pagesize - 1; i >= 1; i-- ) + { + coverImg[i] = coverImg[i-1]; + game[i] = game[i-1]; + gameIndex[i] = gameIndex[i-1]; + } + // set saved Button & gameIndex to right + gameIndex[0] = listOffset; + coverImg[0] = new GuiImageAsync( GameCarouselLoadCoverImage, gameList[gameIndex[0]], sizeof( struct discHdr ), &noCover ); + coverImg[0] ->SetWidescreen( CFG.widescreen ); - - for(int i=0; iStopEffect(); - game[i]->ResetState(); - game[i]->SetEffect(EFFECT_GOROUND, speed, DEG_OFFSET, RADIUS, 270-(pagesize-2*i+1)*DEG_OFFSET/2, 1, 0, RADIUS); - game[i]->UpdateEffects(); // rotate one step for liquid scrolling - } - } - else if(speed < 0) // rotate left - { - GuiButton *tmpButton; - listOffset = OFFSETLIMIT(listOffset + 1, 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]; - - // Move all Page-Entries one step left - for (int i=0; i<(pagesize-1); i++) - { - coverImg[i] = coverImg[i+1]; - game[i] = game[i+1]; - gameIndex[i] = gameIndex[i+1]; - } - // set saved Button & gameIndex to right - int ii = pagesize-1; - gameIndex[ii] = OFFSETLIMIT(listOffset + ii, gameList.size()); - coverImg[ii] = new GuiImageAsync(GameCarouselLoadCoverImage, gameList[gameIndex[ii]], sizeof(struct discHdr), &noCover); - coverImg[ii] ->SetWidescreen(CFG.widescreen); + game[0] = tmpButton; + game[0] ->SetImage( coverImg[0] ); - game[ii] = tmpButton; - game[ii] ->SetImage(coverImg[ii]); - - for(int i=0; iStopEffect(); - game[i]->ResetState(); - game[i]->SetEffect(EFFECT_GOROUND, speed, DEG_OFFSET, RADIUS, 270-(pagesize-2*i-3)*DEG_OFFSET/2, 1, 0, RADIUS); - game[i]->UpdateEffects(); // rotate one step for liquid scrolling - } - } + 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]->UpdateEffects(); // rotate one step for liquid scrolling + } + } + else if ( speed < 0 ) // rotate left + { + GuiButton *tmpButton; + 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]; - } - if(updateCB) - updateCB(this); + // Move all Page-Entries one step left + for ( int i = 0; i < ( pagesize - 1 ); i++ ) + { + coverImg[i] = coverImg[i+1]; + game[i] = game[i+1]; + gameIndex[i] = gameIndex[i+1]; + } + // set saved Button & gameIndex to right + int ii = pagesize - 1; + gameIndex[ii] = OFFSETLIMIT( listOffset + ii, gameList.size() ); + coverImg[ii] = new GuiImageAsync( GameCarouselLoadCoverImage, gameList[gameIndex[ii]], sizeof( struct discHdr ), &noCover ); + coverImg[ii] ->SetWidescreen( CFG.widescreen ); + + game[ii] = tmpButton; + game[ii] ->SetImage( coverImg[ii] ); + + + for ( int i = 0; 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]->UpdateEffects(); // rotate one step for liquid scrolling + } + } + + } + if ( updateCB ) + updateCB( this ); } diff --git a/source/libwiigui/gui_gamecarousel.h b/source/libwiigui/gui_gamecarousel.h index 05be2935..816a3759 100644 --- a/source/libwiigui/gui_gamecarousel.h +++ b/source/libwiigui/gui_gamecarousel.h @@ -6,49 +6,49 @@ class GuiImageAsync; class GuiGameCarousel : public GuiElement { - public: - 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 GetClickedOption(); - int GetSelectedOption(); - void ResetState(); - void SetFocus(int f); - void Draw(); - void Update(GuiTrigger * t); - int GetOffset(); - void Reload(); - //GuiText * optionVal[PAGESIZE]; - protected: - GuiImageData noCover; - int selectedItem; - int listOffset; - int scrollbaron; - int pagesize; - int speed; - int clickedItem; + public: + 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 GetClickedOption(); + int GetSelectedOption(); + void ResetState(); + void SetFocus( int f ); + void Draw(); + void Update( GuiTrigger * t ); + int GetOffset(); + void Reload(); + //GuiText * optionVal[PAGESIZE]; + protected: + GuiImageData noCover; + int selectedItem; + int listOffset; + int scrollbaron; + int pagesize; + int speed; + int clickedItem; - int * gameIndex; - GuiButton ** game; - GuiImageAsync ** coverImg; + int * gameIndex; + GuiButton ** game; + GuiImageAsync ** coverImg; - GuiText * gamename; + GuiText * gamename; - GuiButton * btnRight; - GuiButton * btnLeft; + GuiButton * btnRight; + GuiButton * btnLeft; - GuiImage * btnLeftImg; - GuiImage * btnRightImg; + GuiImage * btnLeftImg; + GuiImage * btnRightImg; - GuiImageData * imgLeft; - GuiImageData * imgRight; + GuiImageData * imgLeft; + GuiImageData * imgRight; - GuiSound * btnSoundOver; - GuiSound * btnSoundClick; - GuiTrigger * trigA; - GuiTrigger * trigL; - GuiTrigger * trigR; - GuiTrigger * trigPlus; - GuiTrigger * trigMinus; + GuiSound * btnSoundOver; + GuiSound * btnSoundClick; + GuiTrigger * trigA; + GuiTrigger * trigL; + GuiTrigger * trigR; + GuiTrigger * trigPlus; + GuiTrigger * trigMinus; }; #endif diff --git a/source/libwiigui/gui_gamegrid.cpp b/source/libwiigui/gui_gamegrid.cpp index 05ef1d78..f2ed7b03 100644 --- a/source/libwiigui/gui_gamegrid.cpp +++ b/source/libwiigui/gui_gamegrid.cpp @@ -23,14 +23,14 @@ #include #include -//#define SCALE 0.8f -//#define DEG_OFFSET 7 -#define RADIUS 780 -//#define IN_SPEED 175 -//#define SHIFT_SPEED 100 -//#define SPEED_STEP 4 -//#define SAFETY 320 -#define goSteps 10 +//#define SCALE 0.8f +//#define DEG_OFFSET 7 +#define RADIUS 780 +//#define IN_SPEED 175 +//#define SHIFT_SPEED 100 +//#define SPEED_STEP 4 +//#define SAFETY 320 +#define goSteps 10 #include "../main.h" @@ -38,331 +38,337 @@ 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}, - - {-5,-49,5,-27,5,0,-5,0}, - {-5,0,5,0,5,27,-5,49}, - - {-4,-22,4,-14,4,0,-4,0}, - {-4,0,4,0,4,14,-4,22}, - - {0,-9,0,-5,0,0,0,0}, - {0,0,0,0,0,5,0,9}, - - {0,0,0,0,0,0,0,0}, - {0,0,0,0,0,0,0,0}, - - {0,-5,0,-9,0,0,0,0}, - {0,0,0,0,0,9,0,5}, - - {-4,-14,4,-22,4,0,-4,0}, - {-4,0,4,0,4,22,-4,14}, - - {-5,-27,5,-49,5,0,-5,0}, - {-5,0,5,0,5,49,-5,27}, - - {-5,-27,5,-49,5,0,-5,0}, - {-5,0,5,0,5,49,-5,27} - }; -static int Pos2[18][2][2] = { - // {{16:9 x,y},{ 4:3 x,y}} - {{-91,50}, {-166,50}}, - {{-91,193},{-166,193}}, - - {{3,50}, {-54,50}}, - {{3,193}, {-54,193}}, - - {{97,50}, {58,50}}, - {{97,193}, {58,193}}, - - {{187,50}, {166,50}}, - {{187,193}, {166,193}}, - - {{272,50}, {272,50}}, - {{272,193}, {272,193}}, - - {{358,50}, {378,50}}, - {{358,193}, {378,193}}, - - {{449,50}, {487,50}}, - {{449,193}, {487,193}}, - - {{545,50}, {599,50}}, - {{545,193}, {599,193}}, - - {{641,50}, {700,50}}, - {{641,193}, {700,193}} - }; -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,-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}, - - {-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,-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}, - - {-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}, - - {-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}, - - {-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} - }; -static int Pos3[45][2][2] = { - // {{16:9 x,y},{ 4:3 x,y}} - {{-42,49}, {-91,49}}, - {{-42,153},{-91,153}}, - {{-42,261},{-91,261}}, - - {{13,58}, {-29,58}}, - {{13,153}, {-29,153}}, - {{13,250}, {-29,250}}, - - {{68,67}, {33,67}}, - {{68,153}, {33,153}}, - {{68,239}, {33,239}}, - - {{120,74}, {92,74}}, - {{120,153}, {92,153}}, - {{120,232}, {92,232}}, - - {{170,78}, {149,78}}, - {{170,153}, {149,153}}, - {{170,228}, {149,228}}, - - {{214,80}, {200,80}}, - {{214,153}, {200,153}}, - {{214,226}, {200,226}}, - - {{258,81}, {251,81}}, - {{258,153}, {251,153}}, - {{258,224}, {251,224}}, - - {{302,81}, {302,81}}, - {{302,153}, {302,153}}, - {{302,223}, {302,223}}, - - {{346,81}, {353,81}}, - {{346,153}, {353,153}}, - {{346,223}, {353,223}}, - - {{390,80}, {404,80}}, - {{390,153}, {404,153}}, - {{390,225}, {404,225}}, - - {{434,77}, {457,77}}, - {{434,153}, {457,153}}, - {{434,227}, {457,227}}, - - {{484,73}, {512,73}}, - {{484,153}, {512,153}}, - {{484,231}, {512,231}}, - - {{537,67}, {572,67}}, - {{537,153}, {572,153}}, - {{537,239}, {572,239}}, - - {{591,58}, {633,58}}, - {{591,153}, {633,153}}, - {{591,250}, {633,250}}, - - {{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 int Skew1[7][8] = { - 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; -} + { -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}, + + { -4, -22, 4, -14, 4, 0, -4, 0}, + { -4, 0, 4, 0, 4, 14, -4, 22}, + + {0, -9, 0, -5, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 5, 0, 9}, + + {0, 0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0}, + + {0, -5, 0, -9, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 9, 0, 5}, + + { -4, -14, 4, -22, 4, 0, -4, 0}, + { -4, 0, 4, 0, 4, 22, -4, 14}, + + { -5, -27, 5, -49, 5, 0, -5, 0}, + { -5, 0, 5, 0, 5, 49, -5, 27}, + + { -5, -27, 5, -49, 5, 0, -5, 0}, + { -5, 0, 5, 0, 5, 49, -5, 27} +}; +static int Pos2[18][2][2] = +{ + // {{16:9 x,y},{ 4:3 x,y}} + {{ -91, 50}, { -166, 50}}, + {{ -91, 193}, { -166, 193}}, + + {{3, 50}, { -54, 50}}, + {{3, 193}, { -54, 193}}, + + {{97, 50}, {58, 50}}, + {{97, 193}, {58, 193}}, + + {{187, 50}, {166, 50}}, + {{187, 193}, {166, 193}}, + + {{272, 50}, {272, 50}}, + {{272, 193}, {272, 193}}, + + {{358, 50}, {378, 50}}, + {{358, 193}, {378, 193}}, + + {{449, 50}, {487, 50}}, + {{449, 193}, {487, 193}}, + + {{545, 50}, {599, 50}}, + {{545, 193}, {599, 193}}, + + {{641, 50}, {700, 50}}, + {{641, 193}, {700, 193}} +}; +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, -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}, + + { -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, -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}, + + { -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}, + + { -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}, + + { -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} +}; +static int Pos3[45][2][2] = +{ + // {{16:9 x,y},{ 4:3 x,y}} + {{ -42, 49}, { -91, 49}}, + {{ -42, 153}, { -91, 153}}, + {{ -42, 261}, { -91, 261}}, + + {{13, 58}, { -29, 58}}, + {{13, 153}, { -29, 153}}, + {{13, 250}, { -29, 250}}, + + {{68, 67}, {33, 67}}, + {{68, 153}, {33, 153}}, + {{68, 239}, {33, 239}}, + + {{120, 74}, {92, 74}}, + {{120, 153}, {92, 153}}, + {{120, 232}, {92, 232}}, + + {{170, 78}, {149, 78}}, + {{170, 153}, {149, 153}}, + {{170, 228}, {149, 228}}, + + {{214, 80}, {200, 80}}, + {{214, 153}, {200, 153}}, + {{214, 226}, {200, 226}}, + + {{258, 81}, {251, 81}}, + {{258, 153}, {251, 153}}, + {{258, 224}, {251, 224}}, + + {{302, 81}, {302, 81}}, + {{302, 153}, {302, 153}}, + {{302, 223}, {302, 223}}, + + {{346, 81}, {353, 81}}, + {{346, 153}, {353, 153}}, + {{346, 223}, {353, 223}}, + + {{390, 80}, {404, 80}}, + {{390, 153}, {404, 153}}, + {{390, 225}, {404, 225}}, + + {{434, 77}, {457, 77}}, + {{434, 153}, {457, 153}}, + {{434, 227}, {457, 227}}, + + {{484, 73}, {512, 73}}, + {{484, 153}, {512, 153}}, + {{484, 231}, {512, 231}}, + + {{537, 67}, {572, 67}}, + {{537, 153}, {572, 153}}, + {{537, 239}, {572, 239}}, + + {{591, 58}, {633, 58}}, + {{591, 153}, {633, 153}}, + {{591, 250}, {633, 250}}, + + {{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 ) +{ + 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 pagesize = ROWS2PAGESIZE(rows); + int skip = ( rows - ( gameCnt % rows ) ) % rows; // count of skiped Entries at end if List + int pagesize = ROWS2PAGESIZE( rows ); - if( gameCnt < (pagesize-2*rows) ) - { - int listStart = (pagesize-gameCnt)>>1; // align list on the center - listStart = listStart - (listStart%rows); // align listStart to the top row - if(pageEntry < listStart || pageEntry >= listStart + gameCnt) - return -1; - return pageEntry - listStart; - } - else - { - listOffset = listOffset - (listOffset%rows); // align listOffset to the top row - listOffset = listOffset - 2*rows; // align listOffset to the left full visible column - if(listOffset < 0) - listOffset += gameCnt + skip; // set the correct Offset - pageEntry = (listOffset + pageEntry) % (gameCnt + skip); // get offset of pageEntry - if(pageEntry >= gameCnt) - return -1; - return pageEntry; - } + if ( gameCnt < ( pagesize - 2*rows ) ) + { + int listStart = ( pagesize - gameCnt ) >> 1; // align list on the center + listStart = listStart - ( listStart % rows ); // align listStart to the top row + if ( pageEntry < listStart || pageEntry >= listStart + gameCnt ) + return -1; + return pageEntry - listStart; + } + else + { + listOffset = listOffset - ( listOffset % rows ); // align listOffset to the top row + listOffset = listOffset - 2 * rows; // align listOffset to the left full visible column + if ( listOffset < 0 ) + listOffset += gameCnt + skip; // set the correct Offset + pageEntry = ( listOffset + pageEntry ) % ( gameCnt + skip ); // get offset of pageEntry + if ( pageEntry >= gameCnt ) + return -1; + return pageEntry; + } } -static GuiImageData *GameGridLoadCoverImage(void * Arg) +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 + width = w; + height = h; +// gameCnt = count; will be set later in Reload +// gameList = l; will be set later in Reload +// listOffset = 0; will be set later in Reload +// goLeft = 0; will be set later in Reload +// goRight = 0; will be set later in Reload - selectable = true; - focus = 1; // allow focus -// 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; + selectable = true; + focus = 1; // allow focus +// selectedItem = -1; will be set later in Reload +// clickedItem = -1; will be set later in Reload + /* will be set later in Reload + rows = Settings.gridRows; + if ((count<45)&&(rows==3))rows=2; + if ((count<18)&&(rows==2))rows=1; - pagesize = ROWS2PAGESIZE(rows); -*/ - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - trigL = new GuiTrigger; - trigL->SetButtonOnlyTrigger(-1, WPAD_BUTTON_LEFT | WPAD_CLASSIC_BUTTON_LEFT, PAD_BUTTON_LEFT); - trigR = new GuiTrigger; - trigR->SetButtonOnlyTrigger(-1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT); - trig1 = new GuiTrigger; - trig1->SetButtonOnlyTrigger(-1, WPAD_BUTTON_UP | WPAD_CLASSIC_BUTTON_X, PAD_BUTTON_X); - trig2 = new GuiTrigger; - trig2->SetButtonOnlyTrigger(-1, WPAD_BUTTON_DOWN | WPAD_CLASSIC_BUTTON_Y, PAD_BUTTON_Y); - trigPlus = new GuiTrigger; - trigPlus->SetButtonOnlyTrigger(-1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0); - trigMinus = new GuiTrigger; - trigMinus->SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0); + pagesize = ROWS2PAGESIZE(rows); + */ + trigA = new GuiTrigger; + trigA->SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigL = new GuiTrigger; + trigL->SetButtonOnlyTrigger( -1, WPAD_BUTTON_LEFT | WPAD_CLASSIC_BUTTON_LEFT, PAD_BUTTON_LEFT ); + trigR = new GuiTrigger; + trigR->SetButtonOnlyTrigger( -1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT ); + trig1 = new GuiTrigger; + trig1->SetButtonOnlyTrigger( -1, WPAD_BUTTON_UP | WPAD_CLASSIC_BUTTON_X, PAD_BUTTON_X ); + trig2 = new GuiTrigger; + trig2->SetButtonOnlyTrigger( -1, WPAD_BUTTON_DOWN | WPAD_CLASSIC_BUTTON_Y, PAD_BUTTON_Y ); + trigPlus = new GuiTrigger; + trigPlus->SetButtonOnlyTrigger( -1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0 ); + trigMinus = new GuiTrigger; + trigMinus->SetButtonOnlyTrigger( -1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0 ); - btnSoundClick = new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - btnSoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); + btnSoundClick = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + btnSoundOver = new GuiSound( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); - int btnHeight = (int) lround(sqrt(RADIUS*RADIUS - 90000)-RADIUS-50); + int btnHeight = ( int ) lround( sqrt( RADIUS * RADIUS - 90000 ) - RADIUS - 50 ); - // Button Left - btnLeft = new GuiButton(0,0); - btnLeft->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - btnLeft->SetPosition(20, btnHeight); - btnLeft->SetParent(this); - btnLeft->SetSoundOver(btnSoundOver); - btnLeft->SetTrigger(trigL); - btnLeft->SetTrigger(trigMinus); + // Button Left + btnLeft = new GuiButton( 0, 0 ); + btnLeft->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + btnLeft->SetPosition( 20, btnHeight ); + btnLeft->SetParent( this ); + btnLeft->SetSoundOver( btnSoundOver ); + btnLeft->SetTrigger( trigL ); + btnLeft->SetTrigger( trigMinus ); - // Button Right - btnRight = new GuiButton(0,0); - btnRight->SetParent(this); - btnRight->SetAlignment(ALIGN_RIGHT, ALIGN_MIDDLE); - btnRight->SetPosition(-20, btnHeight); - btnRight->SetSoundOver(btnSoundOver); - btnRight->SetTrigger(trigR); - btnRight->SetTrigger(trigPlus); + // Button Right + btnRight = new GuiButton( 0, 0 ); + btnRight->SetParent( this ); + btnRight->SetAlignment( ALIGN_RIGHT, ALIGN_MIDDLE ); + btnRight->SetPosition( -20, btnHeight ); + btnRight->SetSoundOver( btnSoundOver ); + btnRight->SetTrigger( trigR ); + btnRight->SetTrigger( trigPlus ); - // Button RowUp - btnRowUp = new GuiButton(0,0); - btnRowUp->SetParent(this); - btnRowUp->SetAlignment(ALIGN_LEFT, ALIGN_TOP); - btnRowUp->SetPosition(0,0); - btnRowUp->SetTrigger(trig2); + // Button RowUp + btnRowUp = new GuiButton( 0, 0 ); + btnRowUp->SetParent( this ); + btnRowUp->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); + btnRowUp->SetPosition( 0, 0 ); + btnRowUp->SetTrigger( trig2 ); - // Button RowDown - btnRowDown = new GuiButton(0,0); - btnRowDown->SetParent(this); - btnRowDown->SetAlignment(ALIGN_LEFT, ALIGN_TOP); - btnRowDown->SetPosition(0,0); - btnRowDown->SetTrigger(trig1); + // Button RowDown + btnRowDown = new GuiButton( 0, 0 ); + btnRowDown->SetParent( this ); + btnRowDown->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); + btnRowDown->SetPosition( 0, 0 ); + btnRowDown->SetTrigger( trig1 ); - // Page-Stuff - gameIndex = NULL; - titleTT = NULL; -// cover = NULL; - coverImg = NULL; - game = NULL; + // Page-Stuff + gameIndex = NULL; + titleTT = NULL; +// cover = NULL; + coverImg = NULL; + game = NULL; - Reload(Settings.gridRows, 0); + Reload( Settings.gridRows, 0 ); } @@ -372,101 +378,102 @@ noCover(nocoverFlat_png) GuiGameGrid::~GuiGameGrid() { - delete btnRight; - delete btnLeft; - delete btnRowUp; - delete btnRowDown; + delete btnRight; + delete btnLeft; + delete btnRowUp; + delete btnRowDown; - delete trigA; - delete trigL; - delete trigR; - delete trigPlus; - delete trigMinus; - delete trig1; - delete trig2; - delete btnSoundClick; - delete btnSoundOver; + delete trigA; + delete trigL; + delete trigR; + delete trigPlus; + delete trigMinus; + delete trig1; + delete trig2; + delete btnSoundClick; + delete btnSoundOver; - for(int i=pagesize-1; i>=0; i--) - { - delete game[i]; - delete coverImg[i]; - delete titleTT[i]; - } + for ( int i = pagesize - 1; i >= 0; i-- ) + { + delete game[i]; + delete coverImg[i]; + delete titleTT[i]; + } - delete [] gameIndex; - delete [] game; - delete [] coverImg; - delete [] titleTT; + delete [] gameIndex; + delete [] game; + delete [] coverImg; + delete [] titleTT; } -void GuiGameGrid::SetFocus(int f) +void GuiGameGrid::SetFocus( int f ) { - LOCK(this); - if(!gameList.size()) - return; + LOCK( this ); + if ( !gameList.size() ) + return; - focus = f; + focus = f; - for(int i=0; iResetState(); + 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) - { - state = STATE_DEFAULT; - stateChan = -1; - } + LOCK( this ); + if ( state != STATE_DISABLED ) + { + state = STATE_DEFAULT; + stateChan = -1; + } - for(int i=0; iResetState(); - } + for ( int i = 0; i < pagesize; i++ ) + { + game[i]->ResetState(); + } } int GuiGameGrid::GetOffset() { - LOCK(this); - return listOffset; + LOCK( this ); + return listOffset; } int GuiGameGrid::GetClickedOption() { - LOCK(this); - int found = -1; - if (clickedItem>=0) - { - game[clickedItem]->SetState(STATE_SELECTED); - found = gameIndex[clickedItem]; - clickedItem=-1; - } - return found; + LOCK( this ); + int found = -1; + if ( clickedItem >= 0 ) + { + game[clickedItem]->SetState( STATE_SELECTED ); + found = gameIndex[clickedItem]; + clickedItem = -1; + } + return found; } int GuiGameGrid::GetSelectedOption() { - LOCK(this); - int found = -1; - for(int i=0; iGetState() == STATE_SELECTED) - { - game[i]->SetState(STATE_SELECTED); - found = gameIndex[i]; - break; - } - } - return found; + LOCK( this ); + int found = -1; + for ( int i = 0; i < pagesize; i++ ) + { + if ( game[i]->GetState() == STATE_SELECTED ) + { + game[i]->SetState( STATE_SELECTED ); + found = gameIndex[i]; + break; + } + } + return found; } /** @@ -474,74 +481,74 @@ int GuiGameGrid::GetSelectedOption() */ void GuiGameGrid::Draw() { - LOCK(this); - if(!this->IsVisible() || !gameList.size()) - return; + LOCK( this ); + if ( !this->IsVisible() || !gameList.size() ) + return; - if(goLeft>0) - { - goLeft--; - int wsi = CFG.widescreen ? 0:1; - float f2 = ((float)goLeft)/goSteps; - float f1 = 1.0-f2; - int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); - int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); + if ( goLeft > 0 ) + { + goLeft--; + int wsi = CFG.widescreen ? 0 : 1; + float f2 = ( ( float )goLeft ) / goSteps; + float f1 = 1.0 - f2; + int ( *Pos )[2][2] = VALUE4ROWS( rows, Pos1, Pos2, Pos3 ); + int ( *Skew )[8] = VALUE4ROWS( rows, Skew1, Skew2, Skew3 ); - for(int i=0; iSetPosition( Pos[i][wsi][0]*f1 + Pos[i+rows][wsi][0]*f2+THEME.gamegrid_x, - Pos[i][wsi][1]*f1 + Pos[i+rows][wsi][1]*f2+THEME.gamegrid_y); - - game[i]->SetSkew( Skew[i][0]*f1 + Skew[i+rows][0]*f2, - Skew[i][1]*f1 + Skew[i+rows][1]*f2, - Skew[i][2]*f1 + Skew[i+rows][2]*f2, - Skew[i][3]*f1 + Skew[i+rows][3]*f2, - Skew[i][4]*f1 + Skew[i+rows][4]*f2, - Skew[i][5]*f1 + Skew[i+rows][5]*f2, - Skew[i][6]*f1 + Skew[i+rows][6]*f2, - Skew[i][7]*f1 + Skew[i+rows][7]*f2); - } - } - else if(goRight>0) - { - goRight--; - int wsi = CFG.widescreen ? 0:1; - float f2 = ((float)goRight)/goSteps; - float f1 = 1.0-f2; - int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); - int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); - for(int i=rows; iSetPosition( Pos[i][wsi][0]*f1 + Pos[i-rows][wsi][0]*f2+THEME.gamegrid_x, - Pos[i][wsi][1]*f1 + Pos[i-rows][wsi][1]*f2+THEME.gamegrid_y); - - game[i]->SetSkew( Skew[i][0]*f1 + Skew[i-rows][0]*f2, - Skew[i][1]*f1 + Skew[i-rows][1]*f2, - Skew[i][2]*f1 + Skew[i-rows][2]*f2, - Skew[i][3]*f1 + Skew[i-rows][3]*f2, - Skew[i][4]*f1 + Skew[i-rows][4]*f2, - Skew[i][5]*f1 + Skew[i-rows][5]*f2, - Skew[i][6]*f1 + Skew[i-rows][6]*f2, - Skew[i][7]*f1 + Skew[i-rows][7]*f2); - } - } + 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 ); - for(int i=0; iDraw(); - if(gameList.size() > pagesize-2*rows) - { - btnRight->Draw(); - btnLeft->Draw(); - } + game[i]->SetSkew( Skew[i][0]*f1 + Skew[i+rows][0]*f2, + Skew[i][1]*f1 + Skew[i+rows][1]*f2, + Skew[i][2]*f1 + Skew[i+rows][2]*f2, + Skew[i][3]*f1 + Skew[i+rows][3]*f2, + Skew[i][4]*f1 + Skew[i+rows][4]*f2, + Skew[i][5]*f1 + Skew[i+rows][5]*f2, + Skew[i][6]*f1 + Skew[i+rows][6]*f2, + Skew[i][7]*f1 + Skew[i+rows][7]*f2 ); + } + } + else if ( goRight > 0 ) + { + goRight--; + int wsi = CFG.widescreen ? 0 : 1; + float f2 = ( ( float )goRight ) / goSteps; + float f1 = 1.0 - f2; + int ( *Pos )[2][2] = VALUE4ROWS( rows, Pos1, Pos2, Pos3 ); + int ( *Skew )[8] = VALUE4ROWS( rows, Skew1, Skew2, Skew3 ); + for ( int i = rows; 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 ); - btnRowUp->Draw(); - btnRowDown->Draw(); + game[i]->SetSkew( Skew[i][0]*f1 + Skew[i-rows][0]*f2, + Skew[i][1]*f1 + Skew[i-rows][1]*f2, + Skew[i][2]*f1 + Skew[i-rows][2]*f2, + Skew[i][3]*f1 + Skew[i-rows][3]*f2, + Skew[i][4]*f1 + Skew[i-rows][4]*f2, + Skew[i][5]*f1 + Skew[i-rows][5]*f2, + Skew[i][6]*f1 + Skew[i-rows][6]*f2, + Skew[i][7]*f1 + Skew[i-rows][7]*f2 ); + } + } - if (focus && Settings.tooltips == TooltipsOn) - for(int i=0; iDrawTooltip(); + for ( int i = 0; i < pagesize; i++ ) + game[i]->Draw(); + if ( gameList.size() > pagesize - 2*rows ) + { + btnRight->Draw(); + btnLeft->Draw(); + } - this->UpdateEffects(); + btnRowUp->Draw(); + btnRowDown->Draw(); + + if ( focus && Settings.tooltips == TooltipsOn ) + for ( int i = 0; i < pagesize; i++ ) + game[i]->DrawTooltip(); + + this->UpdateEffects(); } @@ -549,416 +556,416 @@ void GuiGameGrid::Draw() /** * Change the number of rows */ -void GuiGameGrid::ChangeRows(int n) +void GuiGameGrid::ChangeRows( int n ) { - LOCK(this); - if(n != rows) - Reload(n, -1); + LOCK( this ); + 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; + LOCK( this ); + if ( state == STATE_DISABLED || !t || !gameList.size() ) + return; - if(!(game[0]->GetEffect() || game[0]->GetEffectOnOver())) - { - for(int i=0; iSetEffectGrow(); - } - - btnRight->Update(t); - btnLeft->Update(t); - btnRowUp->Update(t); - btnRowDown->Update(t); - - selectedItem = -1; - clickedItem = -1; - for(int i=0; iUpdate(t); - if(game[i]->GetState() == STATE_SELECTED) - { - selectedItem = i; - } - if(game[i]->GetState() == STATE_CLICKED) - { - clickedItem = i; - } + if ( !( game[0]->GetEffect() || game[0]->GetEffectOnOver() ) ) + { + for ( int i = 0; i < pagesize; i++ ) + game[i]->SetEffectGrow(); + } - } - // navigation - if(focus && gameList.size() >= (pagesize-2*rows) && goLeft==0 && goRight==0) - { - // Left/Right Navigation + btnRight->Update( t ); + btnLeft->Update( t ); + btnRowUp->Update( t ); + btnRowDown->Update( t ); - if (btnLeft->GetState() == STATE_CLICKED) - { - WPAD_ScanPads(); - u16 buttons = 0; - for(int i=0; i<4; i++) - buttons |= WPAD_ButtonsHeld(i); - if(!((buttons & WPAD_BUTTON_A) || (buttons & WPAD_BUTTON_MINUS) || t->Left())) - { - btnLeft->ResetState(); - return; - } + selectedItem = -1; + clickedItem = -1; + for ( int i = 0; i < pagesize; i++ ) + { + game[i]->Update( t ); + if ( game[i]->GetState() == STATE_SELECTED ) + { + selectedItem = i; + } + if ( game[i]->GetState() == STATE_CLICKED ) + { + clickedItem = i; + } - if (Settings.xflip==sysmenu || Settings.xflip==yes || Settings.xflip==disk3d) - goRight = goSteps; - else - goLeft = goSteps; - } - else if(btnRight->GetState() == STATE_CLICKED) - { - WPAD_ScanPads(); - u16 buttons = 0; - for(int i=0; i<4; i++) - buttons |= WPAD_ButtonsHeld(i); - if(!((buttons & WPAD_BUTTON_A) || (buttons & WPAD_BUTTON_PLUS) || t->Right())) - { - btnRight->ResetState(); - return; - } - if (Settings.xflip==sysmenu ||Settings.xflip==yes || Settings.xflip==disk3d) - goLeft = goSteps; - else - goRight = goSteps; - } + } + // navigation + if ( focus && gameList.size() >= ( pagesize - 2*rows ) && goLeft == 0 && goRight == 0 ) + { + // Left/Right Navigation - if (goLeft == goSteps) - { - GuiButton *tmpButton[rows]; - GuiTooltip *tmpTooltip[rows]; - 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; iSetImage(NULL); - tmpTooltip[i] = titleTT[i]; - tmpButton[i] = game[i]; - } - // Move all Page-Entries one step left - for (int i=0; i<(pagesize-rows); i++) - { - titleTT[i] = titleTT[i+rows]; - coverImg[i] = coverImg[i+rows]; - game[i] = game[i+rows]; - gameIndex[i] = gameIndex[i+rows]; - } - // set saved Tooltip, Button & gameIndex to right - int wsi = CFG.widescreen ? 0:1; - int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); - int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); + if ( btnLeft->GetState() == STATE_CLICKED ) + { + WPAD_ScanPads(); + u16 buttons = 0; + for ( int i = 0; i < 4; i++ ) + buttons |= WPAD_ButtonsHeld( i ); + if ( !( ( buttons & WPAD_BUTTON_A ) || ( buttons & WPAD_BUTTON_MINUS ) || t->Left() ) ) + { + btnLeft->ResetState(); + return; + } - for (int i=0; iSetWidescreen(CFG.widescreen); - coverImg[ii] ->SetScale(VALUE4ROWS(rows, 1.0, 0.6, 0.26)); - coverImg[ii] ->SetPosition(0,VALUE4ROWS(rows, 0, -50, -80)); - } - titleTT[ii] ->SetText(get_title(gameList[gameIndex[ii]])); - } - else - { - titleTT[ii] ->SetText(NULL); - } + if ( Settings.xflip == sysmenu || Settings.xflip == yes || Settings.xflip == disk3d ) + goRight = goSteps; + else + goLeft = goSteps; + } + else if ( btnRight->GetState() == STATE_CLICKED ) + { + WPAD_ScanPads(); + u16 buttons = 0; + for ( int i = 0; i < 4; i++ ) + buttons |= WPAD_ButtonsHeld( i ); + if ( !( ( buttons & WPAD_BUTTON_A ) || ( buttons & WPAD_BUTTON_PLUS ) || t->Right() ) ) + { + btnRight->ResetState(); + return; + } + if ( Settings.xflip == sysmenu || Settings.xflip == yes || Settings.xflip == disk3d ) + goLeft = goSteps; + else + goRight = goSteps; + } - game[ii] = tmpButton[i]; - game[ii] ->SetImage(coverImg[ii]); - game[ii] ->SetPosition(Pos[ii][wsi][0], Pos[ii][wsi][1]); - game[ii] ->SetSkew(&Skew[ii][0]); - game[ii] ->RemoveToolTip(); - if(gameIndex[ii] != -1) - { - game[ii] ->SetClickable(true); - game[ii] ->SetVisible(true); - } - else - { - game[ii] ->SetVisible(false); - game[ii] ->SetClickable(false); - game[ii] ->RemoveSoundOver(); - } - } - // Set Tooltip-Position - int ttoffset_x = CFG.widescreen ? VALUE4ROWS(rows, 70, 35, 0) : VALUE4ROWS(rows, 150, 55, 25); - int ttoffset_y = -VALUE4ROWS(rows, 224, 133, 68)/4; - for (int i=0; iSetToolTip(titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE); - break; - case 1: - game[i]->SetToolTip(titleTT[i], 0, ttoffset_y, ALIGN_CENTRE, ALIGN_MIDDLE); - break; - case 2: - game[i]->SetToolTip(titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE); - break; - default: - break; - } - } - } - else if (goRight == goSteps) - { - GuiButton *tmpButton[rows]; - GuiTooltip *tmpTooltip[rows]; - listOffset = OFFSETLIMIT(listOffset - rows, rows, gameList.size()); // set the new listOffset - // Save right Button & Tooltip and destroy right Image-Data - for (int i=0; iSetImage(NULL); - tmpTooltip[i] = titleTT[ii]; - tmpButton[i] = game[ii]; - } - // Move all Page-Entries one step right - for (int i=pagesize-1; i>=rows; i--) - { - titleTT[i] = titleTT[i-rows]; - coverImg[i] = coverImg[i-rows]; - game[i] = game[i-rows]; - gameIndex[i] = gameIndex[i-rows]; - } - // set saved Image, Button & gameIndex to left - int wsi = CFG.widescreen ? 0:1; - int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); - int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); + if ( goLeft == goSteps ) + { + GuiButton *tmpButton[rows]; + GuiTooltip *tmpTooltip[rows]; + 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++ ) + { + 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++ ) + { + titleTT[i] = titleTT[i+rows]; + coverImg[i] = coverImg[i+rows]; + game[i] = game[i+rows]; + gameIndex[i] = gameIndex[i+rows]; + } + // set saved Tooltip, Button & gameIndex to right + int wsi = CFG.widescreen ? 0 : 1; + int ( *Pos )[2][2] = VALUE4ROWS( rows, Pos1, Pos2, Pos3 ); + int ( *Skew )[8] = VALUE4ROWS( rows, Skew1, Skew2, Skew3 ); - for (int i=0; iSetWidescreen(CFG.widescreen); - coverImg[i] ->SetScale(VALUE4ROWS(rows, 1.0, 0.6, 0.26)); - coverImg[i] ->SetPosition(0,VALUE4ROWS(rows, 0, -50, -80)); - } - titleTT[i] ->SetText(get_title(gameList[gameIndex[i]])); - } - else - { - titleTT[i] ->SetText(NULL); - } - game[i] = tmpButton[i]; - game[i] ->SetImage(coverImg[i]); - game[i] ->SetPosition(Pos[i][wsi][0], Pos[i][wsi][1]); - game[i] ->SetSkew(&Skew[i][0]); - game[i] ->RemoveToolTip(); - if(gameIndex[i] != -1) - { - game[i] ->SetClickable(true); - game[i] ->SetVisible(true); - } - else - { - game[i] ->SetVisible(false); - game[i] ->SetClickable(false); - game[i] ->RemoveSoundOver(); - } - } - // Set Tooltip-Position - int ttoffset_x = CFG.widescreen ? VALUE4ROWS(rows, 70, 35, 0) : VALUE4ROWS(rows, 150, 55, 25); - int ttoffset_y = -VALUE4ROWS(rows, 224, 133, 68)/4; - for (int i=0; i< pagesize; i++) - { - switch((i*3)/pagesize) - { - case 0: - game[i]->SetToolTip(titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE); - break; - case 1: - game[i]->SetToolTip(titleTT[i], 0, ttoffset_y, ALIGN_CENTRE, ALIGN_MIDDLE); - break; - case 2: - game[i]->SetToolTip(titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE); - break; - default: - break; - } - } - } - } + 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 ) + { + coverImg[ii] = new GuiImageAsync( GameGridLoadCoverImage, gameList[gameIndex[ii]], sizeof( struct discHdr ), &noCover ); + if ( coverImg[ii] ) + { + coverImg[ii] ->SetWidescreen( CFG.widescreen ); + coverImg[ii] ->SetScale( VALUE4ROWS( rows, 1.0, 0.6, 0.26 ) ); + coverImg[ii] ->SetPosition( 0, VALUE4ROWS( rows, 0, -50, -80 ) ); + } + titleTT[ii] ->SetText( get_title( gameList[gameIndex[ii]] ) ); + } + else + { + titleTT[ii] ->SetText( NULL ); + } - if ((btnRowUp->GetState() == STATE_CLICKED)) - { - if ((rows==1)&&(gameList.size()>=18))this->ChangeRows(2); - else if ((rows==2)&&(gameList.size()>=45))this->ChangeRows(3); - btnRowUp->ResetState(); - return; - } + game[ii] = tmpButton[i]; + game[ii] ->SetImage( coverImg[ii] ); + game[ii] ->SetPosition( Pos[ii][wsi][0], Pos[ii][wsi][1] ); + game[ii] ->SetSkew( &Skew[ii][0] ); + game[ii] ->RemoveToolTip(); + if ( gameIndex[ii] != -1 ) + { + game[ii] ->SetClickable( true ); + game[ii] ->SetVisible( true ); + } + else + { + game[ii] ->SetVisible( false ); + game[ii] ->SetClickable( false ); + game[ii] ->RemoveSoundOver(); + } + } + // Set Tooltip-Position + int ttoffset_x = CFG.widescreen ? VALUE4ROWS( rows, 70, 35, 0 ) : VALUE4ROWS( rows, 150, 55, 25 ); + int ttoffset_y = -VALUE4ROWS( rows, 224, 133, 68 ) / 4; + for ( int i = 0; i < pagesize; i++ ) + { + switch ( ( i*3 ) / pagesize ) + { + case 0: + game[i]->SetToolTip( titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE ); + break; + case 1: + game[i]->SetToolTip( titleTT[i], 0, ttoffset_y, ALIGN_CENTRE, ALIGN_MIDDLE ); + break; + case 2: + game[i]->SetToolTip( titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE ); + break; + default: + break; + } + } + } + else if ( goRight == goSteps ) + { + GuiButton *tmpButton[rows]; + GuiTooltip *tmpTooltip[rows]; + 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++ ) + { + int ii = i + pagesize - rows; + 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-- ) + { + titleTT[i] = titleTT[i-rows]; + coverImg[i] = coverImg[i-rows]; + game[i] = game[i-rows]; + gameIndex[i] = gameIndex[i-rows]; + } + // set saved Image, Button & gameIndex to left + int wsi = CFG.widescreen ? 0 : 1; + int ( *Pos )[2][2] = VALUE4ROWS( rows, Pos1, Pos2, Pos3 ); + int ( *Skew )[8] = VALUE4ROWS( rows, Skew1, Skew2, Skew3 ); - if ((btnRowDown->GetState() == STATE_CLICKED)) - { - if (rows==3)this->ChangeRows(2); - else if (rows==2)this->ChangeRows(1); - btnRowDown->ResetState(); - return; - } + 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 ) + { + coverImg[i] = new GuiImageAsync( GameGridLoadCoverImage, gameList[gameIndex[i]], sizeof( struct discHdr ), &noCover ); + if ( coverImg[i] ) + { + coverImg[i] ->SetWidescreen( CFG.widescreen ); + coverImg[i] ->SetScale( VALUE4ROWS( rows, 1.0, 0.6, 0.26 ) ); + coverImg[i] ->SetPosition( 0, VALUE4ROWS( rows, 0, -50, -80 ) ); + } + titleTT[i] ->SetText( get_title( gameList[gameIndex[i]] ) ); + } + else + { + titleTT[i] ->SetText( NULL ); + } + game[i] = tmpButton[i]; + game[i] ->SetImage( coverImg[i] ); + game[i] ->SetPosition( Pos[i][wsi][0], Pos[i][wsi][1] ); + game[i] ->SetSkew( &Skew[i][0] ); + game[i] ->RemoveToolTip(); + if ( gameIndex[i] != -1 ) + { + game[i] ->SetClickable( true ); + game[i] ->SetVisible( true ); + } + else + { + game[i] ->SetVisible( false ); + game[i] ->SetClickable( false ); + game[i] ->RemoveSoundOver(); + } + } + // Set Tooltip-Position + int ttoffset_x = CFG.widescreen ? VALUE4ROWS( rows, 70, 35, 0 ) : VALUE4ROWS( rows, 150, 55, 25 ); + int ttoffset_y = -VALUE4ROWS( rows, 224, 133, 68 ) / 4; + for ( int i = 0; i < pagesize; i++ ) + { + switch ( ( i*3 ) / pagesize ) + { + case 0: + game[i]->SetToolTip( titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE ); + break; + case 1: + game[i]->SetToolTip( titleTT[i], 0, ttoffset_y, ALIGN_CENTRE, ALIGN_MIDDLE ); + break; + case 2: + game[i]->SetToolTip( titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE ); + break; + default: + break; + } + } + } + } - if(updateCB) - updateCB(this); + if ( ( btnRowUp->GetState() == STATE_CLICKED ) ) + { + 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 ( rows == 3 )this->ChangeRows( 2 ); + else if ( rows == 2 )this->ChangeRows( 1 ); + btnRowDown->ResetState(); + return; + } + + 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]; + LOCK( this ); - if(coverImg) - for(int i=pagesize-1; i>=0; i--) - delete coverImg[i]; + // CleanUp + if ( game ) + for ( int i = pagesize - 1; i >= 0; i-- ) + delete game[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 ( coverImg ) + for ( int i = pagesize - 1; i >= 0; i-- ) + delete coverImg[i]; - delete [] gameIndex; - delete [] game; - delete [] coverImg; -// delete [] cover; - delete [] titleTT; - - goLeft = 0; - goRight = 0; +// if(cover) +// for(int i=pagesize-1; i>=0; i--) +// delete cover[i]; - 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 ( titleTT ) + for ( int i = pagesize - 1; i >= 0; i-- ) + delete titleTT[i]; - if(ListOffset>=0) // if ListOffset < 0 then no change - listOffset = ListOffset; - listOffset = OFFSETLIMIT(listOffset, rows, gameList.size()); + delete [] gameIndex; + delete [] game; + delete [] coverImg; +// delete [] cover; + delete [] titleTT; - selectedItem = -1; - clickedItem = -1; + goLeft = 0; + goRight = 0; - pagesize = ROWS2PAGESIZE(rows); + rows = Rows > 3 ? 3 : ( Rows < 1 ? 1 : Rows ); + if ( ( gameList.size() < 45 ) && ( rows == 3 ) )rows = 2; + if ( ( gameList.size() < 18 ) && ( rows == 2 ) )rows = 1; - // Page-Stuff - gameIndex = new int[pagesize]; - titleTT = new GuiTooltip *[pagesize]; -// cover = new GuiImageData *[pagesize]; - coverImg = new GuiImageAsync *[pagesize]; - game = new GuiButton *[pagesize]; + if ( ListOffset >= 0 ) // if ListOffset < 0 then no change + listOffset = ListOffset; + listOffset = OFFSETLIMIT( listOffset, rows, gameList.size() ); + + selectedItem = -1; + clickedItem = -1; + + 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]; - int wsi = CFG.widescreen ? 0:1; - int (*Pos)[2][2] = VALUE4ROWS(rows, Pos1, Pos2, Pos3); - int (*Skew)[8] = VALUE4ROWS(rows, Skew1, Skew2, Skew3); + int wsi = CFG.widescreen ? 0 : 1; + int ( *Pos )[2][2] = VALUE4ROWS( rows, Pos1, Pos2, Pos3 ); + int ( *Skew )[8] = VALUE4ROWS( rows, Skew1, Skew2, Skew3 ); - int ttoffset_x = CFG.widescreen ? VALUE4ROWS(rows, 70, 35, 0) : VALUE4ROWS(rows, 150, 55, 25); - int ttoffset_y = -VALUE4ROWS(rows, 224, 133, 68)/4; - - for(int i=0; i < pagesize; i++) - { - //------------------------ - // Index - //------------------------ - gameIndex[i] = GetGameIndex(i, rows, listOffset, gameList.size()); + int ttoffset_x = CFG.widescreen ? VALUE4ROWS( rows, 70, 35, 0 ) : VALUE4ROWS( rows, 150, 55, 25 ); + int ttoffset_y = -VALUE4ROWS( rows, 224, 133, 68 ) / 4; - //------------------------ - // Tooltip - //------------------------ - if( gameIndex[i] != -1 ) - titleTT[i] = new GuiTooltip(get_title(gameList[gameIndex[i]]), THEME.tooltipAlpha); - else - titleTT[i] = new GuiTooltip(NULL, THEME.tooltipAlpha); + for ( int i = 0; i < pagesize; i++ ) + { + //------------------------ + // Index + //------------------------ + gameIndex[i] = GetGameIndex( i, rows, listOffset, gameList.size() ); - //------------------------ - // ImageData - //------------------------ -// if( gameIndex[i] != -1 ) -// cover[i] = LoadCoverImage(&gameList[gameIndex[i]], false /*bool Prefere3D*/); -// else -// cover[i] = new GuiImageData(NULL); + //------------------------ + // Tooltip + //------------------------ + if ( gameIndex[i] != -1 ) + titleTT[i] = new GuiTooltip( get_title( gameList[gameIndex[i]] ), THEME.tooltipAlpha ); + else + titleTT[i] = new GuiTooltip( NULL, THEME.tooltipAlpha ); - //------------------------ - // Image - //------------------------ - coverImg[i] = NULL; - if( gameIndex[i] != -1 ) - { - coverImg[i] = new GuiImageAsync(GameGridLoadCoverImage, gameList[gameIndex[i]], sizeof(struct discHdr), &noCover); - if(coverImg[i]) - { - coverImg[i]->SetWidescreen(CFG.widescreen); - // if ( rows == 2 ) coverImg[i]->SetScale(.6); //these are the numbers for 2 rows - // else if ( rows == 3 ) coverImg[i]->SetScale(.26); //these are the numbers for 3 rows - coverImg[i]->SetScale(VALUE4ROWS(rows, 1.0, 0.6, 0.26)); - coverImg[i]->SetPosition(0,VALUE4ROWS(rows, 0, -50, -80)); - } - } - - //------------------------ - // GameButton - //------------------------ - game[i] = new GuiButton(VALUE4ROWS(rows, 160, 75, 35), VALUE4ROWS(rows, 224, 133, 68)); - game[i]->SetParent(this); - game[i]->SetImage(coverImg[i]); - game[i]->SetAlignment(ALIGN_TOP,ALIGN_LEFT); - game[i]->SetPosition(Pos[i][wsi][0]+THEME.gamegrid_x, Pos[i][wsi][1]+THEME.gamegrid_y); - game[i]->SetSkew(&Skew[i][0]); - game[i]->SetTrigger(trigA); - game[i]->SetSoundOver(btnSoundOver); - game[i]->SetSoundClick(btnSoundClick); - game[i]->SetRumble(false); - switch((i*3)/pagesize) - { - case 0: - game[i]->SetToolTip(titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE); - break; - case 1: - game[i]->SetToolTip(titleTT[i], 0, ttoffset_y, ALIGN_CENTRE, ALIGN_MIDDLE); - break; - case 2: - game[i]->SetToolTip(titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE); - break; - default: - break; - } - if(gameIndex[i] >= 0) - { - game[i]->SetClickable(true); - game[i]->SetVisible(true); - } - else - { - game[i]->SetVisible(false); - game[i]->SetClickable(false); - // game[i]->RemoveSoundOver(); - } - } - Settings.gridRows = rows; - if(isInserted(bootDevice)) - cfg_save_global(); + //------------------------ + // ImageData + //------------------------ +// if( gameIndex[i] != -1 ) +// cover[i] = LoadCoverImage(&gameList[gameIndex[i]], false /*bool Prefere3D*/); +// else +// cover[i] = new GuiImageData(NULL); + + //------------------------ + // Image + //------------------------ + coverImg[i] = NULL; + if ( gameIndex[i] != -1 ) + { + coverImg[i] = new GuiImageAsync( GameGridLoadCoverImage, gameList[gameIndex[i]], sizeof( struct discHdr ), &noCover ); + if ( coverImg[i] ) + { + coverImg[i]->SetWidescreen( CFG.widescreen ); + // if ( rows == 2 ) coverImg[i]->SetScale(.6); //these are the numbers for 2 rows + // else if ( rows == 3 ) coverImg[i]->SetScale(.26); //these are the numbers for 3 rows + coverImg[i]->SetScale( VALUE4ROWS( rows, 1.0, 0.6, 0.26 ) ); + coverImg[i]->SetPosition( 0, VALUE4ROWS( rows, 0, -50, -80 ) ); + } + } + + //------------------------ + // GameButton + //------------------------ + game[i] = new GuiButton( VALUE4ROWS( rows, 160, 75, 35 ), VALUE4ROWS( rows, 224, 133, 68 ) ); + game[i]->SetParent( this ); + game[i]->SetImage( coverImg[i] ); + game[i]->SetAlignment( ALIGN_TOP, ALIGN_LEFT ); + game[i]->SetPosition( Pos[i][wsi][0] + THEME.gamegrid_x, Pos[i][wsi][1] + THEME.gamegrid_y ); + game[i]->SetSkew( &Skew[i][0] ); + game[i]->SetTrigger( trigA ); + game[i]->SetSoundOver( btnSoundOver ); + game[i]->SetSoundClick( btnSoundClick ); + game[i]->SetRumble( false ); + switch ( ( i*3 ) / pagesize ) + { + case 0: + game[i]->SetToolTip( titleTT[i], ttoffset_x, ttoffset_y, ALIGN_LEFT, ALIGN_MIDDLE ); + break; + case 1: + game[i]->SetToolTip( titleTT[i], 0, ttoffset_y, ALIGN_CENTRE, ALIGN_MIDDLE ); + break; + case 2: + game[i]->SetToolTip( titleTT[i], -ttoffset_x, ttoffset_y, ALIGN_RIGHT, ALIGN_MIDDLE ); + break; + default: + break; + } + if ( gameIndex[i] >= 0 ) + { + game[i]->SetClickable( true ); + game[i]->SetVisible( true ); + } + else + { + game[i]->SetVisible( false ); + game[i]->SetClickable( false ); + // game[i]->RemoveSoundOver(); + } + } + Settings.gridRows = rows; + if ( isInserted( bootDevice ) ) + cfg_save_global(); } diff --git a/source/libwiigui/gui_gamegrid.h b/source/libwiigui/gui_gamegrid.h index 89625e6b..761a6305 100644 --- a/source/libwiigui/gui_gamegrid.h +++ b/source/libwiigui/gui_gamegrid.h @@ -6,54 +6,54 @@ class GuiImageAsync; class GuiGameGrid : public GuiElement { - public: - 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 GetClickedOption(); - int GetSelectedOption(); - void ResetState(); - void SetFocus(int f); - void Draw(); - void Update(GuiTrigger * t); - int GetOffset(); - void Reload(int Rows, int ListOffset); - void ChangeRows(int n); - protected: - GuiImageData noCover; - int selectedItem; - int listOffset; - int pagesize; - int clickedItem; - int rows; - int goLeft; - int goRight; + public: + 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 GetClickedOption(); + int GetSelectedOption(); + void ResetState(); + void SetFocus( int f ); + void Draw(); + void Update( GuiTrigger * t ); + int GetOffset(); + void Reload( int Rows, int ListOffset ); + void ChangeRows( int n ); + protected: + GuiImageData noCover; + int selectedItem; + int listOffset; + int pagesize; + int clickedItem; + int rows; + int goLeft; + int goRight; - int * gameIndex; - GuiButton ** game; - GuiTooltip ** titleTT; - GuiImageAsync ** coverImg; - - - GuiButton * btnRight; - GuiButton * btnLeft; - GuiButton * btnRowUp; - GuiButton * btnRowDown; + int * gameIndex; + GuiButton ** game; + GuiTooltip ** titleTT; + GuiImageAsync ** coverImg; - GuiImage * btnLeftImg; - GuiImage * btnRightImg; - GuiImageData * imgLeft; - GuiImageData * imgRight; - - GuiSound * btnSoundOver; - GuiSound * btnSoundClick; - GuiTrigger * trigA; - GuiTrigger * trigL; - GuiTrigger * trigR; - GuiTrigger * trigPlus; - GuiTrigger * trigMinus; - GuiTrigger * trig1; - GuiTrigger * trig2; + GuiButton * btnRight; + GuiButton * btnLeft; + GuiButton * btnRowUp; + GuiButton * btnRowDown; + + GuiImage * btnLeftImg; + GuiImage * btnRightImg; + + GuiImageData * imgLeft; + GuiImageData * imgRight; + + GuiSound * btnSoundOver; + GuiSound * btnSoundClick; + GuiTrigger * trigA; + GuiTrigger * trigL; + GuiTrigger * trigR; + GuiTrigger * trigPlus; + GuiTrigger * trigMinus; + GuiTrigger * trig1; + GuiTrigger * trig2; }; #endif diff --git a/source/libwiigui/gui_image.cpp b/source/libwiigui/gui_image.cpp index 9816b50f..4719a173 100644 --- a/source/libwiigui/gui_image.cpp +++ b/source/libwiigui/gui_image.cpp @@ -14,191 +14,192 @@ */ GuiImage::GuiImage() { - image = NULL; - width = 0; - height = 0; - imageangle = 0; - tile = -1; - stripe = 0; - widescreen = 0; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_DATA; + image = NULL; + width = 0; + height = 0; + imageangle = 0; + tile = -1; + stripe = 0; + widescreen = 0; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_DATA; } -GuiImage::GuiImage(GuiImageData * img) +GuiImage::GuiImage( GuiImageData * img ) { - if(img) - { - image = img->GetImage(); - width = img->GetWidth(); - height = img->GetHeight(); - } - else - { - image = NULL; - width = 0; - height = 0; - } - imageangle = 0; - tile = -1; - stripe = 0; - widescreen = 0; - parentangle = true; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_DATA; + if ( img ) + { + image = img->GetImage(); + width = img->GetWidth(); + height = img->GetHeight(); + } + else + { + image = NULL; + width = 0; + height = 0; + } + imageangle = 0; + tile = -1; + stripe = 0; + widescreen = 0; + parentangle = true; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_DATA; } -GuiImage::GuiImage(u8 * img, int w, int h) +GuiImage::GuiImage( u8 * img, int w, int h ) { image = img; - width = w; - height = h; - imageangle = 0; - tile = -1; - stripe = 0; - widescreen = 0; - parentangle = true; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_TEXTURE; + width = w; + height = h; + imageangle = 0; + tile = -1; + stripe = 0; + widescreen = 0; + parentangle = true; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_TEXTURE; } -GuiImage::GuiImage(int w, int h, GXColor c) +GuiImage::GuiImage( int w, int h, GXColor c ) { - image = (u8 *)memalign (32, w * h * 4); - width = w; - height = h; - imageangle = 0; - tile = -1; - stripe = 0; - widescreen = 0; - parentangle = true; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_COLOR; + image = ( u8 * )memalign ( 32, w * h * 4 ); + width = w; + height = h; + imageangle = 0; + tile = -1; + stripe = 0; + widescreen = 0; + parentangle = true; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_COLOR; - if(!image) - return; + if ( !image ) + return; - int x, y; + int x, y; - for(y=0; y < h; y++) - { - for(x=0; x < w; x++) - { - this->SetPixel(x, y, c); - } - } - int len = w*h*4; - if(len%32) len += (32-len%32); - DCFlushRange(image, len); + for ( y = 0; y < h; y++ ) + { + for ( x = 0; x < w; x++ ) + { + this->SetPixel( x, y, c ); + } + } + int len = w * h * 4; + if ( len % 32 ) len += ( 32 - len % 32 ); + DCFlushRange( image, len ); } -GuiImage::GuiImage(GuiImage &srcimage) : GuiElement() +GuiImage::GuiImage( GuiImage &srcimage ) : GuiElement() { - width = srcimage.GetWidth(); - height = srcimage.GetHeight(); + 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(); - tile = -1; - stripe = 0; - widescreen = 0; - parentangle = true; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_COPY; + if ( len % 32 ) len += ( 32 - len % 32 ); + image = ( u8 * )memalign ( 32, len ); + memcpy( image, srcimage.GetImage(), len ); + DCFlushRange( image, len ); + imageangle = srcimage.GetAngle(); + tile = -1; + stripe = 0; + widescreen = 0; + parentangle = true; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_COPY; } -GuiImage::GuiImage(GuiImage *srcimage) : GuiElement() +GuiImage::GuiImage( GuiImage *srcimage ) : GuiElement() { - width = srcimage->GetWidth(); - height = srcimage->GetHeight(); + 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(); - tile = -1; - stripe = 0; - widescreen = 0; - parentangle = true; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_COPY; + if ( len % 32 ) len += ( 32 - len % 32 ); + image = ( u8 * )memalign ( 32, len ); + memcpy( image, srcimage->GetImage(), len ); + DCFlushRange( image, len ); + imageangle = srcimage->GetAngle(); + tile = -1; + stripe = 0; + widescreen = 0; + parentangle = true; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_COPY; } -GuiImage &GuiImage::operator=(GuiImage &srcimage) +GuiImage &GuiImage::operator=( GuiImage & srcimage ) { - if((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { - free(image); + if ( ( imgType == IMAGE_COLOR || imgType == IMAGE_COPY ) && image ) + { + free( image ); image = NULL; } - width = srcimage.GetWidth(); - height = srcimage.GetHeight(); + width = srcimage.GetWidth(); + height = srcimage.GetHeight(); int len = width * height * 4; - if(len%32) len += (32-len%32); - image = (u8 *)memalign (32, len); - memcpy(image, srcimage.GetImage(), len); - DCFlushRange(image, len); - imageangle = srcimage.GetAngle(); - tile = -1; - stripe = 0; - widescreen = 0; - parentangle = true; - xx1 = 0; - yy1 = 0; - xx2 = 0; - yy2 = 0; - xx3 = 0; - yy3 = 0; - xx4 = 0; - yy4 = 0; - imgType = IMAGE_COPY; - return *this; + if ( len % 32 ) len += ( 32 - len % 32 ); + image = ( u8 * )memalign ( 32, len ); + memcpy( image, srcimage.GetImage(), len ); + DCFlushRange( image, len ); + imageangle = srcimage.GetAngle(); + tile = -1; + stripe = 0; + widescreen = 0; + parentangle = true; + xx1 = 0; + yy1 = 0; + xx2 = 0; + yy2 = 0; + xx3 = 0; + yy3 = 0; + xx4 = 0; + yy4 = 0; + imgType = IMAGE_COPY; + return *this; } /** @@ -206,215 +207,220 @@ GuiImage &GuiImage::operator=(GuiImage &srcimage) */ GuiImage::~GuiImage() { - if((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { - free(image); + if ( ( imgType == IMAGE_COLOR || imgType == IMAGE_COPY ) && image ) + { + free( image ); image = NULL; - } + } } u8 * GuiImage::GetImage() { - return image; + return image; } -void GuiImage::SetImage(GuiImageData * img) +void GuiImage::SetImage( GuiImageData * img ) { - LOCK(this); - if((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { - free(image); - image = NULL; - } + LOCK( this ); + if ( ( imgType == IMAGE_COLOR || imgType == IMAGE_COPY ) && image ) + { + free( image ); + image = NULL; + } - image = img->GetImage(); - width = img->GetWidth(); - height = img->GetHeight(); - imgType = IMAGE_DATA; + image = img->GetImage(); + width = img->GetWidth(); + height = img->GetHeight(); + imgType = IMAGE_DATA; } -void GuiImage::SetImage(u8 * img, int w, int h) +void GuiImage::SetImage( u8 * img, int w, int h ) { - LOCK(this); - if((imgType == IMAGE_COLOR || imgType == IMAGE_COPY) && image) { - free(image); - image = NULL; - } - image = img; - width = w; - height = h; - imgType = IMAGE_TEXTURE; + LOCK( this ); + if ( ( imgType == IMAGE_COLOR || imgType == IMAGE_COPY ) && image ) + { + free( image ); + image = NULL; + } + image = img; + width = w; + height = h; + imgType = IMAGE_TEXTURE; } -void GuiImage::SetAngle(float a) +void GuiImage::SetAngle( float a ) { - LOCK(this); - imageangle = a; + LOCK( this ); + imageangle = a; } float GuiImage::GetAngle() { - return imageangle; + return imageangle; } -void GuiImage::SetTile(int t) +void GuiImage::SetTile( int t ) { - LOCK(this); - tile = t; + LOCK( this ); + tile = t; } -void GuiImage::SetWidescreen(bool w) +void GuiImage::SetWidescreen( bool w ) { - LOCK(this); - widescreen = w; + LOCK( this ); + widescreen = w; } -void GuiImage::SetParentAngle(bool a) +void GuiImage::SetParentAngle( bool a ) { - LOCK(this); + 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); - GXColor color; - color.a = *(image+offset); - color.r = *(image+offset+1); - color.g = *(image+offset+32); - color.b = *(image+offset+33); - return color; + u32 offset = ( ( ( y >> 2 ) << 4 ) * this->GetWidth() ) + ( ( x >> 2 ) << 6 ) + ( ( ( y % 4 << 2 ) + x % 4 ) << 1 ); + GXColor color; + color.a = *( image + offset ); + color.r = *( image + offset + 1 ); + color.g = *( image + offset + 32 ); + color.b = *( image + offset + 33 ); + return color; } -void GuiImage::SetPixel(int x, int y, GXColor color) +void GuiImage::SetPixel( int x, int y, GXColor color ) { - LOCK(this); - if(!image || this->GetWidth() <= 0 || x < 0 || y < 0) - return; + LOCK( this ); + if ( !image || this->GetWidth() <= 0 || x < 0 || y < 0 ) + return; - u32 offset = (((y >> 2)<<4)*this->GetWidth()) + ((x >> 2)<<6) + (((y%4 << 2) + x%4 ) << 1); - *(image+offset) = color.a; - *(image+offset+1) = color.r; - *(image+offset+32) = color.g; - *(image+offset+33) = color.b; + u32 offset = ( ( ( y >> 2 ) << 4 ) * this->GetWidth() ) + ( ( x >> 2 ) << 6 ) + ( ( ( y % 4 << 2 ) + x % 4 ) << 1 ); + *( image + offset ) = color.a; + *( image + offset + 1 ) = color.r; + *( image + offset + 32 ) = color.g; + *( image + offset + 33 ) = color.b; } -void GuiImage::SetGrayscale(void) +void GuiImage::SetGrayscale( void ) { - LOCK(this); + LOCK( this ); GXColor color; u32 offset, gray; - for(int x = 0; x < width; x++) { - for(int y = 0; y < height; y++) { - offset = (((y >> 2)<<4)*width) + ((x >> 2)<<6) + (((y%4 << 2) + x%4 ) << 1); - color.r = *(image+offset+1); - color.g = *(image+offset+32); - color.b = *(image+offset+33); + for ( int x = 0; x < width; x++ ) + { + for ( int y = 0; y < height; y++ ) + { + offset = ( ( ( y >> 2 ) << 4 ) * width ) + ( ( x >> 2 ) << 6 ) + ( ( ( y % 4 << 2 ) + x % 4 ) << 1 ); + color.r = *( image + offset + 1 ); + color.g = *( image + offset + 32 ); + 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); + int len = width * height * 4; + if ( len % 32 ) len += ( 32 - len % 32 ); + DCFlushRange( image, len ); } -void GuiImage::SetStripe(int s) +void GuiImage::SetStripe( int s ) { - LOCK(this); - stripe = s; + LOCK( this ); + stripe = s; } -void GuiImage::SetSkew(int XX1, int YY1,int XX2, int YY2,int XX3, int YY3,int XX4, int YY4) +void GuiImage::SetSkew( int XX1, int YY1, int XX2, int YY2, int XX3, int YY3, int XX4, int YY4 ) { - xx1 = XX1; - yy1 = YY1; - xx2 = XX2; - yy2 = YY2; - xx3 = XX3; - yy3 = YY3; - xx4 = XX4; - yy4 = YY4; + xx1 = XX1; + yy1 = YY1; + xx2 = XX2; + yy2 = YY2; + xx3 = XX3; + yy3 = YY3; + xx4 = XX4; + yy4 = YY4; } -void GuiImage::SetSkew(int *skew) +void GuiImage::SetSkew( int *skew ) { - xx1 = *skew++; - yy1 = *skew++; - xx2 = *skew++; - yy2 = *skew++; - xx3 = *skew++; - yy3 = *skew++; - xx4 = *skew++; - yy4 = *skew; + xx1 = *skew++; + yy1 = *skew++; + xx2 = *skew++; + yy2 = *skew++; + xx3 = *skew++; + yy3 = *skew++; + xx4 = *skew++; + yy4 = *skew; } -void GuiImage::ColorStripe(int shift) +void GuiImage::ColorStripe( int shift ) { - LOCK(this); - int x, y; - GXColor color; - int alt = 0; + LOCK( this ); + int x, y; + GXColor color; + int alt = 0; - for(y=0; y < this->GetHeight(); y++) - { - if(y % 3 == 0) - alt ^= 1; + for ( y = 0; y < this->GetHeight(); y++ ) + { + if ( y % 3 == 0 ) + alt ^= 1; - for(x=0; x < this->GetWidth(); x++) - { - color = GetPixel(x, y); + for ( x = 0; x < this->GetWidth(); x++ ) + { + color = GetPixel( x, y ); - if(alt) - { - if(color.r < 255-shift) - color.r += shift; - else - color.r = 255; - if(color.g < 255-shift) - color.g += shift; - else - color.g = 255; - if(color.b < 255-shift) - color.b += shift; - else - color.b = 255; + if ( alt ) + { + if ( color.r < 255 - shift ) + color.r += shift; + else + color.r = 255; + if ( color.g < 255 - shift ) + color.g += shift; + else + color.g = 255; + if ( color.b < 255 - shift ) + color.b += shift; + else + color.b = 255; - color.a = 255; - } - else - { - if(color.r > shift) - color.r -= shift; - else - color.r = 0; - if(color.g > shift) - color.g -= shift; - else - color.g = 0; - if(color.b > shift) - color.b -= shift; - else - color.b = 0; + color.a = 255; + } + else + { + if ( color.r > shift ) + color.r -= shift; + else + color.r = 0; + if ( color.g > shift ) + color.g -= shift; + else + color.g = 0; + if ( color.b > shift ) + color.b -= shift; + else + color.b = 0; - color.a = 255; - } - SetPixel(x, y, color); - } - } + color.a = 255; + } + SetPixel( x, y, color ); + } + } - int len = width*height*4; - if(len%32) len += (32-len%32); - DCFlushRange(image, len); + int len = width * height * 4; + if ( len % 32 ) len += ( 32 - len % 32 ); + DCFlushRange( image, len ); } /** @@ -423,40 +429,40 @@ void GuiImage::ColorStripe(int shift) void GuiImage::Draw() { - LOCK(this); - if(!image || !this->IsVisible() || tile == 0) - return; + LOCK( this ); + if ( !image || !this->IsVisible() || tile == 0 ) + return; - float currScale = this->GetScale(); - int currLeft = this->GetLeft(); + float currScale = this->GetScale(); + int currLeft = this->GetLeft(); float currAngleDyn = this->GetAngleDyn(); - if(currAngleDyn && parentangle) + if ( currAngleDyn && parentangle ) imageangle = currAngleDyn; - if(tile > 0) - { - for(int i=0; iGetTop(), zoffset, width, height, image, imageangle, widescreen ? currScale*0.80 : currScale, currScale, this->GetAlpha(), xx1,yy1,xx2,yy2,xx3,yy3,xx4,yy4); - } - else - { - // temporary (maybe), used to correct offset for scaled images - if(scale != 1) - currLeft = currLeft - width/2 + (width*scale)/2; + if ( tile > 0 ) + { + for ( int i = 0; 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; - Menu_DrawImg(currLeft, this->GetTop(), zoffset, width, height, image, imageangle, widescreen ? currScale*0.80 : currScale, currScale, this->GetAlpha(), xx1,yy1,xx2,yy2,xx3,yy3,xx4,yy4); - } + Menu_DrawImg( currLeft, this->GetTop(), zoffset, width, height, image, imageangle, widescreen ? currScale*0.80 : currScale, currScale, this->GetAlpha(), xx1, yy1, xx2, yy2, xx3, yy3, xx4, yy4 ); + } - if(stripe > 0) - for(int y=0; y < this->GetHeight(); y+=6) - Menu_DrawRectangle(currLeft,this->GetTop()+y,this->GetWidth(),3,(GXColor){0, 0, 0, stripe},1); + if ( stripe > 0 ) + for ( int y = 0; y < this->GetHeight(); y += 6 ) + Menu_DrawRectangle( currLeft, this->GetTop() + y, this->GetWidth(), 3, ( GXColor ) {0, 0, 0, stripe}, 1 ); - this->UpdateEffects(); + this->UpdateEffects(); } diff --git a/source/libwiigui/gui_image_async.cpp b/source/libwiigui/gui_image_async.cpp index d4977193..d84e4eaf 100644 --- a/source/libwiigui/gui_image_async.cpp +++ b/source/libwiigui/gui_image_async.cpp @@ -14,37 +14,37 @@ #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) - { - char theTime[10]; - time_t rawtime = time(0); //this fixes code dump caused by the clock - struct tm * timeinfo = localtime (&rawtime); - strftime(theTime, sizeof(theTime), "%H:%M:%S", timeinfo); - char format[10+strlen(Format)+strlen(theTime)]; - sprintf(format, "%s %i - %s\n", theTime, Line, Format); - va_list va; - va_start(va, Format); - vfprintf(fp, format, va); - va_end(va); - fclose(fp); - } - LWP_MutexUnlock(debugLock); + FILE *fp = fopen( "SD:/debug.txt", "a" ); + if ( fp ) + { + char theTime[10]; + time_t rawtime = time( 0 ); //this fixes code dump caused by the clock + struct tm * timeinfo = localtime ( &rawtime ); + strftime( theTime, sizeof( theTime ), "%H:%M:%S", timeinfo ); + char format[10+strlen( Format )+strlen( theTime )]; + sprintf( format, "%s %i - %s\n", theTime, Line, Format ); + va_list va; + va_start( va, Format ); + vfprintf( fp, format, va ); + va_end( va ); + fclose( fp ); + } + LWP_MutexUnlock( debugLock ); } //#define DEBUG(format, ...) debug(__LINE__, format, ##__VA_ARGS__) #define DEBUG(format, ...) -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); - return dst; + void *dst = malloc( len ); + if ( dst ) memcpy( dst, src, len ); + return dst; } static std::vector List; static u32 ThreadCount = 0; @@ -54,143 +54,143 @@ static mutex_t InUseLock = LWP_MUTEX_NULL; static GuiImageAsync *InUse = NULL; static bool Quit = false; static bool CanSleep = true; -void *GuiImageAsyncThread(void *arg) +void *GuiImageAsyncThread( void *arg ) { - while(!Quit) - { - LWP_MutexLock(ListLock); - if(List.size()) - { - LWP_MutexLock(InUseLock); + while ( !Quit ) + { + LWP_MutexLock( ListLock ); + if ( List.size() ) + { + LWP_MutexLock( InUseLock ); - InUse = List.front(); - List.erase(List.begin()); + InUse = List.front(); + List.erase( List.begin() ); - LWP_MutexUnlock(ListLock); + LWP_MutexUnlock( ListLock ); - if(InUse) - { - GuiImageData *data = InUse->callback(InUse->arg); - InUse->loadet_imgdata = data; - if(InUse->loadet_imgdata && InUse->loadet_imgdata->GetImage()) - { - // InUse->SetImage(InUse->loadet_imgdata); can’t use here. There can occur a deadlock - // Sets the image directly without lock. This is not fine, but it prevents a deadlock - InUse->image = InUse->loadet_imgdata->GetImage(); - InUse->width = InUse->loadet_imgdata->GetWidth(); - InUse->height = InUse->loadet_imgdata->GetHeight(); - } - } - InUse = NULL; - LWP_MutexUnlock(InUseLock); - } - else - { - LWP_MutexUnlock(ListLock); - if(!Quit && CanSleep) - LWP_SuspendThread(Thread); - } - CanSleep = true; - } - Quit = false; - return NULL; + if ( InUse ) + { + GuiImageData *data = InUse->callback( InUse->arg ); + InUse->loadet_imgdata = data; + if ( InUse->loadet_imgdata && InUse->loadet_imgdata->GetImage() ) + { + // InUse->SetImage(InUse->loadet_imgdata); can’t use here. There can occur a deadlock + // Sets the image directly without lock. This is not fine, but it prevents a deadlock + InUse->image = InUse->loadet_imgdata->GetImage(); + InUse->width = InUse->loadet_imgdata->GetWidth(); + InUse->height = InUse->loadet_imgdata->GetHeight(); + } + } + InUse = NULL; + LWP_MutexUnlock( InUseLock ); + } + else + { + LWP_MutexUnlock( ListLock ); + if ( !Quit && CanSleep ) + LWP_SuspendThread( Thread ); + } + CanSleep = true; + } + Quit = false; + return NULL; } static u32 GuiImageAsyncThreadInit() { - if(0 == ThreadCount++) - { - CanSleep = false; - LWP_MutexInit(&ListLock, false); - LWP_MutexInit(&InUseLock, false); - LWP_CreateThread(&Thread, GuiImageAsyncThread, NULL, NULL, 16384, 75); -// while(!CanSleep) -// usleep(20); - } - return 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); + } + return ThreadCount; } static u32 GuiImageAsyncThreadExit() { - if(--ThreadCount == 0) - { - Quit = true; - LWP_ResumeThread(Thread); -// while(Quit) -// usleep(20); - LWP_JoinThread(Thread, NULL); - LWP_MutexDestroy(ListLock); - LWP_MutexDestroy(InUseLock); - Thread = LWP_THREAD_NULL; - ListLock = LWP_MUTEX_NULL; - InUseLock = LWP_MUTEX_NULL; - } - return ThreadCount; + if ( --ThreadCount == 0 ) + { + Quit = true; + LWP_ResumeThread( Thread ); +// while(Quit) +// usleep(20); + LWP_JoinThread( Thread, NULL ); + LWP_MutexDestroy( ListLock ); + LWP_MutexDestroy( InUseLock ); + Thread = LWP_THREAD_NULL; + ListLock = LWP_MUTEX_NULL; + InUseLock = LWP_MUTEX_NULL; + } + return ThreadCount; } -static void GuiImageAsyncThread_AddImage(GuiImageAsync* Image) +static void GuiImageAsyncThread_AddImage( GuiImageAsync* Image ) { - LWP_MutexLock(ListLock); - List.push_back(Image); - LWP_MutexUnlock(ListLock); - CanSleep = false; -// if(LWP_ThreadIsSuspended(Thread)) - LWP_ResumeThread(Thread); + LWP_MutexLock( ListLock ); + List.push_back( Image ); + LWP_MutexUnlock( ListLock ); + CanSleep = false; +// 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++) - { - if(*iter == Image) - { - List.erase(iter); - LWP_MutexUnlock(ListLock); - return; - } - } - if(InUse == Image) - { - LWP_MutexLock(InUseLock); - LWP_MutexUnlock(InUseLock); - } - LWP_MutexUnlock(ListLock); + LWP_MutexLock( ListLock ); + for ( std::vector::iterator iter = List.begin(); iter != List.end(); iter++ ) + { + if ( *iter == Image ) + { + List.erase( iter ); + LWP_MutexUnlock( ListLock ); + return; + } + } + if ( InUse == Image ) + { + LWP_MutexLock( InUseLock ); + LWP_MutexUnlock( InUseLock ); + } + LWP_MutexUnlock( ListLock ); } /** * Constructor for the GuiImageAsync class. */ -GuiImageData *StdImageLoaderCallback(void *arg) +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); + GuiImageAsyncThreadInit(); + GuiImageAsyncThread_AddImage( this ); } -GuiImageAsync::GuiImageAsync(ImageLoaderCallback Callback, void *Arg, int ArgLen, GuiImageData * PreloadImg) : - GuiImage(PreloadImg), - loadet_imgdata(NULL), - callback(Callback), - arg(memdup(Arg, ArgLen)) +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); + DEBUG( "Constructor %p", this ); + GuiImageAsyncThreadInit(); + GuiImageAsyncThread_AddImage( this ); } GuiImageAsync::~GuiImageAsync() { - GuiImageAsyncThread_RemoveImage(this); - GuiImageAsyncThreadExit(); -DEBUG("Deconstructor %p (loadet_imgdata=%p)", this, loadet_imgdata); - if(loadet_imgdata) delete loadet_imgdata; - if(arg) free(arg); + GuiImageAsyncThread_RemoveImage( this ); + GuiImageAsyncThreadExit(); + DEBUG( "Deconstructor %p (loadet_imgdata=%p)", this, loadet_imgdata ); + if ( loadet_imgdata ) delete loadet_imgdata; + if ( arg ) free( arg ); } diff --git a/source/libwiigui/gui_image_async.h b/source/libwiigui/gui_image_async.h index 9c746b84..a951eb93 100644 --- a/source/libwiigui/gui_image_async.h +++ b/source/libwiigui/gui_image_async.h @@ -3,23 +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 { -public: - GuiImageAsync(const char *Filename, GuiImageData * PreloadImg); - GuiImageAsync(ImageLoaderCallback Callback, void *arg, int arglen, GuiImageData * PreloadImg); - ~GuiImageAsync(); + public: + 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); + private: + GuiImageData *loadet_imgdata; + friend void loader( GuiImageAsync *InUse ); -friend void Setter(GuiImageAsync *InUse); - friend void *GuiImageAsyncThread(void *arg); - ImageLoaderCallback callback; - void *arg; + friend void Setter( GuiImageAsync *InUse ); + friend void *GuiImageAsyncThread( void *arg ); + ImageLoaderCallback callback; + void *arg; }; diff --git a/source/libwiigui/gui_imagedata.cpp b/source/libwiigui/gui_imagedata.cpp index 28fc8832..64df95e3 100644 --- a/source/libwiigui/gui_imagedata.cpp +++ b/source/libwiigui/gui_imagedata.cpp @@ -33,264 +33,265 @@ 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; + data = NULL; + width = 0; + height = 0; - if(img) - { - PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromBuffer(img); + if ( img ) + { + PNGUPROP imgProp; + IMGCTX ctx = PNGU_SelectImageFromBuffer( img ); - if(!ctx) - return; + if ( !ctx ) + return; - int res = PNGU_GetImageProperties(ctx, &imgProp); - //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; + int res = PNGU_GetImageProperties( ctx, &imgProp ); + //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; - if(res == PNGU_OK) - { - int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if(len%32) len += (32-len%32); - data = (u8 *)memalign (32, len); + if ( res == PNGU_OK ) + { + int len = imgProp.imgWidth * imgProp.imgHeight * 4; + if ( len % 32 ) len += ( 32 - len % 32 ); + data = ( u8 * )memalign ( 32, len ); - if(data) - { - res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); + if ( data ) + { + res = PNGU_DecodeTo4x4RGBA8 ( ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255 ); - if(res == PNGU_OK) - { - width = imgProp.imgWidth; - height = imgProp.imgHeight; - DCFlushRange(data, len); - } - else - { - free(data); - data = NULL; - idiotFlag=1; - snprintf(idiotChar, sizeof(idiotChar), "%s", img); + if ( res == PNGU_OK ) + { + width = imgProp.imgWidth; + height = imgProp.imgHeight; + DCFlushRange( data, len ); + } + else + { + free( data ); + data = NULL; + idiotFlag = 1; + snprintf( idiotChar, sizeof( idiotChar ), "%s", img ); - } - } - } - PNGU_ReleaseImageContext (ctx); - } -} - -GuiImageData::GuiImageData(const u8 * img, int imgSize) -{ - data = NULL; - width = 0; - height = 0; - - if(img) - { - if (img[0] == 0xFF && img[1] == 0xD8) { // IMAGE_JPEG - LoadJpeg(img, imgSize); + } + } } - } + PNGU_ReleaseImageContext ( ctx ); + } +} + +GuiImageData::GuiImageData( const u8 * img, int imgSize ) +{ + data = NULL; + width = 0; + height = 0; + + if ( img ) + { + if ( img[0] == 0xFF && img[1] == 0xD8 ) // IMAGE_JPEG + { + LoadJpeg( img, imgSize ); + } + } } /** * Constructor for the GuiImageData class. */ -GuiImageData::GuiImageData(const char * imgPath, const u8 * buffer) +GuiImageData::GuiImageData( const char * imgPath, const u8 * buffer ) { - data = NULL; - width = 0; - height = 0; + data = NULL; + width = 0; + height = 0; - if(imgPath) - { - PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromDevice(imgPath); - //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; + if ( imgPath ) + { + PNGUPROP imgProp; + IMGCTX ctx = PNGU_SelectImageFromDevice( imgPath ); + //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; - if(ctx) - { - int res = PNGU_GetImageProperties(ctx, &imgProp); + if ( ctx ) + { + int res = PNGU_GetImageProperties( ctx, &imgProp ); - if(res == PNGU_OK) - { - int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if(len%32) len += (32-len%32); - data = (u8 *)memalign (32, len); + if ( res == PNGU_OK ) + { + int len = imgProp.imgWidth * imgProp.imgHeight * 4; + if ( len % 32 ) len += ( 32 - len % 32 ); + data = ( u8 * )memalign ( 32, len ); - if(data) - { - res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); + if ( data ) + { + res = PNGU_DecodeTo4x4RGBA8 ( ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255 ); - if(res == PNGU_OK) - { - width = imgProp.imgWidth; - height = imgProp.imgHeight; - DCFlushRange(data, len); - } - else - { - free(data); - data = NULL; - idiotFlag=1; - snprintf(idiotChar, sizeof(idiotChar), "%s", imgPath); - } - } - } - PNGU_ReleaseImageContext (ctx); - } - } + if ( res == PNGU_OK ) + { + width = imgProp.imgWidth; + height = imgProp.imgHeight; + DCFlushRange( data, len ); + } + else + { + free( data ); + data = NULL; + idiotFlag = 1; + snprintf( idiotChar, sizeof( idiotChar ), "%s", imgPath ); + } + } + } + PNGU_ReleaseImageContext ( ctx ); + } + } - if (!data) //use buffer data instead - { - width = 0; - height = 0; - if(buffer) - { - PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromBuffer(buffer); + if ( !data ) //use buffer data instead + { + width = 0; + height = 0; + if ( buffer ) + { + PNGUPROP imgProp; + IMGCTX ctx = PNGU_SelectImageFromBuffer( buffer ); - if(!ctx) - return; + if ( !ctx ) + return; - int res = PNGU_GetImageProperties(ctx, &imgProp); + int res = PNGU_GetImageProperties( ctx, &imgProp ); - if(res == PNGU_OK) - { - int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if(len%32) len += (32-len%32); - data = (u8 *)memalign (32, len); + if ( res == PNGU_OK ) + { + int len = imgProp.imgWidth * imgProp.imgHeight * 4; + if ( len % 32 ) len += ( 32 - len % 32 ); + data = ( u8 * )memalign ( 32, len ); - if(data) - { - res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); + if ( data ) + { + res = PNGU_DecodeTo4x4RGBA8 ( ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255 ); - if(res == PNGU_OK) - { - width = imgProp.imgWidth; - height = imgProp.imgHeight; - DCFlushRange(data, len); - } - else - { - free(data); - data = NULL; - } - } - } - PNGU_ReleaseImageContext (ctx); - } - } + if ( res == PNGU_OK ) + { + width = imgProp.imgWidth; + height = imgProp.imgHeight; + DCFlushRange( data, len ); + } + else + { + free( data ); + data = NULL; + } + } + } + PNGU_ReleaseImageContext ( ctx ); + } + } } /** * Constructor for the GuiImageData class. */ -GuiImageData::GuiImageData(const char *path, const char *file, const u8 *buffer, bool force_widescreen/*=false*/, const u8 *wbuffer/*=NULL*/) +GuiImageData::GuiImageData( const char *path, const char *file, const u8 *buffer, bool force_widescreen/*=false*/, const u8 *wbuffer/*=NULL*/ ) { - data = NULL; - width = 0; - height = 0; - char path_4_3[100]; - char path_16_9[100]; - char *imgPath; + data = NULL; + width = 0; + height = 0; + char path_4_3[100]; + char path_16_9[100]; + char *imgPath; - snprintf(path_4_3, sizeof(path_4_3), "%s%s", path, file); - if(force_widescreen) - { - snprintf(path_16_9, sizeof(path_16_9), "%sw%s", path, file); - imgPath = path_16_9; - if(wbuffer) - buffer = wbuffer; - } - else - imgPath = path_4_3; + snprintf( path_4_3, sizeof( path_4_3 ), "%s%s", path, file ); + if ( force_widescreen ) + { + snprintf( path_16_9, sizeof( path_16_9 ), "%sw%s", path, file ); + imgPath = path_16_9; + if ( wbuffer ) + buffer = wbuffer; + } + else + imgPath = path_4_3; - for(;;) - { - if(imgPath) - { - PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromDevice(imgPath); - //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; + for ( ;; ) + { + if ( imgPath ) + { + PNGUPROP imgProp; + IMGCTX ctx = PNGU_SelectImageFromDevice( imgPath ); + //if (((4%imgProp.imgWidth)!=0)||((4%imgProp.imgHeight)!=0))idiotFlag=1; - if(ctx) - { - int res = PNGU_GetImageProperties(ctx, &imgProp); + if ( ctx ) + { + int res = PNGU_GetImageProperties( ctx, &imgProp ); - if(res == PNGU_OK) - { - int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if(len%32) len += (32-len%32); - data = (u8 *)memalign (32, len); + if ( res == PNGU_OK ) + { + int len = imgProp.imgWidth * imgProp.imgHeight * 4; + if ( len % 32 ) len += ( 32 - len % 32 ); + data = ( u8 * )memalign ( 32, len ); - if(data) - { - res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); + if ( data ) + { + res = PNGU_DecodeTo4x4RGBA8 ( ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255 ); - if(res == PNGU_OK) - { - width = imgProp.imgWidth; - height = imgProp.imgHeight; - DCFlushRange(data, len); - } - else - { - free(data); - data = NULL; - idiotFlag=1; - snprintf(idiotChar, sizeof(idiotChar), "%s", imgPath); - } - } - } - PNGU_ReleaseImageContext (ctx); - } - } - if(data || imgPath == path_4_3) - break; - imgPath = path_4_3; - } + if ( res == PNGU_OK ) + { + width = imgProp.imgWidth; + height = imgProp.imgHeight; + DCFlushRange( data, len ); + } + else + { + free( data ); + data = NULL; + idiotFlag = 1; + snprintf( idiotChar, sizeof( idiotChar ), "%s", imgPath ); + } + } + } + PNGU_ReleaseImageContext ( ctx ); + } + } + if ( data || imgPath == path_4_3 ) + break; + imgPath = path_4_3; + } - if (!data) //use buffer data instead - { - width = 0; - height = 0; - if(buffer) - { - PNGUPROP imgProp; - IMGCTX ctx = PNGU_SelectImageFromBuffer(buffer); + if ( !data ) //use buffer data instead + { + width = 0; + height = 0; + if ( buffer ) + { + PNGUPROP imgProp; + IMGCTX ctx = PNGU_SelectImageFromBuffer( buffer ); - if(!ctx) - return; + if ( !ctx ) + return; - int res = PNGU_GetImageProperties(ctx, &imgProp); + int res = PNGU_GetImageProperties( ctx, &imgProp ); - if(res == PNGU_OK) - { - int len = imgProp.imgWidth * imgProp.imgHeight * 4; - if(len%32) len += (32-len%32); - data = (u8 *)memalign (32, len); + if ( res == PNGU_OK ) + { + int len = imgProp.imgWidth * imgProp.imgHeight * 4; + if ( len % 32 ) len += ( 32 - len % 32 ); + data = ( u8 * )memalign ( 32, len ); - if(data) - { - res = PNGU_DecodeTo4x4RGBA8 (ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255); + if ( data ) + { + res = PNGU_DecodeTo4x4RGBA8 ( ctx, imgProp.imgWidth, imgProp.imgHeight, data, 255 ); - if(res == PNGU_OK) - { - width = imgProp.imgWidth; - height = imgProp.imgHeight; - DCFlushRange(data, len); - } - else - { - free(data); - data = NULL; - } - } - } - PNGU_ReleaseImageContext (ctx); - } - } + if ( res == PNGU_OK ) + { + width = imgProp.imgWidth; + height = imgProp.imgHeight; + DCFlushRange( data, len ); + } + else + { + free( data ); + data = NULL; + } + } + } + PNGU_ReleaseImageContext ( ctx ); + } + } } /** @@ -298,109 +299,114 @@ GuiImageData::GuiImageData(const char *path, const char *file, const u8 *buffer, */ GuiImageData::~GuiImageData() { - if(data) - { - free(data); - data = NULL; - } + if ( data ) + { + free( data ); + data = NULL; + } } u8 * GuiImageData::GetImage() { - return data; + return data; } int GuiImageData::GetWidth() { - return width; + return width; } int GuiImageData::GetHeight() { - return height; + return height; } -void GuiImageData::SetGrayscale(void) +void GuiImageData::SetGrayscale( void ) { GXColor color; u32 offset, gray; - for(int x = 0; x < width; x++) { - for(int y = 0; y < height; y++) { - 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); + for ( int x = 0; x < width; x++ ) + { + for ( int y = 0; y < height; y++ ) + { + offset = ( ( ( y >> 2 ) << 4 ) * width ) + ( ( x >> 2 ) << 6 ) + ( ( ( y % 4 << 2 ) + x % 4 ) << 1 ); + color.r = *( data + offset + 1 ); + color.g = *( data + offset + 32 ); + 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; + struct jpeg_decompress_struct cinfo; + struct jpeg_error_mgr jerr; - int n = imgSize; + int n = imgSize; - while (n > 1) { - if (img[n - 1] == 0xff && img[n] == 0xd9) { - break; - } - n--; - } + while ( n > 1 ) + { + if ( img[n - 1] == 0xff && img[n] == 0xd9 ) + { + break; + } + n--; + } - jpeg_create_decompress(&cinfo); - cinfo.err = jpeg_std_error(&jerr); + jpeg_create_decompress( &cinfo ); + 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) - { - float factor = (cinfo.output_width > cinfo.output_height) ? (1.0 * cinfo.output_width) / new_width : (1.0 * cinfo.output_height) / new_height; - cinfo.scale_num = 1; - cinfo.scale_denom = factor; - cinfo.do_fancy_upsampling = true; - cinfo.do_block_smoothing = false; - cinfo.dct_method = JDCT_IFAST; - } + if ( cinfo.output_width > new_width || cinfo.output_height > new_height ) + { + float factor = ( cinfo.output_width > cinfo.output_height ) ? ( 1.0 * cinfo.output_width ) / new_width : ( 1.0 * cinfo.output_height ) / new_height; + cinfo.scale_num = 1; + cinfo.scale_denom = factor; + cinfo.do_fancy_upsampling = true; + cinfo.do_block_smoothing = false; + cinfo.dct_method = JDCT_IFAST; + } - jpeg_start_decompress(&cinfo); + jpeg_start_decompress( &cinfo ); - int rowsize = cinfo.output_width * cinfo.num_components; - unsigned char *tempBuffer = (unsigned char *) malloc(rowsize * cinfo.output_height); + int rowsize = cinfo.output_width * cinfo.num_components; + unsigned char *tempBuffer = ( unsigned char * ) malloc( rowsize * cinfo.output_height ); JSAMPROW row_pointer[1]; - row_pointer[0] = (unsigned char*) malloc(rowsize); + row_pointer[0] = ( unsigned char* ) malloc( rowsize ); size_t location = 0; - while (cinfo.output_scanline < cinfo.output_height) { - jpeg_read_scanlines(&cinfo, row_pointer, 1); - memcpy(tempBuffer + location, row_pointer[0], rowsize); - location += rowsize; + while ( cinfo.output_scanline < cinfo.output_height ) + { + 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; + 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 ); } /** @@ -411,34 +417,40 @@ void GuiImageData::LoadJpeg(const u8 *img, int imgSize) * @param width * @param height */ -void GuiImageData::RawTo4x4RGBA(const unsigned char *src, void *dst, const unsigned int width, const unsigned int height) +void GuiImageData::RawTo4x4RGBA( const unsigned char *src, void *dst, const unsigned int width, const unsigned int height ) { unsigned int block; unsigned int i; unsigned int c; 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 (i = 0; i < width; i += 4) { + for ( block = 0; block < height; block += 4 ) + { + for ( i = 0; i < width; i += 4 ) + { /* Alpha and Red */ - for (c = 0; c < 4; ++c) { - for (ar = 0; ar < 4; ++ar) { + for ( c = 0; c < 4; ++c ) + { + 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 (gb = 0; gb < 4; ++gb) { + for ( c = 0; c < 4; ++c ) + { + 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 dbd01b94..f2746509 100644 --- a/source/libwiigui/gui_keyboard.cpp +++ b/source/libwiigui/gui_keyboard.cpp @@ -18,486 +18,514 @@ */ 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; - shift = 0; - caps = 0; - alt = 0; - alt2 = 0; - m = min; - int mode = lang; - selectable = true; - focus = 0; // allow focus - alignmentHor = ALIGN_CENTRE; - alignmentVert = ALIGN_MIDDLE; - kbtextmaxlen = max>sizeof(kbtextstr) ? sizeof(kbtextstr) : max; // limit max up to sizeof(kbtextstr) -// strlcpy(kbtextstr, t, kbtextmaxlen); - strncpy(kbtextstr, t, kbtextmaxlen); // strncpy is needed to fill the rest with \0 - kbtextstr[sizeof(kbtextstr)-1] = 0; // terminate with \0 - //QWERTY// - if (mode == 0){ - Key thekeys[4][11] = { - { - {'1','!'}, - {'2','@'}, - {'3','#'}, - {'4','$'}, - {'5','%'}, - {'6','^'}, - {'7','&'}, - {'8','*'}, - {'9','('}, - {'0',')'}, - {'\0','\0'} - }, - { - {'q','Q'}, - {'w','W'}, - {'e','E'}, - {'r','R'}, - {'t','T'}, - {'y','Y'}, - {'u','U'}, - {'i','I'}, - {'o','O'}, - {'p','P'}, - {'-','_'} - }, - { - {'a','A'}, - {'s','S'}, - {'d','D'}, - {'f','F'}, - {'g','G'}, - {'h','H'}, - {'j','J'}, - {'k','K'}, - {'l','L'}, - {':',';'}, - {'\'','"'} - }, - - { - {'z','Z'}, - {'x','X'}, - {'c','C'}, - {'v','V'}, - {'b','B'}, - {'n','N'}, - {'m','M'}, - {',','<'}, - {'.','>'}, - {'/','?'}, - {'\0','\0'} - } - }; - - memcpy(keys, thekeys, sizeof(thekeys));} - //DVORAK// - if (mode == 1){ - Key thekeys[4][11] = { - { - {'1','!','\0'}, - {'2','@','\0'}, - {'3','#','\0'}, - {'4','$','\0'}, - {'5','%','\0'}, - {'6','^','\0'}, - {'7','&','\0'}, - {'8','*','\0'}, - {'9','(','\0'}, - {'0',')','\0'}, - {'\0','\0','\0'} - }, - { - {'\'','"','\0'}, - {',','<','\0'}, - {'.','>','\0'}, - {'p','P','\0'}, - {'y','Y','\0'}, - {'f','F','\0'}, - {'g','G','\0'}, - {'c','C','\0'}, - {'r','R','\0'}, - {'l','L','\0'}, - {'/','?','\0'} - }, - { - {'a','A','m'}, - {'o','O','m'}, - {'e','E','m'}, - {'u','U','m'}, - {'i','I','m'}, - {'d','D','m'}, - {'h','H','m'}, - {'t','T','m'}, - {'n','N','m'}, - {'s','S','m'}, - {'-','_','m'} - }, - - { - {';',':','\0'}, - {'q','Q','\0'}, - {'j','J','\0'}, - {'k','K','\0'}, - {'x','X','\0'}, - {'b','B','\0'}, - {'m','M','\0'}, - {'w','W','\0'}, - {'v','V','\0'}, - {'z','Z','\0'}, - {'\0','\0','\0'} - } - }; - memcpy(keys, thekeys, sizeof(thekeys));} - //QWETRZ// - if (mode == 2){ - Key thekeys[4][11] = { - { - {'1','!','^','À'}, - {'2','"','²','à'}, - {'3','#','³','È'}, - {'4','$','«','è'}, - {'5','%','»','Ì'}, - {'6','&','„','ì'}, - {'7','/','”','Ò'}, - {'8','(','[','ò'}, - {'9',')',']','Ù'}, - {'0','=','§','ù'}, - {'ß','?','\'','Ý'} - }, - { - {'q','Q','@','Á'}, - {'w','W','\0','á'}, - {'e','E','€','É'}, - {'r','R','\0','é'}, - {'t','T','\0','Í'}, - {'z','Z','\0','í'}, - {'u','U','\0','Ó'}, - {'i','I','\0','ó'}, - {'o','O','\0','Ú'}, - {'p','P','\0','ú'}, - {'ü','Ü','\0','ý'} - }, - { - {'a','A','\0','Â'}, - {'s','S','\0','â'}, - {'d','D','\0','Ê'}, - {'f','F','\0','ê'}, - {'g','G','\0','Î'}, - {'h','H','\0','î'}, - {'j','J','\0','Ô'}, - {'k','K','\0','ô'}, - {'l','L','\0','Û'}, - {'ö','Ö','\0','û'}, - {'ä','Ä','\0','Ÿ'} - }, - { - {'<','>','|','Ã'}, - {'y','Y','\0','ã'}, - {'x','X','\0','Ñ'}, - {'c','C','ç','ñ'}, - {'v','V','©','Ï'}, - {'b','B','\0','ï'}, - {'n','N','\0','Õ'}, - {'m','M','µ','õ'}, - {',',';','\0','ÿ'}, - {'.',':','\0','\0'}, - {'-','_','\0','\0'} - } - }; - memcpy(keys, thekeys, sizeof(thekeys));} - //AZERTY// - if (mode == 3){ - Key thekeys[4][11] = { + width = 540; + height = 400; + shift = 0; + caps = 0; + alt = 0; + alt2 = 0; + m = min; + int mode = lang; + selectable = true; + focus = 0; // allow focus + alignmentHor = ALIGN_CENTRE; + alignmentVert = ALIGN_MIDDLE; + kbtextmaxlen = max > sizeof( kbtextstr ) ? sizeof( kbtextstr ) : max; // limit max up to sizeof(kbtextstr) +// strlcpy(kbtextstr, t, kbtextmaxlen); + strncpy( kbtextstr, t, kbtextmaxlen ); // strncpy is needed to fill the rest with \0 + kbtextstr[sizeof( kbtextstr )-1] = 0; // terminate with \0 + //QWERTY// + if ( mode == 0 ) { - {'1','&','²','À'}, - {'2','~','³','é'}, - {'3','"','#','È'}, - {'4','`','«','ù'}, - {'5','(','[','Ì'}, - {'6','-','|','ì'}, - {'7','µ','»','è'}, - {'8','_','\'','ò'}, - {'9','+','^','ç'}, - {'0','=','@','à'}, - {'°',')',']','Ý'} - }, - { - {'a','A','Æ','Á'}, - {'z','Z','Œ','á'}, - {'e','E','€','É'}, - {'r','R','®','ë'}, - {'t','T','†','Í'}, - {'y','Y','ÿ','í'}, - {'u','U','Õ','Ó'}, - {'i','I','õ','Ò'}, - {'o','O','Ø','Ú'}, - {'p','P','ø','ú'}, - {'$','£','¤','ý'} - }, - { - {'q','Q','æ','Â'}, - {'s','S','œ','â'}, - {'d','D','\0','Ê'}, - {'f','F','ß','ê'}, - {'g','G','\0','Î'}, - {'h','H','\0','î'}, - {'j','J','\0','Ô'}, - {'k','K','\0','ô'}, - {'l','L','\0','Û'}, - {'m','M','\0','û'}, - {'*','%','¬','Ù'} - }, - { - {'<','>','\0','Ã'}, - {'w','W','\0','Ä'}, - {'x','X','\0','Ë'}, - {'c','C','©','Ç'}, - {'v','V','“','Ï'}, - {'b','B','”','ï'}, - {'n','N','\0','Ñ'}, - {'?',',','?','ñ'}, - {'.',';','.','ó'}, - {'/',':','/','ö'}, - {'§','!','!','Ö'} - } - }; - memcpy(keys, thekeys, sizeof(thekeys));} - //QWERTY 2// - if (mode == 4){ - Key thekeys[4][11] = { - { - {'1','!','|','Á'}, - {'2','"','@','á'}, - {'3','·','#','À'}, - {'4','$','£','à'}, - {'5','%','~','É'}, - {'6','&','¬','é'}, - {'7','/','\'','È'}, - {'8','(','[','è'}, - {'9',')',']','Í'}, - {'0','=','¤','í'}, - {'¡','?','¿','Ï'} - }, - { - {'q','Q','\0','ï'}, - {'w','W','\0','Ó'}, - {'e','E','€','ó'}, - {'r','R','®','Ò'}, - {'t','T','†','ò'}, - {'y','Y','ÿ','Ú'}, - {'u','U','“','ú'}, - {'i','I','”','Ü'}, - {'o','O','Ø','ü'}, - {'p','P','ø','Ù'}, - {'+','*','\0','ù'} - }, - { - {'a','A','^','Ã'}, - {'s','S','²','ã'}, - {'d','D','³','Õ'}, - {'f','F','«','õ'}, - {'g','G','»','Ñ'}, - {'h','H','§','ñ'}, - {'j','J','µ','Ç'}, - {'k','K','¤','ç'}, - {'l','L','„','\0'}, - {'ñ','Ñ','+','\0'}, - {'ç','Ç','°','\0'} - }, - { - {'<','>','\0','Ä'}, - {'z','Z','\0','ä'}, - {'x','X','\0','Â'}, - {'c','C','©','â'}, - {'v','V','\0','å'}, - {'b','B','ß','Ë'}, - {'n','N','\0','ë'}, - {'m','M','\0','Ê'}, - {',',';','\0','ê'}, - {'.',':','\0','\0'}, - {'-','_','\0','\0'} - } - }; - memcpy(keys, thekeys, sizeof(thekeys));} - - keyTextbox = new GuiImageData(keyboard_textbox_png); - keyTextboxImg = new GuiImage(keyTextbox); - keyTextboxImg->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - keyTextboxImg->SetPosition(0, 40);//(0,0); - this->Append(keyTextboxImg); + 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'}, + {':', ';'}, + {'\'', '"'} + }, - 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); + { + {'z', 'Z'}, + {'x', 'X'}, + {'c', 'C'}, + {'v', 'V'}, + {'b', 'B'}, + {'n', 'N'}, + {'m', 'M'}, + {',', '<'}, + {'.', '>'}, + {'/', '?'}, + {'\0', '\0'} + } + }; - 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); + memcpy( keys, thekeys, sizeof( thekeys ) ); + } + //DVORAK// + if ( mode == 1 ) + { + Key thekeys[4][11] = + { + { + {'1', '!', '\0'}, + {'2', '@', '\0'}, + {'3', '#', '\0'}, + {'4', '$', '\0'}, + {'5', '%', '\0'}, + {'6', '^', '\0'}, + {'7', '&', '\0'}, + {'8', '*', '\0'}, + {'9', '(', '\0'}, + {'0', ')', '\0'}, + {'\0', '\0', '\0'} + }, + { + {'\'', '"', '\0'}, + {',', '<', '\0'}, + {'.', '>', '\0'}, + {'p', 'P', '\0'}, + {'y', 'Y', '\0'}, + {'f', 'F', '\0'}, + {'g', 'G', '\0'}, + {'c', 'C', '\0'}, + {'r', 'R', '\0'}, + {'l', 'L', '\0'}, + {'/', '?', '\0'} + }, + { + {'a', 'A', 'm'}, + {'o', 'O', 'm'}, + {'e', 'E', 'm'}, + {'u', 'U', 'm'}, + {'i', 'I', 'm'}, + {'d', 'D', 'm'}, + {'h', 'H', 'm'}, + {'t', 'T', 'm'}, + {'n', 'N', 'm'}, + {'s', 'S', 'm'}, + {'-', '_', 'm'} + }, - keySoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - keySoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - trigB = new GuiTrigger; - trigB->SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - - int eurocheck = 0; - if(mode > 1) { - eurocheck = -20; + { + {';', ':', '\0'}, + {'q', 'Q', '\0'}, + {'j', 'J', '\0'}, + {'k', 'K', '\0'}, + {'x', 'X', '\0'}, + {'b', 'B', '\0'}, + {'m', 'M', '\0'}, + {'w', 'W', '\0'}, + {'v', 'V', '\0'}, + {'z', 'Z', '\0'}, + {'\0', '\0', '\0'} + } + }; + memcpy( keys, thekeys, sizeof( thekeys ) ); + } + //QWETRZ// + if ( mode == 2 ) + { + Key thekeys[4][11] = + { + { + {'1', '!', '^', 'À'}, + {'2', '"', '²', 'à'}, + {'3', '#', '³', 'È'}, + {'4', '$', '«', 'è'}, + {'5', '%', '»', 'Ì'}, + {'6', '&', '„', 'ì'}, + {'7', '/', '”', 'Ò'}, + {'8', '(', '[', 'ò'}, + {'9', ')', ']', 'Ù'}, + {'0', '=', '§', 'ù'}, + {'ß', '?', '\'', 'Ý'} + }, + { + {'q', 'Q', '@', 'Á'}, + {'w', 'W', '\0', 'á'}, + {'e', 'E', '€', 'É'}, + {'r', 'R', '\0', 'é'}, + {'t', 'T', '\0', 'Í'}, + {'z', 'Z', '\0', 'í'}, + {'u', 'U', '\0', 'Ó'}, + {'i', 'I', '\0', 'ó'}, + {'o', 'O', '\0', 'Ú'}, + {'p', 'P', '\0', 'ú'}, + {'ü', 'Ü', '\0', 'ý'} + }, + { + {'a', 'A', '\0', 'Â'}, + {'s', 'S', '\0', 'â'}, + {'d', 'D', '\0', 'Ê'}, + {'f', 'F', '\0', 'ê'}, + {'g', 'G', '\0', 'Î'}, + {'h', 'H', '\0', 'î'}, + {'j', 'J', '\0', 'Ô'}, + {'k', 'K', '\0', 'ô'}, + {'l', 'L', '\0', 'Û'}, + {'ö', 'Ö', '\0', 'û'}, + {'ä', 'Ä', '\0', 'Ÿ'} + }, + { + {'<', '>', '|', 'Ã'}, + {'y', 'Y', '\0', 'ã'}, + {'x', 'X', '\0', 'Ñ'}, + {'c', 'C', 'ç', 'ñ'}, + {'v', 'V', '©', 'Ï'}, + {'b', 'B', '\0', 'ï'}, + {'n', 'N', '\0', 'Õ'}, + {'m', 'M', 'µ', 'õ'}, + {',', ';', '\0', 'ÿ'}, + {'.', ':', '\0', '\0'}, + {'-', '_', '\0', '\0'} + } + }; + memcpy( keys, thekeys, sizeof( thekeys ) ); + } + //AZERTY// + if ( mode == 3 ) + { + Key thekeys[4][11] = + { + { + {'1', '&', '²', 'À'}, + {'2', '~', '³', 'é'}, + {'3', '"', '#', 'È'}, + {'4', '`', '«', 'ù'}, + {'5', '(', '[', 'Ì'}, + {'6', '-', '|', 'ì'}, + {'7', 'µ', '»', 'è'}, + {'8', '_', '\'', 'ò'}, + {'9', '+', '^', 'ç'}, + {'0', '=', '@', 'à'}, + {'°', ')', ']', 'Ý'} + }, + { + {'a', 'A', 'Æ', 'Á'}, + {'z', 'Z', 'Œ', 'á'}, + {'e', 'E', '€', 'É'}, + {'r', 'R', '®', 'ë'}, + {'t', 'T', '†', 'Í'}, + {'y', 'Y', 'ÿ', 'í'}, + {'u', 'U', 'Õ', 'Ó'}, + {'i', 'I', 'õ', 'Ò'}, + {'o', 'O', 'Ø', 'Ú'}, + {'p', 'P', 'ø', 'ú'}, + {'$', '£', '¤', 'ý'} + }, + { + {'q', 'Q', 'æ', 'Â'}, + {'s', 'S', 'œ', 'â'}, + {'d', 'D', '\0', 'Ê'}, + {'f', 'F', 'ß', 'ê'}, + {'g', 'G', '\0', 'Î'}, + {'h', 'H', '\0', 'î'}, + {'j', 'J', '\0', 'Ô'}, + {'k', 'K', '\0', 'ô'}, + {'l', 'L', '\0', 'Û'}, + {'m', 'M', '\0', 'û'}, + {'*', '%', '¬', 'Ù'} + }, + { + {'<', '>', '\0', 'Ã'}, + {'w', 'W', '\0', 'Ä'}, + {'x', 'X', '\0', 'Ë'}, + {'c', 'C', '©', 'Ç'}, + {'v', 'V', '“', 'Ï'}, + {'b', 'B', '”', 'ï'}, + {'n', 'N', '\0', 'Ñ'}, + {'?', ',', '?', 'ñ'}, + {'.', ';', '.', 'ó'}, + {'/', ':', '/', 'ö'}, + {'§', '!', '!', 'Ö'} + } + }; + memcpy( keys, thekeys, sizeof( thekeys ) ); + } + //QWERTY 2// + if ( mode == 4 ) + { + Key thekeys[4][11] = + { + { + {'1', '!', '|', 'Á'}, + {'2', '"', '@', 'á'}, + {'3', '·', '#', 'À'}, + {'4', '$', '£', 'à'}, + {'5', '%', '~', 'É'}, + {'6', '&', '¬', 'é'}, + {'7', '/', '\'', 'È'}, + {'8', '(', '[', 'è'}, + {'9', ')', ']', 'Í'}, + {'0', '=', '¤', 'í'}, + {'¡', '?', '¿', 'Ï'} + }, + { + {'q', 'Q', '\0', 'ï'}, + {'w', 'W', '\0', 'Ó'}, + {'e', 'E', '€', 'ó'}, + {'r', 'R', '®', 'Ò'}, + {'t', 'T', '†', 'ò'}, + {'y', 'Y', 'ÿ', 'Ú'}, + {'u', 'U', '“', 'ú'}, + {'i', 'I', '”', 'Ü'}, + {'o', 'O', 'Ø', 'ü'}, + {'p', 'P', 'ø', 'Ù'}, + {'+', '*', '\0', 'ù'} + }, + { + {'a', 'A', '^', 'Ã'}, + {'s', 'S', '²', 'ã'}, + {'d', 'D', '³', 'Õ'}, + {'f', 'F', '«', 'õ'}, + {'g', 'G', '»', 'Ñ'}, + {'h', 'H', '§', 'ñ'}, + {'j', 'J', 'µ', 'Ç'}, + {'k', 'K', '¤', 'ç'}, + {'l', 'L', '„', '\0'}, + {'ñ', 'Ñ', '+', '\0'}, + {'ç', 'Ç', '°', '\0'} + }, + { + {'<', '>', '\0', 'Ä'}, + {'z', 'Z', '\0', 'ä'}, + {'x', 'X', '\0', 'Â'}, + {'c', 'C', '©', 'â'}, + {'v', 'V', '\0', 'å'}, + {'b', 'B', 'ß', 'Ë'}, + {'n', 'N', '\0', 'ë'}, + {'m', 'M', '\0', 'Ê'}, + {',', ';', '\0', 'ê'}, + {'.', ':', '\0', '\0'}, + {'-', '_', '\0', '\0'} + } + }; + memcpy( keys, thekeys, sizeof( thekeys ) ); } - keyBackImg = new GuiImage(keyMedium); - keyBackOverImg = new GuiImage(keyMediumOver); - if (mode == 3){ - keyBackText = new GuiText("Retour", 20, (GXColor){0, 0, 0, 0xff});} - else { - keyBackText = new GuiText("Back", 20, (GXColor){0, 0, 0, 0xff});} - //GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow); + 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 ); - //keyBack = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); - keyBack = new GuiButton(keyBackImg, keyBackOverImg, 0, 3, 11*42+40+eurocheck, 0*42+120, trigA, keySoundOver, keySoundClick,1); - //keyBack->SetImage(keyBackImg); - //keyBack->SetImageOver(keyBackOverImg); - keyBack->SetLabel(keyBackText); - //keyBack->SetSoundOver(keySoundOver); - //keyBack->SetSoundClick(keySoundClick); - //keyBack->SetTrigger(trigA); - keyBack->SetTrigger(trigB); - if (mode > 1){ - keyBack->SetPosition(11*42+40+eurocheck, 0*42+120);} - else{ - keyBack->SetPosition(10*42+40+eurocheck, 0*42+120);}//(10*42+40, 0*42+80); - //keyBack->SetEffectGrow(); - this->Append(keyBack); + 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 ); - keyClearImg = new GuiImage(keyMedium); - keyClearOverImg = new GuiImage(keyMediumOver); - if (mode == 3){ - keyClearText = new GuiText("Effacer", 20, (GXColor){0, 0, 0, 0xff});} - else { - keyClearText = new GuiText("Clear", 20, (GXColor){0, 0, 0, 0xff});} - keyClear = new GuiButton(keyClearImg, keyClearOverImg, 0, 3, (10*42+40)+eurocheck, 4*42+120, trigA, keySoundOver, keySoundClick,1); - //keyClear = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); - //keyClear->SetImage(keyClearImg); - //keyClear->SetImageOver(keyClearOverImg); - keyClear->SetLabel(keyClearText); - //keyClear->SetSoundOver(keySoundOver); - //keyClear->SetSoundClick(keySoundClick); - //keyClear->SetTrigger(trigA); - //keyClear->SetPosition((10*42+40)+eurocheck, 4*42+120);//(10*42+40, 0*42+80); - //keyClear->SetEffectGrow(); - this->Append(keyClear); + 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 ); - keyAltImg = new GuiImage(keyMedium); - keyAltOverImg = new GuiImage(keyMediumOver); - keyAltText = new GuiText("Alt Gr", 20, (GXColor){0, 0, 0, 0xff}); - keyAlt = new GuiButton(keyAltImg, keyAltOverImg, 0, 3, 84+eurocheck, 4*42+120, trigA, keySoundOver, keySoundClick,1); - //keyAlt = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); - //keyAlt->SetImage(keyAltImg); - //keyAlt->SetImageOver(keyAltOverImg); - keyAlt->SetLabel(keyAltText); - //keyAlt->SetSoundOver(keySoundOver); - //keyAlt->SetSoundClick(keySoundClick); - //keyAlt->SetTrigger(trigA); - //keyAlt->SetPosition(84+eurocheck, 4*42+120);//(10*42+40, 4*42+120); - //keyAlt->SetEffectGrow(); - if (mode > 1){this->Append(keyAlt);} + keySoundOver = new GuiSound( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + keySoundClick = new GuiSound( button_click_pcm, button_click_pcm_size, Settings.sfxvolume ); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigB = new GuiTrigger; + trigB->SetButtonOnlyTrigger( -1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B ); - keyAlt2Img = new GuiImage(keyMedium); - keyAlt2OverImg = new GuiImage(keyMediumOver); - keyAlt2Text = new GuiText("Accent", 20, (GXColor){0, 0, 0, 0xff}); - keyAlt2 = new GuiButton(keyAlt2Img, keyAlt2OverImg, 0, 3, (8*42+40)+eurocheck, 4*42+120, trigA, keySoundOver, keySoundClick,1); - //keyAlt2 = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); - //keyAlt2->SetImage(keyAlt2Img); - //keyAlt2->SetImageOver(keyAlt2OverImg); - keyAlt2->SetLabel(keyAlt2Text); - //keyAlt2->SetSoundOver(keySoundOver); - //keyAlt2->SetSoundClick(keySoundClick); - //keyAlt2->SetTrigger(trigA); - //keyAlt2->SetPosition((8*42+40)+eurocheck, 4*42+120);//(10*42+40, 4*42+120); - //keyAlt2->SetEffectGrow(); - if (mode > 1){this->Append(keyAlt2);} + int eurocheck = 0; + if ( mode > 1 ) + { + eurocheck = -20; + } - keyCapsImg = new GuiImage(keyMedium); - keyCapsOverImg = new GuiImage(keyMediumOver); - keyCapsText = new GuiText("Caps", 20, (GXColor){0, 0, 0, 0xff}); - keyCaps = new GuiButton(keyCapsImg, keyCapsOverImg, 0, 3, 0+eurocheck, 2*42+120, trigA, keySoundOver, keySoundClick,1); - //keyCaps = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); - //keyCaps->SetImage(keyCapsImg); - //keyCaps->SetImageOver(keyCapsOverImg); - keyCaps->SetLabel(keyCapsText); - //keyCaps->SetSoundOver(keySoundOver); - //keyCaps->SetSoundClick(keySoundClick); - //keyCaps->SetTrigger(trigA); - //keyCaps->SetPosition(0+eurocheck, 2*42+120);//(0, 2*42+80); - //keyCaps->SetEffectGrow(); - this->Append(keyCaps); + keyBackImg = new GuiImage( keyMedium ); + keyBackOverImg = new GuiImage( keyMediumOver ); + if ( mode == 3 ) + { + keyBackText = new GuiText( "Retour", 20, ( GXColor ) {0, 0, 0, 0xff} ); + } + else + { + keyBackText = new GuiText( "Back", 20, ( GXColor ) {0, 0, 0, 0xff} ); + } + //GuiButton(GuiImage* img, GuiImage* imgOver, int hor, int vert, int x, int y, GuiTrigger* trig, GuiSound* sndOver, GuiSound* sndClick, u8 grow); - keyShiftImg = new GuiImage(keyMedium); - keyShiftOverImg = new GuiImage(keyMediumOver); - keyShiftText = new GuiText("Shift", 20, (GXColor){0, 0, 0, 0xff}); - keyShift = new GuiButton(keyShiftImg, keyShiftOverImg, 0, 3, 21+eurocheck, 3*42+120, trigA, keySoundOver, keySoundClick,1); - //keyShift = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); - //keyShift->SetImage(keyShiftImg); - //keyShift->SetImageOver(keyShiftOverImg); - keyShift->SetLabel(keyShiftText); - //keyShift->SetSoundOver(keySoundOver); - //keyShift->SetSoundClick(keySoundClick); - //keyShift->SetTrigger(trigA); - //keyShift->SetPosition(21+eurocheck, 3*42+120);//(21, 3*42+80); - //keyShift->SetEffectGrow(); - this->Append(keyShift); + //keyBack = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); + keyBack = new GuiButton( keyBackImg, keyBackOverImg, 0, 3, 11*42 + 40 + eurocheck, 0*42 + 120, trigA, keySoundOver, keySoundClick, 1 ); + //keyBack->SetImage(keyBackImg); + //keyBack->SetImageOver(keyBackOverImg); + keyBack->SetLabel( keyBackText ); + //keyBack->SetSoundOver(keySoundOver); + //keyBack->SetSoundClick(keySoundClick); + //keyBack->SetTrigger(trigA); + keyBack->SetTrigger( trigB ); + if ( mode > 1 ) + { + keyBack->SetPosition( 11*42 + 40 + eurocheck, 0*42 + 120 ); + } + else + { + keyBack->SetPosition( 10*42 + 40 + eurocheck, 0*42 + 120 ); + }//(10*42+40, 0*42+80); + //keyBack->SetEffectGrow(); + this->Append( keyBack ); - keySpaceImg = new GuiImage(keyLarge); - keySpaceOverImg = new GuiImage(keyLargeOver); - keySpace = new GuiButton(keySpaceImg, keySpaceOverImg, 2, 3, 0+eurocheck, 4*42+120, trigA, keySoundOver, keySoundClick,1); - //keySpace = new GuiButton(keyLarge->GetWidth(), keyLarge->GetHeight()); - //keySpace->SetImage(keySpaceImg); - //keySpace->SetImageOver(keySpaceOverImg); - //keySpace->SetSoundOver(keySoundOver); - //keySpace->SetSoundClick(keySoundClick); - //keySpace->SetTrigger(trigA); - //keySpace->SetPosition(0+eurocheck, 4*42+120);//(0, 4*42+80); - //keySpace->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - //keySpace->SetEffectGrow(); - this->Append(keySpace); + keyClearImg = new GuiImage( keyMedium ); + keyClearOverImg = new GuiImage( keyMediumOver ); + if ( mode == 3 ) + { + keyClearText = new GuiText( "Effacer", 20, ( GXColor ) {0, 0, 0, 0xff} ); + } + else + { + keyClearText = new GuiText( "Clear", 20, ( GXColor ) {0, 0, 0, 0xff} ); + } + keyClear = new GuiButton( keyClearImg, keyClearOverImg, 0, 3, ( 10*42 + 40 ) + eurocheck, 4*42 + 120, trigA, keySoundOver, keySoundClick, 1 ); + //keyClear = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); + //keyClear->SetImage(keyClearImg); + //keyClear->SetImageOver(keyClearOverImg); + keyClear->SetLabel( keyClearText ); + //keyClear->SetSoundOver(keySoundOver); + //keyClear->SetSoundClick(keySoundClick); + //keyClear->SetTrigger(trigA); + //keyClear->SetPosition((10*42+40)+eurocheck, 4*42+120);//(10*42+40, 0*42+80); + //keyClear->SetEffectGrow(); + this->Append( keyClear ); - char txt[2] = { 0, 0 }; - for(int i=0; i<4; i++) - { - for(int j=0; j<11; j++) - { - if(keys[i][j].ch != '\0') - { - keyImg[i][j] = new GuiImage(key); - keyImgOver[i][j] = new GuiImage(keyOver); - txt[0] = keys[i][j].ch; - keyTxt[i][j] = new GuiText(txt, 20, (GXColor){0, 0, 0, 0xff}); - keyTxt[i][j]->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - keyTxt[i][j]->SetPosition(0, -10); - keyBtn[i][j] = new GuiButton(keyImg[i][j], keyImgOver[i][j], 0, 3, (j*42+21*i+40)+eurocheck, i*42+120, trigA, keySoundOver, keySoundClick,1); - //keyBtn[i][j] = new GuiButton(key->GetWidth(), key->GetHeight()); - //keyBtn[i][j]->SetImage(keyImg[i][j]); - //keyBtn[i][j]->SetImageOver(keyImgOver[i][j]); - //keyBtn[i][j]->SetSoundOver(keySoundOver); - //keyBtn[i][j]->SetSoundClick(keySoundClick); - //keyBtn[i][j]->SetTrigger(trigA); - keyBtn[i][j]->SetLabel(keyTxt[i][j]); - //keyBtn[i][j]->SetPosition((j*42+21*i+40)+eurocheck, i*42+120);//SetPosition(j*42+21*i+40, i*42+80); - //keyBtn[i][j]->SetEffectGrow(); - this->Append(keyBtn[i][j]); - } - } - } + keyAltImg = new GuiImage( keyMedium ); + keyAltOverImg = new GuiImage( keyMediumOver ); + keyAltText = new GuiText( "Alt Gr", 20, ( GXColor ) {0, 0, 0, 0xff} ); + keyAlt = new GuiButton( keyAltImg, keyAltOverImg, 0, 3, 84 + eurocheck, 4*42 + 120, trigA, keySoundOver, keySoundClick, 1 ); + //keyAlt = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); + //keyAlt->SetImage(keyAltImg); + //keyAlt->SetImageOver(keyAltOverImg); + keyAlt->SetLabel( keyAltText ); + //keyAlt->SetSoundOver(keySoundOver); + //keyAlt->SetSoundClick(keySoundClick); + //keyAlt->SetTrigger(trigA); + //keyAlt->SetPosition(84+eurocheck, 4*42+120);//(10*42+40, 4*42+120); + //keyAlt->SetEffectGrow(); + if ( mode > 1 ) {this->Append( keyAlt );} + + keyAlt2Img = new GuiImage( keyMedium ); + keyAlt2OverImg = new GuiImage( keyMediumOver ); + keyAlt2Text = new GuiText( "Accent", 20, ( GXColor ) {0, 0, 0, 0xff} ); + keyAlt2 = new GuiButton( keyAlt2Img, keyAlt2OverImg, 0, 3, ( 8*42 + 40 ) + eurocheck, 4*42 + 120, trigA, keySoundOver, keySoundClick, 1 ); + //keyAlt2 = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); + //keyAlt2->SetImage(keyAlt2Img); + //keyAlt2->SetImageOver(keyAlt2OverImg); + keyAlt2->SetLabel( keyAlt2Text ); + //keyAlt2->SetSoundOver(keySoundOver); + //keyAlt2->SetSoundClick(keySoundClick); + //keyAlt2->SetTrigger(trigA); + //keyAlt2->SetPosition((8*42+40)+eurocheck, 4*42+120);//(10*42+40, 4*42+120); + //keyAlt2->SetEffectGrow(); + if ( mode > 1 ) {this->Append( keyAlt2 );} + + keyCapsImg = new GuiImage( keyMedium ); + keyCapsOverImg = new GuiImage( keyMediumOver ); + keyCapsText = new GuiText( "Caps", 20, ( GXColor ) {0, 0, 0, 0xff} ); + keyCaps = new GuiButton( keyCapsImg, keyCapsOverImg, 0, 3, 0 + eurocheck, 2*42 + 120, trigA, keySoundOver, keySoundClick, 1 ); + //keyCaps = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); + //keyCaps->SetImage(keyCapsImg); + //keyCaps->SetImageOver(keyCapsOverImg); + keyCaps->SetLabel( keyCapsText ); + //keyCaps->SetSoundOver(keySoundOver); + //keyCaps->SetSoundClick(keySoundClick); + //keyCaps->SetTrigger(trigA); + //keyCaps->SetPosition(0+eurocheck, 2*42+120);//(0, 2*42+80); + //keyCaps->SetEffectGrow(); + this->Append( keyCaps ); + + keyShiftImg = new GuiImage( keyMedium ); + keyShiftOverImg = new GuiImage( keyMediumOver ); + keyShiftText = new GuiText( "Shift", 20, ( GXColor ) {0, 0, 0, 0xff} ); + keyShift = new GuiButton( keyShiftImg, keyShiftOverImg, 0, 3, 21 + eurocheck, 3*42 + 120, trigA, keySoundOver, keySoundClick, 1 ); + //keyShift = new GuiButton(keyMedium->GetWidth(), keyMedium->GetHeight()); + //keyShift->SetImage(keyShiftImg); + //keyShift->SetImageOver(keyShiftOverImg); + keyShift->SetLabel( keyShiftText ); + //keyShift->SetSoundOver(keySoundOver); + //keyShift->SetSoundClick(keySoundClick); + //keyShift->SetTrigger(trigA); + //keyShift->SetPosition(21+eurocheck, 3*42+120);//(21, 3*42+80); + //keyShift->SetEffectGrow(); + this->Append( keyShift ); + + keySpaceImg = new GuiImage( keyLarge ); + keySpaceOverImg = new GuiImage( keyLargeOver ); + keySpace = new GuiButton( keySpaceImg, keySpaceOverImg, 2, 3, 0 + eurocheck, 4*42 + 120, trigA, keySoundOver, keySoundClick, 1 ); + //keySpace = new GuiButton(keyLarge->GetWidth(), keyLarge->GetHeight()); + //keySpace->SetImage(keySpaceImg); + //keySpace->SetImageOver(keySpaceOverImg); + //keySpace->SetSoundOver(keySoundOver); + //keySpace->SetSoundClick(keySoundClick); + //keySpace->SetTrigger(trigA); + //keySpace->SetPosition(0+eurocheck, 4*42+120);//(0, 4*42+80); + //keySpace->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + //keySpace->SetEffectGrow(); + this->Append( keySpace ); + + char txt[2] = { 0, 0 }; + for ( int i = 0; i < 4; i++ ) + { + for ( int j = 0; j < 11; j++ ) + { + if ( keys[i][j].ch != '\0' ) + { + keyImg[i][j] = new GuiImage( key ); + keyImgOver[i][j] = new GuiImage( keyOver ); + txt[0] = keys[i][j].ch; + keyTxt[i][j] = new GuiText( txt, 20, ( GXColor ) {0, 0, 0, 0xff} ); + keyTxt[i][j]->SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); + keyTxt[i][j]->SetPosition( 0, -10 ); + keyBtn[i][j] = new GuiButton( keyImg[i][j], keyImgOver[i][j], 0, 3, ( j*42 + 21*i + 40 ) + eurocheck, i*42 + 120, trigA, keySoundOver, keySoundClick, 1 ); + //keyBtn[i][j] = new GuiButton(key->GetWidth(), key->GetHeight()); + //keyBtn[i][j]->SetImage(keyImg[i][j]); + //keyBtn[i][j]->SetImageOver(keyImgOver[i][j]); + //keyBtn[i][j]->SetSoundOver(keySoundOver); + //keyBtn[i][j]->SetSoundClick(keySoundClick); + //keyBtn[i][j]->SetTrigger(trigA); + keyBtn[i][j]->SetLabel( keyTxt[i][j] ); + //keyBtn[i][j]->SetPosition((j*42+21*i+40)+eurocheck, i*42+120);//SetPosition(j*42+21*i+40, i*42+80); + //keyBtn[i][j]->SetEffectGrow(); + this->Append( keyBtn[i][j] ); + } + } + } } /** @@ -505,187 +533,190 @@ GuiKeyboard::GuiKeyboard(char * t, u32 max, int min, int lang) */ GuiKeyboard::~GuiKeyboard() { - delete kbText; - delete keyTextbox; - delete keyTextboxImg; - delete keyCapsText; - delete keyCapsImg; - delete keyCapsOverImg; - delete keyCaps; - delete keyShiftText; - delete keyShiftImg; - delete keyShiftOverImg; - delete keyShift; - if (keyAlt) - {delete keyAlt;} - if (keyAlt2) - {delete keyAlt2;} - delete keyBackText; - delete keyBackImg; - delete keyBackOverImg; - delete keyBack; - delete keySpaceImg; - delete keySpaceOverImg; - delete keySpace; - delete key; - delete keyOver; - delete keyMedium; - delete keyMediumOver; - delete keyLarge; - delete keyLargeOver; - delete keySoundOver; - delete keySoundClick; - delete trigA; - delete trigB; + delete kbText; + delete keyTextbox; + delete keyTextboxImg; + delete keyCapsText; + delete keyCapsImg; + delete keyCapsOverImg; + delete keyCaps; + delete keyShiftText; + delete keyShiftImg; + delete keyShiftOverImg; + delete keyShift; + if ( keyAlt ) + {delete keyAlt;} + if ( keyAlt2 ) + {delete keyAlt2;} + delete keyBackText; + delete keyBackImg; + delete keyBackOverImg; + delete keyBack; + delete keySpaceImg; + delete keySpaceOverImg; + delete keySpace; + delete key; + delete keyOver; + delete keyMedium; + delete keyMediumOver; + delete keyLarge; + delete keyLargeOver; + delete keySoundOver; + delete keySoundClick; + delete trigA; + delete trigB; - for(int i=0; i<4; i++) - { - for(int j=0; j<11; j++) - { - if(keys[i][j].ch != '\0') - { - delete keyImg[i][j]; - delete keyImgOver[i][j]; - delete keyTxt[i][j]; - delete keyBtn[i][j]; - } - } - } + for ( int i = 0; i < 4; i++ ) + { + for ( int j = 0; j < 11; j++ ) + { + if ( keys[i][j].ch != '\0' ) + { + delete keyImg[i][j]; + delete keyImgOver[i][j]; + delete keyTxt[i][j]; + delete keyBtn[i][j]; + } + } + } } -void GuiKeyboard::Update(GuiTrigger * t) +void GuiKeyboard::Update( GuiTrigger * t ) { - LOCK(this); - if(_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) - return; + LOCK( this ); + if ( _elements.size() == 0 || ( state == STATE_DISABLED && parentElement ) ) + return; - for (u8 i = 0; i < _elements.size(); i++) - { - try { _elements.at(i)->Update(t); } - catch (const std::exception& e) { } - } + for ( u8 i = 0; i < _elements.size(); i++ ) + { + try { _elements.at( i )->Update( t ); } + catch ( const std::exception& e ) { } + } - bool changedShiftKey = false; - - if(keySpace->GetState() == STATE_CLICKED) - { - if(strlen(kbtextstr) < kbtextmaxlen-1) // -1 --> kbtextmaxlen means with terminating '\0' - { - kbtextstr[strlen(kbtextstr)] = ' '; - kbText->SetText(kbtextstr); - } - keySpace->SetState(STATE_SELECTED, t->chan); - } - else if(keyBack->GetState() == STATE_CLICKED) - { - if (strlen(kbtextstr) >(m)){ - kbtextstr[strlen(kbtextstr)-1] = 0; - kbText->SetText(kbtextstr); - } - keyBack->SetState(STATE_SELECTED, t->chan); - } - else if(keyClear->GetState() == STATE_CLICKED) - { - while (strlen(kbtextstr) >(m)){ - kbtextstr[strlen(kbtextstr)-1] = 0; - kbText->SetText(kbtextstr); - } - keyClear->SetState(STATE_SELECTED, t->chan); - } - else if(keyShift->GetState() == STATE_CLICKED) - { - changedShiftKey =true; - shift ^= 1; - if(alt) alt ^= 1; - if(alt2) alt2 ^= 1; - keyShift->SetState(STATE_SELECTED, t->chan); - } - else if(keyAlt->GetState() == STATE_CLICKED) - { - changedShiftKey =true; - alt ^= 1; - if(shift) shift ^= 1; - if(alt2) alt2 ^= 1; - keyAlt->SetState(STATE_SELECTED, t->chan); - } - else if(keyAlt2->GetState() == STATE_CLICKED) - { - changedShiftKey =true; - alt2 ^= 1; - if(shift) shift ^= 1; - if(alt) alt ^= 1; - keyAlt2->SetState(STATE_SELECTED, t->chan); - } - else if(keyCaps->GetState() == STATE_CLICKED) - { - changedShiftKey =true; - caps ^= 1; - keyCaps->SetState(STATE_SELECTED, t->chan); - } + bool changedShiftKey = false; + + if ( keySpace->GetState() == STATE_CLICKED ) + { + if ( strlen( kbtextstr ) < kbtextmaxlen - 1 ) // -1 --> kbtextmaxlen means with terminating '\0' + { + kbtextstr[strlen( kbtextstr )] = ' '; + kbText->SetText( kbtextstr ); + } + keySpace->SetState( STATE_SELECTED, t->chan ); + } + else if ( keyBack->GetState() == STATE_CLICKED ) + { + if ( strlen( kbtextstr ) > ( m ) ) + { + kbtextstr[strlen( kbtextstr )-1] = 0; + kbText->SetText( kbtextstr ); + } + keyBack->SetState( STATE_SELECTED, t->chan ); + } + else if ( keyClear->GetState() == STATE_CLICKED ) + { + while ( strlen( kbtextstr ) > ( m ) ) + { + kbtextstr[strlen( kbtextstr )-1] = 0; + kbText->SetText( kbtextstr ); + } + keyClear->SetState( STATE_SELECTED, t->chan ); + } + else if ( keyShift->GetState() == STATE_CLICKED ) + { + changedShiftKey = true; + shift ^= 1; + if ( alt ) alt ^= 1; + if ( alt2 ) alt2 ^= 1; + keyShift->SetState( STATE_SELECTED, t->chan ); + } + else if ( keyAlt->GetState() == STATE_CLICKED ) + { + changedShiftKey = true; + alt ^= 1; + if ( shift ) shift ^= 1; + if ( alt2 ) alt2 ^= 1; + keyAlt->SetState( STATE_SELECTED, t->chan ); + } + else if ( keyAlt2->GetState() == STATE_CLICKED ) + { + changedShiftKey = true; + alt2 ^= 1; + if ( shift ) shift ^= 1; + if ( alt ) alt ^= 1; + keyAlt2->SetState( STATE_SELECTED, t->chan ); + } + else if ( keyCaps->GetState() == STATE_CLICKED ) + { + changedShiftKey = true; + caps ^= 1; + keyCaps->SetState( STATE_SELECTED, t->chan ); + } - bool update = false; + bool update = false; - char txt[2] = { 0, 0 }; - - do - { - update = false; - for(int i=0; i<4; i++) - { - for(int j=0; j<11; j++) - { - if(keys[i][j].ch != '\0') - { - if(shift || caps) - txt[0] = keys[i][j].chShift; - else if(alt) - txt[0] = keys[i][j].chalt; - else if(alt2) - txt[0] = keys[i][j].chalt2; - else - txt[0] = keys[i][j].ch; + char txt[2] = { 0, 0 }; - if(changedShiftKey) // change text only if needed - keyTxt[i][j]->SetText(txt); + do + { + update = false; + for ( int i = 0; i < 4; i++ ) + { + for ( int j = 0; j < 11; j++ ) + { + if ( keys[i][j].ch != '\0' ) + { + if ( shift || caps ) + txt[0] = keys[i][j].chShift; + else if ( alt ) + txt[0] = keys[i][j].chalt; + else if ( alt2 ) + txt[0] = keys[i][j].chalt2; + else + txt[0] = keys[i][j].ch; - if(keyBtn[i][j]->GetState() == STATE_CLICKED) - { - if(strlen(kbtextstr) < kbtextmaxlen-1) // -1 --> kbtextmaxlen means with term. '\0' - { - kbtextstr[strlen(kbtextstr)] = txt[0]; - kbText->SetText(kbtextstr); - } - keyBtn[i][j]->SetState(STATE_SELECTED, t->chan); - - if(shift || alt || alt2) - { - if(shift) shift ^= 1; - if(alt) alt ^= 1; - if(alt2) alt2 ^= 1; - update = true; - changedShiftKey = true; - } - } - } - } - } - } while(update); + if ( changedShiftKey ) // change text only if needed + keyTxt[i][j]->SetText( txt ); - kbText->SetPosition(0, 53); + if ( keyBtn[i][j]->GetState() == STATE_CLICKED ) + { + if ( strlen( kbtextstr ) < kbtextmaxlen - 1 ) // -1 --> kbtextmaxlen means with term. '\0' + { + kbtextstr[strlen( kbtextstr )] = txt[0]; + kbText->SetText( kbtextstr ); + } + keyBtn[i][j]->SetState( STATE_SELECTED, t->chan ); - this->ToggleFocus(t); + if ( shift || alt || alt2 ) + { + if ( shift ) shift ^= 1; + if ( alt ) alt ^= 1; + if ( alt2 ) alt2 ^= 1; + update = true; + changedShiftKey = true; + } + } + } + } + } + } + while ( update ); - 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); - } + kbText->SetPosition( 0, 53 ); + + this->ToggleFocus( t ); + + if ( focus ) // only send actions to this window if it's in focus + { + // pad/joystick navigation + if ( t->Right() ) + this->MoveSelectionHor( 1 ); + else if ( t->Left() ) + this->MoveSelectionHor( -1 ); + else if ( t->Down() ) + this->MoveSelectionVert( 1 ); + else if ( t->Up() ) + this->MoveSelectionVert( -1 ); + } } diff --git a/source/libwiigui/gui_numpad.cpp b/source/libwiigui/gui_numpad.cpp index 4970cbfc..07517eef 100644 --- a/source/libwiigui/gui_numpad.cpp +++ b/source/libwiigui/gui_numpad.cpp @@ -16,83 +16,83 @@ /** * Constructor for the GuiNumpad class. */ - - #define SAFEFREE(p) if(p){free(p);p=NULL;} - -GuiNumpad::GuiNumpad(char * t, u32 max) + +#define SAFEFREE(p) if(p){free(p);p=NULL;} + +GuiNumpad::GuiNumpad( char * t, u32 max ) { - width = 400; - height = 370; - selectable = true; - focus = 0; // allow focus - alignmentHor = ALIGN_CENTRE; - alignmentVert = ALIGN_MIDDLE; - kbtextmaxlen = max>sizeof(kbtextstr) ? sizeof(kbtextstr) : max; // limit max up to sizeof(kbtextstr) -// strlcpy(kbtextstr, t, kbtextmaxlen); - strncpy(kbtextstr, t, kbtextmaxlen); // strncpy is needed to fill the rest with \0 - kbtextstr[sizeof(kbtextstr)-1] = 0; // terminate with \0 + width = 400; + height = 370; + selectable = true; + focus = 0; // allow focus + alignmentHor = ALIGN_CENTRE; + alignmentVert = ALIGN_MIDDLE; + kbtextmaxlen = max > sizeof( kbtextstr ) ? sizeof( kbtextstr ) : max; // limit max up to sizeof(kbtextstr) +// strlcpy(kbtextstr, t, kbtextmaxlen); + strncpy( kbtextstr, t, kbtextmaxlen ); // strncpy is needed to fill the rest with \0 + kbtextstr[sizeof( kbtextstr )-1] = 0; // terminate with \0 - char thekeys[11] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '\0', '0' }; - memcpy(keys, thekeys, sizeof(thekeys)); - - keyTextbox = new GuiImageData(keyboard_textbox_png); - keyTextboxImg = new GuiImage(keyTextbox); - keyTextboxImg->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - keyTextboxImg->SetPosition(0, 40);//(0,0); - this->Append(keyTextboxImg); + char thekeys[11] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '\0', '0' }; + memcpy( keys, thekeys, sizeof( thekeys ) ); - 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); + 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 ); - keyMedium = new GuiImageData(keyboard_mediumkey_over_png); - keyMediumOver = new GuiImageData(keyboard_mediumkey_over_png); + 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 ); - keySoundOver = new GuiSound(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - keySoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - trigB = new GuiTrigger; - trigB->SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); + keyMedium = new GuiImageData( keyboard_mediumkey_over_png ); + keyMediumOver = new GuiImageData( keyboard_mediumkey_over_png ); - keyBackImg = new GuiImage(keyMedium); - keyBackOverImg = new GuiImage(keyMediumOver); - keyBackText = new GuiText("Back", 20, (GXColor){0, 0, 0, 0xff}); + keySoundOver = new GuiSound( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + keySoundClick = new GuiSound( button_click_pcm, button_click_pcm_size, Settings.sfxvolume ); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + trigB = new GuiTrigger; + trigB->SetButtonOnlyTrigger( -1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B ); - keyBack = new GuiButton(keyBackImg, keyBackOverImg, ALIGN_CENTRE, ALIGN_MIDDLE, 90, 80, trigA, keySoundOver, keySoundClick,1); - keyBack->SetLabel(keyBackText); - keyBack->SetTrigger(trigB); - this->Append(keyBack); + keyBackImg = new GuiImage( keyMedium ); + keyBackOverImg = new GuiImage( keyMediumOver ); + keyBackText = new GuiText( "Back", 20, ( GXColor ) {0, 0, 0, 0xff} ); - 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); + keyBack = new GuiButton( keyBackImg, keyBackOverImg, ALIGN_CENTRE, ALIGN_MIDDLE, 90, 80, trigA, keySoundOver, keySoundClick, 1 ); + keyBack->SetLabel( keyBackText ); + keyBack->SetTrigger( trigB ); + this->Append( keyBack ); - char txt[2] = { 0, 0 }; - for(int i=0; i<11; i++) - { - if (keys[i] != '\0') - { - int col = i % 3; - int row = i / 3; - - keyImg[i] = new GuiImage(keyMedium); - keyImgOver[i] = new GuiImage(keyMediumOver); - txt[0] = keys[i]; - keyTxt[i] = new GuiText(txt, 20, (GXColor){0, 0, 0, 0xff}); - keyTxt[i]->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - keyTxt[i]->SetPosition(0, -10); - keyBtn[i]= new GuiButton(keyImg[i], keyImgOver[i], ALIGN_CENTRE, ALIGN_MIDDLE, -90 + 90 * col, -70 + 50 * row, trigA, keySoundOver, keySoundClick, 1); - keyBtn[i]->SetLabel(keyTxt[i]); + 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 ); - this->Append(keyBtn[i]); - } - } + char txt[2] = { 0, 0 }; + for ( int i = 0; i < 11; i++ ) + { + if ( keys[i] != '\0' ) + { + int col = i % 3; + int row = i / 3; + + keyImg[i] = new GuiImage( keyMedium ); + keyImgOver[i] = new GuiImage( keyMediumOver ); + txt[0] = keys[i]; + keyTxt[i] = new GuiText( txt, 20, ( GXColor ) {0, 0, 0, 0xff} ); + keyTxt[i]->SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); + keyTxt[i]->SetPosition( 0, -10 ); + keyBtn[i] = new GuiButton( keyImg[i], keyImgOver[i], ALIGN_CENTRE, ALIGN_MIDDLE, -90 + 90 * col, -70 + 50 * row, trigA, keySoundOver, keySoundClick, 1 ); + keyBtn[i]->SetLabel( keyTxt[i] ); + + this->Append( keyBtn[i] ); + } + } } /** @@ -100,95 +100,96 @@ GuiNumpad::GuiNumpad(char * t, u32 max) */ GuiNumpad::~GuiNumpad() { - SAFEFREE(kbText) - SAFEFREE(keyTextbox) - SAFEFREE(keyTextboxImg) - SAFEFREE(keyBackText) - SAFEFREE(keyBackImg) - SAFEFREE(keyBackOverImg) - SAFEFREE(keyBack) - SAFEFREE(keyClear) - SAFEFREE(keyClearImg) - SAFEFREE(keyClearOverImg) - SAFEFREE(keyClearText) - SAFEFREE(keyMedium) - SAFEFREE(keyMediumOver) - SAFEFREE(keySoundOver) - SAFEFREE(keySoundClick) - SAFEFREE(trigA) - SAFEFREE(trigB) + SAFEFREE( kbText ) + SAFEFREE( keyTextbox ) + SAFEFREE( keyTextboxImg ) + SAFEFREE( keyBackText ) + SAFEFREE( keyBackImg ) + SAFEFREE( keyBackOverImg ) + SAFEFREE( keyBack ) + SAFEFREE( keyClear ) + SAFEFREE( keyClearImg ) + SAFEFREE( keyClearOverImg ) + SAFEFREE( keyClearText ) + SAFEFREE( keyMedium ) + SAFEFREE( keyMediumOver ) + SAFEFREE( keySoundOver ) + SAFEFREE( keySoundClick ) + SAFEFREE( trigA ) + SAFEFREE( trigB ) - for(int i=0; i<11; i++) - { - if (keys[i] != '\0') - { - SAFEFREE(keyImg[i]) - SAFEFREE(keyImgOver[i]) - SAFEFREE(keyTxt[i]) - SAFEFREE(keyBtn[i]) - } - } + for ( int i = 0; i < 11; i++ ) + { + if ( keys[i] != '\0' ) + { + SAFEFREE( keyImg[i] ) + SAFEFREE( keyImgOver[i] ) + SAFEFREE( keyTxt[i] ) + SAFEFREE( keyBtn[i] ) + } + } } -void GuiNumpad::Update(GuiTrigger * t) +void GuiNumpad::Update( GuiTrigger * t ) { - LOCK(this); - if(_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) - return; + LOCK( this ); + if ( _elements.size() == 0 || ( state == STATE_DISABLED && parentElement ) ) + return; - for (u8 i = 0; i < _elements.size(); i++) - { - try { _elements.at(i)->Update(t); } - catch (const std::exception& e) { } - } + for ( u8 i = 0; i < _elements.size(); i++ ) + { + try { _elements.at( i )->Update( t ); } + catch ( const std::exception& e ) { } + } - if(keyBack->GetState() == STATE_CLICKED) - { - if (strlen(kbtextstr) > 0){ - kbtextstr[strlen(kbtextstr)-1] = 0; - kbText->SetText(kbtextstr); - } - keyBack->SetState(STATE_SELECTED, t->chan); - } - else if(keyClear->GetState() == STATE_CLICKED) - { - memset(kbtextstr, 0, sizeof(kbtextstr)); - kbText->SetText(kbtextstr); - keyClear->SetState(STATE_SELECTED, t->chan); - } + if ( keyBack->GetState() == STATE_CLICKED ) + { + if ( strlen( kbtextstr ) > 0 ) + { + kbtextstr[strlen( kbtextstr )-1] = 0; + kbText->SetText( kbtextstr ); + } + keyBack->SetState( STATE_SELECTED, t->chan ); + } + else if ( keyClear->GetState() == STATE_CLICKED ) + { + memset( kbtextstr, 0, sizeof( kbtextstr ) ); + kbText->SetText( kbtextstr ); + keyClear->SetState( STATE_SELECTED, t->chan ); + } - char txt[2] = { 0, 0 }; - for(int i=0; i<11; i++) - { - if (keys[i] != '\0') - { - if(keyBtn[i]->GetState() == STATE_CLICKED) - { - txt[0] = keys[i]; - if(strlen(kbtextstr) < kbtextmaxlen-1) // -1 --> kbtextmaxlen means with term. '\0' - { - kbtextstr[strlen(kbtextstr)] = txt[0]; - kbText->SetText(kbtextstr); - } - keyBtn[i]->SetState(STATE_SELECTED, t->chan); - } - } - } + char txt[2] = { 0, 0 }; + for ( int i = 0; i < 11; i++ ) + { + if ( keys[i] != '\0' ) + { + if ( keyBtn[i]->GetState() == STATE_CLICKED ) + { + txt[0] = keys[i]; + if ( strlen( kbtextstr ) < kbtextmaxlen - 1 ) // -1 --> kbtextmaxlen means with term. '\0' + { + kbtextstr[strlen( kbtextstr )] = txt[0]; + kbText->SetText( kbtextstr ); + } + keyBtn[i]->SetState( STATE_SELECTED, t->chan ); + } + } + } - kbText->SetPosition(0, 53); + kbText->SetPosition( 0, 53 ); - this->ToggleFocus(t); + this->ToggleFocus( t ); - if(focus) // only send actions to this window if it's in focus - { - // pad/joystick navigation - if(t->Right()) - this->MoveSelectionHor(1); - else if(t->Left()) - this->MoveSelectionHor(-1); - else if(t->Down()) - this->MoveSelectionVert(1); - else if(t->Up()) - this->MoveSelectionVert(-1); - } + if ( focus ) // only send actions to this window if it's in focus + { + // pad/joystick navigation + if ( t->Right() ) + this->MoveSelectionHor( 1 ); + else if ( t->Left() ) + this->MoveSelectionHor( -1 ); + else if ( t->Down() ) + this->MoveSelectionVert( 1 ); + else if ( t->Up() ) + this->MoveSelectionVert( -1 ); + } } diff --git a/source/libwiigui/gui_optionbrowser.cpp b/source/libwiigui/gui_optionbrowser.cpp index cfb02230..7d5c73d3 100644 --- a/source/libwiigui/gui_optionbrowser.cpp +++ b/source/libwiigui/gui_optionbrowser.cpp @@ -21,230 +21,232 @@ 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); - listChanged = true; // trigger an initial list update - selectedItem = 0; - focus = 1; // allow focus + width = w; + height = h; + options = l; + scrollbaron = scrollon; + selectable = true; + listOffset = this->FindMenuItem( -1, 1 ); + listChanged = true; // trigger an initial list update + selectedItem = 0; + focus = 1; // allow focus - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); trigHeldA = new GuiTrigger; - trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A, PAD_BUTTON_A); + trigHeldA->SetHeldTrigger( -1, WPAD_BUTTON_A, PAD_BUTTON_A ); - btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + btnSoundClick = new GuiSound( button_click_pcm, button_click_pcm_size, Settings.sfxvolume ); - bgOptions = new GuiImageData(imagebg); - bgOptionsImg = new GuiImage(bgOptions); - bgOptionsImg->SetParent(this); - bgOptionsImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + bgOptions = new GuiImageData( imagebg ); + bgOptionsImg = new GuiImage( bgOptions ); + bgOptionsImg->SetParent( this ); + bgOptionsImg->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - bgOptionsEntry = new GuiImageData(bg_options_entry_png); - 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); + 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 ); - arrowDown = new GuiImageData(scrollbar_arrowdown_png); - arrowDownImg = new GuiImage(arrowDown); - arrowDownOver = new GuiImageData(scrollbar_arrowdown_png); - arrowDownOverImg = new GuiImage(arrowDownOver); - arrowUp = new GuiImageData(scrollbar_arrowup_png); - arrowUpImg = new GuiImage(arrowUp); - arrowUpOver = new GuiImageData(scrollbar_arrowup_png); - arrowUpOverImg = new GuiImage(arrowUpOver); - scrollbarBox = new GuiImageData(scrollbar_box_png); - scrollbarBoxImg = new GuiImage(scrollbarBox); - scrollbarBoxOver = new GuiImageData(scrollbar_box_png); - scrollbarBoxOverImg = new GuiImage(scrollbarBoxOver); + arrowDown = new GuiImageData( scrollbar_arrowdown_png ); + arrowDownImg = new GuiImage( arrowDown ); + arrowDownOver = new GuiImageData( scrollbar_arrowdown_png ); + arrowDownOverImg = new GuiImage( arrowDownOver ); + arrowUp = new GuiImageData( scrollbar_arrowup_png ); + arrowUpImg = new GuiImage( arrowUp ); + arrowUpOver = new GuiImageData( scrollbar_arrowup_png ); + arrowUpOverImg = new GuiImage( arrowUpOver ); + scrollbarBox = new GuiImageData( scrollbar_box_png ); + scrollbarBoxImg = new GuiImage( scrollbarBox ); + scrollbarBoxOver = new GuiImageData( scrollbar_box_png ); + scrollbarBoxOverImg = new GuiImage( scrollbarBoxOver ); - arrowUpBtn = new GuiButton(arrowUpImg->GetWidth(), arrowUpImg->GetHeight()); - arrowUpBtn->SetParent(this); - arrowUpBtn->SetImage(arrowUpImg); - arrowUpBtn->SetImageOver(arrowUpOverImg); - arrowUpBtn->SetImageHold(arrowUpOverImg); - arrowUpBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - arrowUpBtn->SetPosition(width/2-18+7,-18); - arrowUpBtn->SetSelectable(false); - arrowUpBtn->SetTrigger(trigA); - arrowUpBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowUpBtn->SetSoundClick(btnSoundClick); + arrowUpBtn = new GuiButton( arrowUpImg->GetWidth(), arrowUpImg->GetHeight() ); + arrowUpBtn->SetParent( this ); + arrowUpBtn->SetImage( arrowUpImg ); + arrowUpBtn->SetImageOver( arrowUpOverImg ); + arrowUpBtn->SetImageHold( arrowUpOverImg ); + arrowUpBtn->SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + arrowUpBtn->SetPosition( width / 2 - 18 + 7, -18 ); + arrowUpBtn->SetSelectable( false ); + arrowUpBtn->SetTrigger( trigA ); + arrowUpBtn->SetEffectOnOver( EFFECT_SCALE, 50, 130 ); + arrowUpBtn->SetSoundClick( btnSoundClick ); - arrowDownBtn = new GuiButton(arrowDownImg->GetWidth(), arrowDownImg->GetHeight()); - arrowDownBtn->SetParent(this); - arrowDownBtn->SetImage(arrowDownImg); - arrowDownBtn->SetImageOver(arrowDownOverImg); - arrowDownBtn->SetImageHold(arrowDownOverImg); - arrowDownBtn->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - arrowDownBtn->SetPosition(width/2-18+7,18); - arrowDownBtn->SetSelectable(false); - arrowDownBtn->SetTrigger(trigA); - arrowDownBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowDownBtn->SetSoundClick(btnSoundClick); + arrowDownBtn = new GuiButton( arrowDownImg->GetWidth(), arrowDownImg->GetHeight() ); + arrowDownBtn->SetParent( this ); + arrowDownBtn->SetImage( arrowDownImg ); + arrowDownBtn->SetImageOver( arrowDownOverImg ); + arrowDownBtn->SetImageHold( arrowDownOverImg ); + arrowDownBtn->SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); + arrowDownBtn->SetPosition( width / 2 - 18 + 7, 18 ); + arrowDownBtn->SetSelectable( false ); + arrowDownBtn->SetTrigger( trigA ); + arrowDownBtn->SetEffectOnOver( EFFECT_SCALE, 50, 130 ); + arrowDownBtn->SetSoundClick( btnSoundClick ); - scrollbarBoxBtn = new GuiButton(scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight()); - scrollbarBoxBtn->SetParent(this); - scrollbarBoxBtn->SetImage(scrollbarBoxImg); - scrollbarBoxBtn->SetImageOver(scrollbarBoxOverImg); - scrollbarBoxBtn->SetImageHold(scrollbarBoxOverImg); - scrollbarBoxBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - scrollbarBoxBtn->SetSelectable(false); - scrollbarBoxBtn->SetEffectOnOver(EFFECT_SCALE, 50, 120); - scrollbarBoxBtn->SetMinY(0); - scrollbarBoxBtn->SetMaxY(height); - scrollbarBoxBtn->SetHoldable(true); - scrollbarBoxBtn->SetTrigger(trigHeldA); + scrollbarBoxBtn = new GuiButton( scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight() ); + scrollbarBoxBtn->SetParent( this ); + scrollbarBoxBtn->SetImage( scrollbarBoxImg ); + scrollbarBoxBtn->SetImageOver( scrollbarBoxOverImg ); + scrollbarBoxBtn->SetImageHold( scrollbarBoxOverImg ); + scrollbarBoxBtn->SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + scrollbarBoxBtn->SetSelectable( false ); + scrollbarBoxBtn->SetEffectOnOver( EFFECT_SCALE, 50, 120 ); + scrollbarBoxBtn->SetMinY( 0 ); + scrollbarBoxBtn->SetMaxY( height ); + scrollbarBoxBtn->SetHoldable( true ); + scrollbarBoxBtn->SetTrigger( trigHeldA ); } -// optionBg = new GuiImage(bgOptionsEntry); - for(int i=0; iSetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - optionTxt[i]->SetPosition(24,0); +// 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 ); - 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; - loaded = 0; - scrollbaron = scrollon; - selectable = true; - listOffset = this->FindMenuItem(-1, 1); - selectedItem = 0; - focus = 1; // allow focus - char imgPath[100]; + width = w; + height = h; + options = l; + startat = start; + loaded = 0; + scrollbaron = scrollon; + selectable = true; + listOffset = this->FindMenuItem( -1, 1 ); + selectedItem = 0; + focus = 1; // allow focus + char imgPath[100]; - trigA = new GuiTrigger; - trigA->SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA = new GuiTrigger; + trigA->SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); trigHeldA = new GuiTrigger; - trigHeldA->SetHeldTrigger(-1, WPAD_BUTTON_A, PAD_BUTTON_A); - btnSoundClick = new GuiSound(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + trigHeldA->SetHeldTrigger( -1, WPAD_BUTTON_A, PAD_BUTTON_A ); + btnSoundClick = new GuiSound( button_click_pcm, button_click_pcm_size, Settings.sfxvolume ); - snprintf(imgPath, sizeof(imgPath), "%sbg_options.png", themePath); - bgOptions = new GuiImageData(imgPath, imagebg); + snprintf( imgPath, sizeof( imgPath ), "%sbg_options.png", themePath ); + bgOptions = new GuiImageData( imgPath, imagebg ); - bgOptionsImg = new GuiImage(bgOptions); - bgOptionsImg->SetParent(this); - bgOptionsImg->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); + bgOptionsImg = new GuiImage( bgOptions ); + bgOptionsImg->SetParent( this ); + bgOptionsImg->SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); - snprintf(imgPath, sizeof(imgPath), "%sbg_options_entry.png", themePath); - bgOptionsEntry = new GuiImageData(imgPath, bg_options_entry_png); - 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 ), "%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_arrowdown.png", themePath); - arrowDown = new GuiImageData(imgPath, scrollbar_arrowdown_png); - arrowDownImg = new GuiImage(arrowDown); - arrowDownOver = new GuiImageData(imgPath, scrollbar_arrowdown_png); - arrowDownOverImg = new GuiImage(arrowDownOver); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", themePath); - arrowUp = new GuiImageData(imgPath, scrollbar_arrowup_png); - arrowUpImg = new GuiImage(arrowUp); - arrowUpOver = new GuiImageData(imgPath, scrollbar_arrowup_png); - arrowUpOverImg = new GuiImage(arrowUpOver); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_box.png", themePath); - scrollbarBox = new GuiImageData(imgPath, scrollbar_box_png); - scrollbarBoxImg = new GuiImage(scrollbarBox); - scrollbarBoxOver = new GuiImageData(imgPath, scrollbar_box_png); - scrollbarBoxOverImg = new GuiImage(scrollbarBoxOver); + snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_arrowdown.png", themePath ); + arrowDown = new GuiImageData( imgPath, scrollbar_arrowdown_png ); + arrowDownImg = new GuiImage( arrowDown ); + arrowDownOver = new GuiImageData( imgPath, scrollbar_arrowdown_png ); + arrowDownOverImg = new GuiImage( arrowDownOver ); + snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_arrowup.png", themePath ); + arrowUp = new GuiImageData( imgPath, scrollbar_arrowup_png ); + arrowUpImg = new GuiImage( arrowUp ); + arrowUpOver = new GuiImageData( imgPath, scrollbar_arrowup_png ); + arrowUpOverImg = new GuiImage( arrowUpOver ); + snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_box.png", themePath ); + scrollbarBox = new GuiImageData( imgPath, scrollbar_box_png ); + scrollbarBoxImg = new GuiImage( scrollbarBox ); + scrollbarBoxOver = new GuiImageData( imgPath, scrollbar_box_png ); + scrollbarBoxOverImg = new GuiImage( scrollbarBoxOver ); - arrowUpBtn = new GuiButton(arrowUpImg->GetWidth(), arrowUpImg->GetHeight()); - arrowUpBtn->SetParent(this); - arrowUpBtn->SetImage(arrowUpImg); - arrowUpBtn->SetImageOver(arrowUpOverImg); - arrowUpBtn->SetImageHold(arrowUpOverImg); - arrowUpBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - arrowUpBtn->SetPosition(width/2-18+7,-18); - arrowUpBtn->SetSelectable(false); - arrowUpBtn->SetTrigger(trigA); - arrowUpBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowUpBtn->SetSoundClick(btnSoundClick); + arrowUpBtn = new GuiButton( arrowUpImg->GetWidth(), arrowUpImg->GetHeight() ); + arrowUpBtn->SetParent( this ); + arrowUpBtn->SetImage( arrowUpImg ); + arrowUpBtn->SetImageOver( arrowUpOverImg ); + arrowUpBtn->SetImageHold( arrowUpOverImg ); + arrowUpBtn->SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + arrowUpBtn->SetPosition( width / 2 - 18 + 7, -18 ); + arrowUpBtn->SetSelectable( false ); + arrowUpBtn->SetTrigger( trigA ); + arrowUpBtn->SetEffectOnOver( EFFECT_SCALE, 50, 130 ); + arrowUpBtn->SetSoundClick( btnSoundClick ); - arrowDownBtn = new GuiButton(arrowDownImg->GetWidth(), arrowDownImg->GetHeight()); - arrowDownBtn->SetParent(this); - arrowDownBtn->SetImage(arrowDownImg); - arrowDownBtn->SetImageOver(arrowDownOverImg); - arrowDownBtn->SetImageHold(arrowDownOverImg); - arrowDownBtn->SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - arrowDownBtn->SetPosition(width/2-18+7,18); - arrowDownBtn->SetSelectable(false); - arrowDownBtn->SetTrigger(trigA); - arrowDownBtn->SetEffectOnOver(EFFECT_SCALE, 50, 130); - arrowDownBtn->SetSoundClick(btnSoundClick); + arrowDownBtn = new GuiButton( arrowDownImg->GetWidth(), arrowDownImg->GetHeight() ); + arrowDownBtn->SetParent( this ); + arrowDownBtn->SetImage( arrowDownImg ); + arrowDownBtn->SetImageOver( arrowDownOverImg ); + arrowDownBtn->SetImageHold( arrowDownOverImg ); + arrowDownBtn->SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); + arrowDownBtn->SetPosition( width / 2 - 18 + 7, 18 ); + arrowDownBtn->SetSelectable( false ); + arrowDownBtn->SetTrigger( trigA ); + arrowDownBtn->SetEffectOnOver( EFFECT_SCALE, 50, 130 ); + arrowDownBtn->SetSoundClick( btnSoundClick ); - scrollbarBoxBtn = new GuiButton(scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight()); - scrollbarBoxBtn->SetParent(this); - scrollbarBoxBtn->SetImage(scrollbarBoxImg); - scrollbarBoxBtn->SetImageOver(scrollbarBoxOverImg); - scrollbarBoxBtn->SetImageHold(scrollbarBoxOverImg); - scrollbarBoxBtn->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - scrollbarBoxBtn->SetSelectable(false); - scrollbarBoxBtn->SetEffectOnOver(EFFECT_SCALE, 50, 120); - scrollbarBoxBtn->SetMinY(0); - scrollbarBoxBtn->SetMaxY(height-30); - scrollbarBoxBtn->SetHoldable(true); - scrollbarBoxBtn->SetTrigger(trigHeldA); + scrollbarBoxBtn = new GuiButton( scrollbarBoxImg->GetWidth(), scrollbarBoxImg->GetHeight() ); + scrollbarBoxBtn->SetParent( this ); + scrollbarBoxBtn->SetImage( scrollbarBoxImg ); + scrollbarBoxBtn->SetImageOver( scrollbarBoxOverImg ); + scrollbarBoxBtn->SetImageHold( scrollbarBoxOverImg ); + scrollbarBoxBtn->SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + scrollbarBoxBtn->SetSelectable( false ); + scrollbarBoxBtn->SetEffectOnOver( EFFECT_SCALE, 50, 120 ); + scrollbarBoxBtn->SetMinY( 0 ); + scrollbarBoxBtn->SetMaxY( height - 30 ); + scrollbarBoxBtn->SetHoldable( true ); + scrollbarBoxBtn->SetTrigger( trigHeldA ); } -// optionBg = new GuiImage(bgOptionsEntry); - for(int i=0; iname[i], 20, (GXColor){0, 0, 0, 0xff}); - optionTxt[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - optionTxt[i]->SetPosition(24,0); +// 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 ); - 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 ); + } } /** @@ -252,105 +254,106 @@ GuiOptionBrowser::GuiOptionBrowser(int w, int h, OptionList * l, const char *the */ GuiOptionBrowser::~GuiOptionBrowser() { - if (scrollbaron == 1) { - delete arrowUpBtn; - delete arrowDownBtn; - delete scrollbarBoxBtn; - delete scrollbarImg; - delete arrowDownImg; - delete arrowDownOverImg; - delete arrowUpImg; - delete arrowUpOverImg; - delete scrollbarBoxImg; - delete scrollbarBoxOverImg; - delete scrollbar; - delete arrowDown; - delete arrowDownOver; - delete arrowUp; - delete arrowUpOver; - delete scrollbarBox; - delete scrollbarBoxOver; + if ( scrollbaron == 1 ) + { + delete arrowUpBtn; + delete arrowDownBtn; + delete scrollbarBoxBtn; + delete scrollbarImg; + delete arrowDownImg; + delete arrowDownOverImg; + delete arrowUpImg; + delete arrowUpOverImg; + delete scrollbarBoxImg; + delete scrollbarBoxOverImg; + delete scrollbar; + delete arrowDown; + delete arrowDownOver; + delete arrowUp; + delete arrowUpOver; + delete scrollbarBox; + delete scrollbarBoxOver; } delete bgOptionsImg; - delete bgOptions; - delete bgOptionsEntry; - loaded = 0; + delete bgOptions; + delete bgOptionsEntry; + loaded = 0; - delete trigA; - delete btnSoundClick; + delete trigA; + delete btnSoundClick; -// delete optionBg; - for(int i=0; iSetPosition(x,0); + LOCK( this ); + 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; + LOCK( this ); + focus = f; - for(int i=0; iResetState(); + 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) - { - state = STATE_DEFAULT; - stateChan = -1; - } + LOCK( this ); + if ( state != STATE_DISABLED ) + { + state = STATE_DEFAULT; + stateChan = -1; + } - for(int i=0; iResetState(); - } + for ( int i = 0; i < PAGESIZE; i++ ) + { + optionBtn[i]->ResetState(); + } } int GuiOptionBrowser::GetClickedOption() { - int found = -1; - for(int i=0; iGetState() == STATE_CLICKED) - { - optionBtn[i]->SetState(STATE_SELECTED); - found = optionIndex[i]; - break; - } - } - return found; + int found = -1; + for ( int i = 0; i < PAGESIZE; i++ ) + { + if ( optionBtn[i]->GetState() == STATE_CLICKED ) + { + optionBtn[i]->SetState( STATE_SELECTED ); + found = optionIndex[i]; + break; + } + } + return found; } int GuiOptionBrowser::GetSelectedOption() { - int found = -1; - for(int i=0; iGetState() == STATE_SELECTED) - { - optionBtn[i]->SetState(STATE_SELECTED); - found = optionIndex[i]; - break; - } - } - return found; + int found = -1; + for ( int i = 0; i < PAGESIZE; i++ ) + { + if ( optionBtn[i]->GetState() == STATE_SELECTED ) + { + optionBtn[i]->SetState( STATE_SELECTED ); + found = optionIndex[i]; + break; + } + } + return found; } /**************************************************************************** @@ -359,17 +362,17 @@ 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; + int nextItem = currentItem + direction; - if(nextItem < 0 || nextItem >= options->length) - return -1; + if ( nextItem < 0 || nextItem >= options->length ) + return -1; - if(strlen(options->name[nextItem]) > 0) - return nextItem; - else - return FindMenuItem(nextItem, direction); + if ( strlen( options->name[nextItem] ) > 0 ) + return nextItem; + else + return FindMenuItem( nextItem, direction ); } /** @@ -377,298 +380,313 @@ int GuiOptionBrowser::FindMenuItem(int currentItem, int direction) */ void GuiOptionBrowser::Draw() { - LOCK(this); - if(!this->IsVisible()) - return; + LOCK( this ); + if ( !this->IsVisible() ) + return; - bgOptionsImg->Draw(); + bgOptionsImg->Draw(); - int next = listOffset; + int next = listOffset; - for(int i=0; i= 0) - { - optionBtn[i]->Draw(); - next = this->FindMenuItem(next, 1); - } - else - break; - } - - if(scrollbaron == 1) { - scrollbarImg->Draw(); - arrowUpBtn->Draw(); - arrowDownBtn->Draw(); - scrollbarBoxBtn->Draw(); + for ( int i = 0; i < PAGESIZE; i++ ) + { + if ( next >= 0 ) + { + optionBtn[i]->Draw(); + next = this->FindMenuItem( next, 1 ); + } + else + break; } - this->UpdateEffects(); + + if ( scrollbaron == 1 ) + { + scrollbarImg->Draw(); + arrowUpBtn->Draw(); + arrowDownBtn->Draw(); + scrollbarBoxBtn->Draw(); + } + this->UpdateEffects(); } void GuiOptionBrowser::TriggerUpdate() { - listChanged = true; -} - -void GuiOptionBrowser::Update(GuiTrigger * t) -{ - LOCK(this); - int next, prev, lang = options->length; - - //go to the last game selected - if ((loaded == 0) && (startat>0)) - { - - if (startat > (lang-9)){ - listOffset= (lang-9); - selectedItem=startat; - optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan); - } - else if (startat < 9){ - selectedItem=startat; - optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan); - } - else { - listOffset = (startat-4); - selectedItem=startat; - optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan);} - this->SetFocus(1); - loaded = 1; - } - - if(state == STATE_DISABLED || !t) - return; - - - // scrolldelay affects how fast the list scrolls - // when the arrows are clicked - float scrolldelay = 3.5; - - - if (scrollbaron == 1) { - // update the location of the scroll box based on the position in the option list - - - arrowUpBtn->Update(t); - arrowDownBtn->Update(t); - scrollbarBoxBtn->Update(t); - } - next = listOffset; - - if(listChanged) - { - for(int i=0; i= 0) - { - if(optionBtn[i]->GetState() == STATE_DISABLED) - { - optionBtn[i]->SetVisible(true); - optionBtn[i]->SetState(STATE_DEFAULT); - } - - optionTxt[i]->SetText(options->name[next]); - optionVal[i]->SetText(options->value[next]); - optionIndex[i] = next; - next = this->FindMenuItem(next, 1); - } - else - { - optionBtn[i]->SetVisible(false); - optionBtn[i]->SetState(STATE_DISABLED); - } - } - } - for(int i=0; iGetState() == STATE_SELECTED) - optionBtn[i]->ResetState(); - else if(i == selectedItem && optionBtn[i]->GetState() == STATE_DEFAULT) - optionBtn[selectedItem]->SetState(STATE_SELECTED, t->chan); - } - - optionBtn[i]->Update(t); - - if(optionBtn[i]->GetState() == STATE_SELECTED) - { - selectedItem = i; - } - } - - // pad/joystick navigation - if(!focus) - return; // skip navigation - - if (scrollbaron == 1) { - - if (t->Down() || - arrowDownBtn->GetState() == STATE_CLICKED || ////////////////////////////////////////////down - arrowDownBtn->GetState() == STATE_HELD) - { - - next = this->FindMenuItem(optionIndex[selectedItem], 1); - - if(next >= 0) - { - if(selectedItem == PAGESIZE-1) - { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - } - else if(optionBtn[selectedItem+1]->IsVisible()) - { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } - scrollbarBoxBtn->Draw(); - usleep(10000 * scrolldelay); - - - }WPAD_ScanPads(); - u8 cnt, buttons = NULL; - /* Get pressed buttons */ - for (cnt = 0; cnt < 4; cnt++) - buttons |= WPAD_ButtonsHeld(cnt); - if (buttons == WPAD_BUTTON_A) { - - } else { - arrowDownBtn->ResetState(); - - } - - } - else if(t->Up() || - arrowUpBtn->GetState() == STATE_CLICKED || ////////////////////////////////////////////up - arrowUpBtn->GetState() == STATE_HELD) - { - prev = this->FindMenuItem(optionIndex[selectedItem], -1); - - if(prev >= 0) - { - if(selectedItem == 0) - { - // move list up by 1 - listOffset = prev; - } - else - { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } - scrollbarBoxBtn->Draw(); - usleep(10000 * scrolldelay); - - - }WPAD_ScanPads(); - u8 cnt, buttons = NULL; - /* Get pressed buttons */ - for (cnt = 0; cnt < 4; cnt++) - buttons |= WPAD_ButtonsHeld(cnt); - if (buttons == WPAD_BUTTON_A) { - - } else { - arrowUpBtn->ResetState(); - - } - } - - if(scrollbarBoxBtn->GetState() == STATE_HELD && - scrollbarBoxBtn->GetStateChan() == t->chan && - t->wpad.ir.valid && options->length > PAGESIZE) - { - scrollbarBoxBtn->SetPosition(width/2-18+7,0); - int position = t->wpad.ir.y - 50 - scrollbarBoxBtn->GetTop(); - - listOffset = (position * lang)/180 - selectedItem; - - if(listOffset <= 0) - { - listOffset = 0; - selectedItem = 0; - } - else if(listOffset+PAGESIZE >= lang) - { - listOffset = lang-PAGESIZE; - selectedItem = PAGESIZE-1; - } - - } - int positionbar = 237*(listOffset + selectedItem) / lang; - - if(positionbar > 216) - positionbar = 216; - scrollbarBoxBtn->SetPosition(width/2-18+7, positionbar+8); - - - if(t->Right()) - { - if(listOffset < lang && lang > PAGESIZE) - { - listOffset =listOffset+ PAGESIZE; - if(listOffset+PAGESIZE >= lang) - listOffset = lang-PAGESIZE; - } - } - else if(t->Left()) - { - if(listOffset > 0) - { - listOffset =listOffset- PAGESIZE; - if(listOffset < 0) - listOffset = 0; - } - } - - } else { - - - if(t->Down()) - { - next = this->FindMenuItem(optionIndex[selectedItem], 1); - - if(next >= 0) - { - if(selectedItem == PAGESIZE-1) - { - // move list down by 1 - listOffset = this->FindMenuItem(listOffset, 1); - listChanged = true; - } - else if(optionBtn[selectedItem+1]->IsVisible()) - { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem+1]->SetState(STATE_SELECTED, t->chan); - selectedItem++; - } - } - } - else if(t->Up()) - { - prev = this->FindMenuItem(optionIndex[selectedItem], -1); - - if(prev >= 0) - { - if(selectedItem == 0) - { - // move list up by 1 - listOffset = prev; - listChanged = true; - } - else - { - optionBtn[selectedItem]->ResetState(); - optionBtn[selectedItem-1]->SetState(STATE_SELECTED, t->chan); - selectedItem--; - } - } - } - } - - if(updateCB) - updateCB(this); + listChanged = true; +} + +void GuiOptionBrowser::Update( GuiTrigger * t ) +{ + LOCK( this ); + int next, prev, lang = options->length; + + //go to the last game selected + if ( ( loaded == 0 ) && ( startat > 0 ) ) + { + + if ( startat > ( lang - 9 ) ) + { + listOffset = ( lang - 9 ); + selectedItem = startat; + optionBtn[selectedItem]->SetState( STATE_SELECTED, t->chan ); + } + else if ( startat < 9 ) + { + selectedItem = startat; + optionBtn[selectedItem]->SetState( STATE_SELECTED, t->chan ); + } + else + { + listOffset = ( startat - 4 ); + selectedItem = startat; + optionBtn[selectedItem]->SetState( STATE_SELECTED, t->chan ); + } + this->SetFocus( 1 ); + loaded = 1; + } + + if ( state == STATE_DISABLED || !t ) + return; + + + // scrolldelay affects how fast the list scrolls + // when the arrows are clicked + float scrolldelay = 3.5; + + + if ( scrollbaron == 1 ) + { + // update the location of the scroll box based on the position in the option list + + + arrowUpBtn->Update( t ); + arrowDownBtn->Update( t ); + scrollbarBoxBtn->Update( t ); + } + next = listOffset; + + if ( listChanged ) + { + for ( int i = 0; i < PAGESIZE; i++ ) + { + if ( next >= 0 ) + { + if ( optionBtn[i]->GetState() == STATE_DISABLED ) + { + optionBtn[i]->SetVisible( true ); + optionBtn[i]->SetState( STATE_DEFAULT ); + } + + optionTxt[i]->SetText( options->name[next] ); + optionVal[i]->SetText( options->value[next] ); + optionIndex[i] = next; + next = this->FindMenuItem( next, 1 ); + } + else + { + optionBtn[i]->SetVisible( false ); + optionBtn[i]->SetState( STATE_DISABLED ); + } + } + } + for ( int i = 0; i < PAGESIZE; i++ ) + { + if ( focus ) + { + if ( i != selectedItem && optionBtn[i]->GetState() == STATE_SELECTED ) + optionBtn[i]->ResetState(); + else if ( i == selectedItem && optionBtn[i]->GetState() == STATE_DEFAULT ) + optionBtn[selectedItem]->SetState( STATE_SELECTED, t->chan ); + } + + optionBtn[i]->Update( t ); + + if ( optionBtn[i]->GetState() == STATE_SELECTED ) + { + selectedItem = i; + } + } + + // pad/joystick navigation + if ( !focus ) + return; // skip navigation + + if ( scrollbaron == 1 ) + { + + if ( t->Down() || + arrowDownBtn->GetState() == STATE_CLICKED || ////////////////////////////////////////////down + arrowDownBtn->GetState() == STATE_HELD ) + { + + next = this->FindMenuItem( optionIndex[selectedItem], 1 ); + + if ( next >= 0 ) + { + if ( selectedItem == PAGESIZE - 1 ) + { + // move list down by 1 + listOffset = this->FindMenuItem( listOffset, 1 ); + } + else if ( optionBtn[selectedItem+1]->IsVisible() ) + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + selectedItem++; + } + scrollbarBoxBtn->Draw(); + usleep( 10000 * scrolldelay ); + + + } WPAD_ScanPads(); + u8 cnt, buttons = NULL; + /* Get pressed buttons */ + for ( cnt = 0; cnt < 4; cnt++ ) + buttons |= WPAD_ButtonsHeld( cnt ); + if ( buttons == WPAD_BUTTON_A ) + { + + } + else + { + arrowDownBtn->ResetState(); + + } + + } + else if ( t->Up() || + arrowUpBtn->GetState() == STATE_CLICKED || ////////////////////////////////////////////up + arrowUpBtn->GetState() == STATE_HELD ) + { + prev = this->FindMenuItem( optionIndex[selectedItem], -1 ); + + if ( prev >= 0 ) + { + if ( selectedItem == 0 ) + { + // move list up by 1 + listOffset = prev; + } + else + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + selectedItem--; + } + scrollbarBoxBtn->Draw(); + usleep( 10000 * scrolldelay ); + + + } WPAD_ScanPads(); + u8 cnt, buttons = NULL; + /* Get pressed buttons */ + for ( cnt = 0; cnt < 4; cnt++ ) + buttons |= WPAD_ButtonsHeld( cnt ); + if ( buttons == WPAD_BUTTON_A ) + { + + } + else + { + arrowUpBtn->ResetState(); + + } + } + + if ( scrollbarBoxBtn->GetState() == STATE_HELD && + scrollbarBoxBtn->GetStateChan() == t->chan && + t->wpad.ir.valid && options->length > PAGESIZE ) + { + scrollbarBoxBtn->SetPosition( width / 2 - 18 + 7, 0 ); + int position = t->wpad.ir.y - 50 - scrollbarBoxBtn->GetTop(); + + listOffset = ( position * lang ) / 180 - selectedItem; + + if ( listOffset <= 0 ) + { + listOffset = 0; + selectedItem = 0; + } + else if ( listOffset + PAGESIZE >= lang ) + { + listOffset = lang - PAGESIZE; + selectedItem = PAGESIZE - 1; + } + + } + int positionbar = 237 * ( listOffset + selectedItem ) / lang; + + if ( positionbar > 216 ) + positionbar = 216; + scrollbarBoxBtn->SetPosition( width / 2 - 18 + 7, positionbar + 8 ); + + + if ( t->Right() ) + { + if ( listOffset < lang && lang > PAGESIZE ) + { + listOffset = listOffset + PAGESIZE; + if ( listOffset + PAGESIZE >= lang ) + listOffset = lang - PAGESIZE; + } + } + else if ( t->Left() ) + { + if ( listOffset > 0 ) + { + listOffset = listOffset - PAGESIZE; + if ( listOffset < 0 ) + listOffset = 0; + } + } + + } + else + { + + + if ( t->Down() ) + { + next = this->FindMenuItem( optionIndex[selectedItem], 1 ); + + if ( next >= 0 ) + { + if ( selectedItem == PAGESIZE - 1 ) + { + // move list down by 1 + listOffset = this->FindMenuItem( listOffset, 1 ); + listChanged = true; + } + else if ( optionBtn[selectedItem+1]->IsVisible() ) + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem+1]->SetState( STATE_SELECTED, t->chan ); + selectedItem++; + } + } + } + else if ( t->Up() ) + { + prev = this->FindMenuItem( optionIndex[selectedItem], -1 ); + + if ( prev >= 0 ) + { + if ( selectedItem == 0 ) + { + // move list up by 1 + listOffset = prev; + listChanged = true; + } + else + { + optionBtn[selectedItem]->ResetState(); + optionBtn[selectedItem-1]->SetState( STATE_SELECTED, t->chan ); + selectedItem--; + } + } + } + } + + if ( updateCB ) + updateCB( this ); } diff --git a/source/libwiigui/gui_searchbar.cpp b/source/libwiigui/gui_searchbar.cpp index c31aa498..81662acc 100644 --- a/source/libwiigui/gui_searchbar.cpp +++ b/source/libwiigui/gui_searchbar.cpp @@ -10,163 +10,163 @@ 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) - { - text.SetText(Char); - button.SetLabel(&text); - } - wchar_t wchar; - GuiImage image; - GuiImage imageOver; - GuiText text; - GuiButton button; -private: + 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 ) + { + text.SetText( Char ); + button.SetLabel( &text ); + } + wchar_t wchar; + GuiImage image; + GuiImage imageOver; + GuiText text; + GuiButton button; + private: }; -GuiSearchBar::GuiSearchBar(const wchar_t *SearchChars) -: -inSide(0), -text((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); + char imgPath[100]; + trig.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); - cnt = wcslen(SearchChars); - buttons = new cSearchButton*[cnt]; - - wchar_t charstr[2] = {0, 0}; - int lines = (cnt+9)/10; - int buttonsPerLine = (cnt+lines-1)/lines; - width = 10+buttonsPerLine*42+10; - int x_start=10, x=0, y_start=10+42, y=0; - if(width < 200) { x_start += (200-width)>>1; width=200; } - for(int i=0; i= buttonsPerLine) x=0; - if(x == 0) y++; - charstr[0] = SearchChars[i]; - buttons[i] = new cSearchButton(charstr, &keyImageData, &keyOverImageData, x_start+x*42, y_start-42+y*42, &trig, &sndOver, &sndClick); - this->Append(&(buttons[i]->button)); - } - height = 10+42+y*42+10; + cnt = wcslen( SearchChars ); + buttons = new cSearchButton*[cnt]; + + wchar_t charstr[2] = {0, 0}; + int lines = ( cnt + 9 ) / 10; + int buttonsPerLine = ( cnt + lines - 1 ) / lines; + width = 10 + buttonsPerLine * 42 + 10; + int x_start = 10, x = 0, y_start = 10 + 42, y = 0; + if ( width < 200 ) { x_start += ( 200 - width ) >> 1; width = 200; } + for ( int i = 0; i < 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 ) ); + } + height = 10 + 42 + y * 42 + 10; - text.SetText(gameList.GetCurrentFilter()); - text.SetPosition(10, 15); - text.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - text.SetWidescreen(CFG.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( CFG.widescreen ); + text.SetMaxWidth( width - ( 10 + 2*42 + 10 ), SCROLL_HORIZONTAL ); + this->Append( &text ); - snprintf(imgPath, sizeof(imgPath), "%skeyboard_backspace_over.png", CFG.theme_path); - imgBacspaceBtn = new GuiImageData(imgPath, keyboard_backspace_over_png); - BacspaceBtnImg_Over = new GuiImage(imgBacspaceBtn); - BacspaceBtnImg = new GuiImage(BacspaceBtnImg_Over); BacspaceBtnImg->SetGrayscale(); - BacspaceBtn = new GuiButton(BacspaceBtnImg,BacspaceBtnImg_Over, ALIGN_RIGHT, ALIGN_TOP, -52, 10, &trig, &sndOver, &sndClick,1); - this->Append(BacspaceBtn); - - snprintf(imgPath, sizeof(imgPath), "%skeyboard_clear_over.png", CFG.theme_path); - imgClearBtn = new GuiImageData(imgPath, keyboard_clear_over_png); - ClearBtnImg_Over = new GuiImage(imgClearBtn); - ClearBtnImg = new GuiImage(ClearBtnImg_Over); ClearBtnImg->SetGrayscale(); - ClearBtn = new GuiButton(ClearBtnImg,ClearBtnImg_Over, ALIGN_RIGHT, ALIGN_TOP, -10, 10, &trig, &sndOver, &sndClick,1); - this->Append(ClearBtn); - + snprintf( imgPath, sizeof( imgPath ), "%skeyboard_backspace_over.png", CFG.theme_path ); + imgBacspaceBtn = new GuiImageData( imgPath, keyboard_backspace_over_png ); + BacspaceBtnImg_Over = new GuiImage( imgBacspaceBtn ); + BacspaceBtnImg = new GuiImage( BacspaceBtnImg_Over ); BacspaceBtnImg->SetGrayscale(); + BacspaceBtn = new GuiButton( BacspaceBtnImg, BacspaceBtnImg_Over, ALIGN_RIGHT, ALIGN_TOP, -52, 10, &trig, &sndOver, &sndClick, 1 ); + this->Append( BacspaceBtn ); -// SetPosition(100,100); + snprintf( imgPath, sizeof( imgPath ), "%skeyboard_clear_over.png", CFG.theme_path ); + imgClearBtn = new GuiImageData( imgPath, keyboard_clear_over_png ); + ClearBtnImg_Over = new GuiImage( imgClearBtn ); + ClearBtnImg = new GuiImage( ClearBtnImg_Over ); ClearBtnImg->SetGrayscale(); + ClearBtn = new GuiButton( ClearBtnImg, ClearBtnImg_Over, ALIGN_RIGHT, ALIGN_TOP, -10, 10, &trig, &sndOver, &sndClick, 1 ); + this->Append( ClearBtn ); + + +// SetPosition(100,100); } GuiSearchBar::~GuiSearchBar() { - if(buttons) - { - for(int i=0; iSetState(STATE_DEFAULT); + delete BacspaceBtn; + delete BacspaceBtnImg; + delete BacspaceBtnImg_Over; + delete imgBacspaceBtn; + if ( inSide ) + mainWindow->SetState( STATE_DEFAULT ); } void GuiSearchBar::Draw() { - Menu_DrawRectangle(this->GetLeft(),this->GetTop(),width, height,(GXColor){0, 0, 0, 0xa0},1); - Menu_DrawRectangle(this->GetLeft()+10,this->GetTop()+15,width-(10+2*42+10), 22,(GXColor){255, 255, 255, 255},1); - GuiWindow::Draw(); + 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; - // cursor - if(t->wpad.ir.valid && state != STATE_DISABLED) - { - if(this->IsInside(t->wpad.ir.x, t->wpad.ir.y)) - { - if(inSide == 0) - { - mainWindow->SetState(STATE_DISABLED); - this->SetState(STATE_DEFAULT); - } - inSide |= 1 << t->chan; - } - else if(inSide) - { - inSide &= ~(1 << t->chan); - if(inSide == 0) - mainWindow->SetState(STATE_DEFAULT); - } - } - GuiWindow::Update(t); + LOCK( this ); + if ( _elements.size() == 0 || ( state == STATE_DISABLED && parentElement ) ) + return; + // cursor + if ( t->wpad.ir.valid && state != STATE_DISABLED ) + { + if ( this->IsInside( t->wpad.ir.x, t->wpad.ir.y ) ) + { + if ( inSide == 0 ) + { + mainWindow->SetState( STATE_DISABLED ); + this->SetState( STATE_DEFAULT ); + } + inSide |= 1 << t->chan; + } + else if ( inSide ) + { + inSide &= ~( 1 << t->chan ); + if ( inSide == 0 ) + mainWindow->SetState( STATE_DEFAULT ); + } + } + GuiWindow::Update( t ); } wchar_t GuiSearchBar::GetClicked() { - if(buttons) - { - for(int i=0; ibutton.GetState() == STATE_CLICKED) - { - buttons[i]->button.ResetState(); - return buttons[i]->wchar; - } - } - } - if(BacspaceBtn->GetState() == STATE_CLICKED) - return 8; - if(ClearBtn->GetState() == STATE_CLICKED) - return 7; - - return 0; + if ( buttons ) + { + for ( int i = 0; i < cnt; i++ ) + { + 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; + + return 0; } /* private: - SearchButtons *buttons; + SearchButtons *buttons; }*/ diff --git a/source/libwiigui/gui_searchbar.h b/source/libwiigui/gui_searchbar.h index 920a05c2..3665e3b5 100644 --- a/source/libwiigui/gui_searchbar.h +++ b/source/libwiigui/gui_searchbar.h @@ -6,33 +6,33 @@ class cSearchButton; class GuiSearchBar : public GuiWindow { -public: - GuiSearchBar(const wchar_t *SearchChars); - ~GuiSearchBar(); - void Draw(); - void Update(GuiTrigger * t); - wchar_t GetClicked(); -private: - u16 inSide; - - GuiText text; - - GuiImageData* imgBacspaceBtn; - GuiImage* BacspaceBtnImg; - GuiImage* BacspaceBtnImg_Over; - GuiButton* BacspaceBtn; - - GuiImageData* imgClearBtn; - GuiImage* ClearBtnImg; - GuiImage* ClearBtnImg_Over; - GuiButton* ClearBtn; - - cSearchButton **buttons; - int cnt; - GuiImageData keyImageData; - GuiImageData keyOverImageData; - GuiTrigger trig; - GuiSound sndOver; - GuiSound sndClick; + public: + GuiSearchBar( const wchar_t *SearchChars ); + ~GuiSearchBar(); + void Draw(); + void Update( GuiTrigger * t ); + wchar_t GetClicked(); + private: + u16 inSide; + + GuiText text; + + GuiImageData* imgBacspaceBtn; + GuiImage* BacspaceBtnImg; + GuiImage* BacspaceBtnImg_Over; + GuiButton* BacspaceBtn; + + GuiImageData* imgClearBtn; + GuiImage* ClearBtnImg; + GuiImage* ClearBtnImg_Over; + GuiButton* ClearBtn; + + cSearchButton **buttons; + int cnt; + GuiImageData keyImageData; + GuiImageData keyOverImageData; + GuiTrigger trig; + GuiSound sndOver; + GuiSound sndClick; }; diff --git a/source/libwiigui/gui_sound.cpp b/source/libwiigui/gui_sound.cpp index 11151849..90c408a3 100644 --- a/source/libwiigui/gui_sound.cpp +++ b/source/libwiigui/gui_sound.cpp @@ -28,28 +28,30 @@ ***************************************************************/ 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) - { - Decoder.fnc = fnc; - Decoder.next = DecoderList; - DecoderList = &Decoder; - } - return Decoder; + if ( Decoder.fnc != fnc ) + { + Decoder.fnc = fnc; + Decoder.next = DecoderList; + DecoderList = &Decoder; + } + return Decoder; } -GuiSoundDecoder *GuiSoundDecoder::GetDecoder(const u8 * snd, u32 len, bool snd_is_allocated) +GuiSoundDecoder *GuiSoundDecoder::GetDecoder( const u8 * snd, u32 len, bool snd_is_allocated ) { - for(DecoderListEntry *de = DecoderList; de; de=de->next) - { - GuiSoundDecoder *d = NULL; - try{ d = de->fnc(snd, len, snd_is_allocated); } - catch(const char *error){ - gprintf("%s", error); } - catch(...){} - if(d) return d; - } - return NULL; + for ( DecoderListEntry *de = DecoderList; de; de = de->next ) + { + GuiSoundDecoder *d = NULL; + try { d = de->fnc( snd, len, snd_is_allocated ); } + catch ( const char *error ) + { + gprintf( "%s", error ); + } + catch ( ... ) {} + if ( d ) return d; + } + return NULL; } @@ -62,30 +64,31 @@ GuiSoundDecoder *GuiSoundDecoder::GetDecoder(const u8 * snd, u32 len, bool snd_i 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 bool GuiSoundDecoderDataRquested = 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) - { - GuiSoundDecoderDataRquested = false; - GuiSound **players = GuiSoundPlayer; - for( int i = 0; i < 16; ++i , ++players) - { - GuiSound *player = *players; - if(player) - player->DecoderCallback(); - } - } - if(!GuiSoundDecoderDataRquested) - usleep(50); - } while(GuiSoundDecoderThreadRunning); - return 0; + GuiSoundDecoderThreadRunning = true; + do + { + if ( GuiSoundDecoderDataRquested ) + { + GuiSoundDecoderDataRquested = false; + GuiSound **players = GuiSoundPlayer; + for ( int i = 0; i < 16; ++i , ++players ) + { + GuiSound *player = *players; + if ( player ) + player->DecoderCallback(); + } + } + if ( !GuiSoundDecoderDataRquested ) + usleep( 50 ); + } + while ( GuiSoundDecoderThreadRunning ); + return 0; } /*************************************************************** @@ -95,13 +98,13 @@ void *GuiSoundDecoderThread(void *args) * ***************************************************************/ -void GuiSoundPlayerCallback(s32 Voice) +void GuiSoundPlayerCallback( s32 Voice ) { - if(Voice >= 0 && Voice < 16 && GuiSoundPlayer[Voice]) - { - GuiSoundPlayer[Voice]->PlayerCallback(); - GuiSoundDecoderDataRquested = true; - } + if ( Voice >= 0 && Voice < 16 && GuiSoundPlayer[Voice] ) + { + GuiSoundPlayer[Voice]->PlayerCallback(); + GuiSoundDecoderDataRquested = true; + } } /*************************************************************** @@ -112,65 +115,65 @@ void GuiSoundPlayerCallback(s32 Voice) ***************************************************************/ class GuiSoundDecoderRAW : public GuiSoundDecoder { -protected: - GuiSoundDecoderRAW(const u8 * snd, u32 len, bool snd_is_allocated) - { - pcm_start = snd; - is_allocated = snd_is_allocated; - pcm_end = pcm_start+len; - pos = pcm_start; - is_running = false; + protected: + GuiSoundDecoderRAW( const u8 * snd, u32 len, bool snd_is_allocated ) + { + pcm_start = snd; + is_allocated = snd_is_allocated; + pcm_end = pcm_start + len; + pos = pcm_start; + is_running = false; - } -public: - ~GuiSoundDecoderRAW() - { - while(is_running) usleep(50); - if(is_allocated) delete [] pcm_start; - } - static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) - { - try { return new GuiSoundDecoderRAW(snd, len, snd_is_allocated); } - catch(...) {} - return NULL; - } - s32 GetFormat() - { - return VOICE_STEREO_16BIT; - } - s32 GetSampleRate() - { - return 48000; - } - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read(u8 * buffer, int buffer_size) - { - if(pos >= pcm_end) - return 0; // EOF + } + public: + ~GuiSoundDecoderRAW() + { + while ( is_running ) usleep( 50 ); + if ( is_allocated ) delete [] pcm_start; + } + static GuiSoundDecoder *Create( const u8 * snd, u32 len, bool snd_is_allocated ) + { + try { return new GuiSoundDecoderRAW( snd, len, snd_is_allocated ); } + catch ( ... ) {} + return NULL; + } + s32 GetFormat() + { + return VOICE_STEREO_16BIT; + } + s32 GetSampleRate() + { + return 48000; + } + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read( u8 * buffer, int buffer_size ) + { + if ( pos >= pcm_end ) + return 0; // EOF - is_running = true; - if(pos + buffer_size > pcm_end) - buffer_size = pcm_end-pos; - memcpy(buffer, pos, buffer_size); - pos += buffer_size; - is_running = false; - return buffer_size; - } - int Rewind() - { - pos = pcm_start; - return 0; - } -private: - const u8 *pcm_start; - const u8 *pcm_end; - bool is_allocated; - const u8 *pos; - bool is_running; + is_running = true; + if ( pos + buffer_size > pcm_end ) + buffer_size = pcm_end - pos; + memcpy( buffer, pos, buffer_size ); + pos += buffer_size; + is_running = false; + return buffer_size; + } + int Rewind() + { + pos = pcm_start; + return 0; + } + private: + const u8 *pcm_start; + const u8 *pcm_end; + bool is_allocated; + const u8 *pos; + bool is_running; }; @@ -180,102 +183,102 @@ private: * * ***************************************************************/ -#define GuiSoundBufferReady 0x01 -#define GuiSoundBufferEOF 0x02 -#define GuiSoundFinish 0x04 +#define GuiSoundBufferReady 0x01 +#define GuiSoundBufferEOF 0x02 +#define GuiSoundFinish 0x04 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) - { - 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); + if ( GuiSoundCount++ == 0 || GuiSoundDecoderThreadHandle == LWP_THREAD_NULL ) + { + 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 ); } -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) - { - delete decoder; - decoder = newDecoder; - return true; - } - else if(a) - delete [] s; - return false; + Stop(); + if ( !play_buffer[0] ) return false; + GuiSoundDecoder *newDecoder = GuiSoundDecoder::GetDecoder( s, l, a ); + if ( !newDecoder && r ) newDecoder = GuiSoundDecoderRAW::Create( s, l, a ); + if ( newDecoder ) + { + delete decoder; + decoder = newDecoder; + return true; + } + else if ( a ) + delete [] s; + return false; } -GuiSound::GuiSound(const char *p, int v/*=100*/) +GuiSound::GuiSound( const char *p, int v/*=100*/ ) { - if(GuiSoundCount++ == 0 || GuiSoundDecoderThreadHandle == LWP_THREAD_NULL) - { - LWP_CreateThread(&GuiSoundDecoderThreadHandle,GuiSoundDecoderThread,NULL,NULL,32*1024,80); - } - voice = -1; - play_buffer[0] = (u8*)memalign(32, BUFFER_SIZE*3); // tripple-buffer first is played - play_buffer[1] = play_buffer[0] + BUFFER_SIZE; // second is waiting - play_buffer[2] = play_buffer[1] + BUFFER_SIZE; // third is decoding - buffer_nr = 0; // current playbuffer - buffer_pos = 0; // current idx to write in buffer - buffer_ready = false; - buffer_eof = false; - loop = false; // play looped - volume = v; // volume - decoder = NULL; - if(play_buffer[0]) // playbuffer ok - Load(p); + if ( GuiSoundCount++ == 0 || GuiSoundDecoderThreadHandle == LWP_THREAD_NULL ) + { + LWP_CreateThread( &GuiSoundDecoderThreadHandle, GuiSoundDecoderThread, NULL, NULL, 32*1024, 80 ); + } + voice = -1; + play_buffer[0] = ( u8* )memalign( 32, BUFFER_SIZE * 3 ); // tripple-buffer first is played + play_buffer[1] = play_buffer[0] + BUFFER_SIZE; // second is waiting + play_buffer[2] = play_buffer[1] + BUFFER_SIZE; // third is decoding + buffer_nr = 0; // current playbuffer + buffer_pos = 0; // current idx to write in buffer + buffer_ready = false; + buffer_eof = false; + loop = false; // play looped + volume = v; // volume + decoder = NULL; + if ( play_buffer[0] ) // playbuffer ok + Load( p ); } -bool GuiSound::Load(const char *p) +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 - u32 filesize = 0; - u8 *buffer = NULL; - size_t result; + bool ret = false; + voice = -2; // -2 marks loading from file + u32 filesize = 0; + u8 *buffer = NULL; + size_t result; - FILE * pFile = fopen (p, "rb"); - if(pFile) - { - // get file size: - fseek (pFile , 0 , SEEK_END); - filesize = ftell (pFile); - fseek (pFile , 0 , SEEK_SET); + FILE * pFile = fopen ( p, "rb" ); + if ( pFile ) + { + // get file size: + fseek ( pFile , 0 , SEEK_END ); + filesize = ftell ( pFile ); + fseek ( pFile , 0 , SEEK_SET ); - // allocate memory to contain the whole file: - buffer = new(std::nothrow) u8[filesize]; - if (buffer) - { - // copy the file into the buffer: - result = fread (buffer, 1, filesize, pFile); - if (result == filesize) - ret= Load(buffer, filesize, false, true); - else - delete [] buffer; - } - fclose (pFile); - } - return ret; + // allocate memory to contain the whole file: + buffer = new( std::nothrow ) u8[filesize]; + if ( buffer ) + { + // copy the file into the buffer: + result = fread ( buffer, 1, filesize, pFile ); + if ( result == filesize ) + ret = Load( buffer, filesize, false, true ); + else + delete [] buffer; + } + fclose ( pFile ); + } + return ret; } /** @@ -283,158 +286,158 @@ bool GuiSound::Load(const char *p) */ GuiSound::~GuiSound() { - if(!loop) while(voice >= 0) usleep(50); - Stop(); - if(--GuiSoundCount == 0 && GuiSoundDecoderThreadHandle != LWP_THREAD_NULL) - { - GuiSoundDecoderThreadRunning = false; - LWP_JoinThread(GuiSoundDecoderThreadHandle,NULL); - GuiSoundDecoderThreadHandle = LWP_THREAD_NULL; - } - delete decoder; - free(play_buffer[0]); + if ( !loop ) while ( voice >= 0 ) usleep( 50 ); + Stop(); + if ( --GuiSoundCount == 0 && GuiSoundDecoderThreadHandle != LWP_THREAD_NULL ) + { + GuiSoundDecoderThreadRunning = false; + LWP_JoinThread( GuiSoundDecoderThreadHandle, NULL ); + GuiSoundDecoderThreadHandle = LWP_THREAD_NULL; + } + delete decoder; + free( play_buffer[0] ); } void GuiSound::Play() { - Stop(); // stop playing if it played - if(!play_buffer[0]) return; - if(!decoder) return; // no decoder or no play_buffer -> no playing - // initialize the buffer - buffer_nr = 0; // allways starts with buffer 0 - buffer_pos = 0; // reset position - buffer_ready = false; - buffer_eof = false; - decoder->Rewind(); // play from begin - DecoderCallback(); // fill first buffer; - if(!buffer_ready || buffer_eof) // if first buffer not ready -> no play - return; - voice = ASND_GetFirstUnusedVoice(); - if(voice >= 0) - { - s32 vol = (255*volume)/100; - s32 format = decoder->GetFormat(); - s32 samplerate = decoder->GetSampleRate(); - s32 first_pos = buffer_pos; - // switch to next buffer - buffer_nr = 1; - buffer_pos = 0; - buffer_ready = false; - buffer_eof = false; - DecoderCallback(); // fill second buffer; - GuiSoundPlayer[voice] = this; // activate Callbacks for this voice - // Play the voice - ASND_SetVoice(voice, format, samplerate, 0, play_buffer[0], first_pos, vol, vol, GuiSoundPlayerCallback); - } + Stop(); // stop playing if it played + if ( !play_buffer[0] ) return; + if ( !decoder ) return; // no decoder or no play_buffer -> no playing + // initialize the buffer + buffer_nr = 0; // allways starts with buffer 0 + buffer_pos = 0; // reset position + buffer_ready = false; + buffer_eof = false; + decoder->Rewind(); // play from begin + DecoderCallback(); // fill first buffer; + if ( !buffer_ready || buffer_eof ) // if first buffer not ready -> no play + return; + voice = ASND_GetFirstUnusedVoice(); + if ( voice >= 0 ) + { + s32 vol = ( 255 * volume ) / 100; + s32 format = decoder->GetFormat(); + s32 samplerate = decoder->GetSampleRate(); + s32 first_pos = buffer_pos; + // switch to next buffer + buffer_nr = 1; + buffer_pos = 0; + buffer_ready = false; + buffer_eof = false; + DecoderCallback(); // fill second buffer; + GuiSoundPlayer[voice] = this; // activate Callbacks for this voice + // Play the voice + ASND_SetVoice( voice, format, samplerate, 0, play_buffer[0], first_pos, vol, vol, GuiSoundPlayerCallback ); + } } /* int GuiSound::PlayOggFile(char * path) { - if(Load(path)) - Play(); - return 1; + if(Load(path)) + Play(); + return 1; } */ void GuiSound::Stop() { - if(voice < 0) return ; - GuiSoundPlayer[voice] = NULL; // disable Callbacks - SND_StopVoice(voice); - voice = -1; + if ( voice < 0 ) return ; + GuiSoundPlayer[voice] = NULL; // disable Callbacks + SND_StopVoice( voice ); + voice = -1; } void GuiSound::Pause() { - if(voice < 0) return ; - ASND_PauseVoice(voice, 1); + 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() { - return voice >= 0; + 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); + volume = vol; + 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; + loop = l; } void GuiSound::DecoderCallback() { - if(buffer_ready || buffer_eof) // if buffer ready or EOF -> nothing - return; - bool error=false; - while(buffer_pos < BUFFER_SIZE) - { - int ret = decoder->Read(&play_buffer[buffer_nr][buffer_pos], BUFFER_SIZE-buffer_pos); - if(ret > 0) - buffer_pos += ret; // ok -> fill the buffer more - else if(ret == 0) // EOF from decoder - { - if(loop) - decoder->Rewind(); // if loop -> rewind and fill the buffer more - else if(buffer_pos) - break; // has data in buffer -> play the buffer - else - buffer_eof = true; // no data in buffer -> return EOF - return; - } - else if(ret < 0) // an ERROR - { - if(buffer_pos) - break; // has data in buffer -> play the buffer - else if(loop) - { - if(!error) // if no prev error - { - decoder->Rewind(); // if loop -> rewind - error = true; // set error-state - continue; // and fill the buffer more - } - buffer_eof = true; // has prev error -> error in first block -> return EOF - return; - } - else - { - buffer_eof = true; // no loop -> return EOF - return; - } - } - error = false; // clear error-state - } - buffer_ready = true; + if ( buffer_ready || buffer_eof ) // if buffer ready or EOF -> nothing + return; + bool error = false; + while ( buffer_pos < BUFFER_SIZE ) + { + int ret = decoder->Read( &play_buffer[buffer_nr][buffer_pos], BUFFER_SIZE - buffer_pos ); + if ( ret > 0 ) + buffer_pos += ret; // ok -> fill the buffer more + else if ( ret == 0 ) // EOF from decoder + { + if ( loop ) + decoder->Rewind(); // if loop -> rewind and fill the buffer more + else if ( buffer_pos ) + break; // has data in buffer -> play the buffer + else + buffer_eof = true; // no data in buffer -> return EOF + return; + } + else if ( ret < 0 ) // an ERROR + { + if ( buffer_pos ) + break; // has data in buffer -> play the buffer + else if ( loop ) + { + if ( !error ) // if no prev error + { + decoder->Rewind(); // if loop -> rewind + error = true; // set error-state + continue; // and fill the buffer more + } + buffer_eof = true; // has prev error -> error in first block -> return EOF + return; + } + else + { + buffer_eof = true; // no loop -> return EOF + return; + } + } + error = false; // clear error-state + } + buffer_ready = true; } void GuiSound::PlayerCallback() { - if(buffer_eof) // if EOF - { - if(ASND_TestPointer(voice, play_buffer[(buffer_nr+2)%3])==0) // test prev. Buffer - Stop(); - } - else if(buffer_ready) // if buffer ready - { - if(ASND_AddVoice(voice, play_buffer[buffer_nr], buffer_pos)==SND_OK) // add buffer - { - // next buffer - buffer_nr = (buffer_nr+1)%3; - buffer_pos = 0; - buffer_ready= false; - buffer_eof = false; - } - } + if ( buffer_eof ) // if EOF + { + if ( ASND_TestPointer( voice, play_buffer[( buffer_nr+2 )%3] ) == 0 ) // test prev. Buffer + Stop(); + } + else if ( buffer_ready ) // if buffer ready + { + if ( ASND_AddVoice( voice, play_buffer[buffer_nr], buffer_pos ) == SND_OK ) // add buffer + { + // next buffer + buffer_nr = ( buffer_nr + 1 ) % 3; + buffer_pos = 0; + buffer_ready = false; + buffer_eof = false; + } + } } diff --git a/source/libwiigui/gui_sound_decoder.h b/source/libwiigui/gui_sound_decoder.h index dd62bea3..f520894e 100644 --- a/source/libwiigui/gui_sound_decoder.h +++ b/source/libwiigui/gui_sound_decoder.h @@ -17,94 +17,94 @@ #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(...); -public: - virtual ~GuiSoundDecoder(){}; - // begin API - // --------- - // each Decoder must have an own static Create(...) fnc - // static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated); - virtual s32 GetFormat()=0; - virtual s32 GetSampleRate()=0; - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - virtual int Read(u8 * buffer, int buffer_size)=0; - // set the stream to the start - virtual int Rewind()=0; - // ------- - // end API - - - struct DecoderListEntry - { - GuiSoundDecoderCreate fnc; - DecoderListEntry *next; - }; - static DecoderListEntry &RegisterDecoder(DecoderListEntry &Decoder, GuiSoundDecoderCreate fnc); - static GuiSoundDecoder *GetDecoder(const u8 * snd, u32 len, bool snd_is_allocated); -private: - static DecoderListEntry *DecoderList; - GuiSoundDecoder(GuiSoundDecoder&); // no copy + protected: + GuiSoundDecoder() {}; // Constructors must protected so it can create only with Init(...); + public: + virtual ~GuiSoundDecoder() {}; + // begin API + // --------- + // each Decoder must have an own static Create(...) fnc + // static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated); + virtual s32 GetFormat() = 0; + virtual s32 GetSampleRate() = 0; + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + virtual int Read( u8 * buffer, int buffer_size ) = 0; + // set the stream to the start + virtual int Rewind() = 0; + // ------- + // end API + + + struct DecoderListEntry + { + GuiSoundDecoderCreate fnc; + DecoderListEntry *next; + }; + static DecoderListEntry &RegisterDecoder( DecoderListEntry &Decoder, GuiSoundDecoderCreate fnc ); + static GuiSoundDecoder *GetDecoder( const u8 * snd, u32 len, bool snd_is_allocated ); + private: + static DecoderListEntry *DecoderList; + GuiSoundDecoder( GuiSoundDecoder& ); // no copy }; -#define BIG_ENDIAN_HOST 1 // Wii PPC is a Big-Endian-Host +#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; + 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; + uint32_t ret = p8[3] << 24 | p8[2] << 16 | p8[1] << 8 | p8[0]; + return ret; } #elif LITTLE_ENDIAN_HOST -inline uint16_t be16(const uint8_t *p8) +inline uint16_t be16( const uint8_t *p8 ) { - uint16_t ret = p8[0]<<8 | p8[1]; - return ret; + uint16_t ret = p8[0] << 8 | p8[1]; + return ret; } -inline uint32_t be32(const uint8_t *p8) +inline uint32_t be32( const uint8_t *p8 ) { - uint32_t ret = p8[0]<<24 | p8[1]<<16 | p8[2]<<8 | p8[3]; - return ret; + uint32_t ret = p8[0] << 24 | p8[1] << 16 | p8[2] << 8 | p8[3]; + return ret; } -inline uint16_t le16(const uint8_t *p8) +inline uint16_t le16( const uint8_t *p8 ) { - return *((uint16_t*)p8); + return *( ( uint16_t* )p8 ); } -inline uint32_t le32(const uint8_t *p8) +inline uint32_t le32( const uint8_t *p8 ) { - return *((uint32_t*)p8); + return *( ( uint32_t* )p8 ); } #else - #error "BIG_ENDIAN_HOST or LITTLE_ENDIAN_HOST not setted" +#error "BIG_ENDIAN_HOST or LITTLE_ENDIAN_HOST not setted" #endif /* XXX_ENDIAN_HOST */ -#define be16inc(p8) (p8+=2, be16(p8-2)) -#define le16inc(p8) (p8+=2, le16(p8-2)) -#define be32inc(p8) (p8+=4, be32(p8-4)) -#define le32inc(p8) (p8+=4, le32(p8-4)) +#define be16inc(p8) (p8+=2, be16(p8-2)) +#define le16inc(p8) (p8+=2, le16(p8-2)) +#define be32inc(p8) (p8+=4, be32(p8-4)) +#define le32inc(p8) (p8+=4, le32(p8-4)) diff --git a/source/libwiigui/gui_sound_decoder_aiff.cpp b/source/libwiigui/gui_sound_decoder_aiff.cpp index 688ceadb..c2f85e09 100644 --- a/source/libwiigui/gui_sound_decoder_aiff.cpp +++ b/source/libwiigui/gui_sound_decoder_aiff.cpp @@ -24,142 +24,142 @@ # 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; + double f; + int expon; + u32 hiMant, loMant; - expon = ((bytes[0] & 0x7F) << 8) | (bytes[1] & 0xFF); - hiMant = ((unsigned long)(bytes[2] & 0xFF) << 24) - | ((unsigned long)(bytes[3] & 0xFF) << 16) - | ((unsigned long)(bytes[4] & 0xFF) << 8) - | ((unsigned long)(bytes[5] & 0xFF)); - loMant = ((unsigned long)(bytes[6] & 0xFF) << 24) - | ((unsigned long)(bytes[7] & 0xFF) << 16) - | ((unsigned long)(bytes[8] & 0xFF) << 8) - | ((unsigned long)(bytes[9] & 0xFF)); + expon = ( ( bytes[0] & 0x7F ) << 8 ) | ( bytes[1] & 0xFF ); + hiMant = ( ( unsigned long )( bytes[2] & 0xFF ) << 24 ) + | ( ( unsigned long )( bytes[3] & 0xFF ) << 16 ) + | ( ( unsigned long )( bytes[4] & 0xFF ) << 8 ) + | ( ( unsigned long )( bytes[5] & 0xFF ) ); + loMant = ( ( unsigned long )( bytes[6] & 0xFF ) << 24 ) + | ( ( unsigned long )( bytes[7] & 0xFF ) << 16 ) + | ( ( unsigned long )( bytes[8] & 0xFF ) << 8 ) + | ( ( unsigned long )( bytes[9] & 0xFF ) ); - if (expon == 0 && hiMant == 0 && loMant == 0) - f = 0; - else - { - if (expon == 0x7FFF) - f = HUGE_VAL; - else - { - expon -= 16383; - f = ldexp(UnsignedToFloat(hiMant), expon-=31); - f += ldexp(UnsignedToFloat(loMant), expon-=32); - } - } + if ( expon == 0 && hiMant == 0 && loMant == 0 ) + f = 0; + else + { + if ( expon == 0x7FFF ) + f = HUGE_VAL; + else + { + expon -= 16383; + f = ldexp( UnsignedToFloat( hiMant ), expon -= 31 ); + f += ldexp( UnsignedToFloat( loMant ), expon -= 32 ); + } + } - if (bytes[0] & 0x80) - return -f; - else - return f; + if ( bytes[0] & 0x80 ) + return -f; + else + return f; } // ------ class GuiSoundDecoderAIFF : public GuiSoundDecoder { -protected: - GuiSoundDecoderAIFF(const u8 * snd, u32 len, bool snd_is_allocated) - { - sound = snd; - length =len; - is_allocated = snd_is_allocated; - is_running = false; + protected: + GuiSoundDecoderAIFF( const u8 * snd, u32 len, bool snd_is_allocated ) + { + sound = snd; + length = len; + is_allocated = snd_is_allocated; + is_running = false; - const u8 *in_ptr = sound; + const u8 *in_ptr = sound; - if(be32inc(in_ptr) != 0x464F524D /*'FORM'*/) throw("No FORM chunk"); - if(be32inc(in_ptr)+8 != len) throw("wrong Size"); - if(be32inc(in_ptr) != 0x41494646 /*'AIFF'*/) throw("No AIFF chunk"); + if ( be32inc( in_ptr ) != 0x464F524D /*'FORM'*/ ) throw( "No FORM chunk" ); + if ( be32inc( in_ptr ) + 8 != len ) throw( "wrong Size" ); + if ( be32inc( in_ptr ) != 0x41494646 /*'AIFF'*/ ) throw( "No AIFF chunk" ); - while(in_ptr+8 < sound+len) - { - u32 chunk_id = be32inc(in_ptr); - u32 chunk_size = be32inc(in_ptr); - const u8 *chunk_start = in_ptr; - switch(chunk_id) - { - case 0x434F4D4D /*'COMM'*/: - channelCount = be16inc(in_ptr); - in_ptr += 4; // skip numSampleFrames - bytePerSample = (be16inc(in_ptr)+7)/8; - if(bytePerSample < 1 && bytePerSample > 2) throw("wrong bits per Sample"); - sampleRate = ConvertFromIeeeExtended(in_ptr); - break; - case 0x53534E44 /*'SSND'*/: - pcm_start = in_ptr + 8; - pcm_end = chunk_start+chunk_size; - break; - } - in_ptr = chunk_start+chunk_size; - } - currentPos = pcm_start; - } -public: - ~GuiSoundDecoderAIFF() - { - while(is_running) usleep(50); - if(is_allocated) delete [] sound; - } - static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) - { - if(snd && len>12 && snd[0]=='F' && snd[1]=='O' && snd[2]=='R' && snd[3]=='M' - && snd[8]=='A' && snd[9]=='I' && snd[10]=='F' && snd[11]=='F') - return new GuiSoundDecoderAIFF(snd, len, snd_is_allocated); - return NULL; - } - s32 GetFormat() - { - if(bytePerSample == 2) - return channelCount==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; - else - return channelCount==2 ? VOICE_STEREO_8BIT : VOICE_MONO_8BIT; - } - s32 GetSampleRate() - { - return sampleRate; - } - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read(u8 * buffer, int buffer_size) - { - if(currentPos >= pcm_end) - return 0; // EOF + while ( in_ptr + 8 < sound + len ) + { + u32 chunk_id = be32inc( in_ptr ); + u32 chunk_size = be32inc( in_ptr ); + const u8 *chunk_start = in_ptr; + switch ( chunk_id ) + { + case 0x434F4D4D /*'COMM'*/: + channelCount = be16inc( in_ptr ); + in_ptr += 4; // skip numSampleFrames + bytePerSample = ( be16inc( in_ptr ) + 7 ) / 8; + if ( bytePerSample < 1 && bytePerSample > 2 ) throw( "wrong bits per Sample" ); + sampleRate = ConvertFromIeeeExtended( in_ptr ); + break; + case 0x53534E44 /*'SSND'*/: + pcm_start = in_ptr + 8; + pcm_end = chunk_start + chunk_size; + break; + } + in_ptr = chunk_start + chunk_size; + } + currentPos = pcm_start; + } + public: + ~GuiSoundDecoderAIFF() + { + while ( is_running ) usleep( 50 ); + if ( is_allocated ) delete [] sound; + } + static GuiSoundDecoder *Create( const u8 * snd, u32 len, bool snd_is_allocated ) + { + if ( snd && len > 12 && snd[0] == 'F' && snd[1] == 'O' && snd[2] == 'R' && snd[3] == 'M' + && snd[8] == 'A' && snd[9] == 'I' && snd[10] == 'F' && snd[11] == 'F' ) + return new GuiSoundDecoderAIFF( snd, len, snd_is_allocated ); + return NULL; + } + s32 GetFormat() + { + if ( bytePerSample == 2 ) + return channelCount == 2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; + else + return channelCount == 2 ? VOICE_STEREO_8BIT : VOICE_MONO_8BIT; + } + s32 GetSampleRate() + { + return sampleRate; + } + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read( u8 * buffer, int buffer_size ) + { + if ( currentPos >= pcm_end ) + return 0; // EOF - is_running = true; - if(currentPos + buffer_size > pcm_end) - buffer_size = pcm_end-currentPos; - memcpy(buffer, currentPos, buffer_size); - currentPos += buffer_size; - is_running = false; - return buffer_size; - } - int Rewind() - { - while(is_running) usleep(50); - currentPos = pcm_start; - return 0; - } -private: - const u8 *sound; - u32 length; - bool is_allocated; - bool is_running; + is_running = true; + if ( currentPos + buffer_size > pcm_end ) + buffer_size = pcm_end - currentPos; + memcpy( buffer, currentPos, buffer_size ); + currentPos += buffer_size; + is_running = false; + return buffer_size; + } + int Rewind() + { + while ( is_running ) usleep( 50 ); + currentPos = pcm_start; + return 0; + } + private: + const u8 *sound; + u32 length; + bool is_allocated; + bool is_running; - 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); +REGISTER_GUI_SOUND_DECODER( GuiSoundDecoderAIFF ); diff --git a/source/libwiigui/gui_sound_decoder_bns.cpp b/source/libwiigui/gui_sound_decoder_bns.cpp index e21029bd..0a4b43e7 100644 --- a/source/libwiigui/gui_sound_decoder_bns.cpp +++ b/source/libwiigui/gui_sound_decoder_bns.cpp @@ -23,238 +23,238 @@ class chanel_t { -public: - void Reset() - { - currentPos = startPos; - hist1 = hist2 = 0; - } - int DecodeNextBlock() - { - int Offset = 0; - if(currentPos == loopStart) - { - loop_hist1 = hist1; - loop_hist2 = hist2; - } - if(loop && currentPos >= endPos) - { - currentPos = loopStart; - hist1 = loop_hist1; - hist2 = loop_hist2; - Offset = loopOffset; + public: + void Reset() + { + currentPos = startPos; + hist1 = hist2 = 0; + } + int DecodeNextBlock() + { + int Offset = 0; + if ( currentPos == loopStart ) + { + loop_hist1 = hist1; + loop_hist2 = hist2; + } + if ( loop && currentPos >= endPos ) + { + currentPos = loopStart; + hist1 = loop_hist1; + hist2 = loop_hist2; + Offset = loopOffset; - } - - if(currentPos+8 <= endPos) - { - u16 index = (*currentPos >> 4) & 0x07; - s32 scale = 1 << (*currentPos++ & 0x0F); - for(int i = 0; i < 14; i+=2) - { - nibbles[i] = ((s8)*currentPos) >> 4; - nibbles[i+1] = ((s8)((*currentPos++) << 4)) >> 4; - } - for(int i = 0; i < 14; ++i) - { - s32 sample = (scale * nibbles[i])<<11; - sample += coEfficients[index * 2] * hist1; - sample += coEfficients[index * 2 + 1] * hist2; - sample += 1024; - sample = sample >> 11; - if(sample > 32767) - sample = 32767; - else if(sample < -32768) - sample = -32768; - pcm[i] = sample; + } - hist2 = hist1; - hist1 = sample; - } - return Offset; - } - return -1; - } - - const u8* startPos; - const u8* endPos; - const u8* currentPos; - s16 coEfficients[16]; - s16 nibbles[14]; - s16 pcm[14]; - s16 hist1; - s16 hist2; - bool loop; - const u8* loopStart; - u16 loopOffset; - s16 loop_hist1; - s16 loop_hist2; + if ( currentPos + 8 <= endPos ) + { + u16 index = ( *currentPos >> 4 ) & 0x07; + s32 scale = 1 << ( *currentPos++ & 0x0F ); + for ( int i = 0; i < 14; i += 2 ) + { + nibbles[i] = ( ( s8 ) * currentPos ) >> 4; + nibbles[i+1] = ( ( s8 )( ( *currentPos++ ) << 4 ) ) >> 4; + } + for ( int i = 0; i < 14; ++i ) + { + s32 sample = ( scale * nibbles[i] ) << 11; + sample += coEfficients[index * 2] * hist1; + sample += coEfficients[index * 2 + 1] * hist2; + sample += 1024; + sample = sample >> 11; + if ( sample > 32767 ) + sample = 32767; + else if ( sample < -32768 ) + sample = -32768; + pcm[i] = sample; + + hist2 = hist1; + hist1 = sample; + } + return Offset; + } + return -1; + } + + const u8* startPos; + const u8* endPos; + const u8* currentPos; + s16 coEfficients[16]; + s16 nibbles[14]; + s16 pcm[14]; + s16 hist1; + s16 hist2; + bool loop; + const u8* loopStart; + u16 loopOffset; + s16 loop_hist1; + s16 loop_hist2; }; class GuiSoundDecoderBNS : public GuiSoundDecoder { -protected: - GuiSoundDecoderBNS(const u8 * snd, u32 len, bool snd_is_allocated) - { - sound = snd; - is_running = false; - is_allocated = snd_is_allocated; + protected: + GuiSoundDecoderBNS( const u8 * snd, u32 len, bool snd_is_allocated ) + { + sound = snd; + is_running = false; + is_allocated = snd_is_allocated; - const u8 *in_ptr = sound; - - ///////////////// - // READ HEADER // - ///////////////// - if(be32inc(in_ptr) != 0x424E5320 /*'BNS '*/) throw("Not a BNS"); + const u8 *in_ptr = sound; - in_ptr += 4; // skip 4 byte + ///////////////// + // READ HEADER // + ///////////////// + if ( be32inc( in_ptr ) != 0x424E5320 /*'BNS '*/ ) throw( "Not a BNS" ); - u32 bnssize = be32inc(in_ptr); - if(bnssize != len) throw("Wrong size"); + in_ptr += 4; // skip 4 byte - in_ptr += 4; // skip unknown1 + u32 bnssize = be32inc( in_ptr ); + if ( bnssize != len ) throw( "Wrong size" ); - const u8* infoStart = sound + be32inc(in_ptr); - in_ptr+=4; // skip const u8* infoEnd = infoStart + be32inc(in_ptr); + in_ptr += 4; // skip unknown1 - channel[0].startPos = sound + be32inc(in_ptr) + 8; - channel[0].endPos = channel[0].startPos + be32inc(in_ptr) - 8; + const u8* infoStart = sound + be32inc( in_ptr ); + in_ptr += 4; // skip const u8* infoEnd = infoStart + be32inc(in_ptr); - /////////////// - // READ INFO // - /////////////// - in_ptr = infoStart + 8; // skip 'INFO' and Infosize - - in_ptr++; // skip u8 codeType = *in_ptr++; + channel[0].startPos = sound + be32inc( in_ptr ) + 8; + channel[0].endPos = channel[0].startPos + be32inc( in_ptr ) - 8; - channel[0].loop = channel[1].loop = *in_ptr++; // u8 loopFlag; - - channelCount = *in_ptr++; + /////////////// + // READ INFO // + /////////////// + in_ptr = infoStart + 8; // skip 'INFO' and Infosize - in_ptr++; // skip unknown byte + in_ptr++; // skip u8 codeType = *in_ptr++; - sampleRate = be16inc(in_ptr); + channel[0].loop = channel[1].loop = *in_ptr++; // u8 loopFlag; - 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; + channelCount = *in_ptr++; - in_ptr+=4; // skip u32 SampleCount = be32inc(in_ptr); + in_ptr++; // skip unknown byte - in_ptr+=24; // skip unknown Bytes + sampleRate = be16inc( in_ptr ); - if(channelCount == 2) - { - in_ptr+=4; // skip unknown long - u32 ChannelSplit = be32inc(in_ptr); + in_ptr += 2; // skip unknown word - in_ptr+=8; // skip 2x unknown long - - channel[1].endPos = channel[0].endPos; - channel[0].endPos = channel[1].startPos = channel[0].startPos + ChannelSplit; + 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[1].loopStart = channel[1].startPos + (channel[0].loopStart - channel[0].startPos); - } - for (int a = 0; a < 16; a++) - { - channel[0].coEfficients[a] = (s16)be16inc(in_ptr); - } - if(channelCount == 2) - { - in_ptr+=16; // skip 16 byte - for (int a = 0; a < 16; a++) - { - channel[1].coEfficients[a] = (s16)be16inc(in_ptr); - } - } - channel[0].Reset(); - channel[1].Reset(); - currentBlockPos = 14; - } -public: - ~GuiSoundDecoderBNS() - { - while(is_running) usleep(50); - if(is_allocated) delete [] sound; - } - static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) - { - if(snd && len>4 && snd[0]=='B' && snd[1]=='N' && snd[2]=='S' && snd[3]==' ') - return new GuiSoundDecoderBNS(snd, len, snd_is_allocated); - return NULL; - } - s32 GetFormat() - { - return channelCount==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; - } - s32 GetSampleRate() - { - return sampleRate; - } - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read(u8 * buffer, int buffer_size) - { - is_running = true; - u8 *write_pos = buffer; - u8 *write_end = buffer+buffer_size; - - for(;;) - { - if(currentBlockPos >= 14) - { - int Offset = channel[0].DecodeNextBlock(); - if(Offset<0 || (channelCount == 2 && channel[1].DecodeNextBlock()<0) ) - { - is_running = false; - return write_pos-buffer; - } - currentBlockPos = Offset; - } - for(;currentBlockPos < 14; ++currentBlockPos) - { - if(write_pos >= write_end) - { - is_running = false; - return write_pos-buffer; - } - *((s16*)write_pos) = channel[0].pcm[currentBlockPos]; - write_pos+=2; - if(channelCount==2) // stereo - { - *((s16*)write_pos) = channel[1].pcm[currentBlockPos]; - write_pos+=2; - } - } - } - is_running = false; - return 0; - } - int Rewind() - { - channel[0].Reset(); - channel[1].Reset(); - currentBlockPos = 14; - return 0; - } -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; + in_ptr += 4; // skip u32 SampleCount = be32inc(in_ptr); + + in_ptr += 24; // skip unknown Bytes + + if ( channelCount == 2 ) + { + in_ptr += 4; // skip unknown long + u32 ChannelSplit = be32inc( in_ptr ); + + in_ptr += 8; // skip 2x unknown long + + channel[1].endPos = channel[0].endPos; + channel[0].endPos = channel[1].startPos = channel[0].startPos + ChannelSplit; + + channel[1].loopStart = channel[1].startPos + ( channel[0].loopStart - channel[0].startPos ); + } + for ( int a = 0; a < 16; a++ ) + { + channel[0].coEfficients[a] = ( s16 )be16inc( in_ptr ); + } + if ( channelCount == 2 ) + { + in_ptr += 16; // skip 16 byte + for ( int a = 0; a < 16; a++ ) + { + channel[1].coEfficients[a] = ( s16 )be16inc( in_ptr ); + } + } + channel[0].Reset(); + channel[1].Reset(); + currentBlockPos = 14; + } + public: + ~GuiSoundDecoderBNS() + { + while ( is_running ) usleep( 50 ); + if ( is_allocated ) delete [] sound; + } + static GuiSoundDecoder *Create( const u8 * snd, u32 len, bool snd_is_allocated ) + { + if ( snd && len > 4 && snd[0] == 'B' && snd[1] == 'N' && snd[2] == 'S' && snd[3] == ' ' ) + return new GuiSoundDecoderBNS( snd, len, snd_is_allocated ); + return NULL; + } + s32 GetFormat() + { + return channelCount == 2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; + } + s32 GetSampleRate() + { + return sampleRate; + } + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read( u8 * buffer, int buffer_size ) + { + is_running = true; + u8 *write_pos = buffer; + u8 *write_end = buffer + buffer_size; + + for ( ;; ) + { + if ( currentBlockPos >= 14 ) + { + int Offset = channel[0].DecodeNextBlock(); + if ( Offset < 0 || ( channelCount == 2 && channel[1].DecodeNextBlock() < 0 ) ) + { + is_running = false; + return write_pos - buffer; + } + currentBlockPos = Offset; + } + for ( ; currentBlockPos < 14; ++currentBlockPos ) + { + if ( write_pos >= write_end ) + { + is_running = false; + return write_pos - buffer; + } + *( ( s16* )write_pos ) = channel[0].pcm[currentBlockPos]; + write_pos += 2; + if ( channelCount == 2 ) // stereo + { + *( ( s16* )write_pos ) = channel[1].pcm[currentBlockPos]; + write_pos += 2; + } + } + } + is_running = false; + return 0; + } + int Rewind() + { + channel[0].Reset(); + channel[1].Reset(); + currentBlockPos = 14; + return 0; + } + 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; }; -REGISTER_GUI_SOUND_DECODER(GuiSoundDecoderBNS); +REGISTER_GUI_SOUND_DECODER( GuiSoundDecoderBNS ); diff --git a/source/libwiigui/gui_sound_decoder_mpg.cpp b/source/libwiigui/gui_sound_decoder_mpg.cpp index fa3031c8..ad08032e 100644 --- a/source/libwiigui/gui_sound_decoder_mpg.cpp +++ b/source/libwiigui/gui_sound_decoder_mpg.cpp @@ -22,193 +22,193 @@ #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); + /* Clipping */ + if ( Fixed >= MAD_F_ONE ) + return( SHRT_MAX ); + if ( Fixed <= -MAD_F_ONE ) + return( -SHRT_MAX ); - Fixed=Fixed>>(MAD_F_FRACBITS-15); - return((s16)Fixed); + Fixed = Fixed >> ( MAD_F_FRACBITS - 15 ); + return( ( s16 )Fixed ); } -#define ADMA_BUFFERSIZE (8192) -#define DATABUFFER_SIZE (32768) +#define ADMA_BUFFERSIZE (8192) +#define DATABUFFER_SIZE (32768) // http://www.fr-an.de/fragen/v06/02_01.htm class GuiSoundDecoderMPG : public GuiSoundDecoder { -protected: - GuiSoundDecoderMPG(const u8 * snd, u32 len, bool snd_is_allocated) - { - sound = snd; - length = len; - is_allocated = snd_is_allocated; - // Init mad-structures - mad_stream_init(&madStream); - mad_stream_buffer(&madStream, sound, length); - mad_frame_init(&madFrame); - mad_synth_init(&madSynth); - madSynthPcmPos = 0; - mad_timer_reset(&madTimer); - guardBuffer = NULL; - is_running = false; + protected: + GuiSoundDecoderMPG( const u8 * snd, u32 len, bool snd_is_allocated ) + { + sound = snd; + length = len; + is_allocated = snd_is_allocated; + // Init mad-structures + mad_stream_init( &madStream ); + mad_stream_buffer( &madStream, sound, length ); + mad_frame_init( &madFrame ); + mad_synth_init( &madSynth ); + madSynthPcmPos = 0; + mad_timer_reset( &madTimer ); + guardBuffer = NULL; + is_running = false; - // decode first Frame - if(DecodeFirstFrame()) - { - mad_synth_finish(&madSynth); - mad_frame_finish(&madFrame); - mad_stream_finish(&madStream); - throw("Stream Error"); - } - } -public: - ~GuiSoundDecoderMPG() - { - while(is_running) usleep(50); - mad_synth_finish(&madSynth); - mad_frame_finish(&madFrame); - mad_stream_finish(&madStream); - delete [] guardBuffer; - if(is_allocated) delete [] sound; - } - static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) - { - struct mad_stream madStream; - struct mad_header madHeader; - mad_stream_init(&madStream); - mad_stream_buffer(&madStream, snd, len); - mad_header_init(&madHeader); - s32 ret = mad_header_decode(&madHeader, &madStream); - if(ret == 0 || madStream.error==MAD_ERROR_LOSTSYNC) // LOSTSYNC in first call is ok - { - int i; - for(i=0; i<4 && mad_header_decode(&madHeader, &madStream)==0; i++); - if( i == 4 ) - { - mad_header_finish(&madHeader); - mad_stream_finish(&madStream); - return new GuiSoundDecoderMPG(snd, len, snd_is_allocated); - } - } - mad_header_finish(&madHeader); - mad_stream_finish(&madStream); - return NULL; - } - s32 GetFormat() - { - return MAD_NCHANNELS(&madFrame.header)==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; - } - s32 GetSampleRate() - { - return madFrame.header.samplerate; - } - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read(u8 * buffer, int buffer_size) - { - is_running = true; - if(MAD_NCHANNELS(&madFrame.header)==2) // stereo - buffer_size &= ~0x0003; // make size to a kind of 4 - else - buffer_size &= ~0x0001; // make size to a kind of 2 - u8 *write_pos = buffer; - u8 *write_end = buffer+buffer_size; - - for(;;) - { - for(;madSynthPcmPos < madSynth.pcm.length; ++madSynthPcmPos) - { - if(write_pos >= write_end) - { - is_running = false; - return write_pos-buffer; - } - *((s16*)write_pos) = FixedToShort(madSynth.pcm.samples[0][madSynthPcmPos]); write_pos+=2; - if(MAD_NCHANNELS(&madFrame.header)==2) // stereo - { - *((s16*)write_pos) = FixedToShort(madSynth.pcm.samples[1][madSynthPcmPos]); write_pos+=2; - } - } + // decode first Frame + if ( DecodeFirstFrame() ) + { + mad_synth_finish( &madSynth ); + mad_frame_finish( &madFrame ); + mad_stream_finish( &madStream ); + throw( "Stream Error" ); + } + } + public: + ~GuiSoundDecoderMPG() + { + while ( is_running ) usleep( 50 ); + mad_synth_finish( &madSynth ); + mad_frame_finish( &madFrame ); + mad_stream_finish( &madStream ); + delete [] guardBuffer; + if ( is_allocated ) delete [] sound; + } + static GuiSoundDecoder *Create( const u8 * snd, u32 len, bool snd_is_allocated ) + { + struct mad_stream madStream; + struct mad_header madHeader; + mad_stream_init( &madStream ); + mad_stream_buffer( &madStream, snd, len ); + mad_header_init( &madHeader ); + s32 ret = mad_header_decode( &madHeader, &madStream ); + if ( ret == 0 || madStream.error == MAD_ERROR_LOSTSYNC ) // LOSTSYNC in first call is ok + { + int i; + for ( i = 0; i < 4 && mad_header_decode( &madHeader, &madStream ) == 0; i++ ); + if ( i == 4 ) + { + mad_header_finish( &madHeader ); + mad_stream_finish( &madStream ); + return new GuiSoundDecoderMPG( snd, len, snd_is_allocated ); + } + } + mad_header_finish( &madHeader ); + mad_stream_finish( &madStream ); + return NULL; + } + s32 GetFormat() + { + return MAD_NCHANNELS( &madFrame.header ) == 2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; + } + s32 GetSampleRate() + { + return madFrame.header.samplerate; + } + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read( u8 * buffer, int buffer_size ) + { + is_running = true; + if ( MAD_NCHANNELS( &madFrame.header ) == 2 ) // stereo + buffer_size &= ~0x0003; // make size to a kind of 4 + else + buffer_size &= ~0x0001; // make size to a kind of 2 + u8 *write_pos = buffer; + u8 *write_end = buffer + buffer_size; - madStream.error = MAD_ERROR_NONE; - if(mad_frame_decode(&madFrame,&madStream)) - { - if(MAD_RECOVERABLE(madStream.error)) - { - if(madStream.error!=MAD_ERROR_LOSTSYNC || !guardBuffer) - continue; - } - else if(madStream.error==MAD_ERROR_BUFLEN) - { - if(!guardBuffer) - { - u32 guardLen = (madStream.bufend-madStream.next_frame); - guardBuffer = new(std::nothrow) u8[guardLen + MAD_BUFFER_GUARD]; - if(guardBuffer) - { - memcpy(guardBuffer, madStream.next_frame, guardLen); - memset(guardBuffer+guardLen, 0, MAD_BUFFER_GUARD); - mad_stream_buffer(&madStream, guardBuffer, guardLen + MAD_BUFFER_GUARD); - continue; - } - } - } - break; - } - mad_timer_add(&madTimer,madFrame.header.duration); - mad_synth_frame(&madSynth,&madFrame); - madSynthPcmPos = 0; - } - is_running = false; - return write_pos-buffer; - } - int Rewind() - { - while(is_running) usleep(50); - delete [] guardBuffer; guardBuffer = NULL; - mad_stream_buffer(&madStream, sound, length); - mad_synth_finish(&madSynth); - mad_synth_init(&madSynth); - madSynthPcmPos = 0; - mad_timer_reset(&madTimer); - // decode first Frame - return DecodeFirstFrame(); - } -private: - int DecodeFirstFrame() - { - for(;;) - { - madStream.error = MAD_ERROR_NONE; - if(mad_frame_decode(&madFrame,&madStream)) - { - if(MAD_RECOVERABLE(madStream.error)) - continue; - else - return -1; - } - mad_timer_add(&madTimer,madFrame.header.duration); - mad_synth_frame(&madSynth,&madFrame); - return 0; - } - } - const u8 *sound; - u32 length; - bool is_allocated; - struct mad_stream madStream; - struct mad_frame madFrame; - struct mad_synth madSynth; - u16 madSynthPcmPos; - mad_timer_t madTimer; - u8 *guardBuffer; - bool is_running; + for ( ;; ) + { + for ( ; madSynthPcmPos < madSynth.pcm.length; ++madSynthPcmPos ) + { + if ( write_pos >= write_end ) + { + is_running = false; + return write_pos - buffer; + } + *( ( s16* )write_pos ) = FixedToShort( madSynth.pcm.samples[0][madSynthPcmPos] ); write_pos += 2; + if ( MAD_NCHANNELS( &madFrame.header ) == 2 ) // stereo + { + *( ( s16* )write_pos ) = FixedToShort( madSynth.pcm.samples[1][madSynthPcmPos] ); write_pos += 2; + } + } + + madStream.error = MAD_ERROR_NONE; + if ( mad_frame_decode( &madFrame, &madStream ) ) + { + if ( MAD_RECOVERABLE( madStream.error ) ) + { + if ( madStream.error != MAD_ERROR_LOSTSYNC || !guardBuffer ) + continue; + } + else if ( madStream.error == MAD_ERROR_BUFLEN ) + { + if ( !guardBuffer ) + { + u32 guardLen = ( madStream.bufend - madStream.next_frame ); + guardBuffer = new( std::nothrow ) u8[guardLen + MAD_BUFFER_GUARD]; + if ( guardBuffer ) + { + memcpy( guardBuffer, madStream.next_frame, guardLen ); + memset( guardBuffer + guardLen, 0, MAD_BUFFER_GUARD ); + mad_stream_buffer( &madStream, guardBuffer, guardLen + MAD_BUFFER_GUARD ); + continue; + } + } + } + break; + } + mad_timer_add( &madTimer, madFrame.header.duration ); + mad_synth_frame( &madSynth, &madFrame ); + madSynthPcmPos = 0; + } + is_running = false; + return write_pos - buffer; + } + int Rewind() + { + while ( is_running ) usleep( 50 ); + delete [] guardBuffer; guardBuffer = NULL; + mad_stream_buffer( &madStream, sound, length ); + mad_synth_finish( &madSynth ); + mad_synth_init( &madSynth ); + madSynthPcmPos = 0; + mad_timer_reset( &madTimer ); + // decode first Frame + return DecodeFirstFrame(); + } + private: + int DecodeFirstFrame() + { + for ( ;; ) + { + madStream.error = MAD_ERROR_NONE; + if ( mad_frame_decode( &madFrame, &madStream ) ) + { + if ( MAD_RECOVERABLE( madStream.error ) ) + continue; + else + return -1; + } + mad_timer_add( &madTimer, madFrame.header.duration ); + mad_synth_frame( &madSynth, &madFrame ); + return 0; + } + } + const u8 *sound; + u32 length; + bool is_allocated; + struct mad_stream madStream; + struct mad_frame madFrame; + struct mad_synth madSynth; + u16 madSynthPcmPos; + mad_timer_t madTimer; + u8 *guardBuffer; + bool is_running; }; -REGISTER_GUI_SOUND_DECODER(GuiSoundDecoderMPG); +REGISTER_GUI_SOUND_DECODER( GuiSoundDecoderMPG ); diff --git a/source/libwiigui/gui_sound_decoder_ogg.cpp b/source/libwiigui/gui_sound_decoder_ogg.cpp index de1920a8..0e91cfa1 100644 --- a/source/libwiigui/gui_sound_decoder_ogg.cpp +++ b/source/libwiigui/gui_sound_decoder_ogg.cpp @@ -24,280 +24,281 @@ 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; + int b; + int c = 0; + int d; - if (bytes * blocks <= 0) - return 0; + if ( bytes * blocks <= 0 ) + return 0; - blocks *= bytes; + blocks *= bytes; - while (blocks > 0) - { - b = blocks; - if (b > 4096) - b = 4096; + while ( blocks > 0 ) + { + b = blocks; + if ( b > 4096 ) + b = 4096; - 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) - { - memcpy(punt, file[d].mem + file[d].pos, b); - file[d].pos += b; - } - } - else - b = read(*f, ((char *) punt) + c, b); + 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 ) + { + memcpy( punt, file[d].mem + file[d].pos, b ); + file[d].pos += b; + } + } + else + b = read( *f, ( ( char * ) punt ) + c, b ); - if (b <= 0) - { - return c / bytes; - } - c += b; - blocks -= b; - } - return c / bytes; + if ( b <= 0 ) + { + return c / bytes; + } + c += b; + blocks -= b; + } + 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 k; + mode &= 3; - int d = (*f) - 0x666; - if((unsigned)(d) <= (0x669 - 0x666)) - { - k = 0; + 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 ((offset) >= file[d].size) - { - file[d].pos = file[d].size; - k = -1; - } - else if ((offset) < 0) - { - file[d].pos = 0; - k = -1; - } - else - file[d].pos = offset; - } - else if (mode == 1) - { - if ((file[d].pos + offset) >= file[d].size) - { - file[d].pos = file[d].size; - k = -1; - } - else if ((file[d].pos + offset) < 0) - { - file[d].pos = 0; - k = -1; - } - else - file[d].pos += offset; - } - else if (mode == 2) - { + if ( mode == 0 ) + { + if ( ( offset ) >= file[d].size ) + { + file[d].pos = file[d].size; + k = -1; + } + else if ( ( offset ) < 0 ) + { + file[d].pos = 0; + k = -1; + } + else + file[d].pos = offset; + } + else if ( mode == 1 ) + { + if ( ( file[d].pos + offset ) >= file[d].size ) + { + file[d].pos = file[d].size; + k = -1; + } + else if ( ( file[d].pos + offset ) < 0 ) + { + file[d].pos = 0; + k = -1; + } + else + file[d].pos += offset; + } + else if ( mode == 2 ) + { - if ((file[d].size + offset) >= file[d].size) - { - file[d].pos = file[d].size; - k = -1; - } - else if ((file[d].size + offset) < 0) - { - file[d].pos = 0; - k = -1; - } - else - file[d].pos = file[d].size + offset; - } + if ( ( file[d].size + offset ) >= file[d].size ) + { + file[d].pos = file[d].size; + k = -1; + } + else if ( ( file[d].size + offset ) < 0 ) + { + file[d].pos = 0; + k = -1; + } + 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) - k = -1; - else - k = 0; - return k; + if ( k < 0 ) + k = -1; + 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)) - { - file[d].size = 0; - file[d].pos = 0; - if (file[d].mem) - { - file[d].mem = (char *) 0; - } - return 0; - } - else - return close(*f); - return 0; + int d = ( *f ) - 0x666; + if ( ( unsigned )( d ) <= ( 0x669 - 0x666 ) ) + { + file[d].size = 0; + file[d].pos = 0; + if ( file[d].mem ) + { + file[d].mem = ( char * ) 0; + } + return 0; + } + else + return close( *f ); + return 0; } -static long f_tell(int *f) +static long f_tell( int *f ) { - int k; + int k; - int d = (*f) - 0x666; - if((unsigned)(d) <= (0x669 - 0x666)) - { - k = file[d].pos; - } - else - k = lseek(*f, 0, 1); + int d = ( *f ) - 0x666; + if ( ( unsigned )( d ) <= ( 0x669 - 0x666 ) ) + { + k = file[d].pos; + } + 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) - { - one = 0; + static int one = 1; + int n; + if ( one ) + { + one = 0; - file[0].size = 0; - file[1].size = 0; - file[2].size = 0; - file[3].size = 0; - file[0].mem = ogg; - file[0].size = size; - file[0].pos = 0; - return (0x666); - } + file[0].size = 0; + file[1].size = 0; + file[2].size = 0; + file[3].size = 0; + file[0].mem = ogg; + file[0].size = size; + file[0].pos = 0; + return ( 0x666 ); + } - for (n = 0; n < 4; n++) - { - if (file[n].size == 0) - { - file[n].mem = ogg; - file[n].size = size; - file[n].pos = 0; - return (0x666 + n); - } - } - return -1; + for ( n = 0; n < 4; n++ ) + { + if ( file[n].size == 0 ) + { + file[n].mem = ogg; + file[n].size = size; + file[n].pos = 0; + 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? - { - fd -= 0x666; - file[fd].size = 0; - return 0; - } - else - return f_close(&fd); + 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 ); } -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 { -protected: - GuiSoundDecoderOGG(const u8 * snd, u32 len, bool snd_is_allocated) - { - sound = snd; - is_allocated = snd_is_allocated; - ogg_fd = mem_open((char *)snd, len); - if(ogg_fd < 0) throw("mem open failed"); + protected: + GuiSoundDecoderOGG( const u8 * snd, u32 len, bool snd_is_allocated ) + { + sound = snd; + is_allocated = snd_is_allocated; + ogg_fd = mem_open( ( char * )snd, len ); + if ( ogg_fd < 0 ) throw( "mem open failed" ); - if (ov_open_callbacks((void*)&ogg_fd, &ogg_file, NULL, 0, callbacks) < 0) - { - mem_close(ogg_fd); - throw("ogg open failed"); - } - ogg_info = ov_info(&ogg_file, -1); - bitstream = 0; - is_running = false; - } -public: - ~GuiSoundDecoderOGG() - { - while(is_running) usleep(50); - ov_clear(&ogg_file); - if(is_allocated) delete [] sound; - } - static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) - { - if(snd && len>4 && snd[0]=='O' && snd[1]=='g' && snd[2]=='g' && snd[3]=='S') - return new GuiSoundDecoderOGG(snd, len, snd_is_allocated); - return NULL; - } - s32 GetFormat() - { - return ogg_info->channels==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; - } - s32 GetSampleRate() - { - return ogg_info->rate; - } - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read(u8 * buffer, int buffer_size) - { - is_running = true; - int ret = ov_read(&ogg_file, (char *)buffer, buffer_size, &bitstream); - if (ret < 0) - { - /* error in the stream. Not a problem, just reporting it in - case we (the app) cares. In this case, we don't. */ - if (ret != OV_HOLE) - ret = 0; // we says EOF - } - is_running = false; - return ret; - } - int Rewind() - { - return ov_time_seek(&ogg_file, 0); - } -private: - const u8 *sound; - bool is_allocated; - int ogg_fd; - OggVorbis_File ogg_file; - vorbis_info *ogg_info; - int bitstream; - bool is_running; + if ( ov_open_callbacks( ( void* )&ogg_fd, &ogg_file, NULL, 0, callbacks ) < 0 ) + { + mem_close( ogg_fd ); + throw( "ogg open failed" ); + } + ogg_info = ov_info( &ogg_file, -1 ); + bitstream = 0; + is_running = false; + } + public: + ~GuiSoundDecoderOGG() + { + while ( is_running ) usleep( 50 ); + ov_clear( &ogg_file ); + if ( is_allocated ) delete [] sound; + } + static GuiSoundDecoder *Create( const u8 * snd, u32 len, bool snd_is_allocated ) + { + if ( snd && len > 4 && snd[0] == 'O' && snd[1] == 'g' && snd[2] == 'g' && snd[3] == 'S' ) + return new GuiSoundDecoderOGG( snd, len, snd_is_allocated ); + return NULL; + } + s32 GetFormat() + { + return ogg_info->channels == 2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; + } + s32 GetSampleRate() + { + return ogg_info->rate; + } + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read( u8 * buffer, int buffer_size ) + { + is_running = true; + int ret = ov_read( &ogg_file, ( char * )buffer, buffer_size, &bitstream ); + if ( ret < 0 ) + { + /* error in the stream. Not a problem, just reporting it in + case we (the app) cares. In this case, we don't. */ + if ( ret != OV_HOLE ) + ret = 0; // we says EOF + } + is_running = false; + return ret; + } + int Rewind() + { + return ov_time_seek( &ogg_file, 0 ); + } + private: + 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); +REGISTER_GUI_SOUND_DECODER( GuiSoundDecoderOGG ); diff --git a/source/libwiigui/gui_sound_decoder_wav.cpp b/source/libwiigui/gui_sound_decoder_wav.cpp index 234366d2..89d25f91 100644 --- a/source/libwiigui/gui_sound_decoder_wav.cpp +++ b/source/libwiigui/gui_sound_decoder_wav.cpp @@ -21,217 +21,217 @@ typedef struct { - u32 cueID; - u32 len; - u32 loops; -}plst_t; -typedef struct + u32 cueID; + u32 len; + u32 loops; +} plst_t; +typedef struct { - const u8 *start; - const u8 *end; - u32 loops; -}playlist_t; + const u8 *start; + const u8 *end; + u32 loops; +} playlist_t; class GuiSoundDecoderWAV : public GuiSoundDecoder { -protected: - GuiSoundDecoderWAV(const u8 * snd, u32 len, bool snd_is_allocated) - { - sound = snd; - is_running = false; - is_allocated = snd_is_allocated; + protected: + GuiSoundDecoderWAV( const u8 * snd, u32 len, bool snd_is_allocated ) + { + sound = snd; + is_running = false; + is_allocated = snd_is_allocated; - const u8 *in_ptr = sound; - - if(be32inc(in_ptr) != 0x52494646 /*'RIFF' (WAV)*/) throw("Not a WAV"); + const u8 *in_ptr = sound; - u32 riffsize = le32inc(in_ptr); - if(riffsize > (len-8)) throw("Wrong size"); + if ( be32inc( in_ptr ) != 0x52494646 /*'RIFF' (WAV)*/ ) throw( "Not a WAV" ); - if(be32inc(in_ptr) != 0x57415645 /*'WAVE'*/) throw("No WAVE-Tag"); + u32 riffsize = le32inc( in_ptr ); + if ( riffsize > ( len - 8 ) ) throw( "Wrong size" ); - if(be32inc(in_ptr) != 0x666D7420 /*'fmt '*/) throw("No fmt-Tag"); + if ( be32inc( in_ptr ) != 0x57415645 /*'WAVE'*/ ) throw( "No WAVE-Tag" ); - u32 fmtLen = le32inc(in_ptr); + if ( be32inc( in_ptr ) != 0x666D7420 /*'fmt '*/ ) throw( "No fmt-Tag" ); - if(le16inc(in_ptr) != 1) throw("Not PCM data"); + u32 fmtLen = le32inc( in_ptr ); - channelCount = le16inc(in_ptr); - if(channelCount < 1 || channelCount > 2) throw("only mono or stereo"); - - sampleRate = le32inc(in_ptr); - - in_ptr += 6; // skip and - - bytePerSample = (le16inc(in_ptr)+7)/8; - if(bytePerSample < 1 || bytePerSample > 2) throw("only 1-16 bit/Sample"); - - in_ptr += fmtLen-16; + if ( le16inc( in_ptr ) != 1 ) throw( "Not PCM data" ); - if(be32inc(in_ptr) != 0x64617461 /*'data'*/) throw("No data-Tag"); - + channelCount = le16inc( in_ptr ); + if ( channelCount < 1 || channelCount > 2 ) throw( "only mono or stereo" ); - soundDataStart = in_ptr+4; - soundDataEnd = soundDataStart + le32(in_ptr); + sampleRate = le32inc( in_ptr ); - in_ptr = soundDataEnd; + in_ptr += 6; // skip and - std::map cue; - std::vectorplst; + 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" ); + + + soundDataStart = in_ptr + 4; + soundDataEnd = soundDataStart + le32( in_ptr ); + + in_ptr = soundDataEnd; + + std::map cue; + std::vectorplst; + + if ( ( ( u32 )in_ptr ) & 0x0001UL ) in_ptr++; + while ( ( in_ptr + 4 ) < ( sound + riffsize ) ) + { + u32 tag = be32inc( in_ptr ); + switch ( tag ) + { + case 0x63756520 /*'cue '*/: + in_ptr += 4; // skip size + for ( u32 count = le32inc( in_ptr ); count > 0; count-- ) + { + u32 ID = be32inc( in_ptr ); + in_ptr += 4; // skip dwPosition + if ( be32inc( in_ptr ) == 0x64617461 /*'data'*/ ) + { + in_ptr += 8; // skip chunkStart - dwBlockStart + cue[ID] = le32inc( in_ptr ); + } + else + in_ptr += 12; // skip chunkStart - SammpleOffset + } + break; + case 0x706C7374 /*' plst'*/: + in_ptr += 4; // skip size + for ( u32 count = le32inc( in_ptr ); count > 0; count-- ) + plst.push_back( ( plst_t ) {le32inc( in_ptr ), le32inc( in_ptr ), le32inc( in_ptr )} ); + break; + default: + in_ptr -= 2; + break; + } + } + for ( std::vector::iterator i = plst.begin(); i != plst.end(); ++i ) + { + const u8 *start = soundDataStart + cue[i->cueID]; + const u8 *end = soundDataStart + ( i->len * bytePerSample * channelCount ); + u32 loops = i->loops; + playlist.push_back( ( playlist_t ) {start, end, loops} ); + } + if ( playlist.size() == 0 ) + { + playlist.push_back( ( playlist_t ) {soundDataStart, soundDataEnd, 1} ); + } + Rewind(); + } + public: + ~GuiSoundDecoderWAV() + { + while ( is_running ) usleep( 50 ); + if ( is_allocated ) delete [] sound; + } + static GuiSoundDecoder *Create( const u8 * snd, u32 len, bool snd_is_allocated ) + { + if ( snd && len > 4 && snd[0] == 'R' && snd[1] == 'I' && snd[2] == 'F' && snd[3] == 'F' + && snd[8] == 'W' && snd[9] == 'A' && snd[10] == 'V' && snd[11] == 'E' ) + return new GuiSoundDecoderWAV( snd, len, snd_is_allocated ); + return NULL; + } + s32 GetFormat() + { + if ( bytePerSample == 2 ) + return channelCount == 2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; + else + return channelCount == 2 ? VOICE_STEREO_8BIT : VOICE_MONO_8BIT; + } + s32 GetSampleRate() + { + return sampleRate; + } + /* Read reads data from stream to buffer + return: >0 = readed bytes; + 0 = EOF; + <0 = Error; + */ + int Read( u8 * buffer, int buffer_size ) + { + is_running = true; + u8 *write_pos = buffer; + u8 *write_end = buffer + buffer_size; + + for ( ;; ) + { + while ( currentPos < currentEnd ) + { + if ( write_pos >= write_end ) + { + is_running = false; + return write_pos - buffer; + } + if ( bytePerSample == 2 ) + { + *( ( s16* )write_pos ) = le16inc( currentPos ); + write_pos += 2; + if ( channelCount == 2 ) // stereo + { + *( ( s16* )write_pos ) = le16inc( currentPos ); + write_pos += 2; + } + } + else + { + *write_pos++ = *currentPos++; + if ( channelCount == 2 ) // stereo + *write_pos++ = *currentPos++; + } + } + if ( currentLoops > 1 ) + { + currentLoops--; + currentPos = currentStart; + continue; + } + if ( currentPlaylist != playlist.end() ) + currentPlaylist++; + if ( currentPlaylist != playlist.end() ) + { + currentStart = currentPos = currentPlaylist->start; + currentEnd = currentPlaylist->end; + currentLoops = currentPlaylist->loops; + continue; + } + else + { + is_running = false; + return write_pos - buffer; + } + } + is_running = false; + return 0; + } + int Rewind() + { + currentPlaylist = playlist.begin(); + currentStart = currentPos = currentPlaylist->start; + currentEnd = currentPlaylist->end; + currentLoops = currentPlaylist->loops; + return 0; + } + private: + const u8 *sound; + bool is_allocated; + bool is_running; + + u16 channelCount; + u32 sampleRate; + u16 bytePerSample; + const u8 *soundDataStart; + const u8 *soundDataEnd; + std::vector playlist; + std::vector::iterator currentPlaylist; + const u8 *currentStart; + const u8 *currentEnd; + u32 currentLoops; + const u8 *currentPos; - if(((u32)in_ptr) & 0x0001UL) in_ptr++; - while((in_ptr+4) < (sound + riffsize)) - { - u32 tag = be32inc(in_ptr); - switch(tag) - { - case 0x63756520 /*'cue '*/: - in_ptr += 4; // skip size - for(u32 count = le32inc(in_ptr); count>0; count--) - { - u32 ID = be32inc(in_ptr); - in_ptr += 4; // skip dwPosition - if(be32inc(in_ptr) == 0x64617461 /*'data'*/) - { - in_ptr += 8; // skip chunkStart - dwBlockStart - cue[ID] = le32inc(in_ptr); - } - else - in_ptr += 12; // skip chunkStart - SammpleOffset - } - break; - case 0x706C7374 /*' plst'*/: - in_ptr += 4; // skip size - for(u32 count = le32inc(in_ptr); count>0; count--) - plst.push_back((plst_t){le32inc(in_ptr), le32inc(in_ptr), le32inc(in_ptr)}); - break; - default: - in_ptr -= 2; - break; - } - } - for(std::vector::iterator i = plst.begin(); i != plst.end(); ++i) - { - const u8 *start = soundDataStart + cue[i->cueID]; - const u8 *end = soundDataStart + (i->len*bytePerSample*channelCount); - u32 loops = i->loops; - playlist.push_back((playlist_t){start,end,loops}); - } - if(playlist.size() == 0) - { - playlist.push_back((playlist_t){soundDataStart, soundDataEnd, 1}); - } - Rewind(); - } -public: - ~GuiSoundDecoderWAV() - { - while(is_running) usleep(50); - if(is_allocated) delete [] sound; - } - static GuiSoundDecoder *Create(const u8 * snd, u32 len, bool snd_is_allocated) - { - if(snd && len>4 && snd[0]=='R' && snd[1]=='I' && snd[2]=='F' && snd[3]=='F' - && snd[8]=='W' && snd[9]=='A' && snd[10]=='V' && snd[11]=='E') - return new GuiSoundDecoderWAV(snd, len, snd_is_allocated); - return NULL; - } - s32 GetFormat() - { - if(bytePerSample == 2) - return channelCount==2 ? VOICE_STEREO_16BIT : VOICE_MONO_16BIT; - else - return channelCount==2 ? VOICE_STEREO_8BIT : VOICE_MONO_8BIT; - } - s32 GetSampleRate() - { - return sampleRate; - } - /* Read reads data from stream to buffer - return: >0 = readed bytes; - 0 = EOF; - <0 = Error; - */ - int Read(u8 * buffer, int buffer_size) - { - is_running = true; - u8 *write_pos = buffer; - u8 *write_end = buffer+buffer_size; - - for(;;) - { - while(currentPos < currentEnd) - { - if(write_pos >= write_end) - { - is_running = false; - return write_pos-buffer; - } - if(bytePerSample == 2) - { - *((s16*)write_pos) = le16inc(currentPos); - write_pos+=2; - if(channelCount==2) // stereo - { - *((s16*)write_pos) = le16inc(currentPos); - write_pos+=2; - } - } - else - { - *write_pos++ = *currentPos++; - if(channelCount==2) // stereo - *write_pos++ = *currentPos++; - } - } - if(currentLoops>1) - { - currentLoops--; - currentPos = currentStart; - continue; - } - if(currentPlaylist != playlist.end()) - currentPlaylist++; - if(currentPlaylist != playlist.end()) - { - currentStart = currentPos = currentPlaylist->start; - currentEnd = currentPlaylist->end; - currentLoops = currentPlaylist->loops; - continue; - } - else - { - is_running = false; - return write_pos-buffer; - } - } - is_running = false; - return 0; - } - int Rewind() - { - currentPlaylist = playlist.begin(); - currentStart = currentPos = currentPlaylist->start; - currentEnd = currentPlaylist->end; - currentLoops = currentPlaylist->loops; - return 0; - } -private: - const u8 *sound; - bool is_allocated; - bool is_running; - - u16 channelCount; - u32 sampleRate; - u16 bytePerSample; - const u8 *soundDataStart; - const u8 *soundDataEnd; - std::vector playlist; - std::vector::iterator currentPlaylist; - const u8 *currentStart; - const u8 *currentEnd; - u32 currentLoops; - const u8 *currentPos; - }; -REGISTER_GUI_SOUND_DECODER(GuiSoundDecoderWAV); +REGISTER_GUI_SOUND_DECODER( GuiSoundDecoderWAV ); diff --git a/source/libwiigui/gui_text.cpp b/source/libwiigui/gui_text.cpp index 4ddbeaa5..f8b1be0a 100644 --- a/source/libwiigui/gui_text.cpp +++ b/source/libwiigui/gui_text.cpp @@ -11,115 +11,115 @@ #include "gui.h" #include "wstring.hpp" -#define MAX_LINES_TO_DRAW 9 +#define MAX_LINES_TO_DRAW 9 static int presetSize = 18; 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 +#define TEXT_SCROLL_DELAY 5 +#define TEXT_SCROLL_INITIAL_DELAY 8 /** * 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; - currentSize = size; - color = c; - alpha = c.a; - style = FTGX_JUSTIFY_CENTER | FTGX_ALIGN_MIDDLE; - maxWidth = 0; - wrapMode = 0; - passChar = 0; - font = NULL; - linestodraw = MAX_LINES_TO_DRAW; - textScrollPos = 0; - textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - textScrollDelay = TEXT_SCROLL_DELAY; + text = NULL; + size = s; + currentSize = size; + color = c; + alpha = c.a; + style = FTGX_JUSTIFY_CENTER | FTGX_ALIGN_MIDDLE; + maxWidth = 0; + wrapMode = 0; + passChar = 0; + font = NULL; + linestodraw = MAX_LINES_TO_DRAW; + textScrollPos = 0; + textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; + textScrollDelay = TEXT_SCROLL_DELAY; - alignmentHor = ALIGN_CENTRE; - alignmentVert = ALIGN_MIDDLE; + alignmentHor = ALIGN_CENTRE; + alignmentVert = ALIGN_MIDDLE; - if(t) - { - text = charToWideChar(t); - if(!text) - return; - - textWidth = fontSystem->getWidth(text, currentSize); - } -} - -GuiText::GuiText(const wchar_t * t, int s, GXColor c) -{ - text = NULL; - size = s; - currentSize = size; - color = c; - alpha = c.a; - style = FTGX_JUSTIFY_CENTER | FTGX_ALIGN_MIDDLE; - maxWidth = 0; - wrapMode = 0; - passChar = 0; - font = NULL; - linestodraw = MAX_LINES_TO_DRAW; - textScrollPos = 0; - textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - textScrollDelay = TEXT_SCROLL_DELAY; - - alignmentHor = ALIGN_CENTRE; - alignmentVert = ALIGN_MIDDLE; - - if(t) - { - text = new (std::nothrow) wchar_t[wcslen(t)+1]; - if(!text) + if ( t ) + { + text = charToWideChar( t ); + if ( !text ) return; - wcscpy(text, t); + textWidth = fontSystem->getWidth( text, currentSize ); + } +} - textWidth = fontSystem->getWidth(text, currentSize); - } +GuiText::GuiText( const wchar_t * t, int s, GXColor c ) +{ + text = NULL; + size = s; + currentSize = size; + color = c; + alpha = c.a; + style = FTGX_JUSTIFY_CENTER | FTGX_ALIGN_MIDDLE; + maxWidth = 0; + wrapMode = 0; + passChar = 0; + font = NULL; + linestodraw = MAX_LINES_TO_DRAW; + textScrollPos = 0; + textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; + textScrollDelay = TEXT_SCROLL_DELAY; + + alignmentHor = ALIGN_CENTRE; + alignmentVert = ALIGN_MIDDLE; + + if ( t ) + { + text = new ( std::nothrow ) wchar_t[wcslen( t )+1]; + if ( !text ) + return; + + wcscpy( text, t ); + + 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; - currentSize = size; - color = presetColor; - alpha = presetColor.a; - style = presetStyle; - maxWidth = presetMaxWidth; - wrapMode = 0; - passChar = 0; - font = NULL; - linestodraw = MAX_LINES_TO_DRAW; - textScrollPos = 0; - textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - textScrollDelay = TEXT_SCROLL_DELAY; + text = NULL; + size = presetSize; + currentSize = size; + color = presetColor; + alpha = presetColor.a; + style = presetStyle; + maxWidth = presetMaxWidth; + wrapMode = 0; + passChar = 0; + font = NULL; + linestodraw = MAX_LINES_TO_DRAW; + textScrollPos = 0; + textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; + textScrollDelay = TEXT_SCROLL_DELAY; - alignmentHor = presetAlignmentHor; - alignmentVert = presetAlignmentVert; + alignmentHor = presetAlignmentHor; + alignmentVert = presetAlignmentVert; - if(t) - { - text = charToWideChar(t); - if(!text) - return; + if ( t ) + { + text = charToWideChar( t ); + if ( !text ) + return; - textWidth = fontSystem->getWidth(text, currentSize); - } + textWidth = fontSystem->getWidth( text, currentSize ); + } } @@ -128,12 +128,12 @@ GuiText::GuiText(const char * t) */ GuiText::~GuiText() { - if(text) - delete [] text; - text = NULL; + if ( text ) + delete [] text; + text = NULL; - if(font) - { + if ( font ) + { delete font; font = NULL; } @@ -141,201 +141,201 @@ GuiText::~GuiText() ClearDynamicText(); } -void GuiText::SetText(const char * t) +void GuiText::SetText( const char * t ) { - LOCK(this); + LOCK( this ); - if(text) - delete [] text; + if ( text ) + delete [] text; text = NULL; ClearDynamicText(); - textScrollPos = 0; - textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; + textScrollPos = 0; + textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - if(t) - { - text = charToWideChar(t); - if(!text) - return; - - if (passChar != 0) - { - for (u8 i = 0; i < wcslen(text); i++) - text[i] = passChar; - } - - textWidth = fontSystem->getWidth(text, currentSize); - } -} - -void GuiText::SetTextf(const char *format, ...) -{ - if(!format) - SetText((char *) NULL); - - char *tmp=0; - va_list va; - va_start(va, format); - if((vasprintf(&tmp, format, va)>=0) && tmp) - { - SetText(tmp); - } - va_end(va); - - if(tmp) - free(tmp); -} - - -void GuiText::SetText(const wchar_t * t) -{ - LOCK(this); - - if(text) - delete [] text; - text = NULL; - - ClearDynamicText(); - - textScrollPos = 0; - textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; - - if(t) - { - text = new (std::nothrow) wchar_t[wcslen(t)+1]; - if(!text) + if ( t ) + { + text = charToWideChar( t ); + if ( !text ) return; - wcscpy(text, t); + if ( passChar != 0 ) + { + for ( u8 i = 0; i < wcslen( text ); i++ ) + text[i] = passChar; + } - if (passChar != 0) - { - 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, ... ) +{ + if ( !format ) + SetText( ( char * ) NULL ); + + char *tmp = 0; + va_list va; + va_start( va, format ); + if ( ( vasprintf( &tmp, format, va ) >= 0 ) && tmp ) + { + SetText( tmp ); + } + va_end( va ); + + if ( tmp ) + free( tmp ); +} + + +void GuiText::SetText( const wchar_t * t ) +{ + LOCK( this ); + + if ( text ) + delete [] text; + text = NULL; + + ClearDynamicText(); + + textScrollPos = 0; + textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; + + if ( t ) + { + text = new ( std::nothrow ) wchar_t[wcslen( t )+1]; + if ( !text ) + return; + + wcscpy( text, t ); + + if ( passChar != 0 ) + { + for ( u8 i = 0; i < wcslen( text ); i++ ) + text[i] = passChar; + } + + 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]) + 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; - presetStyle = s; - presetMaxWidth = w; - presetAlignmentHor = h; - presetAlignmentVert = v; + presetSize = sz; + presetColor = c; + presetStyle = s; + presetMaxWidth = w; + presetAlignmentHor = h; + presetAlignmentVert = v; } -void GuiText::SetFontSize(int s) +void GuiText::SetFontSize( int s ) { - LOCK(this); + LOCK( this ); - size = s; + size = s; } -void GuiText::SetMaxWidth(int width, int w) +void GuiText::SetMaxWidth( int width, int w ) { - LOCK(this); + LOCK( this ); - maxWidth = width; - wrapMode = w; + maxWidth = width; + wrapMode = w; - if(w == SCROLL_HORIZONTAL) - { + if ( w == SCROLL_HORIZONTAL ) + { textScrollPos = 0; textScrollInitialDelay = TEXT_SCROLL_INITIAL_DELAY; textScrollDelay = TEXT_SCROLL_DELAY; - } + } ClearDynamicText(); } -void GuiText::SetPassChar(wchar_t p) +void GuiText::SetPassChar( wchar_t p ) { - LOCK(this); - passChar = p; + LOCK( this ); + passChar = p; } -void GuiText::SetColor(GXColor c) +void GuiText::SetColor( GXColor c ) { - LOCK(this); - color = c; - alpha = c.a; + LOCK( this ); + color = c; + alpha = c.a; } -void GuiText::SetStyle(u16 s) +void GuiText::SetStyle( u16 s ) { - LOCK(this); - style = s; + LOCK( this ); + style = s; } -void GuiText::SetAlignment(int hor, int vert) +void GuiText::SetAlignment( int hor, int vert ) { - LOCK(this); - style = 0; + LOCK( this ); + style = 0; - switch(hor) - { - case ALIGN_LEFT: - style |= FTGX_JUSTIFY_LEFT; - break; - case ALIGN_RIGHT: - style |= FTGX_JUSTIFY_RIGHT; - break; - default: - style |= FTGX_JUSTIFY_CENTER; - break; - } - switch(vert) - { - case ALIGN_TOP: - style |= FTGX_ALIGN_TOP; - break; - case ALIGN_BOTTOM: - style |= FTGX_ALIGN_BOTTOM; - break; - default: - style |= FTGX_ALIGN_MIDDLE; - break; - } + switch ( hor ) + { + case ALIGN_LEFT: + style |= FTGX_JUSTIFY_LEFT; + break; + case ALIGN_RIGHT: + style |= FTGX_JUSTIFY_RIGHT; + break; + default: + style |= FTGX_JUSTIFY_CENTER; + break; + } + switch ( vert ) + { + case ALIGN_TOP: + style |= FTGX_ALIGN_TOP; + break; + case ALIGN_BOTTOM: + style |= FTGX_ALIGN_BOTTOM; + break; + default: + style |= FTGX_ALIGN_MIDDLE; + break; + } - alignmentHor = hor; - alignmentVert = vert; + alignmentHor = hor; + alignmentVert = vert; } -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,9 +343,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()) + if ( ind < 0 || ind >= ( int ) textDyn.size() ) return text; return textDyn[ind]; @@ -359,37 +359,37 @@ 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) + if ( !fontbuffer || !filesize ) return false; - LOCK(this); - if(font) + LOCK( this ); + 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; + return true; } 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] = '.'; @@ -407,19 +407,19 @@ 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,39 +428,39 @@ 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; } int ch = textScrollPos; - int pos = textDyn.size()-1; + int pos = textDyn.size() - 1; - if(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,14 +472,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) + if ( textDyn.size() > 0 ) return; int i = 0; @@ -489,22 +489,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; - 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,7 +512,7 @@ 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] = '.'; @@ -524,7 +524,7 @@ void GuiText::WrapText() ++linenum; i = -1; } - if(text[ch] == ' ' && i >= 0) + if ( text[ch] == ' ' && i >= 0 ) { lastSpace = ch; lastSpaceIndex = i; @@ -539,62 +539,62 @@ void GuiText::WrapText() */ void GuiText::Draw() { - if(!text) - return; + if ( !text ) + return; - if(!IsVisible()) - return; + if ( !IsVisible() ) + return; - GXColor c = color; - c.a = GetAlpha(); + GXColor c = color; + c.a = GetAlpha(); - int newSize = size*GetScale(); + int newSize = size * GetScale(); - if(newSize != currentSize) - { - currentSize = newSize; + 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(wrapMode == DOTTED) // text dotted - { - if(textDyn.size() == 0) - MakeDottedText(); + if ( maxWidth > 0 && maxWidth <= textWidth ) + { + if ( wrapMode == DOTTED ) // text dotted + { + 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); - } - - 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 == SCROLL_HORIZONTAL ) + { + ScrollText(); + + if ( textDyn.size() > 0 ) + ( font ? font : fontSystem )->drawText( this->GetLeft(), this->GetTop(), 0, textDyn[textDyn.size()-1], currentSize, c, style ); + } + 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) + 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); - } - this->UpdateEffects(); + } + } + else + { + ( 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 58a17f5d..1972894e 100644 --- a/source/libwiigui/gui_tooltip.cpp +++ b/source/libwiigui/gui_tooltip.cpp @@ -10,28 +10,28 @@ #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); + 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 ); } /* @@ -39,53 +39,53 @@ leftImage(&tooltipLeft), tileImage(&tooltipTile), rightImage(&tooltipRight) */ GuiTooltip::~GuiTooltip() { - if(text) delete text; + if ( text ) delete text; } float GuiTooltip::GetScale() { - float s = scale * scaleDyn; + float s = scale * scaleDyn; - return s; + return s; } /* !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) - { - delete text; - text = NULL; - } - int tile_cnt = 0; - if(t && (text = new GuiText(t, 22, (GXColor){0, 0, 0, 255}))) - { - text->SetParent(this); - tile_cnt = (text->GetTextWidth()-12) /tileImage.GetWidth(); - if(tile_cnt < 0) tile_cnt = 0; - } - tileImage.SetPosition(leftImage.GetWidth(), 0); - tileImage.SetTile(tile_cnt); - rightImage.SetPosition(leftImage.GetWidth() + tile_cnt * tileImage.GetWidth(), 0); - width = leftImage.GetWidth() + tile_cnt * tileImage.GetWidth() + rightImage.GetWidth(); + LOCK( this ); + if ( text ) + { + delete text; + text = NULL; + } + int tile_cnt = 0; + if ( t && ( text = new GuiText( t, 22, ( GXColor ) {0, 0, 0, 255} ) ) ) + { + text->SetParent( this ); + tile_cnt = ( text->GetTextWidth() - 12 ) / tileImage.GetWidth(); + if ( tile_cnt < 0 ) tile_cnt = 0; + } + tileImage.SetPosition( leftImage.GetWidth(), 0 ); + tileImage.SetTile( tile_cnt ); + rightImage.SetPosition( leftImage.GetWidth() + tile_cnt * tileImage.GetWidth(), 0 ); + width = leftImage.GetWidth() + tile_cnt * tileImage.GetWidth() + rightImage.GetWidth(); } -void GuiTooltip::SetWidescreen(bool){} +void GuiTooltip::SetWidescreen( bool ) {} /* * Draw the Tooltip on screen */ void GuiTooltip::Draw() { - LOCK(this); - if(!this->IsVisible()) return; + LOCK( this ); + if ( !this->IsVisible() ) return; - leftImage.Draw(); - tileImage.Draw(); - rightImage.Draw(); - if(text) text->Draw(); + leftImage.Draw(); + tileImage.Draw(); + rightImage.Draw(); + if ( text ) text->Draw(); - this->UpdateEffects(); + this->UpdateEffects(); } diff --git a/source/libwiigui/gui_trigger.cpp b/source/libwiigui/gui_trigger.cpp index 1d9207ec..94e443be 100644 --- a/source/libwiigui/gui_trigger.cpp +++ b/source/libwiigui/gui_trigger.cpp @@ -17,9 +17,9 @@ static int scrollDelay = 0; */ GuiTrigger::GuiTrigger() { - chan = -1; - memset(&wpad, 0, sizeof(WPADData)); - memset(&pad, 0, sizeof(PADData)); + chan = -1; + memset( &wpad, 0, sizeof( WPADData ) ); + memset( &pad, 0, sizeof( PADData ) ); } /** @@ -34,12 +34,12 @@ 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; - wpad.btns_d = wiibtns; - pad.btns_d = gcbtns; + type = TRIGGER_SIMPLE; + chan = ch; + wpad.btns_d = wiibtns; + pad.btns_d = gcbtns; } /** @@ -47,24 +47,24 @@ void GuiTrigger::SetSimpleTrigger(s32 ch, u32 wiibtns, u16 gcbtns) * - Element is selected * - Trigger button is pressed and held */ -void GuiTrigger::SetHeldTrigger(s32 ch, u32 wiibtns, u16 gcbtns) +void GuiTrigger::SetHeldTrigger( s32 ch, u32 wiibtns, u16 gcbtns ) { - type = TRIGGER_HELD; - chan = ch; - wpad.btns_h = wiibtns; - pad.btns_h = gcbtns; + type = TRIGGER_HELD; + chan = ch; + wpad.btns_h = wiibtns; + pad.btns_h = gcbtns; } /** * Sets a button trigger. Requires: * - Trigger button is pressed */ -void GuiTrigger::SetButtonOnlyTrigger(s32 ch, u32 wiibtns, u16 gcbtns) +void GuiTrigger::SetButtonOnlyTrigger( s32 ch, u32 wiibtns, u16 gcbtns ) { - type = TRIGGER_BUTTON_ONLY; - chan = ch; - wpad.btns_d = wiibtns; - pad.btns_d = gcbtns; + type = TRIGGER_BUTTON_ONLY; + chan = ch; + wpad.btns_d = wiibtns; + pad.btns_d = gcbtns; } /** @@ -72,12 +72,12 @@ void GuiTrigger::SetButtonOnlyTrigger(s32 ch, u32 wiibtns, u16 gcbtns) * - Trigger button is pressed * - Parent window is in focus */ -void GuiTrigger::SetButtonOnlyInFocusTrigger(s32 ch, u32 wiibtns, u16 gcbtns) +void GuiTrigger::SetButtonOnlyInFocusTrigger( s32 ch, u32 wiibtns, u16 gcbtns ) { - type = TRIGGER_BUTTON_ONLY_IN_FOCUS; - chan = ch; - wpad.btns_d = wiibtns; - pad.btns_d = gcbtns; + type = TRIGGER_BUTTON_ONLY_IN_FOCUS; + chan = ch; + wpad.btns_d = wiibtns; + pad.btns_d = gcbtns; } /**************************************************************************** @@ -86,170 +86,170 @@ void GuiTrigger::SetButtonOnlyInFocusTrigger(s32 ch, u32 wiibtns, u16 gcbtns) * Get X/Y value from Wii Joystick (classic, nunchuk) input ***************************************************************************/ -s8 GuiTrigger::WPAD_Stick(u8 right, int axis) +s8 GuiTrigger::WPAD_Stick( u8 right, int axis ) { - #ifdef HW_RVL +#ifdef HW_RVL - float mag = 0.0; - float ang = 0.0; + float mag = 0.0; + float ang = 0.0; - switch (wpad.exp.type) - { - case WPAD_EXP_NUNCHUK: - case WPAD_EXP_GUITARHERO3: - if (right == 0) - { - mag = wpad.exp.nunchuk.js.mag; - ang = wpad.exp.nunchuk.js.ang; - } - break; + switch ( wpad.exp.type ) + { + case WPAD_EXP_NUNCHUK: + case WPAD_EXP_GUITARHERO3: + if ( right == 0 ) + { + mag = wpad.exp.nunchuk.js.mag; + ang = wpad.exp.nunchuk.js.ang; + } + break; - case WPAD_EXP_CLASSIC: - if (right == 0) - { - mag = wpad.exp.classic.ljs.mag; - ang = wpad.exp.classic.ljs.ang; - } - else - { - mag = wpad.exp.classic.rjs.mag; - ang = wpad.exp.classic.rjs.ang; - } - break; + case WPAD_EXP_CLASSIC: + if ( right == 0 ) + { + mag = wpad.exp.classic.ljs.mag; + ang = wpad.exp.classic.ljs.ang; + } + else + { + mag = wpad.exp.classic.rjs.mag; + ang = wpad.exp.classic.rjs.ang; + } + break; - default: - break; - } + default: + break; + } - /* calculate x/y value (angle need to be converted into radian) */ - if (mag > 1.0) mag = 1.0; - else if (mag < -1.0) mag = -1.0; - double val; + /* calculate x/y value (angle need to be converted into radian) */ + if ( mag > 1.0 ) mag = 1.0; + else if ( mag < -1.0 ) mag = -1.0; + double val; - if(axis == 0) // x-axis - val = mag * sin((PI * ang)/180.0f); - else // y-axis - val = mag * cos((PI * ang)/180.0f); + if ( axis == 0 ) // x-axis + val = mag * sin( ( PI * ang ) / 180.0f ); + else // y-axis + val = mag * cos( ( PI * ang ) / 180.0f ); - return (s8)(val * 128.0f); + return ( s8 )( val * 128.0f ); - #else - return 0; - #endif +#else + return 0; +#endif } bool GuiTrigger::Left() { - u32 wiibtn = WPAD_BUTTON_LEFT; + u32 wiibtn = WPAD_BUTTON_LEFT; - if((wpad.btns_d | wpad.btns_h) & (wiibtn | WPAD_CLASSIC_BUTTON_LEFT) - || (pad.btns_d | pad.btns_h) & PAD_BUTTON_LEFT - || pad.stickX < -PADCAL - || WPAD_Stick(0,0) < -PADCAL) - { - if(wpad.btns_d & (wiibtn | WPAD_CLASSIC_BUTTON_LEFT) - || pad.btns_d & PAD_BUTTON_LEFT) - { - scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. - return true; - } - else if(scrollDelay == 0) - { - scrollDelay = SCROLL_LOOP_DELAY; - return true; - } - else - { - if(scrollDelay > 0) - scrollDelay--; - } - } - return false; + if ( ( wpad.btns_d | wpad.btns_h ) & ( wiibtn | WPAD_CLASSIC_BUTTON_LEFT ) + || ( pad.btns_d | pad.btns_h ) & PAD_BUTTON_LEFT + || pad.stickX < -PADCAL + || WPAD_Stick( 0, 0 ) < -PADCAL ) + { + if ( wpad.btns_d & ( wiibtn | WPAD_CLASSIC_BUTTON_LEFT ) + || pad.btns_d & PAD_BUTTON_LEFT ) + { + scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. + return true; + } + else if ( scrollDelay == 0 ) + { + scrollDelay = SCROLL_LOOP_DELAY; + return true; + } + else + { + if ( scrollDelay > 0 ) + scrollDelay--; + } + } + return false; } bool GuiTrigger::Right() { - u32 wiibtn = WPAD_BUTTON_RIGHT; + u32 wiibtn = WPAD_BUTTON_RIGHT; - if((wpad.btns_d | wpad.btns_h) & (wiibtn | WPAD_CLASSIC_BUTTON_RIGHT) - || (pad.btns_d | pad.btns_h) & PAD_BUTTON_RIGHT - || pad.stickX > PADCAL - || WPAD_Stick(0,0) > PADCAL) - { - if(wpad.btns_d & (wiibtn | WPAD_CLASSIC_BUTTON_RIGHT) - || pad.btns_d & PAD_BUTTON_RIGHT) - { - scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. - return true; - } - else if(scrollDelay == 0) - { - scrollDelay = SCROLL_LOOP_DELAY; - return true; - } - else - { - if(scrollDelay > 0) - scrollDelay--; - } - } - return false; + if ( ( wpad.btns_d | wpad.btns_h ) & ( wiibtn | WPAD_CLASSIC_BUTTON_RIGHT ) + || ( pad.btns_d | pad.btns_h ) & PAD_BUTTON_RIGHT + || pad.stickX > PADCAL + || WPAD_Stick( 0, 0 ) > PADCAL ) + { + if ( wpad.btns_d & ( wiibtn | WPAD_CLASSIC_BUTTON_RIGHT ) + || pad.btns_d & PAD_BUTTON_RIGHT ) + { + scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. + return true; + } + else if ( scrollDelay == 0 ) + { + scrollDelay = SCROLL_LOOP_DELAY; + return true; + } + else + { + if ( scrollDelay > 0 ) + scrollDelay--; + } + } + return false; } bool GuiTrigger::Up() { - u32 wiibtn = WPAD_BUTTON_UP; + u32 wiibtn = WPAD_BUTTON_UP; - if((wpad.btns_d | wpad.btns_h) & (wiibtn | WPAD_CLASSIC_BUTTON_UP) - || (pad.btns_d | pad.btns_h) & PAD_BUTTON_UP - || pad.stickY > PADCAL - || WPAD_Stick(0,1) > PADCAL) - { - if(wpad.btns_d & (wiibtn | WPAD_CLASSIC_BUTTON_UP) - || pad.btns_d & PAD_BUTTON_UP) - { - scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. - return true; - } - else if(scrollDelay == 0) - { - scrollDelay = SCROLL_LOOP_DELAY; - return true; - } - else - { - if(scrollDelay > 0) - scrollDelay--; - } - } - return false; + if ( ( wpad.btns_d | wpad.btns_h ) & ( wiibtn | WPAD_CLASSIC_BUTTON_UP ) + || ( pad.btns_d | pad.btns_h ) & PAD_BUTTON_UP + || pad.stickY > PADCAL + || WPAD_Stick( 0, 1 ) > PADCAL ) + { + if ( wpad.btns_d & ( wiibtn | WPAD_CLASSIC_BUTTON_UP ) + || pad.btns_d & PAD_BUTTON_UP ) + { + scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. + return true; + } + else if ( scrollDelay == 0 ) + { + scrollDelay = SCROLL_LOOP_DELAY; + return true; + } + else + { + if ( scrollDelay > 0 ) + scrollDelay--; + } + } + return false; } bool GuiTrigger::Down() { - u32 wiibtn = WPAD_BUTTON_DOWN; + u32 wiibtn = WPAD_BUTTON_DOWN; - if((wpad.btns_d | wpad.btns_h) & (wiibtn | WPAD_CLASSIC_BUTTON_DOWN) - || (pad.btns_d | pad.btns_h) & PAD_BUTTON_DOWN - || pad.stickY < -PADCAL - || WPAD_Stick(0,1) < -PADCAL) - { - if(wpad.btns_d & (wiibtn | WPAD_CLASSIC_BUTTON_DOWN) - || pad.btns_d & PAD_BUTTON_DOWN) - { - scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. - return true; - } - else if(scrollDelay == 0) - { - scrollDelay = SCROLL_LOOP_DELAY; - return true; - } - else - { - if(scrollDelay > 0) - scrollDelay--; - } - } - return false; + if ( ( wpad.btns_d | wpad.btns_h ) & ( wiibtn | WPAD_CLASSIC_BUTTON_DOWN ) + || ( pad.btns_d | pad.btns_h ) & PAD_BUTTON_DOWN + || pad.stickY < -PADCAL + || WPAD_Stick( 0, 1 ) < -PADCAL ) + { + if ( wpad.btns_d & ( wiibtn | WPAD_CLASSIC_BUTTON_DOWN ) + || pad.btns_d & PAD_BUTTON_DOWN ) + { + scrollDelay = SCROLL_INITIAL_DELAY; // reset scroll delay. + return true; + } + else if ( scrollDelay == 0 ) + { + scrollDelay = SCROLL_LOOP_DELAY; + return true; + } + else + { + if ( scrollDelay > 0 ) + scrollDelay--; + } + } + return false; } diff --git a/source/libwiigui/gui_window.cpp b/source/libwiigui/gui_window.cpp index 303b4b2d..0552b444 100644 --- a/source/libwiigui/gui_window.cpp +++ b/source/libwiigui/gui_window.cpp @@ -12,419 +12,419 @@ GuiWindow::GuiWindow() { - width = 0; - height = 0; - focus = 0; // allow focus + width = 0; + height = 0; + focus = 0; // allow focus } -GuiWindow::GuiWindow(int w, int h) +GuiWindow::GuiWindow( int w, int h ) { - width = w; - height = h; - focus = 0; // allow focus + width = w; + height = h; + focus = 0; // allow focus } GuiWindow::~GuiWindow() { } -void GuiWindow::Append(GuiElement* e) +void GuiWindow::Append( GuiElement* e ) { - LOCK(this); - if (e == NULL) - return; + LOCK( this ); + if ( e == NULL ) + return; - Remove(e); - _elements.push_back(e); - e->SetParent(this); + Remove( e ); + _elements.push_back( e ); + e->SetParent( this ); } -void GuiWindow::Insert(GuiElement* e, u32 index) +void GuiWindow::Insert( GuiElement* e, u32 index ) { - LOCK(this); - if (e == NULL || index > (_elements.size() - 1)) - return; + LOCK( this ); + if ( e == NULL || index > ( _elements.size() - 1 ) ) + return; - Remove(e); - _elements.insert(_elements.begin()+index, e); - e->SetParent(this); + Remove( e ); + _elements.insert( _elements.begin() + index, e ); + e->SetParent( this ); } -void GuiWindow::Remove(GuiElement* e) +void GuiWindow::Remove( GuiElement* e ) { - LOCK(this); - if (e == NULL) - return; + LOCK( this ); + if ( e == NULL ) + return; - for (u8 i = 0; i < _elements.size(); i++) - { - if(e == _elements.at(i)) - { - _elements.erase(_elements.begin()+i); - break; - } - } + for ( u8 i = 0; i < _elements.size(); i++ ) + { + if ( e == _elements.at( i ) ) + { + _elements.erase( _elements.begin() + i ); + break; + } + } } void GuiWindow::RemoveAll() { - LOCK(this); - _elements.clear(); + LOCK( this ); + _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() { - return _elements.size(); + return _elements.size(); } void GuiWindow::Draw() { - LOCK(this); - if(_elements.size() == 0 || !this->IsVisible()) - return; + LOCK( this ); + if ( _elements.size() == 0 || !this->IsVisible() ) + return; - for (u8 i = 0; i < _elements.size(); i++) - { - try { _elements.at(i)->Draw(); } - catch (const std::exception& e) { } - } + for ( u8 i = 0; i < _elements.size(); i++ ) + { + try { _elements.at( i )->Draw(); } + catch ( const std::exception& e ) { } + } - this->UpdateEffects(); + this->UpdateEffects(); - if(parentElement && state == STATE_DISABLED) - //Menu_DrawRectangle(0,0,screenwidth,screenheight,(GXColor){0xbe, 0xca, 0xd5, 0x70},1); - Menu_DrawRectangle(0,0,screenwidth,screenheight,(GXColor){0, 0, 0, 0x70},1); + if ( parentElement && state == STATE_DISABLED ) + //Menu_DrawRectangle(0,0,screenwidth,screenheight,(GXColor){0xbe, 0xca, 0xd5, 0x70},1); + Menu_DrawRectangle( 0, 0, screenwidth, screenheight, ( GXColor ) {0, 0, 0, 0x70}, 1 ); } void GuiWindow::DrawTooltip() { - LOCK(this); - if(_elements.size() == 0 || !this->IsVisible()) - return; + LOCK( this ); + if ( _elements.size() == 0 || !this->IsVisible() ) + return; - for (u8 i = 0; i < _elements.size(); i++) - { - try { _elements.at(i)->DrawTooltip(); } - catch (const std::exception& e) { } - } + for ( u8 i = 0; i < _elements.size(); i++ ) + { + try { _elements.at( i )->DrawTooltip(); } + catch ( const std::exception& e ) { } + } } void GuiWindow::ResetState() { - LOCK(this); - if(state != STATE_DISABLED) - state = STATE_DEFAULT; + LOCK( this ); + if ( state != STATE_DISABLED ) + state = STATE_DEFAULT; - for (u8 i = 0; i < _elements.size(); i++) - { - try { _elements.at(i)->ResetState(); } - catch (const std::exception& e) { } - } + for ( u8 i = 0; i < _elements.size(); i++ ) + { + try { _elements.at( i )->ResetState(); } + catch ( const std::exception& e ) { } + } } -void GuiWindow::SetState(int s) +void GuiWindow::SetState( int s ) { - LOCK(this); - state = s; + LOCK( this ); + state = s; - for (u8 i = 0; i < _elements.size(); i++) - { - try { _elements.at(i)->SetState(s); } - catch (const std::exception& e) { } - } + for ( u8 i = 0; i < _elements.size(); i++ ) + { + try { _elements.at( i )->SetState( s ); } + catch ( const std::exception& e ) { } + } } -void GuiWindow::SetVisible(bool v) +void GuiWindow::SetVisible( bool v ) { - LOCK(this); - visible = v; + LOCK( this ); + visible = v; - for (u8 i = 0; i < _elements.size(); i++) - { - try { _elements.at(i)->SetVisible(v); } - catch (const std::exception& e) { } - } + for ( u8 i = 0; i < _elements.size(); i++ ) + { + try { _elements.at( i )->SetVisible( v ); } + catch ( const std::exception& e ) { } + } } -void GuiWindow::SetFocus(int f) +void GuiWindow::SetFocus( int f ) { - LOCK(this); - focus = 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 + LOCK( this ); + if ( parentElement ) + return; // this is only intended for the main window - for (u8 i = 0; i < _elements.size(); i++) - { - if(e == _elements.at(i)) - _elements.at(i)->SetFocus(1); - else if(_elements.at(i)->IsFocused() == 1) - _elements.at(i)->SetFocus(0); - } + for ( u8 i = 0; i < _elements.size(); i++ ) + { + if ( e == _elements.at( i ) ) + _elements.at( i )->SetFocus( 1 ); + else if ( _elements.at( i )->IsFocused() == 1 ) + _elements.at( i )->SetFocus( 0 ); + } } -void GuiWindow::ToggleFocus(GuiTrigger * t) +void GuiWindow::ToggleFocus( GuiTrigger * t ) { - LOCK(this); - if(parentElement) - return; // this is only intended for the main window + LOCK( this ); + if ( parentElement ) + return; // this is only intended for the main window - int found = -1; - int newfocus = -1; - u8 i; + int found = -1; + int newfocus = -1; + u8 i; - // look for currently in focus element - for (i = 0; i < _elements.size(); i++) - { - try - { - if(_elements.at(i)->IsFocused() == 1) - { - found = i; - break; - } - } - catch (const std::exception& e) { } - } + // look for currently in focus element + for ( i = 0; i < _elements.size(); i++ ) + { + try + { + if ( _elements.at( i )->IsFocused() == 1 ) + { + found = i; + break; + } + } + catch ( const std::exception& e ) { } + } - // element with focus not found, try to give focus - if(found == -1) - { - for (i = 0; i < _elements.size(); i++) - { - try - { - if(_elements.at(i)->IsFocused() == 0 && _elements.at(i)->GetState() != STATE_DISABLED) // focus is possible (but not set) - { - _elements.at(i)->SetFocus(1); // give this element focus - break; - } - } - catch (const std::exception& e) { } - } - } - // change focus - else if(t->wpad.btns_d & (WPAD_BUTTON_1 | WPAD_BUTTON_1 | WPAD_CLASSIC_BUTTON_PLUS) - || t->pad.btns_d & PAD_BUTTON_B) - { - for (i = found; i < _elements.size(); i++) - { - try - { - if(_elements.at(i)->IsFocused() == 0 && _elements.at(i)->GetState() != STATE_DISABLED) // focus is possible (but not set) - { - newfocus = i; - _elements.at(i)->SetFocus(1); // give this element focus - _elements.at(found)->SetFocus(0); // disable focus on other element - break; - } - } - catch (const std::exception& e) { } - } + // element with focus not found, try to give focus + if ( found == -1 ) + { + for ( i = 0; i < _elements.size(); i++ ) + { + try + { + if ( _elements.at( i )->IsFocused() == 0 && _elements.at( i )->GetState() != STATE_DISABLED ) // focus is possible (but not set) + { + _elements.at( i )->SetFocus( 1 ); // give this element focus + break; + } + } + catch ( const std::exception& e ) { } + } + } + // change focus + else if ( t->wpad.btns_d & ( WPAD_BUTTON_1 | WPAD_BUTTON_1 | WPAD_CLASSIC_BUTTON_PLUS ) + || t->pad.btns_d & PAD_BUTTON_B ) + { + for ( i = found; i < _elements.size(); i++ ) + { + try + { + if ( _elements.at( i )->IsFocused() == 0 && _elements.at( i )->GetState() != STATE_DISABLED ) // focus is possible (but not set) + { + newfocus = i; + _elements.at( i )->SetFocus( 1 ); // give this element focus + _elements.at( found )->SetFocus( 0 ); // disable focus on other element + break; + } + } + catch ( const std::exception& e ) { } + } - if(newfocus == -1) - { - for (i = 0; i < found; i++) - { - try - { - if(_elements.at(i)->IsFocused() == 0 && _elements.at(i)->GetState() != STATE_DISABLED) // focus is possible (but not set) - { - _elements.at(i)->SetFocus(1); // give this element focus - _elements.at(found)->SetFocus(0); // disable focus on other element - break; - } - } - catch (const std::exception& e) { } - } - } - } + if ( newfocus == -1 ) + { + for ( i = 0; i < found; i++ ) + { + try + { + if ( _elements.at( i )->IsFocused() == 0 && _elements.at( i )->GetState() != STATE_DISABLED ) // focus is possible (but not set) + { + _elements.at( i )->SetFocus( 1 ); // give this element focus + _elements.at( found )->SetFocus( 0 ); // disable focus on other element + break; + } + } + catch ( const std::exception& e ) { } + } + } + } } int GuiWindow::GetSelected() { - // find selected element - int found = -1; - for (u8 i = 0; i < _elements.size(); i++) - { - try - { - if(_elements.at(i)->GetState() == STATE_SELECTED) - { - found = i; - break; - } - } - catch (const std::exception& e) { } - } - return found; + // find selected element + int found = -1; + for ( u8 i = 0; i < _elements.size(); i++ ) + { + try + { + if ( _elements.at( i )->GetState() == STATE_SELECTED ) + { + found = i; + break; + } + } + catch ( const std::exception& e ) { } + } + return found; } // set element to left/right as selected // there's probably a more clever way to do this, but this way works -void GuiWindow::MoveSelectionHor(int dir) +void GuiWindow::MoveSelectionHor( int dir ) { - LOCK(this); - int found = -1; - u16 left = 0; - u16 top = 0; - u8 i = 0; + LOCK( this ); + int found = -1; + u16 left = 0; + u16 top = 0; + u8 i = 0; - int selected = this->GetSelected(); + int selected = this->GetSelected(); - if(selected >= 0) - { - left = _elements.at(selected)->GetLeft(); - top = _elements.at(selected)->GetTop(); - } + if ( selected >= 0 ) + { + left = _elements.at( selected )->GetLeft(); + top = _elements.at( selected )->GetTop(); + } - // look for a button on the same row, to the left/right - for (i = 0; i < _elements.size(); i++) - { - try - { - if(_elements.at(i)->IsSelectable()) - { - if(_elements.at(i)->GetLeft()*dir > left*dir && _elements.at(i)->GetTop() == top) - { - if(found == -1) - found = i; - else if(_elements.at(i)->GetLeft()*dir < _elements.at(found)->GetLeft()*dir) - found = i; // this is a better match - } - } - } - catch (const std::exception& e) { } - } - if(found >= 0) - goto matchfound; + // look for a button on the same row, to the left/right + for ( i = 0; i < _elements.size(); i++ ) + { + try + { + if ( _elements.at( i )->IsSelectable() ) + { + if ( _elements.at( i )->GetLeft()*dir > left*dir && _elements.at( i )->GetTop() == top ) + { + if ( found == -1 ) + found = i; + else if ( _elements.at( i )->GetLeft()*dir < _elements.at( found )->GetLeft()*dir ) + found = i; // this is a better match + } + } + } + catch ( const std::exception& e ) { } + } + if ( found >= 0 ) + goto matchfound; - // match still not found, let's try the first button in the next row - for (i = 0; i < _elements.size(); i++) - { - try - { - if(_elements.at(i)->IsSelectable()) - { - if(_elements.at(i)->GetTop()*dir > top*dir) - { - if(found == -1) - found = i; - else if(_elements.at(i)->GetTop()*dir < _elements.at(found)->GetTop()*dir) - found = i; // this is a better match - else if(_elements.at(i)->GetTop()*dir == _elements.at(found)->GetTop()*dir - && - _elements.at(i)->GetLeft()*dir < _elements.at(found)->GetLeft()*dir) - found = i; // this is a better match - } - } - } - catch (const std::exception& e) { } - } + // match still not found, let's try the first button in the next row + for ( i = 0; i < _elements.size(); i++ ) + { + try + { + if ( _elements.at( i )->IsSelectable() ) + { + if ( _elements.at( i )->GetTop()*dir > top*dir ) + { + if ( found == -1 ) + found = i; + else if ( _elements.at( i )->GetTop()*dir < _elements.at( found )->GetTop()*dir ) + found = i; // this is a better match + else if ( _elements.at( i )->GetTop()*dir == _elements.at( found )->GetTop()*dir + && + _elements.at( i )->GetLeft()*dir < _elements.at( found )->GetLeft()*dir ) + found = i; // this is a better match + } + } + } + catch ( const std::exception& e ) { } + } - // match found - matchfound: - if(found >= 0) - { - _elements.at(found)->SetState(STATE_SELECTED); - if(selected >= 0) - _elements.at(selected)->ResetState(); - } + // match found +matchfound: + if ( found >= 0 ) + { + _elements.at( found )->SetState( STATE_SELECTED ); + if ( selected >= 0 ) + _elements.at( selected )->ResetState(); + } } -void GuiWindow::MoveSelectionVert(int dir) +void GuiWindow::MoveSelectionVert( int dir ) { - LOCK(this); - int found = -1; - u16 left = 0; - u16 top = 0; - u8 i = 0; + LOCK( this ); + int found = -1; + u16 left = 0; + u16 top = 0; + u8 i = 0; - int selected = this->GetSelected(); + int selected = this->GetSelected(); - if(selected >= 0) - { - left = _elements.at(selected)->GetLeft(); - top = _elements.at(selected)->GetTop(); - } + if ( selected >= 0 ) + { + left = _elements.at( selected )->GetLeft(); + top = _elements.at( selected )->GetTop(); + } - // look for a button above/below, with the least horizontal difference - for (i = 0; i < _elements.size(); i++) - { - try - { - if(_elements.at(i)->IsSelectable()) - { - if(_elements.at(i)->GetTop()*dir > top*dir) - { - if(found == -1) - found = i; - else if(_elements.at(i)->GetTop()*dir < _elements.at(found)->GetTop()*dir) - found = i; // this is a better match - else if(_elements.at(i)->GetTop()*dir == _elements.at(found)->GetTop()*dir - && - abs(_elements.at(i)->GetLeft() - left) < - abs(_elements.at(found)->GetLeft() - left)) - found = i; - } - } - } - catch (const std::exception& e) { } - } - if(found >= 0) - goto matchfound; + // look for a button above/below, with the least horizontal difference + for ( i = 0; i < _elements.size(); i++ ) + { + try + { + if ( _elements.at( i )->IsSelectable() ) + { + if ( _elements.at( i )->GetTop()*dir > top*dir ) + { + if ( found == -1 ) + found = i; + else if ( _elements.at( i )->GetTop()*dir < _elements.at( found )->GetTop()*dir ) + found = i; // this is a better match + else if ( _elements.at( i )->GetTop()*dir == _elements.at( found )->GetTop()*dir + && + abs( _elements.at( i )->GetLeft() - left ) < + abs( _elements.at( found )->GetLeft() - left ) ) + found = i; + } + } + } + catch ( const std::exception& e ) { } + } + if ( found >= 0 ) + goto matchfound; - // match found - matchfound: - if(found >= 0) - { - _elements.at(found)->SetState(STATE_SELECTED); - if(selected >= 0) - _elements.at(selected)->ResetState(); - } + // match found +matchfound: + if ( found >= 0 ) + { + _elements.at( found )->SetState( STATE_SELECTED ); + if ( selected >= 0 ) + _elements.at( selected )->ResetState(); + } } -void GuiWindow::Update(GuiTrigger * t) +void GuiWindow::Update( GuiTrigger * t ) { - LOCK(this); - if(_elements.size() == 0 || (state == STATE_DISABLED && parentElement)) - return; + LOCK( this ); + if ( _elements.size() == 0 || ( state == STATE_DISABLED && parentElement ) ) + return; - for (u8 i = 0; i < _elements.size(); i++) - { - try { _elements.at(i)->Update(t); } - catch (const std::exception& e) { } - } + for ( u8 i = 0; i < _elements.size(); i++ ) + { + try { _elements.at( i )->Update( t ); } + catch ( const std::exception& e ) { } + } - this->ToggleFocus(t); + this->ToggleFocus( t ); - if(focus) // only send actions to this window if it's in focus - { - // pad/joystick navigation - if(t->Right()) - this->MoveSelectionHor(1); - else if(t->Left()) - this->MoveSelectionHor(-1); - else if(t->Down()) - this->MoveSelectionVert(1); - else if(t->Up()) - this->MoveSelectionVert(-1); - } + if ( focus ) // only send actions to this window if it's in focus + { + // pad/joystick navigation + if ( t->Right() ) + this->MoveSelectionHor( 1 ); + else if ( t->Left() ) + this->MoveSelectionHor( -1 ); + else if ( t->Down() ) + this->MoveSelectionVert( 1 ); + else if ( t->Up() ) + this->MoveSelectionVert( -1 ); + } - if(updateCB) - updateCB(this); + if ( updateCB ) + updateCB( this ); } diff --git a/source/listfiles.c b/source/listfiles.c index d016b581..7c6f2e28 100644 --- a/source/listfiles.c +++ b/source/listfiles.c @@ -13,172 +13,184 @@ 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))) { - snprintf(temp,sizeof(temp),"%s",file->d_name); - if (!strncmpi(temp,filename,11)) { - closedir(dir); + while ( ( file = readdir( dir ) ) ) + { + snprintf( temp, sizeof( temp ), "%s", file->d_name ); + if ( !strncmpi( temp, filename, 11 ) ) + { + closedir( dir ); return true; } } - closedir(dir); + closedir( dir ); return false; } -bool subfoldercreate(const char * fullpath) { - //check forsubfolders - char dir[300]; - char * pch = NULL; - u32 len; - struct stat st; +bool subfoldercreate( const char * fullpath ) +{ + //check forsubfolders + char dir[300]; + char * pch = NULL; + u32 len; + struct stat st; - strlcpy(dir, fullpath, sizeof(dir)); - len = strlen(dir); - if(len && len< sizeof(dir)-2 && dir[len-1] != '/') - { - dir[len++] = '/'; - dir[len] = '\0'; - } - if (stat(dir, &st) != 0) // fullpath not exist? - { - while(len && dir[len-1] == '/') - dir[--len] = '\0'; // remove all trailing / - pch = strrchr(dir, '/'); - if(pch == NULL) return false; - *pch = '\0'; - if(subfoldercreate(dir)) - { - *pch = '/'; - if (mkdir(dir, 0777) == -1) - return false; - } - else - return false; - } - return true; + strlcpy( dir, fullpath, sizeof( dir ) ); + len = strlen( dir ); + if ( len && len < sizeof( dir ) - 2 && dir[len-1] != '/' ) + { + dir[len++] = '/'; + dir[len] = '\0'; + } + if ( stat( dir, &st ) != 0 ) // fullpath not exist? + { + while ( len && dir[len-1] == '/' ) + dir[--len] = '\0'; // remove all trailing / + pch = strrchr( dir, '/' ); + if ( pch == NULL ) return false; + *pch = '\0'; + if ( subfoldercreate( dir ) ) + { + *pch = '/'; + if ( mkdir( dir, 0777 ) == -1 ) + return false; + } + else + return false; + } + return true; } -bool subfolderremove(const char * fullpath, const char*fp) { - struct stat st; - if (stat(fullpath, &st) != 0) // fullpath not exist? - return false; - if(S_ISDIR(st.st_mode)) - { - DIR_ITER *dir = NULL; - char filename[256]; - bool cont = true; - while(cont) - { - cont = false; - dir = diropen(fullpath); - if(dir) - { - char* bind = fullpath[strlen(fullpath)-1] == '/' ? "":"/"; - while (dirnext(dir,filename,&st) == 0) - { - if (strcmp(filename,".") != 0 && strcmp(filename,"..") != 0) - { - char currentname[256]; - if(S_ISDIR(st.st_mode)) - snprintf(currentname, sizeof(currentname), "%s%s%s/", fullpath, bind, filename); - else - snprintf(currentname, sizeof(currentname), "%s%s%s", fullpath, bind, filename); - subfolderremove(currentname, fp); - cont = true; - break; - } - } - dirclose(dir); - } - } - } - return unlink(fullpath) == 0; +bool subfolderremove( const char * fullpath, const char*fp ) +{ + struct stat st; + if ( stat( fullpath, &st ) != 0 ) // fullpath not exist? + return false; + if ( S_ISDIR( st.st_mode ) ) + { + DIR_ITER *dir = NULL; + char filename[256]; + bool cont = true; + while ( cont ) + { + cont = false; + dir = diropen( fullpath ); + if ( dir ) + { + char* bind = fullpath[strlen( fullpath )-1] == '/' ? "" : "/"; + while ( dirnext( dir, filename, &st ) == 0 ) + { + if ( strcmp( filename, "." ) != 0 && strcmp( filename, ".." ) != 0 ) + { + char currentname[256]; + if ( S_ISDIR( st.st_mode ) ) + snprintf( currentname, sizeof( currentname ), "%s%s%s/", fullpath, bind, filename ); + else + snprintf( currentname, sizeof( currentname ), "%s%s%s", fullpath, bind, filename ); + subfolderremove( currentname, fp ); + cont = true; + break; + } + } + dirclose( dir ); + } + } + } + return unlink( fullpath ) == 0; } -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 + if ( dir == NULL ) //If empty return 0; - while (dirnext(dir,filenames,&st) == 0) { - if ((st.st_mode & S_IFDIR) == 0) { + while ( dirnext( dir, filenames, &st ) == 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) { - fclose(f); + f = fopen( path, "r" ); + if ( 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) + dir = diropen( pathptr ); + if ( !dir ) return false; - while (dirnext(dir,filename,&st) == 0 && result == false) - { - if(strcasecmp(filename, searched_filename) == 0) - { - if(outfilepath) - { - sprintf(outfilepath, "%s/%s", pathptr, filename); - } - result = true; - } - else if((st.st_mode & S_IFDIR) != 0) + while ( dirnext( dir, filename, &st ) == 0 && result == false ) + { + if ( strcasecmp( filename, searched_filename ) == 0 ) { - if(strcmp(filename, ".") != 0 && strcmp(filename, "..") != 0) + if ( outfilepath ) + { + sprintf( outfilepath, "%s/%s", pathptr, filename ); + } + result = true; + } + else if ( ( st.st_mode & S_IFDIR ) != 0 ) + { + if ( strcmp( filename, "." ) != 0 && strcmp( filename, ".." ) != 0 ) { char newpath[1024]; - snprintf(newpath, sizeof(newpath), "%s/%s", pathptr, filename); - result = SearchFile(newpath, searched_filename, outfilepath); + 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 e36ef114..bed90a7d 100644 --- a/source/listfiles.h +++ b/source/listfiles.h @@ -2,15 +2,16 @@ #define _LISTFILES_H_ #ifdef __cplusplus -extern "C" { +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.c b/source/lstub.c deleted file mode 100644 index 860d161c..00000000 --- a/source/lstub.c +++ /dev/null @@ -1,152 +0,0 @@ -//functions for manipulating the HBC stub by giantpune - -#include -#include -#include -#include - - -#include "lstub.h" -#include "stub_bin.h" -#include "gecko.h" - -#define TITLE_1(x) ((u8)((x) >> 8)) -#define TITLE_2(x) ((u8)((x) >> 16)) -#define TITLE_3(x) ((u8)((x) >> 24)) -#define TITLE_4(x) ((u8)((x) >> 32)) -#define TITLE_5(x) ((u8)((x) >> 40)) -#define TITLE_6(x) ((u8)((x) >> 48)) -#define TITLE_7(x) ((u8)((x) >> 56)) -#define TITLE_ID(x,y) (((u64)(x) << 32) | (y)) - -static char* determineStubTIDLocation() -{ - u32 *stubID = (u32*)0x80001818; - - //HBC stub 1.0.6 and lower, and stub.bin - 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; - - //hexdump( stubID, 0x20 ); - return NULL; - -} - -s32 Set_Stub(u64 reqID) -{ - u32 tmdsize; - u64 tid = 0; - u64 *list; - u32 titlecount; - s32 ret; - u32 i; - - ret = ES_GetNumTitles(&titlecount); - if(ret < 0) - return WII_EINTERNAL; - - list = memalign(32, titlecount * sizeof(u64) + 32); - - ret = ES_GetTitles(list, titlecount); - if(ret < 0) { - free(list); - return WII_EINTERNAL; - } - - for(i=0; i extern "C" { - extern void __exception_setreload(int t); + extern void __exception_setreload( int t ); } @@ -67,91 +67,86 @@ NandTitle titles; #define CONSOLE_HEIGHT 218 PartList partitions; -u8 dbvideo =0; +u8 dbvideo = 0; -int main(int argc, char *argv[]) +int main( int argc, char *argv[] ) { - MEM2_init(48); + MEM2_init( 48 ); InitVideo(); - setlocale(LC_ALL, "en.UTF-8"); + setlocale( LC_ALL, "en.UTF-8" ); geckoinit = InitGecko(); - __exception_setreload(20); + __exception_setreload( 20 ); - printf("\tStarting up\n"); + printf( "\tStarting up\n" ); titles.Get(); - titles.Exists( 0x100014e414c45ULL ); - bool bootDevice_found=false; - if (argc >= 1) + bool bootDevice_found = false; + if ( argc >= 1 ) { - if (!strncasecmp(argv[0], "usb:/", 5)) + if ( !strncasecmp( argv[0], "usb:/", 5 ) ) { - strcpy(bootDevice, "USB:"); + strcpy( bootDevice, "USB:" ); + bootDevice_found = true; + } + else if ( !strncasecmp( argv[0], "sd:/", 4 ) ) bootDevice_found = true; - } else if (!strncasecmp(argv[0], "sd:/", 4)) - bootDevice_found = true; } //Let's use libogc sd/usb for config loading - printf("\tInitialize sd card\n"); + printf( "\tInitialize sd card\n" ); SDCard_Init(); - printf("\tInitialize usb device\n"); + printf( "\tInitialize usb device\n" ); USBDevice_Init(); - if (!bootDevice_found) + if ( !bootDevice_found ) { - printf("\tSearch for configuration file\n"); + printf( "\tSearch for configuration file\n" ); //try USB //left in all the dol and elf files in this check in case this is the first time running the app and they dont have the config - if (checkfile((char*) "USB:/config/GXglobal.cfg") || (checkfile((char*) "USB:/apps/usbloader_gx/boot.elf")) - || checkfile((char*) "USB:/apps/usbloadergx/boot.dol") || (checkfile((char*) "USB:/apps/usbloadergx/boot.elf")) - || checkfile((char*) "USB:/apps/usbloader_gx/boot.dol")) - strcpy(bootDevice, "USB:"); + if ( checkfile( ( char* ) "USB:/config/GXglobal.cfg" ) || ( checkfile( ( char* ) "USB:/apps/usbloader_gx/boot.elf" ) ) + || checkfile( ( char* ) "USB:/apps/usbloadergx/boot.dol" ) || ( checkfile( ( char* ) "USB:/apps/usbloadergx/boot.elf" ) ) + || checkfile( ( char* ) "USB:/apps/usbloader_gx/boot.dol" ) ) + strcpy( bootDevice, "USB:" ); - printf("\tConfiguration file is on %s\n", bootDevice); + printf( "\tConfiguration file is on %s\n", bootDevice ); } gettextCleanUp(); - printf("\tLoading configuration..."); + printf( "\tLoading configuration..." ); CFG_Load(); - printf("done\n"); + printf( "done\n" ); SDCard_deInit();// unmount SD for reloading IOS USBDevice_deInit();// unmount USB for reloading IOS USBStorage2_Deinit(); - // This part is added, because we need a identify patched ios - //! pune please replace this with your magic patch functions - Dimok - //if (IOS_ReloadIOSsafe(236) < 0) - // IOS_ReloadIOSsafe(36); - - printf("\tCheck for an existing cIOS\n"); + printf( "\tCheck for an existing cIOS\n" ); CheckForCIOS(); // Let's load the cIOS now - if(LoadAppCIOS() < 0) + if ( LoadAppCIOS() < 0 ) { - printf("\n\tERROR: No cIOS could be loaded. Exiting...."); - sleep(5); + printf( "\n\tERROR: No cIOS could be loaded. Exiting...." ); + sleep( 5 ); Sys_BackToLoader(); } - printf("\n\tLoaded cIOS = %u (Rev %u)",IOS_GetVersion(), IOS_GetRevision()); + printf( "\n\tLoaded cIOS = %u (Rev %u)", IOS_GetVersion(), IOS_GetRevision() ); - printf("\n\tWaiting for USB: "); - if (MountWBFS() < 0) + printf( "\n\tWaiting for USB: " ); + if ( MountWBFS() < 0 ) { - printf("\nERROR: No WBFS drive mounted."); - sleep(5); - exit(0); + printf( "\nERROR: No WBFS drive mounted." ); + sleep( 5 ); + exit( 0 ); } //if a ID was passed via args copy it and try to boot it after the partition is mounted //its not really a headless mode. more like hairless. - if (argc > 1 && argv[1]) + if ( argc > 1 && argv[1] ) { - if (strlen(argv[1])==6) - strncpy(headlessID, argv[1], sizeof(headlessID)); + if ( strlen( argv[1] ) == 6 ) + strncpy( headlessID, argv[1], sizeof( headlessID ) ); } //! Init the rest of the System @@ -160,12 +155,12 @@ int main(int argc, char *argv[]) InitAudio(); char *fontPath = NULL; - asprintf(&fontPath, "%sfont.ttf", CFG.theme_path); - SetupDefaultFont(fontPath); - free(fontPath); + asprintf( &fontPath, "%sfont.ttf", CFG.theme_path ); + SetupDefaultFont( fontPath ); + free( fontPath ); - gprintf("\n\tEnd of Main()"); + gprintf( "\n\tEnd of Main()" ); InitGUIThreads(); - MainMenu(MENU_CHECK); + MainMenu( MENU_CHECK ); return 0; } diff --git a/source/memory.h b/source/memory.h index 4a767eff..9e6f9a1f 100644 --- a/source/memory.h +++ b/source/memory.h @@ -2,29 +2,30 @@ #define __MEMORY_H_ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -#define Disc_ID ((u32*) 0x80000000) -#define Disc_Region ((u32*) 0x80000003) -#define Disc_Magic ((u32*) 0x80000018) -#define Sys_Magic ((u32*) 0x80000020) -#define Version ((u32*) 0x80000024) -#define Mem_Size ((u32*) 0x80000028) -#define Board_Model ((u32*) 0x8000002C) -#define Arena_L ((u32*) 0x80000030) -#define Arena_H ((u32*) 0x80000034) -#define FST ((u32*) 0x80000038) -#define Max_FST ((u32*) 0x8000003C) -#define Assembler ((u32*) 0x80000060) -#define Video_Mode ((u32*) 0x800000CC) -#define Dev_Debugger ((u32*) 0x800000EC) +#define Disc_ID ((u32*) 0x80000000) +#define Disc_Region ((u32*) 0x80000003) +#define Disc_Magic ((u32*) 0x80000018) +#define Sys_Magic ((u32*) 0x80000020) +#define Version ((u32*) 0x80000024) +#define Mem_Size ((u32*) 0x80000028) +#define Board_Model ((u32*) 0x8000002C) +#define Arena_L ((u32*) 0x80000030) +#define Arena_H ((u32*) 0x80000034) +#define FST ((u32*) 0x80000038) +#define Max_FST ((u32*) 0x8000003C) +#define Assembler ((u32*) 0x80000060) +#define Video_Mode ((u32*) 0x800000CC) +#define Dev_Debugger ((u32*) 0x800000EC) #define Simulated_Mem ((u32*) 0x800000F0) -#define BI2 ((u32*) 0x800000F4) -#define Bus_Speed ((u32*) 0x800000F8) -#define CPU_Speed ((u32*) 0x800000FC) -#define Online_Check ((u32*) 0x80003180) -#define GameID_Address ((u32*) 0x80003184) +#define BI2 ((u32*) 0x800000F4) +#define Bus_Speed ((u32*) 0x800000F8) +#define CPU_Speed ((u32*) 0x800000FC) +#define Online_Check ((u32*) 0x80003180) +#define GameID_Address ((u32*) 0x80003184) #define allocate_memory(size) memalign(32, (size+31)&(~31)) diff --git a/source/memory/mem2.cpp b/source/memory/mem2.cpp index 7f7361c7..a30a0877 100644 --- a/source/memory/mem2.cpp +++ b/source/memory/mem2.cpp @@ -5,7 +5,7 @@ #include #include -#define MEM2_PRIORITY_SIZE 2097152 //2MB +#define MEM2_PRIORITY_SIZE 2097152 //2MB // Forbid the use of MEM2 through malloc u32 MALLOC_MEM2 = 0; @@ -17,175 +17,185 @@ static bool g_bigGoesToMem2 = false; extern "C" { -void MEM2_takeBigOnes(bool b) -{ - g_bigGoesToMem2 = b; -} + void MEM2_takeBigOnes( bool b ) + { + g_bigGoesToMem2 = b; + } -void MEM2_init(unsigned int mem2Size) -{ - g_mem2gp.init(mem2Size); -} + void MEM2_init( unsigned int mem2Size ) + { + g_mem2gp.init( mem2Size ); + } -void MEM2_cleanup(void) -{ - g_mem2gp.cleanup(); -} + void MEM2_cleanup( void ) + { + g_mem2gp.cleanup(); + } -void *MEM2_alloc(unsigned int s) -{ - return g_mem2gp.allocate(s); -} + void *MEM2_alloc( unsigned int s ) + { + return g_mem2gp.allocate( s ); + } -void MEM2_free(void *p) -{ - g_mem2gp.release(p); -} + void MEM2_free( void *p ) + { + g_mem2gp.release( p ); + } -void *MEM2_realloc(void *p, unsigned int s) -{ - return g_mem2gp.reallocate(p, s); -} + void *MEM2_realloc( void *p, unsigned int s ) + { + return g_mem2gp.reallocate( p, s ); + } -unsigned int MEM2_usableSize(void *p) -{ - return CMEM2Alloc::usableSize(p); -} + unsigned int MEM2_usableSize( void *p ) + { + return CMEM2Alloc::usableSize( p ); + } -unsigned int MEM2_freesize() -{ - return g_mem2gp.FreeSize(); -} + unsigned int MEM2_freesize() + { + return g_mem2gp.FreeSize(); + } -extern __typeof(malloc) __real_malloc; -extern __typeof(calloc) __real_calloc; -extern __typeof(realloc) __real_realloc; -extern __typeof(memalign) __real_memalign; -extern __typeof(free) __real_free; -extern __typeof(malloc_usable_size) __real_malloc_usable_size; + extern __typeof( malloc ) __real_malloc; + extern __typeof( calloc ) __real_calloc; + extern __typeof( realloc ) __real_realloc; + extern __typeof( memalign ) __real_memalign; + extern __typeof( free ) __real_free; + extern __typeof( malloc_usable_size ) __real_malloc_usable_size; -void *__wrap_malloc(size_t size) -{ - void *p; - if (g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE) - { - p = MEM2_alloc(size); - if (p != 0) { - return p; - } - return __real_malloc(size); - } - p = __real_malloc(size); - if (p != 0) { - return p; - } - return MEM2_alloc(size); -} + void *__wrap_malloc( size_t size ) + { + void *p; + if ( g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE ) + { + p = MEM2_alloc( size ); + if ( p != 0 ) + { + return p; + } + return __real_malloc( size ); + } + p = __real_malloc( size ); + if ( p != 0 ) + { + return p; + } + return MEM2_alloc( size ); + } -void *__wrap_calloc(size_t n, size_t size) -{ - void *p; - if (g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE) - { - p = MEM2_alloc(n * size); - if (p != 0) - { - memset(p, 0, n * size); - return p; - } - return __real_calloc(n, size); - } - p = __real_calloc(n, size); - if (p != 0) { - return p; - } - p = MEM2_alloc(n * size); - if (p != 0) { - memset(p, 0, n * size); - } - return p; -} + void *__wrap_calloc( size_t n, size_t size ) + { + void *p; + if ( g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE ) + { + p = MEM2_alloc( n * size ); + if ( p != 0 ) + { + memset( p, 0, n * size ); + return p; + } + return __real_calloc( n, size ); + } + p = __real_calloc( n, size ); + if ( p != 0 ) + { + return p; + } + p = MEM2_alloc( n * size ); + if ( p != 0 ) + { + memset( p, 0, n * size ); + } + return p; + } -void *__wrap_memalign(size_t a, size_t size) -{ - void *p; - if (g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE) - { - if (a <= 32 && 32 % a == 0) - { - p = MEM2_alloc(size); - if (p != 0) { - return p; - } - } - return __real_memalign(a, size); - } - p = __real_memalign(a, size); - if (p != 0 || a > 32 || 32 % a != 0) { - return p; - } + void *__wrap_memalign( size_t a, size_t size ) + { + void *p; + if ( g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE ) + { + if ( a <= 32 && 32 % a == 0 ) + { + p = MEM2_alloc( size ); + if ( p != 0 ) + { + return p; + } + } + return __real_memalign( a, size ); + } + p = __real_memalign( a, size ); + if ( p != 0 || a > 32 || 32 % a != 0 ) + { + return p; + } - return MEM2_alloc(size); -} + return MEM2_alloc( size ); + } -void __wrap_free(void *p) -{ - if(!p) - return; + void __wrap_free( void *p ) + { + if ( !p ) + return; - if (((u32)p & 0x10000000) != 0) - { - MEM2_free(p); - } - else - { - __real_free(p); - } -} + if ( ( ( u32 )p & 0x10000000 ) != 0 ) + { + MEM2_free( p ); + } + else + { + __real_free( p ); + } + } -void *__wrap_realloc(void *p, size_t size) -{ - void *n; - // ptr from mem2 - if (((u32)p & 0x10000000) != 0 || (p == 0 && g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE)) - { - n = MEM2_realloc(p, size); - if (n != 0) { - return n; - } - n = __real_malloc(size); - if (n == 0) { - return 0; - } - if (p != 0) - { - memcpy(n, p, MEM2_usableSize(p) < size ? MEM2_usableSize(p) : size); - MEM2_free(p); - } - return n; - } - // ptr from malloc - n = __real_realloc(p, size); - if (n != 0) { - return n; - } - n = MEM2_alloc(size); - if (n == 0) { - return 0; - } - if (p != 0) - { - memcpy(n, p, __real_malloc_usable_size(p) < size ? __real_malloc_usable_size(p) : size); - __real_free(p); - } - return n; -} + void *__wrap_realloc( void *p, size_t size ) + { + void *n; + // ptr from mem2 + if ( ( ( u32 )p & 0x10000000 ) != 0 || ( p == 0 && g_bigGoesToMem2 && size > MEM2_PRIORITY_SIZE ) ) + { + n = MEM2_realloc( p, size ); + if ( n != 0 ) + { + return n; + } + n = __real_malloc( size ); + if ( n == 0 ) + { + return 0; + } + if ( p != 0 ) + { + memcpy( n, p, MEM2_usableSize( p ) < size ? MEM2_usableSize( p ) : size ); + MEM2_free( p ); + } + return n; + } + // ptr from malloc + n = __real_realloc( p, size ); + if ( n != 0 ) + { + return n; + } + n = MEM2_alloc( size ); + if ( n == 0 ) + { + return 0; + } + if ( p != 0 ) + { + memcpy( n, p, __real_malloc_usable_size( p ) < size ? __real_malloc_usable_size( p ) : size ); + __real_free( p ); + } + return n; + } -size_t __wrap_malloc_usable_size(void *p) -{ - if (((u32)p & 0x10000000) != 0) - return MEM2_usableSize(p); - return __real_malloc_usable_size(p); -} + size_t __wrap_malloc_usable_size( void *p ) + { + if ( ( ( u32 )p & 0x10000000 ) != 0 ) + return MEM2_usableSize( p ); + return __real_malloc_usable_size( p ); + } } ///extern "C" diff --git a/source/memory/mem2.h b/source/memory/mem2.h index b8659631..f71a013e 100644 --- a/source/memory/mem2.h +++ b/source/memory/mem2.h @@ -5,17 +5,18 @@ #define __MEM2_H_ #ifdef __cplusplus -extern "C" { +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); -unsigned int MEM2_freesize(); + 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 50209ee2..c8cde9f1 100644 --- a/source/memory/mem2alloc.cpp +++ b/source/memory/mem2alloc.cpp @@ -8,231 +8,231 @@ class LockMutex { - mutex_t &m_mutex; -public: - LockMutex(mutex_t &m) : m_mutex(m) { LWP_MutexLock(m_mutex); } - ~LockMutex(void) { LWP_MutexUnlock(m_mutex); } + mutex_t &m_mutex; + public: + 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); - 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); - m_baseAddress = 0; - m_endAddress = 0; + 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 ); + 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); + m_first = 0; + 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; - // - LockMutex lock(m_mutex); - // - s = (s - 1) / sizeof (SBlock) + 1; - // First block - if (m_first == 0) - { - if (m_baseAddress + s + 1 >= m_endAddress) - return 0; - m_first = m_baseAddress; - m_first->next = 0; - m_first->prev = 0; - m_first->s = s; - m_first->f = false; - return (void *)(m_first + 1); - } - // Search for a free block - SBlock *i; - SBlock *j; - for (i = m_first; i != 0; i = i->next) - { - if (i->f && i->s >= s) - break; - j = i; - } - // Create a new block - if (i == 0) - { - i = j + j->s + 1; - if (i + s + 1 >= m_endAddress) - return 0; - j->next = i; - i->prev = j; - i->next = 0; - i->s = s; - i->f = false; - return (void *)(i + 1); - } - // Reuse a free block - i->f = false; - // Split it - if (i->s > s + 1) - { - j = i + s + 1; - j->f = true; - j->s = i->s - s - 1; - i->s = s; - j->next = i->next; - j->prev = i; - i->next = j; - if (j->next != 0) - j->next->prev = j; - } - return (void *)(i + 1); + if ( s == 0 ) + s = 1; + // + LockMutex lock( m_mutex ); + // + s = ( s - 1 ) / sizeof ( SBlock ) + 1; + // First block + if ( m_first == 0 ) + { + if ( m_baseAddress + s + 1 >= m_endAddress ) + return 0; + m_first = m_baseAddress; + m_first->next = 0; + m_first->prev = 0; + m_first->s = s; + m_first->f = false; + return ( void * )( m_first + 1 ); + } + // Search for a free block + SBlock *i; + SBlock *j; + for ( i = m_first; i != 0; i = i->next ) + { + if ( i->f && i->s >= s ) + break; + j = i; + } + // Create a new block + if ( i == 0 ) + { + i = j + j->s + 1; + if ( i + s + 1 >= m_endAddress ) + return 0; + j->next = i; + i->prev = j; + i->next = 0; + i->s = s; + i->f = false; + return ( void * )( i + 1 ); + } + // Reuse a free block + i->f = false; + // Split it + if ( i->s > s + 1 ) + { + j = i + s + 1; + j->f = true; + j->s = i->s - s - 1; + i->s = s; + j->next = i->next; + j->prev = i; + i->next = j; + if ( j->next != 0 ) + j->next->prev = j; + } + return ( void * )( i + 1 ); } -void CMEM2Alloc::release(void *p) +void CMEM2Alloc::release( void *p ) { - if (p == 0) - return; + if ( p == 0 ) + return; - LockMutex lock(m_mutex); - SBlock *i = (SBlock *)p - 1; - i->f = true; + 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) + if ( i->next == 0 ) i->s = m_endAddress - i - 1; - // Merge with previous block - if (i->prev != 0 && i->prev->f) - { - i = i->prev; - i->s += i->next->s + 1; - i->next = i->next->next; - if (i->next != 0) - i->next->prev = i; - } - // Merge with next block - if (i->next != 0 && i->next->f) - { - i->s += i->next->s + 1; - i->next = i->next->next; - if (i->next != 0) - i->next->prev = i; - } + // Merge with previous block + if ( i->prev != 0 && i->prev->f ) + { + i = i->prev; + i->s += i->next->s + 1; + i->next = i->next->next; + if ( i->next != 0 ) + i->next->prev = i; + } + // Merge with next block + if ( i->next != 0 && i->next->f ) + { + i->s += i->next->s + 1; + i->next = i->next->next; + if ( i->next != 0 ) + i->next->prev = i; + } } -void *CMEM2Alloc::reallocate(void *p, unsigned int s) +void *CMEM2Alloc::reallocate( void *p, unsigned int s ) { - SBlock *i; - SBlock *j; - void *n; + 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; - { - LockMutex lock(m_mutex); + i = ( SBlock * )p - 1; + s = ( s - 1 ) / sizeof ( SBlock ) + 1; + { + LockMutex lock( m_mutex ); //out of memory /* Dimok */ - if (i + s + 1 >= m_endAddress) - { - return 0; - } + if ( i + s + 1 >= m_endAddress ) + { + return 0; + } - // Last block - 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) - { - // Merge - i->s += i->next->s + 1; - i->next = i->next->next; - if (i->next != 0) - i->next->prev = i; - } - // Size <= current size - if (i->s >= s) - { - // Split - if (i->s > s + 1) - { - j = i + s + 1; - j->f = true; - j->s = i->s - s - 1; - i->s = s; - j->next = i->next; - j->prev = i; - i->next = j; - if (j->next != 0) - j->next->prev = j; - } - return p; - } - } - // Size > current size - n = allocate(s * sizeof (SBlock)); - if (n == 0) - return 0; - memcpy(n, p, i->s * sizeof (SBlock)); - release(p); - return n; + // Last block + 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 ) + { + // Merge + i->s += i->next->s + 1; + i->next = i->next->next; + if ( i->next != 0 ) + i->next->prev = i; + } + // Size <= current size + if ( i->s >= s ) + { + // Split + if ( i->s > s + 1 ) + { + j = i + s + 1; + j->f = true; + j->s = i->s - s - 1; + i->s = s; + j->next = i->next; + j->prev = i; + i->next = j; + if ( j->next != 0 ) + j->next->prev = j; + } + return p; + } + } + // Size > current size + n = allocate( s * sizeof ( SBlock ) ); + if ( n == 0 ) + return 0; + memcpy( n, p, i->s * sizeof ( SBlock ) ); + release( p ); + return n; } 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; + SBlock *i; unsigned int size = 0; - for(i = m_first; i != 0; i = i->next) - { - if(i->f && i->next != 0) + for ( i = m_first; i != 0; i = i->next ) + { + 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) + 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/menu.cpp b/source/menu.cpp index 1445a9c0..481d5143 100644 --- a/source/menu.cpp +++ b/source/menu.cpp @@ -45,7 +45,7 @@ GuiSound *btnClick2 = NULL; struct discHdr *dvdheader = NULL; int currentMenu; -u8 mountMethod=0; +u8 mountMethod = 0; char game_partition[6]; int load_from_fs; @@ -78,9 +78,10 @@ extern u8 dbvideo; * after finishing the removal/insertion of new elements, and after initial * GUI setup. ***************************************************************************/ -void ResumeGui() { +void ResumeGui() +{ guiHalt = false; - LWP_ResumeThread (guithread); + LWP_ResumeThread ( guithread ); } /**************************************************************************** @@ -91,13 +92,14 @@ void ResumeGui() { * This eliminates the possibility that the GUI is in the middle of accessing * an element that is being changed. ***************************************************************************/ -void HaltGui() { - if (guiHalt)return; +void HaltGui() +{ + if ( guiHalt )return; guiHalt = true; // wait for thread to finish - while (!LWP_ThreadIsSuspended(guithread)) - usleep(50); + while ( !LWP_ThreadIsSuspended( guithread ) ) + usleep( 50 ); } /**************************************************************************** @@ -105,28 +107,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) + 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, CFG.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, CFG.widescreen ? 0.8 : 1, 1, 255, 0, 0, 0, 0, 0, 0, 0, 0 ); } } @@ -134,40 +136,40 @@ 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) + 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) + if ( strcmp( headlessID, "" ) == 0 ) mainWindow->Draw(); - Menu_DrawRectangle(0,0,screenwidth,screenheight,(GXColor) {0, 0, 0, i},1); + Menu_DrawRectangle( 0, 0, screenwidth, screenheight, ( GXColor ) {0, 0, 0, i}, 1 ); Menu_Render(); } mainWindow->RemoveAll(); @@ -181,244 +183,253 @@ static void * UpdateGUI (void *arg) * * Startup GUI threads ***************************************************************************/ -void InitGUIThreads() { - LWP_CreateThread(&guithread, UpdateGUI, NULL, NULL, 65536, LWP_PRIO_HIGHEST); +void InitGUIThreads() +{ + LWP_CreateThread( &guithread, UpdateGUI, NULL, NULL, 65536, LWP_PRIO_HIGHEST ); InitProgressThread(); InitNetworkThread(); - if (Settings.autonetwork) + if ( Settings.autonetwork ) ResumeNetworkThread(); } -void ExitGUIThreads() { +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; - GuiImageData *Cover = NULL; - char ID[4]; - char IDfull[7]; - char Path[100]; - bool flag = Prefere3D; + if ( !header ) return NULL; + GuiImageData *Cover = NULL; + char ID[4]; + char IDfull[7]; + char Path[100]; + bool flag = Prefere3D; - snprintf(ID, sizeof(ID), "%c%c%c", header->id[0], header->id[1], header->id[2]); - snprintf(IDfull, sizeof(IDfull), "%s%c%c%c", ID, header->id[3], header->id[4], header->id[5]); + snprintf( ID, sizeof( ID ), "%c%c%c", header->id[0], header->id[1], header->id[2] ); + snprintf( IDfull, sizeof( IDfull ), "%s%c%c%c", ID, header->id[3], header->id[4], header->id[5] ); - for(int i=0; i<2; ++i) - { - char *coverPath = flag ? Settings.covers_path : Settings.covers2d_path; flag = !flag; - //Load full id image - snprintf(Path, sizeof(Path), "%s%s.png", coverPath, IDfull); - delete Cover; Cover = new(std::nothrow) GuiImageData(Path, NULL); - //Load short id image - if (!Cover || !Cover->GetImage()) - { - snprintf(Path, sizeof(Path), "%s%s.png", coverPath, ID); - delete Cover; Cover = new(std::nothrow) GuiImageData(Path, NULL); - } - if(Cover && Cover->GetImage()) - break; - } - //Load no image - if (noCover && (!Cover || !Cover->GetImage())) - { - flag = Prefere3D; - for(int i=0; i<2; ++i) - { - const char *nocoverPath = (flag ? "%snoimage.png" : "%snoimage2d.png"); flag = !flag; - snprintf(Path, sizeof(Path), nocoverPath, CFG.theme_path); - delete Cover; Cover = new(std::nothrow) GuiImageData(Path, (Prefere3D ? nocover_png : nocoverFlat_png)); - if (Cover && Cover->GetImage()) - break; - } - } - if(Cover && !Cover->GetImage()) - { - delete Cover; - Cover = NULL; - } - return Cover; + for ( int i = 0; i < 2; ++i ) + { + char *coverPath = flag ? Settings.covers_path : Settings.covers2d_path; flag = !flag; + //Load full id image + snprintf( Path, sizeof( Path ), "%s%s.png", coverPath, IDfull ); + delete Cover; Cover = new( std::nothrow ) GuiImageData( Path, NULL ); + //Load short id image + if ( !Cover || !Cover->GetImage() ) + { + snprintf( Path, sizeof( Path ), "%s%s.png", coverPath, ID ); + delete Cover; Cover = new( std::nothrow ) GuiImageData( Path, NULL ); + } + if ( Cover && Cover->GetImage() ) + break; + } + //Load no image + if ( noCover && ( !Cover || !Cover->GetImage() ) ) + { + flag = Prefere3D; + for ( int i = 0; i < 2; ++i ) + { + const char *nocoverPath = ( flag ? "%snoimage.png" : "%snoimage2d.png" ); flag = !flag; + snprintf( Path, sizeof( Path ), nocoverPath, CFG.theme_path ); + delete Cover; Cover = new( std::nothrow ) GuiImageData( Path, ( Prefere3D ? nocover_png : nocoverFlat_png ) ); + if ( Cover && Cover->GetImage() ) + break; + } + } + if ( Cover && !Cover->GetImage() ) + { + delete Cover; + Cover = NULL; + } + return Cover; } /**************************************************************************** * MainMenu ***************************************************************************/ -int MainMenu(int menu) { +int MainMenu( int menu ) +{ currentMenu = menu; char imgPath[100]; - //if (strcmp(headlessID,"")!=0)HaltGui(); - //WindowPrompt("Can you see me now",0,"ok"); + //if (strcmp(headlessID,"")!=0)HaltGui(); + //WindowPrompt("Can you see me now",0,"ok"); - snprintf(imgPath, sizeof(imgPath), "%splayer1_point.png", CFG.theme_path); - pointer[0] = new GuiImageData(imgPath, player1_point_png); - snprintf(imgPath, sizeof(imgPath), "%splayer2_point.png", CFG.theme_path); - pointer[1] = new GuiImageData(imgPath, player2_point_png); - snprintf(imgPath, sizeof(imgPath), "%splayer3_point.png", CFG.theme_path); - pointer[2] = new GuiImageData(imgPath, player3_point_png); - snprintf(imgPath, sizeof(imgPath), "%splayer4_point.png", CFG.theme_path); - pointer[3] = new GuiImageData(imgPath, player4_point_png); + snprintf( imgPath, sizeof( imgPath ), "%splayer1_point.png", CFG.theme_path ); + pointer[0] = new GuiImageData( imgPath, player1_point_png ); + snprintf( imgPath, sizeof( imgPath ), "%splayer2_point.png", CFG.theme_path ); + pointer[1] = new GuiImageData( imgPath, player2_point_png ); + snprintf( imgPath, sizeof( imgPath ), "%splayer3_point.png", CFG.theme_path ); + pointer[2] = new GuiImageData( imgPath, player3_point_png ); + snprintf( imgPath, sizeof( imgPath ), "%splayer4_point.png", CFG.theme_path ); + pointer[3] = new GuiImageData( imgPath, player4_point_png ); - mainWindow = new GuiWindow(screenwidth, screenheight); + mainWindow = new GuiWindow( screenwidth, screenheight ); - if (CFG.widescreen) - snprintf(imgPath, sizeof(imgPath), "%swbackground.png", CFG.theme_path); + if ( CFG.widescreen ) + snprintf( imgPath, sizeof( imgPath ), "%swbackground.png", CFG.theme_path ); else - snprintf(imgPath, sizeof(imgPath), "%sbackground.png", CFG.theme_path); + snprintf( imgPath, sizeof( imgPath ), "%sbackground.png", CFG.theme_path ); - background = new GuiImageData(imgPath, CFG.widescreen? wbackground_png : background_png); + background = new GuiImageData( imgPath, CFG.widescreen ? wbackground_png : background_png ); - bgImg = new GuiImage(background); - mainWindow->Append(bgImg); + 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->Play(); + 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) { - bgMusic->SetVolume(Settings.volume); -// gprintf("Current menu: %d\n", currentMenu); + while ( currentMenu != MENU_EXIT ) + { + bgMusic->SetVolume( Settings.volume ); +// gprintf("Current menu: %d\n", currentMenu); - switch (currentMenu) { - case MENU_CHECK: - currentMenu = MenuCheck(); - break; - case MENU_FORMAT: - currentMenu = MenuFormat(); - break; - case MENU_INSTALL: - currentMenu = MenuInstall(); - break; - case MENU_SETTINGS: - currentMenu = MenuSettings(); - break; - case MENU_THEMEDOWNLOADER: - currentMenu = Theme_Downloader(); - break; - case MENU_HOMEBREWBROWSE: - currentMenu = MenuHomebrewBrowse(); - break; - case MENU_DISCLIST: - currentMenu = MenuDiscList(); - break; - default: // unrecognized menu - currentMenu = MenuCheck(); - break; + switch ( currentMenu ) + { + case MENU_CHECK: + currentMenu = MenuCheck(); + break; + case MENU_FORMAT: + currentMenu = MenuFormat(); + break; + case MENU_INSTALL: + currentMenu = MenuInstall(); + break; + case MENU_SETTINGS: + currentMenu = MenuSettings(); + break; + case MENU_THEMEDOWNLOADER: + currentMenu = Theme_Downloader(); + break; + case MENU_HOMEBREWBROWSE: + currentMenu = MenuHomebrewBrowse(); + break; + case MENU_DISCLIST: + currentMenu = MenuDiscList(); + break; + default: // unrecognized menu + currentMenu = MenuCheck(); + break; } } - // MemInfoPrompt(); - gprintf("Exiting main GUI. mountMethod = %d\n",mountMethod); + // MemInfoPrompt(); + gprintf( "Exiting main GUI. mountMethod = %d\n", mountMethod ); - CloseXMLDatabase(); + CloseXMLDatabase(); NewTitles::DestroyInstance(); - CFG_Cleanup(); + CFG_Cleanup(); - if (strcmp(headlessID,"")!=0)//the GUIthread was never started, so it cant be ended and joined properly if headless mode was used. so we resume it and close it. - ResumeGui(); - ExitGUIThreads(); + 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(); delete bgMusic; 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; delete cover; delete coverImg; - delete fontSystem; - ShutdownAudio(); + delete fontSystem; + ShutdownAudio(); StopGX(); - gettextCleanUp(); + gettextCleanUp(); - if(dbvideo) + if ( dbvideo ) InitVideodebug (); - if (mountMethod==3) - { - struct discHdr *header = gameList[gameSelected]; - char tmp[20]; - u32 tid; - sprintf(tmp,"%c%c%c%c",header->id[0],header->id[1],header->id[2],header->id[3]); - memcpy(&tid, tmp, 4); - gprintf("\nBooting title %016llx",TITLE_ID((header->id[5]=='1'?0x00010001:0x00010002),tid)); - WII_Initialize(); - WII_LaunchTitle(TITLE_ID((header->id[5]=='1'?0x00010001:0x00010002),tid)); - } - if (mountMethod==2) - { - gprintf("\nLoading BC for GameCube"); - WII_Initialize(); - WII_LaunchTitle(0x0000000100000100ULL); - } + if ( mountMethod == 3 ) + { + struct discHdr *header = gameList[gameSelected]; + char tmp[20]; + u32 tid; + sprintf( tmp, "%c%c%c%c", header->id[0], header->id[1], header->id[2], header->id[3] ); + memcpy( &tid, tmp, 4 ); + gprintf( "\nBooting title %016llx", TITLE_ID( ( header->id[5] == '1' ? 0x00010001 : 0x00010002 ), tid ) ); + WII_Initialize(); + WII_LaunchTitle( TITLE_ID( ( header->id[5] == '1' ? 0x00010001 : 0x00010002 ), tid ) ); + } + if ( mountMethod == 2 ) + { + gprintf( "\nLoading BC for GameCube" ); + WII_Initialize(); + WII_LaunchTitle( 0x0000000100000100ULL ); + } - if (boothomebrew == 1) { - gprintf("\nBootHomebrew"); - BootHomebrew(Settings.selected_homebrew); + if ( boothomebrew == 1 ) + { + gprintf( "\nBootHomebrew" ); + BootHomebrew( Settings.selected_homebrew ); } - else if (boothomebrew == 2) { - gprintf("\nBootHomebrew from Menu"); - //BootHomebrew(); - BootHomebrewFromMem(); + else if ( boothomebrew == 2 ) + { + gprintf( "\nBootHomebrew from Menu" ); + //BootHomebrew(); + BootHomebrewFromMem(); } - else { - 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) - { - gprintf("\tHeadless mode (%s)\n",headlessID); - gameList.LoadUnfiltered(); - if (!gameList.size()) - { - gprintf(" ERROR : !gameCnt"); - exit(0); - } - //gprintf("\n\tgameCnt:%d",gameCnt); - 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) - { - gameSelected = i; - gprintf(" found (%d)\n",i); - break; - } - //if the game was not found - if (i==gameList.GameCount()-1) - { - gprintf(" not found (%d IDs checked)\n",i); - exit(0); - } - } - } + else + { + 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 ) + { + gprintf( "\tHeadless mode (%s)\n", headlessID ); + gameList.LoadUnfiltered(); + if ( !gameList.size() ) + { + gprintf( " ERROR : !gameCnt" ); + exit( 0 ); + } + //gprintf("\n\tgameCnt:%d",gameCnt); + 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 ) + { + gameSelected = i; + gprintf( " found (%d)\n", i ); + break; + } + //if the game was not found + if ( i == gameList.GameCount() - 1 ) + { + 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; ocarinaChoice = game_cfg->ocarina; @@ -426,230 +437,250 @@ int MainMenu(int menu) { fix002 = game_cfg->errorfix002; iosChoice = game_cfg->ios; countrystrings = game_cfg->patchcountrystrings; - if (!altdoldefault) { - alternatedol = game_cfg->loadalternatedol; - alternatedoloffset = game_cfg->alternatedolstart; - } + if ( !altdoldefault ) + { + alternatedol = game_cfg->loadalternatedol; + alternatedoloffset = game_cfg->alternatedolstart; + } reloadblock = game_cfg->iosreloadblock; - } else { + } + else + { videoChoice = Settings.video; languageChoice = Settings.language; ocarinaChoice = Settings.ocarina; viChoice = Settings.vpatch; - if (Settings.cios == ios222) { + if ( Settings.cios == ios222 ) + { iosChoice = i222; - } else { + } + else + { iosChoice = i249; } fix002 = Settings.error002; countrystrings = Settings.patchcountrystrings; - if (!altdoldefault) { - alternatedol = off; - alternatedoloffset = 0; - } + if ( !altdoldefault ) + { + alternatedol = off; + alternatedoloffset = 0; + } reloadblock = off; } - int ios2; + int ios2; - switch (iosChoice) { - case i249: - ios2 = 249; - break; + switch ( iosChoice ) + { + case i249: + ios2 = 249; + break; - case i222: - ios2 = 222; - break; + case i222: + ios2 = 222; + break; - case i223: - ios2 = 223; - break; + case i223: + ios2 = 223; + break; - default: - ios2 = 249; - break; - } + default: + ios2 = 249; + break; + } - // When the selected ios is 249, and you're loading from FAT, reset ios to 222 - if (load_from_fs != PART_FS_WBFS && ios2 == 249) { - ios2 = 222; - } + // When the selected ios is 249, and you're loading from FAT, reset ios to 222 + if ( load_from_fs != PART_FS_WBFS && ios2 == 249 ) + { + ios2 = 222; + } bool onlinefix = ShutdownWC24(); - // You cannot reload ios when loading from fat - if (IOS_GetVersion() != ios2 || onlinefix) { - ret = Sys_ChangeIos(ios2); - if (ret < 0) { - Sys_ChangeIos(249); + // You cannot reload ios when loading from fat + if ( IOS_GetVersion() != ios2 || onlinefix ) + { + ret = Sys_ChangeIos( ios2 ); + if ( ret < 0 ) + { + Sys_ChangeIos( 249 ); } } - if (!mountMethod) - { - gprintf("Loading fragment list..."); - ret = get_frag_list(header->id); - gprintf("%d\n", ret); + if ( !mountMethod ) + { + 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"); - } - else { - gprintf("\tUSB not set, loading DVD\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" ); + } 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) { - mload_close(); - } + if ( load_from_fs == PART_FS_WBFS ) + { + mload_close(); + } } u8 errorfixer002 = 0; - switch (fix002) { - case on: - errorfixer002 = 1; - break; - case off: - errorfixer002 = 0; - break; - case anti: - errorfixer002 = 2; - break; + switch ( fix002 ) + { + case on: + errorfixer002 = 1; + break; + case off: + errorfixer002 = 0; + break; + case anti: + errorfixer002 = 2; + break; } - switch (languageChoice) { - case ConsoleLangDefault: - configbytes[0] = 0xCD; - break; + switch ( languageChoice ) + { + case ConsoleLangDefault: + configbytes[0] = 0xCD; + break; - case jap: - configbytes[0] = 0x00; - break; + case jap: + configbytes[0] = 0x00; + break; - case eng: - configbytes[0] = 0x01; - break; + case eng: + configbytes[0] = 0x01; + break; - case ger: - configbytes[0] = 0x02; - break; + case ger: + configbytes[0] = 0x02; + break; - case fren: - configbytes[0] = 0x03; - break; + case fren: + configbytes[0] = 0x03; + break; - case esp: - configbytes[0] = 0x04; - break; + case esp: + configbytes[0] = 0x04; + break; - case it: - configbytes[0] = 0x05; - break; + case it: + configbytes[0] = 0x05; + break; - case dut: - configbytes[0] = 0x06; - break; + case dut: + configbytes[0] = 0x06; + break; - case schin: - configbytes[0] = 0x07; - break; + case schin: + configbytes[0] = 0x07; + break; - case tchin: - configbytes[0] = 0x08; - break; + case tchin: + configbytes[0] = 0x08; + break; - case kor: - configbytes[0] = 0x09; - break; - //wenn nicht genau klar ist welches - default: - configbytes[0] = 0xCD; - break; + case kor: + configbytes[0] = 0x09; + break; + //wenn nicht genau klar ist welches + default: + configbytes[0] = 0xCD; + break; } u8 videoselected = 0; - switch (videoChoice) { - case discdefault: - videoselected = 0; - break; + switch ( videoChoice ) + { + case discdefault: + videoselected = 0; + break; - case pal50: - videoselected = 1; - break; + case pal50: + videoselected = 1; + break; - case pal60: - videoselected = 2; - break; + case pal60: + videoselected = 2; + break; - case ntsc: - videoselected = 3; - break; + case ntsc: + videoselected = 3; + break; - case systemdefault: - videoselected = 4; - break; + case systemdefault: + videoselected = 4; + break; - case patch: - videoselected = 5; - break; + case patch: + videoselected = 5; + break; - default: - videoselected = 0; - break; + default: + videoselected = 0; + break; } u32 cheat = 0; - switch (ocarinaChoice) { - case on: - cheat = 1; - break; + switch ( ocarinaChoice ) + { + case on: + cheat = 1; + break; - case off: - cheat = 0; - break; + case off: + cheat = 0; + break; - default: - cheat = 1; - break; + default: + cheat = 1; + break; } u8 vipatch = 0; - switch (viChoice) { - case on: - vipatch = 1; - break; + switch ( viChoice ) + { + case on: + vipatch = 1; + break; - case off: - vipatch = 0; - break; + case off: + vipatch = 0; + break; - default: - vipatch = 0; - break; + default: + vipatch = 0; + break; } - gprintf("\tDisc_wiiBoot\n"); + gprintf( "\tDisc_wiiBoot\n" ); - ret = Disc_WiiBoot(videoselected, cheat, vipatch, countrystrings, errorfixer002, alternatedol, alternatedoloffset); - if (ret < 0) { + ret = Disc_WiiBoot( videoselected, cheat, vipatch, countrystrings, errorfixer002, alternatedol, alternatedoloffset ); + if ( ret < 0 ) + { Sys_LoadMenu(); } - //should never get here - printf("Returning entry point: 0x%0x\n", ret); + //should never get here + printf( "Returning entry point: 0x%0x\n", ret ); } - return 0; + return 0; } diff --git a/source/menu.h b/source/menu.h index 0ffb3a75..db0bdb1a 100644 --- a/source/menu.h +++ b/source/menu.h @@ -13,12 +13,13 @@ #include "settings/cfg.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 { +enum +{ MENU_EXIT = -1, MENU_NONE, MENU_SETTINGS, @@ -32,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 9527ccfb..abbed563 100644 --- a/source/menu/menu_check.cpp +++ b/source/menu/menu_check.cpp @@ -13,8 +13,9 @@ extern char headlessID[8]; /**************************************************************************** * MenuCheck ***************************************************************************/ -int MenuCheck() { - gprintf("\nMenuCheck()"); +int MenuCheck() +{ + gprintf( "\nMenuCheck()" ); int menu = MENU_NONE; int i = 0; int choice; @@ -24,120 +25,148 @@ int MenuCheck() { VIDEO_WaitVSync (); - 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")); + 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" ) ); 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 = ios249; - } else if (ret2 == 2) { + } + else if ( ret2 == 2 ) + { Settings.cios = ios222; - } else { + } + else + { 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) { - WindowPrompt (tr("Error !"),tr("USB Device not found"), tr("OK")); + 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" ) ); Sys_LoadMenu(); } } - ret2 = -1; - memset(game_partition, 0, 6); - load_from_fs = -1; + ret2 = -1; + memset( game_partition, 0, 6 ); + load_from_fs = -1; - extern PartList partitions; - // Added for slow HDD - for (int runs = 0; runs < 10; runs++) { - if (Partition_GetList(WBFS_DEVICE_USB, &partitions) != 0) { - sleep(1); - continue; - } - - 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)) - { - ret2 = 0; - load_from_fs = pinfo.part_fs; - break; - } - } + extern PartList partitions; + // Added for slow HDD + for ( int runs = 0; runs < 10; runs++ ) + { + if ( Partition_GetList( WBFS_DEVICE_USB, &partitions ) != 0 ) + { + sleep( 1 ); + continue; + } - if (partitions.wbfs_n != 0) { - ret2 = WBFS_Open(); - for (int p = 0; p < partitions.num; p++) { - if (partitions.pinfo[p].fs_type == FS_TYPE_WBFS) { - Settings.partition = p; - load_from_fs = PART_FS_WBFS; - break; - } - } - } else if (Sys_IsHermes() && (partitions.fat_n != 0 || partitions.ntfs_n != 0)) { - // Loop through FAT/NTFS partitions, and find the first partition with games on it (if there is one) - u32 count; - - for (int i = 0; i < partitions.num; i++) { - if (partitions.pinfo[i].fs_type == FS_TYPE_FAT32 || partitions.pinfo[i].fs_type == FS_TYPE_NTFS) { + if ( 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 ) ) + { + ret2 = 0; + load_from_fs = pinfo.part_fs; + break; + } + } - if (!WBFS_OpenPart(partitions.pinfo[i].part_fs, partitions.pinfo[i].index, partitions.pentry[i].sector, partitions.pentry[i].size, (char *) &game_partition)) { - // Get the game count... - WBFS_GetCount(&count); + if ( partitions.wbfs_n != 0 ) + { + ret2 = WBFS_Open(); + for ( int p = 0; p < partitions.num; p++ ) + { + if ( partitions.pinfo[p].fs_type == FS_TYPE_WBFS ) + { + Settings.partition = p; + load_from_fs = PART_FS_WBFS; + break; + } + } + } + else if ( Sys_IsHermes() && ( partitions.fat_n != 0 || partitions.ntfs_n != 0 ) ) + { + // Loop through FAT/NTFS partitions, and find the first partition with games on it (if there is one) + u32 count; - if (count > 0) { - load_from_fs = partitions.pinfo[i].part_fs; - Settings.partition = i; - break; - } else { - WBFS_Close(); - } - } - } - } - } + 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 ((ret2 >= 0 || load_from_fs != PART_FS_WBFS) && isInserted(bootDevice)) { - cfg_save_global(); - break; - } - sleep(1); - } - - if (ret2 < 0 && load_from_fs != PART_FS_WBFS) { - choice = WindowPrompt(tr("No WBFS or FAT/NTFS partition found"),tr("You need to select or format a partition"), tr("Select"), tr("Format"), tr("Return")); - if (choice == 0) { + if ( !WBFS_OpenPart( partitions.pinfo[i].part_fs, partitions.pinfo[i].index, partitions.pentry[i].sector, partitions.pentry[i].size, ( char * ) &game_partition ) ) + { + // Get the game count... + WBFS_GetCount( &count ); + + if ( count > 0 ) + { + load_from_fs = partitions.pinfo[i].part_fs; + Settings.partition = i; + break; + } + else + { + WBFS_Close(); + } + } + } + } + } + + if ( ( ret2 >= 0 || load_from_fs != PART_FS_WBFS ) && isInserted( bootDevice ) ) + { + cfg_save_global(); + break; + } + sleep( 1 ); + } + + if ( ret2 < 0 && load_from_fs != PART_FS_WBFS ) + { + choice = WindowPrompt( tr( "No WBFS or FAT/NTFS partition found" ), tr( "You need to select or format a partition" ), tr( "Select" ), tr( "Format" ), tr( "Return" ) ); + if ( choice == 0 ) + { Sys_LoadMenu(); - } else { - load_from_fs = choice == 1 ? PART_FS_FAT : PART_FS_WBFS; + } + else + { + load_from_fs = choice == 1 ? PART_FS_FAT : PART_FS_WBFS; menu = MENU_FORMAT; } } - + ret2 = Disc_Init(); - if (ret2 < 0) { - WindowPrompt (tr("Error !"),tr("Could not initialize DIP module!"),tr("OK")); + if ( ret2 < 0 ) + { + WindowPrompt ( tr( "Error !" ), tr( "Could not initialize DIP module!" ), tr( "OK" ) ); Sys_LoadMenu(); } - if (shutdown == 1) + if ( shutdown == 1 ) Sys_Shutdown(); - if (reset == 1) + if ( reset == 1 ) Sys_Reboot(); - if (wbfsinit < 0) { - sleep(1); + if ( wbfsinit < 0 ) + { + sleep( 1 ); } - - // open database if needed, load titles if needed - if(isInserted(bootDevice))OpenXMLDatabase(Settings.titlestxt_path,Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true); + + // open database if needed, load titles if needed + if ( isInserted( bootDevice ) )OpenXMLDatabase( Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride == 1 ? true : false, true ); // titles.txt loaded after database to override database titles with custom titles //snprintf(pathname, sizeof(pathname), "%stitles.txt", Settings.titlestxt_path); @@ -146,15 +175,16 @@ 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) + if ( menu == MENU_NONE ) menu = MENU_DISCLIST; //for HDDs with issues - if (wbfsinit < 0) { - sleep(1); + if ( wbfsinit < 0 ) + { + sleep( 1 ); USBDevice_Init(); SDCard_Init(); } diff --git a/source/menu/menu_disclist.cpp b/source/menu/menu_disclist.cpp index 96d79652..ef1f4001 100644 --- a/source/menu/menu_disclist.cpp +++ b/source/menu/menu_disclist.cpp @@ -16,7 +16,7 @@ #include "libwiigui/gui_gamecarousel.h" #include "libwiigui/gui_searchbar.h" -#define MAX_CHARACTERS 38 +#define MAX_CHARACTERS 38 extern u8 * gameScreenTex; extern struct discHdr *dvdheader; extern u8 mountMethod; @@ -35,48 +35,49 @@ extern bool altdoldefault; extern GuiImage * bgImg; GuiButton *Toolbar[9]; -int idiotFlag=-1; +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; /**************************************************************************** * MenuDiscList ***************************************************************************/ -int MenuDiscList() { +int MenuDiscList() +{ - gprintf("\nMenuDiscList()"); + gprintf( "\nMenuDiscList()" ); //TakeScreenshot("SD:/screenshot1.png"); gameList.FilterList(); - int offset = MIN((int)startat,gameList.size()-1); + int offset = MIN( ( int )startat, gameList.size() - 1 ); startat = offset; //gprintf("\n\tstartat:%d offset:%d",startat,offset); int datag = 0; - int datagB =0; + int datagB = 0; int dataed = -1; - int cosa=0,sina=0; + int cosa = 0, sina = 0; int selectImg1 = 0; char ID[4]; char IDfull[7]; u32 covert = 0; char imgPath[100]; - if (!dvdheader) - dvdheader = new struct discHdr; - u8 mountMethodOLD =0; + if ( !dvdheader ) + dvdheader = new struct discHdr; + u8 mountMethodOLD = 0; - WDVD_GetCoverStatus(&covert); - u32 covertOld=covert; + WDVD_GetCoverStatus( &covert ); + u32 covertOld = covert; - f32 freespace, used, size = 0.0; - wchar_t searchChar; + f32 freespace, used, size = 0.0; + wchar_t searchChar; //SCREENSAVER int check = 0; //to skip the first cycle when wiimote isn't completely connected - datagB=0; - int menu = MENU_NONE, dataef=0; + datagB = 0; + int menu = MENU_NONE, dataef = 0; u32 nolist; @@ -86,586 +87,628 @@ int MenuDiscList() { //CLOCK struct tm * timeinfo; - char theTime[80]=""; - time_t lastrawtime=0; + char theTime[80] = ""; + time_t lastrawtime = 0; - if (mountMethod != 3 && WBFS_ShowFreeSpace()) { - WBFS_DiskSpace(&used, &freespace); - } + if ( mountMethod != 3 && WBFS_ShowFreeSpace() ) + { + 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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - snprintf(imgPath, sizeof(imgPath), "%sbutton_install.png", CFG.theme_path); - GuiImageData btnInstall(imgPath, button_install_png); - snprintf(imgPath, sizeof(imgPath), "%sbutton_install_over.png", CFG.theme_path); - GuiImageData btnInstallOver(imgPath, button_install_over_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_install.png", CFG.theme_path ); + GuiImageData btnInstall( imgPath, button_install_png ); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_install_over.png", CFG.theme_path ); + GuiImageData btnInstallOver( imgPath, button_install_over_png ); - snprintf(imgPath, sizeof(imgPath), "%ssettings_button.png", CFG.theme_path); - GuiImageData btnSettings(imgPath, settings_button_png); - snprintf(imgPath, sizeof(imgPath), "%ssettings_button_over.png", CFG.theme_path); - GuiImageData btnSettingsOver(imgPath, settings_button_over_png); - GuiImageData dataID(&data1); + snprintf( imgPath, sizeof( imgPath ), "%ssettings_button.png", CFG.theme_path ); + GuiImageData btnSettings( imgPath, settings_button_png ); + snprintf( imgPath, sizeof( imgPath ), "%ssettings_button_over.png", CFG.theme_path ); + GuiImageData btnSettingsOver( imgPath, settings_button_over_png ); + GuiImageData dataID( &data1 ); - snprintf(imgPath, sizeof(imgPath), "%swiimote_poweroff.png", CFG.theme_path); - GuiImageData btnpwroff(imgPath, wiimote_poweroff_png); - snprintf(imgPath, sizeof(imgPath), "%swiimote_poweroff_over.png", CFG.theme_path); - GuiImageData btnpwroffOver(imgPath, wiimote_poweroff_over_png); - snprintf(imgPath, sizeof(imgPath), "%smenu_button.png", CFG.theme_path); - GuiImageData btnhome(imgPath, menu_button_png); - snprintf(imgPath, sizeof(imgPath), "%smenu_button_over.png", CFG.theme_path); - GuiImageData btnhomeOver(imgPath, menu_button_over_png); - snprintf(imgPath, sizeof(imgPath), "%sSDcard_over.png", CFG.theme_path); - GuiImageData btnsdcardOver(imgPath, sdcard_over_png); - snprintf(imgPath, sizeof(imgPath), "%sSDcard.png", CFG.theme_path); - GuiImageData btnsdcard(imgPath, sdcard_png); + snprintf( imgPath, sizeof( imgPath ), "%swiimote_poweroff.png", CFG.theme_path ); + GuiImageData btnpwroff( imgPath, wiimote_poweroff_png ); + snprintf( imgPath, sizeof( imgPath ), "%swiimote_poweroff_over.png", CFG.theme_path ); + GuiImageData btnpwroffOver( imgPath, wiimote_poweroff_over_png ); + snprintf( imgPath, sizeof( imgPath ), "%smenu_button.png", CFG.theme_path ); + GuiImageData btnhome( imgPath, menu_button_png ); + snprintf( imgPath, sizeof( imgPath ), "%smenu_button_over.png", CFG.theme_path ); + GuiImageData btnhomeOver( imgPath, menu_button_over_png ); + snprintf( imgPath, sizeof( imgPath ), "%sSDcard_over.png", CFG.theme_path ); + GuiImageData btnsdcardOver( imgPath, sdcard_over_png ); + snprintf( imgPath, sizeof( imgPath ), "%sSDcard.png", CFG.theme_path ); + GuiImageData btnsdcard( imgPath, sdcard_png ); - snprintf(imgPath, sizeof(imgPath), "%sfavIcon.png", CFG.theme_path); - GuiImageData imgfavIcon(imgPath, favIcon_png); - snprintf(imgPath, sizeof(imgPath), "%sfavIcon_gray.png", CFG.theme_path); - GuiImageData imgfavIcon_gray(imgPath, NULL); - snprintf(imgPath, sizeof(imgPath), "%ssearchIcon.png", CFG.theme_path); - GuiImageData imgsearchIcon(imgPath, searchIcon_png); - snprintf(imgPath, sizeof(imgPath), "%ssearchIcon_gray.png", CFG.theme_path); - GuiImageData imgsearchIcon_gray(imgPath, NULL); - snprintf(imgPath, sizeof(imgPath), "%sabcIcon.png", CFG.theme_path); - GuiImageData imgabcIcon(imgPath, abcIcon_png); - snprintf(imgPath, sizeof(imgPath), "%sabcIcon_gray.png", CFG.theme_path); - GuiImageData imgabcIcon_gray(imgPath, NULL); - snprintf(imgPath, sizeof(imgPath), "%srankIcon.png", CFG.theme_path); - GuiImageData imgrankIcon(imgPath, rankIcon_png); - snprintf(imgPath, sizeof(imgPath), "%srankIcon_gray.png", CFG.theme_path); - GuiImageData imgrankIcon_gray(imgPath, NULL); - snprintf(imgPath, sizeof(imgPath), "%splayCountIcon.png", CFG.theme_path); - GuiImageData imgplayCountIcon(imgPath, playCountIcon_png); - snprintf(imgPath, sizeof(imgPath), "%splayCountIcon_gray.png", CFG.theme_path); - GuiImageData imgplayCountIcon_gray(imgPath, NULL); - snprintf(imgPath, sizeof(imgPath), "%sarrangeGrid.png", CFG.theme_path); - GuiImageData imgarrangeGrid(imgPath, arrangeGrid_png); - snprintf(imgPath, sizeof(imgPath), "%sarrangeGrid_gray.png", CFG.theme_path); - GuiImageData imgarrangeGrid_gray(imgPath, NULL); - snprintf(imgPath, sizeof(imgPath), "%sarrangeList.png", CFG.theme_path); - GuiImageData imgarrangeList(imgPath, arrangeList_png); - snprintf(imgPath, sizeof(imgPath), "%sarrangeList_gray.png", CFG.theme_path); - GuiImageData imgarrangeList_gray(imgPath, NULL); - snprintf(imgPath, sizeof(imgPath), "%sarrangeCarousel.png", CFG.theme_path); - GuiImageData imgarrangeCarousel(imgPath, arrangeCarousel_png); - snprintf(imgPath, sizeof(imgPath), "%sarrangeCarousel_gray.png", CFG.theme_path); - GuiImageData imgarrangeCarousel_gray(imgPath, NULL); + snprintf( imgPath, sizeof( imgPath ), "%sfavIcon.png", CFG.theme_path ); + GuiImageData imgfavIcon( imgPath, favIcon_png ); + snprintf( imgPath, sizeof( imgPath ), "%sfavIcon_gray.png", CFG.theme_path ); + GuiImageData imgfavIcon_gray( imgPath, NULL ); + snprintf( imgPath, sizeof( imgPath ), "%ssearchIcon.png", CFG.theme_path ); + GuiImageData imgsearchIcon( imgPath, searchIcon_png ); + snprintf( imgPath, sizeof( imgPath ), "%ssearchIcon_gray.png", CFG.theme_path ); + GuiImageData imgsearchIcon_gray( imgPath, NULL ); + snprintf( imgPath, sizeof( imgPath ), "%sabcIcon.png", CFG.theme_path ); + GuiImageData imgabcIcon( imgPath, abcIcon_png ); + snprintf( imgPath, sizeof( imgPath ), "%sabcIcon_gray.png", CFG.theme_path ); + GuiImageData imgabcIcon_gray( imgPath, NULL ); + snprintf( imgPath, sizeof( imgPath ), "%srankIcon.png", CFG.theme_path ); + GuiImageData imgrankIcon( imgPath, rankIcon_png ); + snprintf( imgPath, sizeof( imgPath ), "%srankIcon_gray.png", CFG.theme_path ); + GuiImageData imgrankIcon_gray( imgPath, NULL ); + snprintf( imgPath, sizeof( imgPath ), "%splayCountIcon.png", CFG.theme_path ); + GuiImageData imgplayCountIcon( imgPath, playCountIcon_png ); + snprintf( imgPath, sizeof( imgPath ), "%splayCountIcon_gray.png", CFG.theme_path ); + GuiImageData imgplayCountIcon_gray( imgPath, NULL ); + snprintf( imgPath, sizeof( imgPath ), "%sarrangeGrid.png", CFG.theme_path ); + GuiImageData imgarrangeGrid( imgPath, arrangeGrid_png ); + snprintf( imgPath, sizeof( imgPath ), "%sarrangeGrid_gray.png", CFG.theme_path ); + GuiImageData imgarrangeGrid_gray( imgPath, NULL ); + snprintf( imgPath, sizeof( imgPath ), "%sarrangeList.png", CFG.theme_path ); + GuiImageData imgarrangeList( imgPath, arrangeList_png ); + snprintf( imgPath, sizeof( imgPath ), "%sarrangeList_gray.png", CFG.theme_path ); + GuiImageData imgarrangeList_gray( imgPath, NULL ); + snprintf( imgPath, sizeof( imgPath ), "%sarrangeCarousel.png", CFG.theme_path ); + GuiImageData imgarrangeCarousel( imgPath, arrangeCarousel_png ); + snprintf( imgPath, sizeof( imgPath ), "%sarrangeCarousel_gray.png", CFG.theme_path ); + GuiImageData imgarrangeCarousel_gray( imgPath, NULL ); - snprintf(imgPath, sizeof(imgPath), "%slock.png", CFG.theme_path); - GuiImageData imgLock(imgPath, lock_png); - snprintf(imgPath, sizeof(imgPath), "%slock_gray.png", CFG.theme_path); - GuiImageData imgLock_gray(imgPath, NULL); - snprintf(imgPath, sizeof(imgPath), "%sunlock.png", CFG.theme_path); - GuiImageData imgUnlock(imgPath, unlock_png); - snprintf(imgPath, sizeof(imgPath), "%sunlock_gray.png", CFG.theme_path); - GuiImageData imgUnlock_gray(imgPath, NULL); + snprintf( imgPath, sizeof( imgPath ), "%slock.png", CFG.theme_path ); + GuiImageData imgLock( imgPath, lock_png ); + snprintf( imgPath, sizeof( imgPath ), "%slock_gray.png", CFG.theme_path ); + GuiImageData imgLock_gray( imgPath, NULL ); + snprintf( imgPath, sizeof( imgPath ), "%sunlock.png", CFG.theme_path ); + GuiImageData imgUnlock( imgPath, unlock_png ); + snprintf( imgPath, sizeof( imgPath ), "%sunlock_gray.png", CFG.theme_path ); + GuiImageData imgUnlock_gray( imgPath, NULL ); - snprintf(imgPath, sizeof(imgPath), "%sdvd.png", CFG.theme_path); - GuiImageData imgdvd(imgPath, dvd_png); - snprintf(imgPath, sizeof(imgPath), "%sdvd_gray.png", CFG.theme_path); - GuiImageData imgdvd_gray(imgPath, NULL); + snprintf( imgPath, sizeof( imgPath ), "%sdvd.png", CFG.theme_path ); + GuiImageData imgdvd( imgPath, dvd_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdvd_gray.png", CFG.theme_path ); + GuiImageData imgdvd_gray( imgPath, NULL ); - snprintf(imgPath, sizeof(imgPath), "%sbrowser.png", CFG.theme_path); - GuiImageData homebrewImgData(imgPath, browser_png); - snprintf(imgPath, sizeof(imgPath), "%sbrowser_over.png", CFG.theme_path); - GuiImageData homebrewImgDataOver(imgPath, browser_over_png); + snprintf( imgPath, sizeof( imgPath ), "%sbrowser.png", CFG.theme_path ); + GuiImageData homebrewImgData( imgPath, browser_png ); + snprintf( imgPath, sizeof( imgPath ), "%sbrowser_over.png", CFG.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) { - memset(spaceinfo, 0, 30); - } else { - if (!strcmp(Settings.db_language,"JA")) { - // needs to be "total...used" for Japanese - sprintf(spaceinfo,(mountMethod!=3?"%.2fGB %s %.2fGB %s":" "),(freespace+used),tr("of"),freespace,tr("free")); - } else { - sprintf(spaceinfo,(mountMethod!=3?"%.2fGB %s %.2fGB %s":" "),freespace,tr("of"),(freespace+used),tr("free")); - } - } - GuiText usedSpaceTxt(spaceinfo, 18, THEME.info); - usedSpaceTxt.SetAlignment(THEME.hddinfo_align, ALIGN_TOP); - usedSpaceTxt.SetPosition(THEME.hddinfo_x, THEME.hddinfo_y); - - char GamesCnt[15]; - 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); - gamecntBtn.SetEffectGrow(); - gamecntBtn.SetTrigger(&trigA); - - GuiTooltip installBtnTT(tr("Install a game")); - if (Settings.wsprompt == yes) - installBtnTT.SetWidescreen(CFG.widescreen); - installBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage installBtnImg(&btnInstall); - GuiImage installBtnImgOver(&btnInstallOver); - installBtnImg.SetWidescreen(CFG.widescreen); - installBtnImgOver.SetWidescreen(CFG.widescreen); - - GuiButton installBtn(&installBtnImg, &installBtnImgOver, ALIGN_LEFT, ALIGN_TOP, THEME.install_x, THEME.install_y, &trigA, &btnSoundOver, btnClick2, 1, &installBtnTT,24,-30, 0,5); - - - GuiTooltip settingsBtnTT(tr("Settings")); - if (Settings.wsprompt == yes) - settingsBtnTT.SetWidescreen(CFG.widescreen); - settingsBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage settingsBtnImg(&btnSettings); - settingsBtnImg.SetWidescreen(CFG.widescreen); - GuiImage settingsBtnImgOver(&btnSettingsOver); - settingsBtnImgOver.SetWidescreen(CFG.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(CFG.widescreen); - settingsBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage homeBtnImg(&btnhome); - homeBtnImg.SetWidescreen(CFG.widescreen); - GuiImage homeBtnImgOver(&btnhomeOver); - homeBtnImgOver.SetWidescreen(CFG.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); - - GuiTooltip poweroffBtnTT(tr("Power off the Wii")); - if (Settings.wsprompt == yes) - poweroffBtnTT.SetWidescreen(CFG.widescreen); - poweroffBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage poweroffBtnImg(&btnpwroff); - GuiImage poweroffBtnImgOver(&btnpwroffOver); - poweroffBtnImg.SetWidescreen(CFG.widescreen); - poweroffBtnImgOver.SetWidescreen(CFG.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(CFG.widescreen); - sdcardBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage sdcardImg(&btnsdcard); - GuiImage sdcardImgOver(&btnsdcardOver); - sdcardImg.SetWidescreen(CFG.widescreen); - sdcardImgOver.SetWidescreen(CFG.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); - - - GuiImage wiiBtnImg(&dataID); - wiiBtnImg.SetWidescreen(CFG.widescreen); - GuiButton wiiBtn(&wiiBtnImg,&wiiBtnImg, 0, 4, 0, -10, &trigA, &btnSoundOver, btnClick2,0); - - GuiTooltip favoriteBtnTT(tr("Display favorites")); - if (Settings.wsprompt == yes) - favoriteBtnTT.SetWidescreen(CFG.widescreen); - favoriteBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage favoriteBtnImg(&imgfavIcon); - favoriteBtnImg.SetWidescreen(CFG.widescreen); -// GuiImage favoriteBtnImg_g(favoriteBtnImg);favoriteBtnImg_g.SetGrayscale(); - GuiImage favoriteBtnImg_g(&imgfavIcon_gray); - if(favoriteBtnImg_g.GetImage() == NULL) { favoriteBtnImg_g = favoriteBtnImg; favoriteBtnImg_g.SetGrayscale();} - favoriteBtnImg_g.SetWidescreen(CFG.widescreen); - GuiButton favoriteBtn(&favoriteBtnImg_g,&favoriteBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_favorite_x, THEME.gamelist_favorite_y, &trigA, &btnSoundOver, btnClick2,1, &favoriteBtnTT, -15, 52, 0, 3); - favoriteBtn.SetAlpha(180); - - GuiTooltip searchBtnTT(tr("Set Search-Filter")); - if (Settings.wsprompt == yes) - searchBtnTT.SetWidescreen(CFG.widescreen); - searchBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage searchBtnImg(&imgsearchIcon); - searchBtnImg.SetWidescreen(CFG.widescreen); -// GuiImage searchBtnImg_g(searchBtnImg); searchBtnImg_g.SetGrayscale(); - GuiImage searchBtnImg_g(&imgsearchIcon_gray); - if(searchBtnImg_g.GetImage() == NULL) { searchBtnImg_g = searchBtnImg; searchBtnImg_g.SetGrayscale();} - searchBtnImg_g.SetWidescreen(CFG.widescreen); - GuiButton searchBtn(&searchBtnImg_g,&searchBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_search_x, THEME.gamelist_search_y, &trigA, &btnSoundOver, btnClick2,1, &searchBtnTT, -15, 52, 0, 3); - searchBtn.SetAlpha(180); - - GuiTooltip abcBtnTT(Settings.fave ? tr("Sort by rank") : tr("Sort alphabetically")); - if (Settings.wsprompt == yes) - abcBtnTT.SetWidescreen(CFG.widescreen); - abcBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage abcBtnImg(Settings.fave ? &imgrankIcon : &imgabcIcon); - abcBtnImg.SetWidescreen(CFG.widescreen); -// GuiImage abcBtnImg_g(abcBtnImg); abcBtnImg_g.SetGrayscale(); - GuiImage abcBtnImg_g(Settings.fave ? &imgrankIcon_gray : &imgabcIcon_gray); - if(abcBtnImg_g.GetImage() == NULL) { abcBtnImg_g = abcBtnImg; abcBtnImg_g.SetGrayscale();} - abcBtnImg_g.SetWidescreen(CFG.widescreen); - GuiButton abcBtn(&abcBtnImg_g,&abcBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_abc_x, THEME.gamelist_abc_y, &trigA, &btnSoundOver, btnClick2,1,&abcBtnTT, -15, 52, 0, 3); - abcBtn.SetAlpha(180); - - GuiTooltip countBtnTT(tr("Sort order by most played")); - if (Settings.wsprompt == yes) - countBtnTT.SetWidescreen(CFG.widescreen); - countBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage countBtnImg(&imgplayCountIcon); - countBtnImg.SetWidescreen(CFG.widescreen); -// GuiImage countBtnImg_g(countBtnImg); countBtnImg_g.SetGrayscale(); - GuiImage countBtnImg_g(&imgplayCountIcon_gray); - if(countBtnImg_g.GetImage() == NULL) { countBtnImg_g = countBtnImg; countBtnImg_g.SetGrayscale();} - countBtnImg_g.SetWidescreen(CFG.widescreen); - GuiButton countBtn(&countBtnImg_g,&countBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_count_x, THEME.gamelist_count_y, &trigA, &btnSoundOver, btnClick2,1, &countBtnTT, -15, 52, 0, 3); - countBtn.SetAlpha(180); - - GuiTooltip listBtnTT(tr("Display as a list")); - if (Settings.wsprompt == yes) - listBtnTT.SetWidescreen(CFG.widescreen); - listBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage listBtnImg(&imgarrangeList); - listBtnImg.SetWidescreen(CFG.widescreen); -// GuiImage listBtnImg_g(listBtnImg); listBtnImg_g.SetGrayscale(); - GuiImage listBtnImg_g(&imgarrangeList_gray); - if(listBtnImg_g.GetImage() == NULL) { listBtnImg_g = listBtnImg; listBtnImg_g.SetGrayscale();} - listBtnImg_g.SetWidescreen(CFG.widescreen); - GuiButton listBtn(&listBtnImg_g,&listBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_list_x, THEME.gamelist_list_y, &trigA, &btnSoundOver, btnClick2,1, &listBtnTT, 15, 52, 1, 3); - listBtn.SetAlpha(180); - - GuiTooltip gridBtnTT(tr("Display as a grid")); - if (Settings.wsprompt == yes) - gridBtnTT.SetWidescreen(CFG.widescreen); - gridBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage gridBtnImg(&imgarrangeGrid); - gridBtnImg.SetWidescreen(CFG.widescreen); -// GuiImage gridBtnImg_g(gridBtnImg); gridBtnImg_g.SetGrayscale(); - GuiImage gridBtnImg_g(&imgarrangeGrid_gray); - if(gridBtnImg_g.GetImage() == NULL) { gridBtnImg_g = gridBtnImg; gridBtnImg_g.SetGrayscale();} - gridBtnImg_g.SetWidescreen(CFG.widescreen); - GuiButton gridBtn(&gridBtnImg_g,&gridBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_grid_x, THEME.gamelist_grid_y, &trigA, &btnSoundOver, btnClick2,1, &gridBtnTT, 15, 52, 1, 3); - gridBtn.SetAlpha(180); - - GuiTooltip carouselBtnTT(tr("Display as a carousel")); - if (Settings.wsprompt == yes) - carouselBtnTT.SetWidescreen(CFG.widescreen); - carouselBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage carouselBtnImg(&imgarrangeCarousel); - carouselBtnImg.SetWidescreen(CFG.widescreen); -// GuiImage carouselBtnImg_g(carouselBtnImg); carouselBtnImg_g.SetGrayscale(); - GuiImage carouselBtnImg_g(&imgarrangeCarousel_gray); - if(carouselBtnImg_g.GetImage() == NULL) { carouselBtnImg_g = carouselBtnImg; carouselBtnImg_g.SetGrayscale();} - carouselBtnImg_g.SetWidescreen(CFG.widescreen); - GuiButton carouselBtn(&carouselBtnImg_g,&carouselBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_carousel_x, THEME.gamelist_carousel_y, &trigA, &btnSoundOver, btnClick2,1, &carouselBtnTT, 15, 52, 1, 3); - carouselBtn.SetAlpha(180); - - bool canUnlock = (Settings.parentalcontrol == 0 && Settings.parental.enabled == 1); - - GuiTooltip lockBtnTT(canUnlock ? tr("Unlock Parental Control") : tr("Parental Control disabled")); - if (Settings.wsprompt == yes) - lockBtnTT.SetWidescreen(CFG.widescreen); - lockBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage lockBtnImg(&imgLock); - lockBtnImg.SetWidescreen(CFG.widescreen); - GuiImage lockBtnImg_g(&imgLock_gray); - if(lockBtnImg_g.GetImage() == NULL) { lockBtnImg_g = lockBtnImg; lockBtnImg_g.SetGrayscale(); } - lockBtnImg_g.SetWidescreen(CFG.widescreen); - GuiButton lockBtn(&lockBtnImg_g, &lockBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_lock_x, THEME.gamelist_lock_y, &trigA, &btnSoundOver, btnClick2,1, &lockBtnTT, 15, 52, 1, 3); - lockBtn.SetAlpha(180); - - GuiTooltip unlockBtnTT(tr("Enable Parental Control")); - if (Settings.wsprompt == yes) - unlockBtnTT.SetWidescreen(CFG.widescreen); - unlockBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage unlockBtnImg(&imgUnlock); - unlockBtnImg.SetWidescreen(CFG.widescreen); - GuiImage unlockBtnImg_g(&imgUnlock_gray); - if(unlockBtnImg_g.GetImage() == NULL) { unlockBtnImg_g = unlockBtnImg; unlockBtnImg_g.SetGrayscale(); } - unlockBtnImg_g.SetWidescreen(CFG.widescreen); - - if (canUnlock && Settings.godmode) - { - lockBtn.SetImage(&unlockBtnImg_g); - lockBtn.SetImageOver(&unlockBtnImg_g); - lockBtn.SetToolTip(&unlockBtnTT, 15, 52, 1, 3); - } - -/* - GuiButton unlockBtn(&unlockBtnImg_g, &unlockBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_lock_x, THEME.gamelist_lock_y, &trigA, &btnSoundOver, btnClick2,1, &lockBtnTT, 15, 52, 1, 3); - unlockBtn.SetAlpha(180); -*/ - - GuiTooltip dvdBtnTT(tr("Mount DVD drive")); - if (Settings.wsprompt == yes) - dvdBtnTT.SetWidescreen(CFG.widescreen); - dvdBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage dvdBtnImg(&imgdvd); - dvdBtnImg.SetWidescreen(CFG.widescreen); - GuiImage dvdBtnImg_g(dvdBtnImg); //dvdBtnImg_g.SetGrayscale(); -// GuiImage carouselBtnImg_g(&imgarrangeCarousel_gray); - dvdBtnImg_g.SetWidescreen(CFG.widescreen); - GuiButton dvdBtn(&dvdBtnImg_g,&dvdBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_dvd_x, THEME.gamelist_dvd_y, &trigA, &btnSoundOver, btnClick2,1, &dvdBtnTT, 15, 52, 1, 3); - dvdBtn.SetAlpha(180); - - GuiTooltip homebrewBtnTT(tr("Homebrew Launcher")); - if (Settings.wsprompt == yes) - homebrewBtnTT.SetWidescreen(CFG.widescreen); - homebrewBtnTT.SetAlpha(THEME.tooltipAlpha); - GuiImage homebrewImg(&homebrewImgData); - GuiImage homebrewImgOver(&homebrewImgDataOver); - homebrewImg.SetWidescreen(CFG.widescreen); - homebrewImgOver.SetWidescreen(CFG.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) { - favoriteBtn.SetImage(&favoriteBtnImg); - favoriteBtn.SetImageOver(&favoriteBtnImg); - favoriteBtn.SetAlpha(255); - } - static bool show_searchwindow = false; - if(*gameList.GetCurrentFilter()) + if ( load_from_fs == PART_FS_FAT ) { - 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) { - abcBtn.SetImage(&abcBtnImg); - abcBtn.SetImageOver(&abcBtnImg); - abcBtn.SetAlpha(255); - } else if (Settings.sort==PLAYCOUNT) { - countBtn.SetImage(&countBtnImg); - countBtn.SetImageOver(&countBtnImg); - countBtn.SetAlpha(255); + memset( spaceinfo, 0, 30 ); } - if (Settings.gameDisplay==list) { - listBtn.SetImage(&listBtnImg); - listBtn.SetImageOver(&listBtnImg); - listBtn.SetAlpha(255); - } else if (Settings.gameDisplay==grid) { - gridBtn.SetImage(&gridBtnImg); - gridBtn.SetImageOver(&gridBtnImg); - gridBtn.SetAlpha(255); - } else if (Settings.gameDisplay==carousel) { - carouselBtn.SetImage(&carouselBtnImg); - carouselBtn.SetImageOver(&carouselBtnImg); - carouselBtn.SetAlpha(255); + else + { + if ( !strcmp( Settings.db_language, "JA" ) ) + { + // needs to be "total...used" for Japanese + sprintf( spaceinfo, ( mountMethod != 3 ? "%.2fGB %s %.2fGB %s" : " " ), ( freespace + used ), tr( "of" ), freespace, tr( "free" ) ); + } + else + { + sprintf( spaceinfo, ( mountMethod != 3 ? "%.2fGB %s %.2fGB %s" : " " ), freespace, tr( "of" ), ( freespace + used ), tr( "free" ) ); + } + } + GuiText usedSpaceTxt( spaceinfo, 18, THEME.info ); + usedSpaceTxt.SetAlignment( THEME.hddinfo_align, ALIGN_TOP ); + usedSpaceTxt.SetPosition( THEME.hddinfo_x, THEME.hddinfo_y ); + + char GamesCnt[15]; + 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 ); + gamecntBtn.SetEffectGrow(); + gamecntBtn.SetTrigger( &trigA ); + + GuiTooltip installBtnTT( tr( "Install a game" ) ); + if ( Settings.wsprompt == yes ) + installBtnTT.SetWidescreen( CFG.widescreen ); + installBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage installBtnImg( &btnInstall ); + GuiImage installBtnImgOver( &btnInstallOver ); + installBtnImg.SetWidescreen( CFG.widescreen ); + installBtnImgOver.SetWidescreen( CFG.widescreen ); + + GuiButton installBtn( &installBtnImg, &installBtnImgOver, ALIGN_LEFT, ALIGN_TOP, THEME.install_x, THEME.install_y, &trigA, &btnSoundOver, btnClick2, 1, &installBtnTT, 24, -30, 0, 5 ); + + + GuiTooltip settingsBtnTT( tr( "Settings" ) ); + if ( Settings.wsprompt == yes ) + settingsBtnTT.SetWidescreen( CFG.widescreen ); + settingsBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage settingsBtnImg( &btnSettings ); + settingsBtnImg.SetWidescreen( CFG.widescreen ); + GuiImage settingsBtnImgOver( &btnSettingsOver ); + settingsBtnImgOver.SetWidescreen( CFG.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( CFG.widescreen ); + settingsBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage homeBtnImg( &btnhome ); + homeBtnImg.SetWidescreen( CFG.widescreen ); + GuiImage homeBtnImgOver( &btnhomeOver ); + homeBtnImgOver.SetWidescreen( CFG.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 ); + + GuiTooltip poweroffBtnTT( tr( "Power off the Wii" ) ); + if ( Settings.wsprompt == yes ) + poweroffBtnTT.SetWidescreen( CFG.widescreen ); + poweroffBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage poweroffBtnImg( &btnpwroff ); + GuiImage poweroffBtnImgOver( &btnpwroffOver ); + poweroffBtnImg.SetWidescreen( CFG.widescreen ); + poweroffBtnImgOver.SetWidescreen( CFG.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( CFG.widescreen ); + sdcardBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage sdcardImg( &btnsdcard ); + GuiImage sdcardImgOver( &btnsdcardOver ); + sdcardImg.SetWidescreen( CFG.widescreen ); + sdcardImgOver.SetWidescreen( CFG.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 ); + + + GuiImage wiiBtnImg( &dataID ); + wiiBtnImg.SetWidescreen( CFG.widescreen ); + GuiButton wiiBtn( &wiiBtnImg, &wiiBtnImg, 0, 4, 0, -10, &trigA, &btnSoundOver, btnClick2, 0 ); + + GuiTooltip favoriteBtnTT( tr( "Display favorites" ) ); + if ( Settings.wsprompt == yes ) + favoriteBtnTT.SetWidescreen( CFG.widescreen ); + favoriteBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage favoriteBtnImg( &imgfavIcon ); + favoriteBtnImg.SetWidescreen( CFG.widescreen ); +// GuiImage favoriteBtnImg_g(favoriteBtnImg);favoriteBtnImg_g.SetGrayscale(); + GuiImage favoriteBtnImg_g( &imgfavIcon_gray ); + if ( favoriteBtnImg_g.GetImage() == NULL ) { favoriteBtnImg_g = favoriteBtnImg; favoriteBtnImg_g.SetGrayscale();} + favoriteBtnImg_g.SetWidescreen( CFG.widescreen ); + GuiButton favoriteBtn( &favoriteBtnImg_g, &favoriteBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_favorite_x, THEME.gamelist_favorite_y, &trigA, &btnSoundOver, btnClick2, 1, &favoriteBtnTT, -15, 52, 0, 3 ); + favoriteBtn.SetAlpha( 180 ); + + GuiTooltip searchBtnTT( tr( "Set Search-Filter" ) ); + if ( Settings.wsprompt == yes ) + searchBtnTT.SetWidescreen( CFG.widescreen ); + searchBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage searchBtnImg( &imgsearchIcon ); + searchBtnImg.SetWidescreen( CFG.widescreen ); +// GuiImage searchBtnImg_g(searchBtnImg); searchBtnImg_g.SetGrayscale(); + GuiImage searchBtnImg_g( &imgsearchIcon_gray ); + if ( searchBtnImg_g.GetImage() == NULL ) { searchBtnImg_g = searchBtnImg; searchBtnImg_g.SetGrayscale();} + searchBtnImg_g.SetWidescreen( CFG.widescreen ); + GuiButton searchBtn( &searchBtnImg_g, &searchBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_search_x, THEME.gamelist_search_y, &trigA, &btnSoundOver, btnClick2, 1, &searchBtnTT, -15, 52, 0, 3 ); + searchBtn.SetAlpha( 180 ); + + GuiTooltip abcBtnTT( Settings.fave ? tr( "Sort by rank" ) : tr( "Sort alphabetically" ) ); + if ( Settings.wsprompt == yes ) + abcBtnTT.SetWidescreen( CFG.widescreen ); + abcBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage abcBtnImg( Settings.fave ? &imgrankIcon : &imgabcIcon ); + abcBtnImg.SetWidescreen( CFG.widescreen ); +// GuiImage abcBtnImg_g(abcBtnImg); abcBtnImg_g.SetGrayscale(); + GuiImage abcBtnImg_g( Settings.fave ? &imgrankIcon_gray : &imgabcIcon_gray ); + if ( abcBtnImg_g.GetImage() == NULL ) { abcBtnImg_g = abcBtnImg; abcBtnImg_g.SetGrayscale();} + abcBtnImg_g.SetWidescreen( CFG.widescreen ); + GuiButton abcBtn( &abcBtnImg_g, &abcBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_abc_x, THEME.gamelist_abc_y, &trigA, &btnSoundOver, btnClick2, 1, &abcBtnTT, -15, 52, 0, 3 ); + abcBtn.SetAlpha( 180 ); + + GuiTooltip countBtnTT( tr( "Sort order by most played" ) ); + if ( Settings.wsprompt == yes ) + countBtnTT.SetWidescreen( CFG.widescreen ); + countBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage countBtnImg( &imgplayCountIcon ); + countBtnImg.SetWidescreen( CFG.widescreen ); +// GuiImage countBtnImg_g(countBtnImg); countBtnImg_g.SetGrayscale(); + GuiImage countBtnImg_g( &imgplayCountIcon_gray ); + if ( countBtnImg_g.GetImage() == NULL ) { countBtnImg_g = countBtnImg; countBtnImg_g.SetGrayscale();} + countBtnImg_g.SetWidescreen( CFG.widescreen ); + GuiButton countBtn( &countBtnImg_g, &countBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_count_x, THEME.gamelist_count_y, &trigA, &btnSoundOver, btnClick2, 1, &countBtnTT, -15, 52, 0, 3 ); + countBtn.SetAlpha( 180 ); + + GuiTooltip listBtnTT( tr( "Display as a list" ) ); + if ( Settings.wsprompt == yes ) + listBtnTT.SetWidescreen( CFG.widescreen ); + listBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage listBtnImg( &imgarrangeList ); + listBtnImg.SetWidescreen( CFG.widescreen ); +// GuiImage listBtnImg_g(listBtnImg); listBtnImg_g.SetGrayscale(); + GuiImage listBtnImg_g( &imgarrangeList_gray ); + if ( listBtnImg_g.GetImage() == NULL ) { listBtnImg_g = listBtnImg; listBtnImg_g.SetGrayscale();} + listBtnImg_g.SetWidescreen( CFG.widescreen ); + GuiButton listBtn( &listBtnImg_g, &listBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_list_x, THEME.gamelist_list_y, &trigA, &btnSoundOver, btnClick2, 1, &listBtnTT, 15, 52, 1, 3 ); + listBtn.SetAlpha( 180 ); + + GuiTooltip gridBtnTT( tr( "Display as a grid" ) ); + if ( Settings.wsprompt == yes ) + gridBtnTT.SetWidescreen( CFG.widescreen ); + gridBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage gridBtnImg( &imgarrangeGrid ); + gridBtnImg.SetWidescreen( CFG.widescreen ); +// GuiImage gridBtnImg_g(gridBtnImg); gridBtnImg_g.SetGrayscale(); + GuiImage gridBtnImg_g( &imgarrangeGrid_gray ); + if ( gridBtnImg_g.GetImage() == NULL ) { gridBtnImg_g = gridBtnImg; gridBtnImg_g.SetGrayscale();} + gridBtnImg_g.SetWidescreen( CFG.widescreen ); + GuiButton gridBtn( &gridBtnImg_g, &gridBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_grid_x, THEME.gamelist_grid_y, &trigA, &btnSoundOver, btnClick2, 1, &gridBtnTT, 15, 52, 1, 3 ); + gridBtn.SetAlpha( 180 ); + + GuiTooltip carouselBtnTT( tr( "Display as a carousel" ) ); + if ( Settings.wsprompt == yes ) + carouselBtnTT.SetWidescreen( CFG.widescreen ); + carouselBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage carouselBtnImg( &imgarrangeCarousel ); + carouselBtnImg.SetWidescreen( CFG.widescreen ); +// GuiImage carouselBtnImg_g(carouselBtnImg); carouselBtnImg_g.SetGrayscale(); + GuiImage carouselBtnImg_g( &imgarrangeCarousel_gray ); + if ( carouselBtnImg_g.GetImage() == NULL ) { carouselBtnImg_g = carouselBtnImg; carouselBtnImg_g.SetGrayscale();} + carouselBtnImg_g.SetWidescreen( CFG.widescreen ); + GuiButton carouselBtn( &carouselBtnImg_g, &carouselBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_carousel_x, THEME.gamelist_carousel_y, &trigA, &btnSoundOver, btnClick2, 1, &carouselBtnTT, 15, 52, 1, 3 ); + carouselBtn.SetAlpha( 180 ); + + bool canUnlock = ( Settings.parentalcontrol == 0 && Settings.parental.enabled == 1 ); + + GuiTooltip lockBtnTT( canUnlock ? tr( "Unlock Parental Control" ) : tr( "Parental Control disabled" ) ); + if ( Settings.wsprompt == yes ) + lockBtnTT.SetWidescreen( CFG.widescreen ); + lockBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage lockBtnImg( &imgLock ); + lockBtnImg.SetWidescreen( CFG.widescreen ); + GuiImage lockBtnImg_g( &imgLock_gray ); + if ( lockBtnImg_g.GetImage() == NULL ) { lockBtnImg_g = lockBtnImg; lockBtnImg_g.SetGrayscale(); } + lockBtnImg_g.SetWidescreen( CFG.widescreen ); + GuiButton lockBtn( &lockBtnImg_g, &lockBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_lock_x, THEME.gamelist_lock_y, &trigA, &btnSoundOver, btnClick2, 1, &lockBtnTT, 15, 52, 1, 3 ); + lockBtn.SetAlpha( 180 ); + + GuiTooltip unlockBtnTT( tr( "Enable Parental Control" ) ); + if ( Settings.wsprompt == yes ) + unlockBtnTT.SetWidescreen( CFG.widescreen ); + unlockBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage unlockBtnImg( &imgUnlock ); + unlockBtnImg.SetWidescreen( CFG.widescreen ); + GuiImage unlockBtnImg_g( &imgUnlock_gray ); + if ( unlockBtnImg_g.GetImage() == NULL ) { unlockBtnImg_g = unlockBtnImg; unlockBtnImg_g.SetGrayscale(); } + unlockBtnImg_g.SetWidescreen( CFG.widescreen ); + + if ( canUnlock && Settings.godmode ) + { + lockBtn.SetImage( &unlockBtnImg_g ); + lockBtn.SetImageOver( &unlockBtnImg_g ); + lockBtn.SetToolTip( &unlockBtnTT, 15, 52, 1, 3 ); } - if (Settings.gameDisplay==list) { - favoriteBtn.SetPosition(THEME.gamelist_favorite_x, THEME.gamelist_favorite_y); - searchBtn.SetPosition(THEME.gamelist_search_x, THEME.gamelist_search_y); - abcBtn.SetPosition(THEME.gamelist_abc_x, THEME.gamelist_abc_y); - countBtn.SetPosition(THEME.gamelist_count_x, THEME.gamelist_count_y); - listBtn.SetPosition(THEME.gamelist_list_x, THEME.gamelist_list_y); - gridBtn.SetPosition(THEME.gamelist_grid_x, THEME.gamelist_grid_y); - carouselBtn.SetPosition(THEME.gamelist_carousel_x, THEME.gamelist_carousel_y); - lockBtn.SetPosition(THEME.gamelist_lock_x, THEME.gamelist_lock_y); - dvdBtn.SetPosition(THEME.gamelist_dvd_x, THEME.gamelist_dvd_y); - } else if(Settings.gameDisplay==grid) { - favoriteBtn.SetPosition(THEME.gamegrid_favorite_x, THEME.gamegrid_favorite_y); - searchBtn.SetPosition(THEME.gamegrid_search_x, THEME.gamegrid_search_y); - abcBtn.SetPosition(THEME.gamegrid_abc_x, THEME.gamegrid_abc_y); - countBtn.SetPosition(THEME.gamegrid_count_x, THEME.gamegrid_count_y); - listBtn.SetPosition(THEME.gamegrid_list_x, THEME.gamegrid_list_y); - gridBtn.SetPosition(THEME.gamegrid_grid_x, THEME.gamegrid_grid_y); - carouselBtn.SetPosition(THEME.gamegrid_carousel_x, THEME.gamegrid_carousel_y); - lockBtn.SetPosition(THEME.gamegrid_lock_x, THEME.gamegrid_lock_y); - dvdBtn.SetPosition(THEME.gamegrid_dvd_x, THEME.gamegrid_dvd_y); - } else if(Settings.gameDisplay==carousel) { - favoriteBtn.SetPosition(THEME.gamecarousel_favorite_x, THEME.gamecarousel_favorite_y); - searchBtn.SetPosition(THEME.gamecarousel_search_x, THEME.gamecarousel_favorite_y); - abcBtn.SetPosition(THEME.gamecarousel_abc_x, THEME.gamecarousel_abc_y); - countBtn.SetPosition(THEME.gamecarousel_count_x, THEME.gamecarousel_count_y); - listBtn.SetPosition(THEME.gamecarousel_list_x, THEME.gamecarousel_list_y); - gridBtn.SetPosition(THEME.gamecarousel_grid_x, THEME.gamecarousel_grid_y); - carouselBtn.SetPosition(THEME.gamecarousel_carousel_x, THEME.gamecarousel_carousel_y); - lockBtn.SetPosition(THEME.gamecarousel_lock_x, THEME.gamecarousel_lock_y); - dvdBtn.SetPosition(THEME.gamecarousel_dvd_x, THEME.gamecarousel_dvd_y); - } + /* + GuiButton unlockBtn(&unlockBtnImg_g, &unlockBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_lock_x, THEME.gamelist_lock_y, &trigA, &btnSoundOver, btnClick2,1, &lockBtnTT, 15, 52, 1, 3); + unlockBtn.SetAlpha(180); + */ + + GuiTooltip dvdBtnTT( tr( "Mount DVD drive" ) ); + if ( Settings.wsprompt == yes ) + dvdBtnTT.SetWidescreen( CFG.widescreen ); + dvdBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage dvdBtnImg( &imgdvd ); + dvdBtnImg.SetWidescreen( CFG.widescreen ); + GuiImage dvdBtnImg_g( dvdBtnImg ); //dvdBtnImg_g.SetGrayscale(); +// GuiImage carouselBtnImg_g(&imgarrangeCarousel_gray); + dvdBtnImg_g.SetWidescreen( CFG.widescreen ); + GuiButton dvdBtn( &dvdBtnImg_g, &dvdBtnImg_g, ALIGN_LEFT, ALIGN_TOP, THEME.gamelist_dvd_x, THEME.gamelist_dvd_y, &trigA, &btnSoundOver, btnClick2, 1, &dvdBtnTT, 15, 52, 1, 3 ); + dvdBtn.SetAlpha( 180 ); + + GuiTooltip homebrewBtnTT( tr( "Homebrew Launcher" ) ); + if ( Settings.wsprompt == yes ) + homebrewBtnTT.SetWidescreen( CFG.widescreen ); + homebrewBtnTT.SetAlpha( THEME.tooltipAlpha ); + GuiImage homebrewImg( &homebrewImgData ); + GuiImage homebrewImgOver( &homebrewImgDataOver ); + homebrewImg.SetWidescreen( CFG.widescreen ); + homebrewImgOver.SetWidescreen( CFG.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 ) + { + favoriteBtn.SetImage( &favoriteBtnImg ); + favoriteBtn.SetImageOver( &favoriteBtnImg ); + favoriteBtn.SetAlpha( 255 ); + } + static bool show_searchwindow = false; + 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 ( Settings.sort == ALL ) + { + abcBtn.SetImage( &abcBtnImg ); + abcBtn.SetImageOver( &abcBtnImg ); + abcBtn.SetAlpha( 255 ); + } + else if ( Settings.sort == PLAYCOUNT ) + { + countBtn.SetImage( &countBtnImg ); + countBtn.SetImageOver( &countBtnImg ); + countBtn.SetAlpha( 255 ); + } + if ( Settings.gameDisplay == list ) + { + listBtn.SetImage( &listBtnImg ); + listBtn.SetImageOver( &listBtnImg ); + listBtn.SetAlpha( 255 ); + } + else if ( Settings.gameDisplay == grid ) + { + gridBtn.SetImage( &gridBtnImg ); + gridBtn.SetImageOver( &gridBtnImg ); + gridBtn.SetAlpha( 255 ); + } + else if ( Settings.gameDisplay == carousel ) + { + carouselBtn.SetImage( &carouselBtnImg ); + carouselBtn.SetImageOver( &carouselBtnImg ); + carouselBtn.SetAlpha( 255 ); + } + + if ( Settings.gameDisplay == list ) + { + favoriteBtn.SetPosition( THEME.gamelist_favorite_x, THEME.gamelist_favorite_y ); + searchBtn.SetPosition( THEME.gamelist_search_x, THEME.gamelist_search_y ); + abcBtn.SetPosition( THEME.gamelist_abc_x, THEME.gamelist_abc_y ); + countBtn.SetPosition( THEME.gamelist_count_x, THEME.gamelist_count_y ); + listBtn.SetPosition( THEME.gamelist_list_x, THEME.gamelist_list_y ); + gridBtn.SetPosition( THEME.gamelist_grid_x, THEME.gamelist_grid_y ); + carouselBtn.SetPosition( THEME.gamelist_carousel_x, THEME.gamelist_carousel_y ); + lockBtn.SetPosition( THEME.gamelist_lock_x, THEME.gamelist_lock_y ); + dvdBtn.SetPosition( THEME.gamelist_dvd_x, THEME.gamelist_dvd_y ); + } + else if ( Settings.gameDisplay == grid ) + { + favoriteBtn.SetPosition( THEME.gamegrid_favorite_x, THEME.gamegrid_favorite_y ); + searchBtn.SetPosition( THEME.gamegrid_search_x, THEME.gamegrid_search_y ); + abcBtn.SetPosition( THEME.gamegrid_abc_x, THEME.gamegrid_abc_y ); + countBtn.SetPosition( THEME.gamegrid_count_x, THEME.gamegrid_count_y ); + listBtn.SetPosition( THEME.gamegrid_list_x, THEME.gamegrid_list_y ); + gridBtn.SetPosition( THEME.gamegrid_grid_x, THEME.gamegrid_grid_y ); + carouselBtn.SetPosition( THEME.gamegrid_carousel_x, THEME.gamegrid_carousel_y ); + lockBtn.SetPosition( THEME.gamegrid_lock_x, THEME.gamegrid_lock_y ); + dvdBtn.SetPosition( THEME.gamegrid_dvd_x, THEME.gamegrid_dvd_y ); + } + else if ( Settings.gameDisplay == carousel ) + { + favoriteBtn.SetPosition( THEME.gamecarousel_favorite_x, THEME.gamecarousel_favorite_y ); + searchBtn.SetPosition( THEME.gamecarousel_search_x, THEME.gamecarousel_favorite_y ); + abcBtn.SetPosition( THEME.gamecarousel_abc_x, THEME.gamecarousel_abc_y ); + countBtn.SetPosition( THEME.gamecarousel_count_x, THEME.gamecarousel_count_y ); + listBtn.SetPosition( THEME.gamecarousel_list_x, THEME.gamecarousel_list_y ); + gridBtn.SetPosition( THEME.gamecarousel_grid_x, THEME.gamecarousel_grid_y ); + carouselBtn.SetPosition( THEME.gamecarousel_carousel_x, THEME.gamecarousel_carousel_y ); + lockBtn.SetPosition( THEME.gamecarousel_lock_x, THEME.gamecarousel_lock_y ); + dvdBtn.SetPosition( THEME.gamecarousel_dvd_x, THEME.gamecarousel_dvd_y ); + } //Downloading Covers - GuiTooltip DownloadBtnTT(tr("Click to Download Covers")); - if (Settings.wsprompt == yes) - DownloadBtnTT.SetWidescreen(CFG.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( CFG.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(CFG.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( CFG.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 - DownloadBtn.SetSoundOver(&btnSoundOver); - DownloadBtn.SetTrigger(&trigA); - DownloadBtn.SetTrigger(&trig1); - DownloadBtn.SetToolTip(&DownloadBtnTT,205,-30); + 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 ); - 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); - } + } + else + { + DownloadBtn.SetRumble( false ); + idBtn.SetRumble( false ); + } GuiGameBrowser * gameBrowser = NULL; GuiGameGrid * gameGrid = NULL; GuiGameCarousel * gameCarousel = NULL; - if (Settings.gameDisplay==list) { - gameBrowser = new GuiGameBrowser(THEME.gamelist_w, THEME.gamelist_h, CFG.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) { - gameGrid = new GuiGameGrid(THEME.gamegrid_w,THEME.gamegrid_h, CFG.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) { + if ( Settings.gameDisplay == list ) + { + gameBrowser = new GuiGameBrowser( THEME.gamelist_w, THEME.gamelist_h, CFG.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 ) + { + gameGrid = new GuiGameGrid( THEME.gamegrid_w, THEME.gamegrid_h, CFG.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 ) + { //GuiGameCarousel gameCarousel(THEME.gamecarousel_w, THEME.gamecarousel_h, gameList, gameList.size(), CFG.theme_path, bg_options_png, startat, offset); - gameCarousel = new GuiGameCarousel(640, 400, CFG.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, CFG.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 - w.Append(&usedSpaceTxt); + if ( THEME.show_hddinfo == -1 || THEME.show_hddinfo == 1 ) //force show hdd info + { + w.Append( &usedSpaceTxt ); } - if (THEME.show_gamecount == -1 || THEME.show_gamecount == 1) { //force show game cnt info - w.Append(&gamecntBtn); + if ( THEME.show_gamecount == -1 || THEME.show_gamecount == 1 ) //force show game cnt info + { + 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); - Toolbar[0] = &favoriteBtn; - w.Append(&searchBtn); - Toolbar[1] = &searchBtn; - w.Append(&abcBtn); - Toolbar[2] = &abcBtn; - w.Append(&countBtn); - Toolbar[3] = &countBtn; - w.Append(&listBtn); - Toolbar[4] = &listBtn; - w.Append(&gridBtn); - Toolbar[5] = &gridBtn; - w.Append(&carouselBtn); - Toolbar[6] = &carouselBtn; - w.Append(&lockBtn); - Toolbar[7] = &lockBtn; - w.Append(&dvdBtn); - Toolbar[8] = &dvdBtn; - w.SetUpdateCallback(DiscListWinUpdateCallback); - // End Toolbar + // Begin Toolbar + w.Append( &favoriteBtn ); + Toolbar[0] = &favoriteBtn; + w.Append( &searchBtn ); + Toolbar[1] = &searchBtn; + w.Append( &abcBtn ); + Toolbar[2] = &abcBtn; + w.Append( &countBtn ); + Toolbar[3] = &countBtn; + w.Append( &listBtn ); + Toolbar[4] = &listBtn; + w.Append( &gridBtn ); + Toolbar[5] = &gridBtn; + w.Append( &carouselBtn ); + Toolbar[6] = &carouselBtn; + w.Append( &lockBtn ); + Toolbar[7] = &lockBtn; + w.Append( &dvdBtn ); + Toolbar[8] = &dvdBtn; + w.SetUpdateCallback( DiscListWinUpdateCallback ); + // End Toolbar - if (Settings.godmode == 1) - w.Append(&homebrewBtn); + if ( Settings.godmode == 1 ) + w.Append( &homebrewBtn ); - if ((Settings.hddinfo == hr12)||(Settings.hddinfo == hr24)) { - w.Append(&clockTimeBack); - w.Append(&clockTime); + if ( ( Settings.hddinfo == hr12 ) || ( Settings.hddinfo == hr24 ) ) + { + w.Append( &clockTimeBack ); + w.Append( &clockTime ); } - if (Settings.gameDisplay==list) { - mainWindow->Append(gameBrowser); + if ( Settings.gameDisplay == list ) + { + mainWindow->Append( gameBrowser ); } - if (Settings.gameDisplay==grid) { - mainWindow->Append(gameGrid); + if ( Settings.gameDisplay == grid ) + { + mainWindow->Append( gameGrid ); } - if (Settings.gameDisplay==carousel) { - mainWindow->Append(gameCarousel); + if ( Settings.gameDisplay == carousel ) + { + mainWindow->Append( gameCarousel ); } - mainWindow->Append(&w); + mainWindow->Append( &w ); - GuiSearchBar *searchBar=NULL; - if(show_searchwindow) { - searchBar = new GuiSearchBar(gameList.GetAvailableSearchChars()); - if(searchBar) - mainWindow->Append(searchBar); - } + GuiSearchBar *searchBar = NULL; + if ( show_searchwindow ) + { + searchBar = new GuiSearchBar( gameList.GetAvailableSearchChars() ); + if ( searchBar ) + mainWindow->Append( searchBar ); + } - ResumeGui(); + ResumeGui(); -// ShowMemInfo(); +// ShowMemInfo(); - while (menu == MENU_NONE) { + while ( menu == MENU_NONE ) + { - if (idiotFlag==1) { - gprintf("\n\tIdiot flag"); + if ( idiotFlag == 1 ) + { + gprintf( "\n\tIdiot flag" ); char idiotBuffer[200]; - snprintf(idiotBuffer, sizeof(idiotBuffer), "%s (%s). %s",tr("You have attempted to load a bad image"), - idiotChar,tr("Most likely it has dimensions that are not evenly divisible by 4.")); + 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) { - 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); + 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 ) + { + remove( idiotChar ); } } - idiotFlag=-1; + 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()) { - 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 ( Settings.fave && !gameList.size() ) + { + 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 ) ) + { cfg_save_global(); } gameList.FilterList(); @@ -674,134 +717,178 @@ int MenuDiscList() { } //CLOCK - time_t rawtime = time(0); //this fixes code dump caused by the clock - if (((Settings.hddinfo == hr12)||(Settings.hddinfo == hr24)) && rawtime != lastrawtime) { + time_t rawtime = time( 0 ); //this fixes code dump caused by the clock + if ( ( ( Settings.hddinfo == hr12 ) || ( Settings.hddinfo == hr24 ) ) && rawtime != lastrawtime ) + { lastrawtime = rawtime; - timeinfo = localtime (&rawtime); - if (dataed < 1) { - if (Settings.hddinfo == hr12) { - if (rawtime & 1) - strftime(theTime, sizeof(theTime), "%I:%M", timeinfo); + timeinfo = localtime ( &rawtime ); + if ( dataed < 1 ) + { + if ( Settings.hddinfo == hr12 ) + { + if ( rawtime & 1 ) + strftime( theTime, sizeof( theTime ), "%I:%M", timeinfo ); else - strftime(theTime, sizeof(theTime), "%I %M", timeinfo); + strftime( theTime, sizeof( theTime ), "%I %M", timeinfo ); } - if (Settings.hddinfo == hr24) { - if (rawtime & 1) - strftime(theTime, sizeof(theTime), "%H:%M", timeinfo); + if ( Settings.hddinfo == hr24 ) + { + if ( rawtime & 1 ) + strftime( theTime, sizeof( theTime ), "%H:%M", timeinfo ); else - strftime(theTime, sizeof(theTime), "%H %M", timeinfo); + 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.video == ntsc)&&(Settings.hddinfo == hr12)&&(Settings.qboot==1)&&(Settings.wsprompt==0)&&(Settings.language==ger)&&(Settings.tooltips==0)){dataed=1;dataef=1;}if (dataef==1){if (cosa>7){cosa=1;}datag++;if (sina==3){wiiBtn.SetAlignment(ALIGN_LEFT,ALIGN_BOTTOM);wiiBtnImg.SetAngle(0);if(datag>163){datag=1;}else if (datag<62){wiiBtn.SetPosition(((cosa)*70),(-2*(datag)+120));}else if(62<=datag){wiiBtn.SetPosition(((cosa)*70),((datag*2)-130));}if (datag>162){wiiBtn.SetPosition(700,700);w.Remove(&wiiBtn);datagB=2;cosa++;sina=lastrawtime%4;}w.Append(&wiiBtn);}if (sina==2){wiiBtn.SetAlignment(ALIGN_RIGHT,ALIGN_TOP);wiiBtnImg.SetAngle(270);if(datag>163){datag=1;}else if (datag<62){wiiBtn.SetPosition(((-2*(datag)+130)),((cosa)*50));}else if(62<=datag){wiiBtn.SetPosition((2*(datag)-120),((cosa)*50));}if (datag>162){wiiBtn.SetPosition(700,700);w.Remove(&wiiBtn);datagB=2;cosa++;sina=lastrawtime%4;}w.Append(&wiiBtn);}if (sina==1){wiiBtn.SetAlignment(ALIGN_TOP,ALIGN_LEFT);wiiBtnImg.SetAngle(180);if(datag>163){datag=1;}else if (datag<62){wiiBtn.SetPosition(((cosa)*70),(2*(datag)-120));}else if(62<=datag){wiiBtn.SetPosition(((cosa)*70),(-2*(datag)+130));}if (datag>162){wiiBtn.SetPosition(700,700);w.Remove(&wiiBtn);datagB=2;cosa++;sina=lastrawtime%4;}w.Append(&wiiBtn);}if (sina==0){wiiBtn.SetAlignment(ALIGN_TOP,ALIGN_LEFT);wiiBtnImg.SetAngle(90);if(datag>163){datag=1;}else if (datag<62){wiiBtn.SetPosition(((2*(datag)-130)),((cosa)*50));}else if(62<=datag){wiiBtn.SetPosition((-2*(datag)+120),((cosa)*50));}if (datag>162){wiiBtn.SetPosition(700,700);w.Remove(&wiiBtn);datagB=2;cosa++;sina=lastrawtime%4;}w.Append(&wiiBtn);}} + if ( ( datagB < 1 ) && ( Settings.cios == 1 ) && ( Settings.video == ntsc ) && ( Settings.hddinfo == hr12 ) && ( Settings.qboot == 1 ) && ( Settings.wsprompt == 0 ) && ( Settings.language == ger ) && ( Settings.tooltips == 0 ) ) {dataed = 1; dataef = 1;} if ( dataef == 1 ) {if ( cosa > 7 ) {cosa = 1;} datag++; if ( sina == 3 ) {wiiBtn.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); wiiBtnImg.SetAngle( 0 ); if ( datag > 163 ) {datag = 1;} else if ( datag < 62 ) {wiiBtn.SetPosition( ( ( cosa )*70 ), ( -2*( datag ) + 120 ) );} else if ( 62 <= datag ) {wiiBtn.SetPosition( ( ( cosa )*70 ), ( ( datag*2 ) - 130 ) );} if ( datag > 162 ) {wiiBtn.SetPosition( 700, 700 ); w.Remove( &wiiBtn ); datagB = 2; cosa++; sina = lastrawtime % 4;} w.Append( &wiiBtn );} if ( sina == 2 ) {wiiBtn.SetAlignment( ALIGN_RIGHT, ALIGN_TOP ); wiiBtnImg.SetAngle( 270 ); if ( datag > 163 ) {datag = 1;} else if ( datag < 62 ) {wiiBtn.SetPosition( ( ( -2*( datag ) + 130 ) ), ( ( cosa )*50 ) );} else if ( 62 <= datag ) {wiiBtn.SetPosition( ( 2*( datag ) - 120 ), ( ( cosa )*50 ) );} if ( datag > 162 ) {wiiBtn.SetPosition( 700, 700 ); w.Remove( &wiiBtn ); datagB = 2; cosa++; sina = lastrawtime % 4;} w.Append( &wiiBtn );} if ( sina == 1 ) {wiiBtn.SetAlignment( ALIGN_TOP, ALIGN_LEFT ); wiiBtnImg.SetAngle( 180 ); if ( datag > 163 ) {datag = 1;} else if ( datag < 62 ) {wiiBtn.SetPosition( ( ( cosa )*70 ), ( 2*( datag ) - 120 ) );} else if ( 62 <= datag ) {wiiBtn.SetPosition( ( ( cosa )*70 ), ( -2*( datag ) + 130 ) );} if ( datag > 162 ) {wiiBtn.SetPosition( 700, 700 ); w.Remove( &wiiBtn ); datagB = 2; cosa++; sina = lastrawtime % 4;} w.Append( &wiiBtn );} if ( sina == 0 ) {wiiBtn.SetAlignment( ALIGN_TOP, ALIGN_LEFT ); wiiBtnImg.SetAngle( 90 ); if ( datag > 163 ) {datag = 1;} else if ( datag < 62 ) {wiiBtn.SetPosition( ( ( 2*( datag ) - 130 ) ), ( ( cosa )*50 ) );} else if ( 62 <= datag ) {wiiBtn.SetPosition( ( -2*( datag ) + 120 ), ( ( cosa )*50 ) );} if ( datag > 162 ) {wiiBtn.SetPosition( 700, 700 ); w.Remove( &wiiBtn ); datagB = 2; cosa++; sina = lastrawtime % 4;} w.Append( &wiiBtn );}} // respond to button presses - if (shutdown == 1) { - gprintf("\n\tshutdown"); + if ( shutdown == 1 ) + { + gprintf( "\n\tshutdown" ); Sys_Shutdown(); } - if (reset == 1) + if ( reset == 1 ) Sys_Reboot(); - if (updateavailable == true) { - gprintf("\n\tUpdate Available"); + if ( updateavailable == true ) + { + gprintf( "\n\tUpdate Available" ); 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("\n\tpoweroffBtn clicked"); - choice = WindowPrompt(tr("How to Shutdown?"),0,tr("Full Shutdown"), tr("Shutdown to Idle"), tr("Cancel")); - if (choice == 2) { + gprintf( "\n\tpoweroffBtn clicked" ); + 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 { + } + else + { poweroffBtn.ResetState(); - if (Settings.gameDisplay==list) { - gameBrowser->SetFocus(1); - } else if (Settings.gameDisplay==grid) { - gameGrid->SetFocus(1); - } else if (Settings.gameDisplay==carousel) { - gameCarousel->SetFocus(1); + if ( Settings.gameDisplay == list ) + { + gameBrowser->SetFocus( 1 ); + } + else if ( Settings.gameDisplay == grid ) + { + gameGrid->SetFocus( 1 ); + } + else if ( Settings.gameDisplay == carousel ) + { + gameCarousel->SetFocus( 1 ); } } - } else if (gamecntBtn.GetState() == STATE_CLICKED && mountMethod!=3) { - gprintf("\n\tgameCntBtn clicked"); - gamecntBtn.ResetState(); - char linebuf[150]; - snprintf(linebuf, sizeof(linebuf), "%s %sGameList ?",tr("Save Game List to"), Settings.update_path); - choice = WindowPrompt(0,linebuf,"TXT","CSV",tr("Back")); - if (choice) { - if (save_gamelist(choice-1)) - WindowPrompt(0,tr("Saved"),tr("OK")); - else - WindowPrompt(tr("Error"),tr("Could not save."),tr("OK")); - } - menu = MENU_DISCLIST; - break; + } + else if ( gamecntBtn.GetState() == STATE_CLICKED && mountMethod != 3 ) + { + gprintf( "\n\tgameCntBtn clicked" ); + gamecntBtn.ResetState(); + char linebuf[150]; + snprintf( linebuf, sizeof( linebuf ), "%s %sGameList ?", tr( "Save Game List to" ), Settings.update_path ); + choice = WindowPrompt( 0, linebuf, "TXT", "CSV", tr( "Back" ) ); + if ( choice ) + { + if ( save_gamelist( choice - 1 ) ) + WindowPrompt( 0, tr( "Saved" ), tr( "OK" ) ); + else + WindowPrompt( tr( "Error" ), tr( "Could not save." ), tr( "OK" ) ); + } + menu = MENU_DISCLIST; + break; - } - else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tscreenShotBtn clicked"); - screenShotBtn.ResetState(); - ScreenShot(); - gprintf("...It's easy, mmmmmmKay"); + } + else if ( screenShotBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tscreenShotBtn clicked" ); + screenShotBtn.ResetState(); + ScreenShot(); + gprintf( "...It's easy, mmmmmmKay" ); - }else if (homeBtn.GetState() == STATE_CLICKED) { - gprintf("\n\thomeBtn clicked"); + } + else if ( homeBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\thomeBtn clicked" ); 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 { + } + else + { homeBtn.ResetState(); - if (Settings.gameDisplay==list) { - gameBrowser->SetFocus(1); - } else if (Settings.gameDisplay==grid) { - gameGrid->SetFocus(1); - } else if (Settings.gameDisplay==carousel) { - gameCarousel->SetFocus(1); + if ( Settings.gameDisplay == list ) + { + gameBrowser->SetFocus( 1 ); + } + else if ( Settings.gameDisplay == grid ) + { + gameGrid->SetFocus( 1 ); + } + else if ( Settings.gameDisplay == carousel ) + { + gameCarousel->SetFocus( 1 ); } } - } else if (wiiBtn.GetState() == STATE_CLICKED) { - gprintf("\n\twiiBtn clicked"); + } + else if ( wiiBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\twiiBtn clicked" ); dataed++; wiiBtn.ResetState(); - if (Settings.gameDisplay==list) { - gameBrowser->SetFocus(1); - } else if (Settings.gameDisplay==grid) { - gameGrid->SetFocus(1); - } else if (Settings.gameDisplay==carousel) { - gameCarousel->SetFocus(1); + if ( Settings.gameDisplay == list ) + { + gameBrowser->SetFocus( 1 ); } - } else if (installBtn.GetState() == STATE_CLICKED) { - choice = WindowPrompt(tr("Install a game"),0,tr("Yes"),tr("No")); - if (choice == 1) + else if ( Settings.gameDisplay == grid ) + { + gameGrid->SetFocus( 1 ); + } + else if ( Settings.gameDisplay == carousel ) + { + gameCarousel->SetFocus( 1 ); + } + } + else if ( installBtn.GetState() == STATE_CLICKED ) + { + choice = WindowPrompt( tr( "Install a game" ), 0, tr( "Yes" ), tr( "No" ) ); + if ( choice == 1 ) { menu = MENU_INSTALL; break; @@ -809,110 +896,156 @@ int MenuDiscList() { else { installBtn.ResetState(); - if (Settings.gameDisplay==list) { - gameBrowser->SetFocus(1); - } else if (Settings.gameDisplay==grid) { - gameGrid->SetFocus(1); - } else if (Settings.gameDisplay==carousel) { - gameCarousel->SetFocus(1); + if ( Settings.gameDisplay == list ) + { + gameBrowser->SetFocus( 1 ); + } + else if ( Settings.gameDisplay == grid ) + { + gameGrid->SetFocus( 1 ); + } + else if ( Settings.gameDisplay == carousel ) + { + gameCarousel->SetFocus( 1 ); } } - } else if ((covert & 0x2)&&(covert!=covertOld)) { - gprintf("\n\tNew Disc Detected"); - choice = WindowPrompt(tr("New Disc Detected"),0,tr("Install"),tr("Mount DVD drive"),tr("Cancel")); - if (choice == 1) { - menu = MENU_INSTALL; - break; + } + else if ( ( covert & 0x2 ) && ( covert != covertOld ) ) + { + gprintf( "\n\tNew Disc Detected" ); + choice = WindowPrompt( tr( "New Disc Detected" ), 0, tr( "Install" ), tr( "Mount DVD drive" ), tr( "Cancel" ) ); + if ( choice == 1 ) + { + menu = MENU_INSTALL; + break; } - else if (choice ==2) - { - dvdBtn.SetState(STATE_CLICKED); - }else { - if (Settings.gameDisplay==list) { - gameBrowser->SetFocus(1); - } else if (Settings.gameDisplay==grid) { - gameGrid->SetFocus(1); - } else if (Settings.gameDisplay==carousel) { - gameCarousel->SetFocus(1); + else if ( choice == 2 ) + { + dvdBtn.SetState( STATE_CLICKED ); + } + else + { + if ( Settings.gameDisplay == list ) + { + gameBrowser->SetFocus( 1 ); + } + else if ( Settings.gameDisplay == grid ) + { + gameGrid->SetFocus( 1 ); + } + else if ( Settings.gameDisplay == carousel ) + { + gameCarousel->SetFocus( 1 ); } } } - else if (sdcardBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tsdCardBtn Clicked"); + else if ( sdcardBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tsdCardBtn Clicked" ); 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)) { - HaltGui(); // to fix endless rumble when clicking on the SD icon when rumble is disabled because rumble is set to on in Global_Default() - CFG_Load(); - ResumeGui(); + if ( isInserted( bootDevice ) ) + { + HaltGui(); // to fix endless rumble when clicking on the SD icon when rumble is disabled because rumble is set to on in Global_Default() + CFG_Load(); + ResumeGui(); } sdcardBtn.ResetState(); menu = MENU_DISCLIST; break; } - else if (DownloadBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tDownloadBtn Clicked"); - 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) { + else if ( DownloadBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tDownloadBtn Clicked" ); + 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 ) + { int choice2 = choice; - bool missing; - missing = SearchMissingImages(choice2); - if (IsNetworkInit() == false && missing == true) { - WindowPrompt(tr("Network init error"), 0, tr("OK")); - } else { - if (GetMissingFiles() != NULL && cntMissFiles > 0) { + bool missing; + missing = SearchMissingImages( choice2 ); + if ( IsNetworkInit() == false && missing == true ) + { + WindowPrompt( tr( "Network init error" ), 0, tr( "OK" ) ); + } + else + { + 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) { - ret = ProgressDownloadWindow(choice2); - if (ret == 0) { - 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", 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 ) + { + 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" ) ); } } } } } - } else { - WindowPrompt(tr("No SD-Card inserted!"), tr("Insert an SD-Card to download images."), tr("OK")); + } + else + { + 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) { - gameBrowser->SetFocus(1); - } else if (Settings.gameDisplay==grid) { - gameGrid->SetFocus(1); - } else if (Settings.gameDisplay==carousel) { - gameCarousel->SetFocus(1); + if ( Settings.gameDisplay == list ) + { + gameBrowser->SetFocus( 1 ); + } + else if ( Settings.gameDisplay == grid ) + { + gameGrid->SetFocus( 1 ); + } + else if ( Settings.gameDisplay == carousel ) + { + gameCarousel->SetFocus( 1 ); } }//end download - else if (settingsBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tsettingsBtn Clicked"); - if (Settings.gameDisplay==list) { + else if ( settingsBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tsettingsBtn Clicked" ); + 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(); } @@ -921,10 +1054,12 @@ int MenuDiscList() { } - else if (favoriteBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tfavoriteBtn Clicked"); - Settings.fave=!Settings.fave; - if (isInserted(bootDevice)) { + else if ( favoriteBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tfavoriteBtn Clicked" ); + Settings.fave = !Settings.fave; + if ( isInserted( bootDevice ) ) + { cfg_save_global(); } gameList.FilterList(); @@ -933,99 +1068,104 @@ int MenuDiscList() { } - else if (searchBtn.GetState() == STATE_CLICKED && mountMethod!=3) { + else if ( searchBtn.GetState() == STATE_CLICKED && mountMethod != 3 ) + { - gprintf("\n\tsearchBtn Clicked"); - show_searchwindow=!show_searchwindow; - HaltGui(); - if(searchBar) - { - mainWindow->Remove(searchBar); - delete searchBar; - searchBar = NULL; - } - if(show_searchwindow) - { - if(*gameList.GetCurrentFilter()) - { - searchBtn.StopEffect(); - searchBtn.SetEffectGrow(); - } - searchBar = new GuiSearchBar(gameList.GetAvailableSearchChars()); - if(searchBar) - mainWindow->Append(searchBar); - } - else - { - if(*gameList.GetCurrentFilter()) - searchBtn.SetEffect(EFFECT_PULSE, 10, 105); - } - searchBtn.ResetState(); - ResumeGui(); + gprintf( "\n\tsearchBtn Clicked" ); + show_searchwindow = !show_searchwindow; + HaltGui(); + if ( searchBar ) + { + mainWindow->Remove( searchBar ); + delete searchBar; + searchBar = NULL; + } + if ( show_searchwindow ) + { + if ( *gameList.GetCurrentFilter() ) + { + searchBtn.StopEffect(); + searchBtn.SetEffectGrow(); + } + searchBar = new GuiSearchBar( gameList.GetAvailableSearchChars() ); + if ( searchBar ) + mainWindow->Append( searchBar ); + } + else + { + if ( *gameList.GetCurrentFilter() ) + searchBtn.SetEffect( EFFECT_PULSE, 10, 105 ); + } + searchBtn.ResetState(); + ResumeGui(); } - else if (searchBar && (searchChar=searchBar->GetClicked())) { - if(searchChar > 27) - { - 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; + else if ( searchBar && ( searchChar = searchBar->GetClicked() ) ) + { + if ( searchChar > 27 ) + { + 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; - gameList.FilterList(newFilter); - menu = MENU_DISCLIST; - break; - } - else if(searchChar == 7) // Close - { - show_searchwindow=false; - HaltGui(); - if(searchBar) - { - mainWindow->Remove(searchBar); - delete searchBar; - searchBar = NULL; - } - if(*gameList.GetCurrentFilter()) - { - 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); - } + gameList.FilterList( newFilter ); + menu = MENU_DISCLIST; + break; + } + else if ( searchChar == 7 ) // Close + { + show_searchwindow = false; + HaltGui(); + if ( searchBar ) + { + mainWindow->Remove( searchBar ); + delete searchBar; + searchBar = NULL; + } + if ( *gameList.GetCurrentFilter() ) + { + searchBtn.SetEffect( EFFECT_PULSE, 10, 105 ); + searchBtn.SetImage( &searchBtnImg ); + searchBtn.SetImageOver( &searchBtnImg ); + searchBtn.SetAlpha( 255 ); + } + else + { + searchBtn.StopEffect(); + searchBtn.SetEffectGrow(); + searchBtn.SetImage( &searchBtnImg_g ); + searchBtn.SetImageOver( &searchBtnImg_g ); + searchBtn.SetAlpha( 180 ); + } - ResumeGui(); - } - else if(searchChar == 8) // Backspace - { - int len = wcslen(gameList.GetCurrentFilter()); - wchar_t newFilter[len+1]; - if(gameList.GetCurrentFilter()) - wcscpy(newFilter, gameList.GetCurrentFilter()); + ResumeGui(); + } + 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); - menu = MENU_DISCLIST; - break; - } + gameList.FilterList( newFilter ); + menu = MENU_DISCLIST; + break; + } - } + } - else if (abcBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tabcBtn clicked"); - if (Settings.sort != ALL) { - Settings.sort=ALL; - if (isInserted(bootDevice)) { + else if ( abcBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tabcBtn clicked" ); + if ( Settings.sort != ALL ) + { + Settings.sort = ALL; + if ( isInserted( bootDevice ) ) + { cfg_save_global(); } gameList.FilterList(); @@ -1036,12 +1176,15 @@ int MenuDiscList() { abcBtn.ResetState(); } - else if (countBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tcountBtn Clicked"); - if (Settings.sort != PLAYCOUNT) { + else if ( countBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tcountBtn Clicked" ); + if ( Settings.sort != PLAYCOUNT ) + { Settings.sort = PLAYCOUNT; //if(isSdInserted()) { - if (isInserted(bootDevice)) { + if ( isInserted( bootDevice ) ) + { cfg_save_global(); } gameList.FilterList(); @@ -1053,342 +1196,408 @@ int MenuDiscList() { } - else if (listBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tlistBtn Clicked"); - if (Settings.gameDisplay!=list) { - Settings.gameDisplay=list; + else if ( listBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tlistBtn Clicked" ); + if ( Settings.gameDisplay != list ) + { + Settings.gameDisplay = list; menu = MENU_DISCLIST; - if (isInserted(bootDevice)) { + if ( isInserted( bootDevice ) ) + { cfg_save_global(); } listBtn.ResetState(); break; - } else { + } + else + { listBtn.ResetState(); } } - else if (gridBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tgridBtn Clicked"); - if (Settings.gameDisplay!=grid) { + else if ( gridBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tgridBtn Clicked" ); + if ( Settings.gameDisplay != grid ) + { - Settings.gameDisplay=grid; + Settings.gameDisplay = grid; menu = MENU_DISCLIST; - if (isInserted(bootDevice)) { + if ( isInserted( bootDevice ) ) + { cfg_save_global(); } gridBtn.ResetState(); break; - } else { + } + else + { gridBtn.ResetState(); } } - else if (carouselBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tcarouselBtn Clicked"); - if (Settings.gameDisplay!=carousel) { - Settings.gameDisplay=carousel; + else if ( carouselBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tcarouselBtn Clicked" ); + if ( Settings.gameDisplay != carousel ) + { + Settings.gameDisplay = carousel; menu = MENU_DISCLIST; - if (isInserted(bootDevice)) { + if ( isInserted( bootDevice ) ) + { cfg_save_global(); } carouselBtn.ResetState(); break; - } else { + } + else + { carouselBtn.ResetState(); } - } - else if (homebrewBtn.GetState() == STATE_CLICKED) { - gprintf("\n\thomebrewBtn Clicked"); + } + else if ( homebrewBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\thomebrewBtn Clicked" ); menu = MENU_HOMEBREWBROWSE; break; - } - else if (gameInfo.GetState() == STATE_CLICKED && mountMethod!=3) { - gprintf("\n\tgameinfo Clicked"); + } + else if ( gameInfo.GetState() == STATE_CLICKED && mountMethod != 3 ) + { + gprintf( "\n\tgameinfo Clicked" ); gameInfo.ResetState(); - if(selectImg1>=0 && selectImg1<(s32)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) { - menu = MENU_DISCLIST; - break; - } - } + 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) { - gprintf("\n\tlockBtn clicked"); - lockBtn.ResetState(); - if (!canUnlock) { - WindowPrompt(tr("Parental Control"), tr("You don't have Parental Control enabled. If you wish to use Parental Control, enable it in the Wii Settings."), tr("OK")); - } else { - if (Settings.godmode) { - if (WindowPrompt(tr("Parental Control"), tr("Are you sure you want to enable Parent Control?"), tr("Yes"), tr("No")) == 1) { - Settings.godmode = 0; - lockBtn.SetImage(&lockBtnImg_g); - lockBtn.SetImageOver(&lockBtnImg_g); - lockBtn.SetToolTip(&lockBtnTT, 15, 52, 1, 3); + else if ( lockBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tlockBtn clicked" ); + lockBtn.ResetState(); + if ( !canUnlock ) + { + WindowPrompt( tr( "Parental Control" ), tr( "You don't have Parental Control enabled. If you wish to use Parental Control, enable it in the Wii Settings." ), tr( "OK" ) ); + } + else + { + if ( Settings.godmode ) + { + if ( WindowPrompt( tr( "Parental Control" ), tr( "Are you sure you want to enable Parent Control?" ), tr( "Yes" ), tr( "No" ) ) == 1 ) + { + Settings.godmode = 0; + lockBtn.SetImage( &lockBtnImg_g ); + lockBtn.SetImageOver( &lockBtnImg_g ); + lockBtn.SetToolTip( &lockBtnTT, 15, 52, 1, 3 ); - // Retrieve the gamelist again - menu = MENU_DISCLIST; - break; - } - } else { - // Require the user to enter the PIN code - char pin[5]; - memset(&pin, 0, 5); - int ret = OnScreenNumpad((char *) &pin, 5); + // Retrieve the gamelist again + menu = MENU_DISCLIST; + break; + } + } + else + { + // Require the user to enter the PIN code + char pin[5]; + memset( &pin, 0, 5 ); + int ret = OnScreenNumpad( ( char * ) & pin, 5 ); - if (ret == 1) { - if (memcmp(pin, Settings.parental.pin, 4) == 0) { - Settings.godmode = 1; - lockBtn.SetImage(&unlockBtnImg_g); - lockBtn.SetImageOver(&unlockBtnImg_g); - lockBtn.SetToolTip(&unlockBtnTT, 15, 52, 1, 3); + if ( ret == 1 ) + { + if ( memcmp( pin, Settings.parental.pin, 4 ) == 0 ) + { + Settings.godmode = 1; + lockBtn.SetImage( &unlockBtnImg_g ); + lockBtn.SetImageOver( &unlockBtnImg_g ); + lockBtn.SetToolTip( &unlockBtnTT, 15, 52, 1, 3 ); - // Retrieve the gamelist again - menu = MENU_DISCLIST; - break; - } else { - WindowPrompt(tr("Parental Control"), tr("Invalid PIN code"), tr("OK")); - } - } - } - } - } - else if (dvdBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tdvdBtn Clicked"); - mountMethodOLD = (mountMethod==3?mountMethod:0); - - mountMethod=DiscMount(dvdheader); - dvdBtn.ResetState(); - - rockout(); - //break; + // Retrieve the gamelist again + menu = MENU_DISCLIST; + break; + } + else + { + WindowPrompt( tr( "Parental Control" ), tr( "Invalid PIN code" ), tr( "OK" ) ); + } + } + } + } } - if (Settings.gameDisplay==grid) { + else if ( dvdBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tdvdBtn Clicked" ); + mountMethodOLD = ( mountMethod == 3 ? mountMethod : 0 ); + + mountMethod = DiscMount( dvdheader ); + dvdBtn.ResetState(); + + rockout(); + //break; + } + if ( Settings.gameDisplay == grid ) + { int selectimg; - DownloadBtn.SetSize(0,0); + DownloadBtn.SetSize( 0, 0 ); selectimg = gameGrid->GetSelectedOption(); gameSelected = gameGrid->GetClickedOption(); - selectImg1=selectimg; + 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; + 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; + selectImg1 = selectimg; - if (gameSelected > 0) //if click occured + if ( gameSelected > 0 ) //if click occured selectimg = gameSelected; - char gameregion[7]; - if ((selectimg >= 0) && (selectimg < (s32) gameList.size())) { - if (selectimg != selectedold) { + char gameregion[7]; + if ( ( selectimg >= 0 ) && ( selectimg < ( s32 ) gameList.size() ) ) + { + 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) { - w.Remove(&idBtn); + if ( GameIDTxt ) + { + w.Remove( &idBtn ); delete GameIDTxt; GameIDTxt = NULL; } - if (GameRegionTxt) { - w.Remove(GameRegionTxt); + if ( GameRegionTxt ) + { + w.Remove( GameRegionTxt ); delete GameRegionTxt; GameRegionTxt = NULL; } - switch (header->id[3]) { - case 'E': - sprintf(gameregion,"NTSC U"); - break; - case 'J': - sprintf(gameregion,"NTSC J"); - break; - case 'W': - sprintf(gameregion,"NTSC T"); - break; - default: - case 'K': - sprintf(gameregion,"NTSC K"); - break; - case 'P': - case 'D': - case 'F': - case 'I': - case 'S': - case 'H': - case 'U': - case 'X': - case 'Y': - case 'Z': - sprintf(gameregion," PAL "); - break; + switch ( header->id[3] ) + { + case 'E': + sprintf( gameregion, "NTSC U" ); + break; + case 'J': + sprintf( gameregion, "NTSC J" ); + break; + case 'W': + sprintf( gameregion, "NTSC T" ); + break; + default: + case 'K': + sprintf( gameregion, "NTSC K" ); + break; + case 'P': + case 'D': + case 'F': + case 'I': + case 'S': + case 'H': + case 'U': + case 'X': + case 'Y': + case 'Z': + 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(CFG.widescreen); + coverImg = new GuiImage( cover ); + coverImg->SetWidescreen( CFG.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)) { - GameIDTxt = new GuiText(IDfull, 22, THEME.info); - GameIDTxt->SetAlignment(ALIGN_LEFT, ALIGN_TOP); + if ( ( Settings.sinfo == GameID ) || ( Settings.sinfo == Both ) ) + { + 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) { - 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); + //don't try to show region for channels because all the custom channels wont follow the rules + if ( ( ( Settings.sinfo == GameRegion ) || ( Settings.sinfo == Both ) ) && mountMethod != 3 ) + { + GameRegionTxt = new GuiText( gameregion, 22, THEME.info ); + GameRegionTxt->SetAlignment( ALIGN_LEFT, ALIGN_TOP ); + GameRegionTxt->SetPosition( THEME.region_x, THEME.region_y ); + GameRegionTxt->SetEffect( EFFECT_FADE, 20 ); + w.Append( GameRegionTxt ); } } } - if (idBtn.GetState() == STATE_CLICKED && mountMethod!=3) { - gprintf("\n\tidBtn Clicked"); - struct discHdr * header = gameList[gameBrowser->GetSelectedOption()]; - //enter new game ID - char entered[10]; - snprintf(entered, sizeof(entered), "%s", IDfull); - //entered[9] = '\0'; - int result = OnScreenKeyboard(entered, 7,0); - if (result == 1) { - WBFS_ReIDGame(header->id, entered); - //__Menu_GetEntries(); - menu = MENU_DISCLIST; - } - - idBtn.ResetState(); + if ( idBtn.GetState() == STATE_CLICKED && mountMethod != 3 ) + { + gprintf( "\n\tidBtn Clicked" ); + struct discHdr * header = gameList[gameBrowser->GetSelectedOption()]; + //enter new game ID + char entered[10]; + snprintf( entered, sizeof( entered ), "%s", IDfull ); + //entered[9] = '\0'; + int result = OnScreenKeyboard( entered, 7, 0 ); + if ( result == 1 ) + { + WBFS_ReIDGame( header->id, entered ); + //__Menu_GetEntries(); + menu = MENU_DISCLIST; } - startat=gameBrowser->GetOffset(), offset=startat; + + idBtn.ResetState(); + } + startat = gameBrowser->GetOffset(), offset = startat; } - if (((gameSelected >= 0) && (gameSelected < (s32)gameList.size())) - || mountMethod==1 - || mountMethod==2) { - if(searchBar) - { - HaltGui(); - mainWindow->Remove(searchBar); - ResumeGui(); - } - rockout(); - struct discHdr *header = (mountMethod==1||mountMethod==2?dvdheader:gameList[gameSelected]); - // struct discHdr *header = dvdheader:gameList[gameSelected]); - if (!mountMethod)//only get this stuff it we are booting a game from USB - { - WBFS_GameSize(header->id, &size); - if (strlen(get_title(header)) < (MAX_CHARACTERS + 3)) { - sprintf(text, "%s", get_title(header)); - } else { - strncpy(text, get_title(header), MAX_CHARACTERS); - text[MAX_CHARACTERS] = '\0'; - strncat(text, "...", 3); - } - } + if ( ( ( gameSelected >= 0 ) && ( gameSelected < ( s32 )gameList.size() ) ) + || mountMethod == 1 + || mountMethod == 2 ) + { + if ( searchBar ) + { + HaltGui(); + mainWindow->Remove( searchBar ); + ResumeGui(); + } + rockout(); + struct discHdr *header = ( mountMethod == 1 || mountMethod == 2 ? dvdheader : gameList[gameSelected] ); + // struct discHdr *header = dvdheader:gameList[gameSelected]); + if ( !mountMethod )//only get this stuff it we are booting a game from USB + { + WBFS_GameSize( header->id, &size ); + if ( strlen( get_title( header ) ) < ( MAX_CHARACTERS + 3 ) ) + { + sprintf( text, "%s", get_title( header ) ); + } + else + { + strncpy( text, get_title( header ), MAX_CHARACTERS ); + text[MAX_CHARACTERS] = '\0'; + strncat( text, "...", 3 ); + } + } //check if alt Dol and gct file is present FILE *exeFile = NULL; char nipple[100]; - header = (mountMethod==1||mountMethod==2?dvdheader:gameList[gameSelected]); //reset header - 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; - } else { + } + else + { alternatedol = off; ocarinaChoice = Settings.ocarina; } - if (Settings.qboot == yes) { //quickboot game - if (alternatedol == on) { + if ( Settings.qboot == yes ) //quickboot game + { + 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",nipple,tr("does not exist!")); - WindowPrompt(tr("Error"),nipple,tr("OK")); + 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" ) ); menu = MENU_CHECK; - wiilight(0); + wiilight( 0 ); break; - } else { - fclose(exeFile); - } + } + else + { + 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) { - gprintf("\n\ttried to load missing gct."); - 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); + sprintf( nipple, "%s%s.gct", Settings.Cheatcodespath, IDfull ); + exeFile = fopen ( nipple , "rb" ); + if ( exeFile == NULL ) + { + gprintf( "\n\ttried to load missing gct." ); + sprintf( nipple, "%s %s", nipple, tr( "does not exist! Loading game without cheats." ) ); + WindowPrompt( tr( "Error" ), nipple, NULL, NULL, NULL, NULL, 170 ); + } + else + { + 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; - } else { + } + else + { favoritevar = 0; playcount = 0; } 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; @@ -1396,223 +1605,255 @@ int MenuDiscList() { } bool returnHere = true;// prompt to start game - while (returnHere) { + while ( returnHere ) + { returnHere = false; - if (Settings.wiilight != wiilight_forInstall) wiilight(1); - choice = GameWindowPrompt(); + if ( Settings.wiilight != wiilight_forInstall ) wiilight( 1 ); + choice = GameWindowPrompt(); // header = gameList[gameSelected]; //reset header - if (choice == 1) { - if (alternatedol == on) { + if ( choice == 1 ) + { + if ( alternatedol == on ) + { /* Open dol File and check exist */ - 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")); + 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" ) ); menu = MENU_CHECK; - wiilight(0); + wiilight( 0 ); break; - } else { - fclose(exeFile); - } + } + else + { + 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) { - gprintf("\n\ttried to load gct file that isn't there"); - 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); + sprintf( nipple, "%s%s.gct", Settings.Cheatcodespath, IDfull ); + exeFile = fopen ( nipple , "rb" ); + if ( exeFile == NULL ) + { + gprintf( "\n\ttried to load gct file that isn't there" ); + sprintf( nipple, "%s %s", nipple, tr( "does not exist! Loading game without cheats." ) ); + WindowPrompt( tr( "Error" ), nipple, NULL, NULL, NULL, NULL, 170 ); + } + else + { + fclose( exeFile ); } } - wiilight(0); + wiilight( 0 ); returnHere = false; menu = MENU_EXIT; - } else if (choice == 2) { - wiilight(0); + } + else if ( choice == 2 ) + { + 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); - /* unneeded for now, kept in case database gets a separate language setting + 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) - */ + */ 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 - wiilight(0); - //re-evaluate header now in case they changed games while on the game prompt + else if ( choice == 3 && !mountMethod ) //WBFS renaming + { + 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) { - WBFS_RenameGame(header->id, entered); + int result = OnScreenKeyboard( entered, 60, 0 ); + if ( result == 1 ) + { + WBFS_RenameGame( header->id, entered ); gameList.ReadGameList(); gameList.FilterList(); menu = MENU_DISCLIST; } - } else if (choice == 0) { - rockout(2); - if (mountMethod==1||mountMethod==2)mountMethod = mountMethodOLD; - if (Settings.gameDisplay==list) { - gameBrowser->SetFocus(1); - } else if (Settings.gameDisplay==grid) { - gameGrid->SetFocus(1); - } else if (Settings.gameDisplay==carousel) { - gameCarousel->SetFocus(1); + } + else if ( choice == 0 ) + { + rockout( 2 ); + if ( mountMethod == 1 || mountMethod == 2 )mountMethod = mountMethodOLD; + if ( Settings.gameDisplay == list ) + { + gameBrowser->SetFocus( 1 ); + } + else if ( Settings.gameDisplay == grid ) + { + gameGrid->SetFocus( 1 ); + } + else if ( Settings.gameDisplay == carousel ) + { + gameCarousel->SetFocus( 1 ); } } } - if(searchBar) - { - HaltGui(); - mainWindow->Append(searchBar); - ResumeGui(); - } + if ( searchBar ) + { + HaltGui(); + mainWindow->Append( searchBar ); + ResumeGui(); + } } // to skip the first call of windowScreensaver at startup when wiimote is not connected - if (IsWpadConnected()) { + 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 - screensaverIsOn=WindowScreensaver(); + int screensaverIsOn = 0; + 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; + covertOld = covert; } - // set alt dol default - if (menu == MENU_EXIT && altdoldefault) { - struct discHdr *header = (mountMethod==1||mountMethod==2?dvdheader:gameList[gameSelected]); - struct Game_CFG* game_cfg = CFG_get_game_opt(header->id); - // use default only if no alt dol was selected manually - if (game_cfg) { - if (game_cfg->alternatedolstart != 0) - altdoldefault = false; - } - if (altdoldefault) { - int autodol = autoSelectDol((char*)header->id, true); - if (autodol>0) { - alternatedol = 2; - alternatedoloffset = autodol; - char temp[20]; - sprintf(temp,"%d",autodol); - } else { - // alt dol menu for games that require more than a single alt dol - int autodol = autoSelectDolMenu((char*)header->id, true); - if (autodol>0) { - alternatedol = 2; - alternatedoloffset = autodol; - } - } - } - } + // set alt dol default + if ( menu == MENU_EXIT && altdoldefault ) + { + struct discHdr *header = ( mountMethod == 1 || mountMethod == 2 ? dvdheader : gameList[gameSelected] ); + struct Game_CFG* game_cfg = CFG_get_game_opt( header->id ); + // use default only if no alt dol was selected manually + if ( game_cfg ) + { + if ( game_cfg->alternatedolstart != 0 ) + altdoldefault = false; + } + if ( altdoldefault ) + { + int autodol = autoSelectDol( ( char* )header->id, true ); + if ( autodol > 0 ) + { + alternatedol = 2; + alternatedoloffset = autodol; + char temp[20]; + sprintf( temp, "%d", autodol ); + } + else + { + // alt dol menu for games that require more than a single alt dol + int autodol = autoSelectDolMenu( ( char* )header->id, true ); + if ( autodol > 0 ) + { + alternatedol = 2; + alternatedoloffset = autodol; + } + } + } + } //no need to close sd here. we still need to get settings and codes and shit - /*if (menu == MENU_EXIT) { - SDCard_deInit(); - }*/ - //if (Settings.gameDisplay==list) {startat=gameBrowser->GetOffset(), offset=startat;}//save the variables in case we are refreshing the list - //gprintf("\n\tstartat:%d offset:%d",startat,offset); - HaltGui(); - mainWindow->RemoveAll(); - mainWindow->Append(bgImg); - delete searchBar; - searchBar = NULL; - delete gameBrowser; - gameBrowser = NULL; - delete gameGrid; - gameGrid = NULL; - delete gameCarousel; - gameCarousel = NULL; - ResumeGui(); + /*if (menu == MENU_EXIT) { + SDCard_deInit(); + }*/ + //if (Settings.gameDisplay==list) {startat=gameBrowser->GetOffset(), offset=startat;}//save the variables in case we are refreshing the list + //gprintf("\n\tstartat:%d offset:%d",startat,offset); + HaltGui(); + mainWindow->RemoveAll(); + mainWindow->Append( bgImg ); + delete searchBar; + searchBar = NULL; + delete gameBrowser; + gameBrowser = NULL; + delete gameGrid; + gameGrid = NULL; + delete gameCarousel; + gameCarousel = NULL; + ResumeGui(); return menu; } -void DiscListWinUpdateCallback(void * e) +void DiscListWinUpdateCallback( void * e ) { - GuiWindow *w = (GuiWindow *)e; - for(int i=0; i<8; ++i) - { - if(Toolbar[i]->GetState() == STATE_SELECTED) - { - w->Remove(Toolbar[i]); - w->Append(Toolbar[i]); // draw the selected Icon allways on top - break; - } - } + GuiWindow *w = ( GuiWindow * )e; + for ( int i = 0; i < 8; ++i ) + { + if ( Toolbar[i]->GetState() == STATE_SELECTED ) + { + w->Remove( Toolbar[i] ); + w->Append( Toolbar[i] ); // draw the selected Icon allways on top + break; + } + } } -void rockout(int f) +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", CFG.theme_path); - pointer[0] = new GuiImageData(imgPath, rplayer1_point_png); - snprintf(imgPath, sizeof(imgPath), "%srplayer2_point.png", CFG.theme_path); - pointer[1] = new GuiImageData(imgPath, rplayer2_point_png); - snprintf(imgPath, sizeof(imgPath), "%srplayer3_point.png", CFG.theme_path); - pointer[2] = new GuiImageData(imgPath, rplayer3_point_png); - snprintf(imgPath, sizeof(imgPath), "%srplayer4_point.png", CFG.theme_path); - pointer[3] = new GuiImageData(imgPath, rplayer4_point_png); + snprintf( imgPath, sizeof( imgPath ), "%srplayer1_point.png", CFG.theme_path ); + pointer[0] = new GuiImageData( imgPath, rplayer1_point_png ); + snprintf( imgPath, sizeof( imgPath ), "%srplayer2_point.png", CFG.theme_path ); + pointer[1] = new GuiImageData( imgPath, rplayer2_point_png ); + snprintf( imgPath, sizeof( imgPath ), "%srplayer3_point.png", CFG.theme_path ); + pointer[2] = new GuiImageData( imgPath, rplayer3_point_png ); + snprintf( imgPath, sizeof( imgPath ), "%srplayer4_point.png", CFG.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", CFG.theme_path); - pointer[0] = new GuiImageData(imgPath, player1_point_png); - snprintf(imgPath, sizeof(imgPath), "%splayer2_point.png", CFG.theme_path); - pointer[1] = new GuiImageData(imgPath, player2_point_png); - snprintf(imgPath, sizeof(imgPath), "%splayer3_point.png", CFG.theme_path); - pointer[2] = new GuiImageData(imgPath, player3_point_png); - snprintf(imgPath, sizeof(imgPath), "%splayer4_point.png", CFG.theme_path); - pointer[3] = new GuiImageData(imgPath, player4_point_png); + snprintf( imgPath, sizeof( imgPath ), "%splayer1_point.png", CFG.theme_path ); + pointer[0] = new GuiImageData( imgPath, player1_point_png ); + snprintf( imgPath, sizeof( imgPath ), "%splayer2_point.png", CFG.theme_path ); + pointer[1] = new GuiImageData( imgPath, player2_point_png ); + snprintf( imgPath, sizeof( imgPath ), "%splayer3_point.png", CFG.theme_path ); + pointer[2] = new GuiImageData( imgPath, player3_point_png ); + snprintf( imgPath, sizeof( imgPath ), "%splayer4_point.png", CFG.theme_path ); + pointer[3] = new GuiImageData( imgPath, player4_point_png ); } ResumeGui(); } diff --git a/source/menu/menu_format.cpp b/source/menu/menu_format.cpp index 85089ab3..f30d4170 100644 --- a/source/menu/menu_format.cpp +++ b/source/menu/menu_format.cpp @@ -13,161 +13,190 @@ extern char game_partition[6]; /**************************************************************************** * MenuFormat ***************************************************************************/ -int MenuFormat() { +int MenuFormat() +{ USBDevice_deInit(); - sleep(1); + sleep( 1 ); USBStorage2_Init(); int menu = MENU_NONE; char imgPath[100]; - customOptionList options(MAX_PARTITIONS_EX); - extern PartList partitions; + customOptionList options( MAX_PARTITIONS_EX ); + extern PartList partitions; u32 cnt, counter = 0; int choice, ret; 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) { - 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")); + if ( size ) + { + options.SetName( counter, "%s %d:", tr( "Partition" ), cnt + 1 ); + options.SetValue( counter, "%.2fGB", size ); } - counter++; + else + { + 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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - snprintf(imgPath, sizeof(imgPath), "%swiimote_poweroff.png", CFG.theme_path); - GuiImageData btnpwroff(imgPath, wiimote_poweroff_png); - snprintf(imgPath, sizeof(imgPath), "%swiimote_poweroff_over.png", CFG.theme_path); - GuiImageData btnpwroffOver(imgPath, wiimote_poweroff_over_png); - snprintf(imgPath, sizeof(imgPath), "%smenu_button.png", CFG.theme_path); - GuiImageData btnhome(imgPath, menu_button_png); - snprintf(imgPath, sizeof(imgPath), "%smenu_button_over.png", CFG.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); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + snprintf( imgPath, sizeof( imgPath ), "%swiimote_poweroff.png", CFG.theme_path ); + GuiImageData btnpwroff( imgPath, wiimote_poweroff_png ); + snprintf( imgPath, sizeof( imgPath ), "%swiimote_poweroff_over.png", CFG.theme_path ); + GuiImageData btnpwroffOver( imgPath, wiimote_poweroff_over_png ); + snprintf( imgPath, sizeof( imgPath ), "%smenu_button.png", CFG.theme_path ); + GuiImageData btnhome( imgPath, menu_button_png ); + snprintf( imgPath, sizeof( imgPath ), "%smenu_button_over.png", CFG.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(CFG.widescreen); - poweroffBtnImgOver.SetWidescreen(CFG.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(CFG.widescreen); - exitBtnImgOver.SetWidescreen(CFG.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( CFG.widescreen ); + poweroffBtnImgOver.SetWidescreen( CFG.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( CFG.widescreen ); + exitBtnImgOver.SetWidescreen( CFG.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, CFG.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, CFG.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 (); ret = optionBrowser.GetClickedOption(); - if(ret >= 0) { - if(Settings.godmode == 1) { + if ( ret >= 0 ) + { + if ( Settings.godmode == 1 ) + { partitionEntry *entry = &partitions.pentry[ret]; - if (entry->size) { - if (load_from_fs == PART_FS_FAT) { - WBFS_OpenPart(partitions.pinfo[ret].part_fs, partitions.pinfo[ret].index, entry->sector, - entry->size, (char *) &game_partition); - load_from_fs = partitions.pinfo[ret].part_fs; - menu = MENU_DISCLIST; - - Settings.partition = ret; - if(isInserted(bootDevice))cfg_save_global(); - } else { - sprintf(text, "%s %d : %.2fGB",tr("Partition"), ret+1, entry->size * (partitions.sector_size / GB_SIZE)); - choice = WindowPrompt( tr("Do you want to format:"), text,tr("Yes"),tr("No")); - if (choice == 1) { - ret = FormatingPartition(tr("Formatting, please wait..."), entry); - if (ret < 0) { - WindowPrompt(tr("Error !"),tr("Failed formating"),tr("Return")); - menu = MENU_SETTINGS; - } else { - sleep(1); - ret = WBFS_Open(); - sprintf(text, "%s %s", text,tr("formatted!")); - WindowPrompt(tr("Success:"),text,tr("OK")); - if(ret < 0) { - WindowPrompt(tr("ERROR"), tr("Failed to open partition"), tr("OK")); - Sys_LoadMenu(); - } - menu = MENU_DISCLIST; - } - } - } - } else if(Settings.godmode == 0) { - mainWindow->Remove(&optionBrowser); + if ( entry->size ) + { + if ( load_from_fs == PART_FS_FAT ) + { + WBFS_OpenPart( partitions.pinfo[ret].part_fs, partitions.pinfo[ret].index, entry->sector, + entry->size, ( char * ) &game_partition ); + load_from_fs = partitions.pinfo[ret].part_fs; + menu = MENU_DISCLIST; + + Settings.partition = ret; + if ( isInserted( bootDevice ) )cfg_save_global(); + } + else + { + sprintf( text, "%s %d : %.2fGB", tr( "Partition" ), ret + 1, entry->size * ( partitions.sector_size / GB_SIZE ) ); + choice = WindowPrompt( tr( "Do you want to format:" ), text, tr( "Yes" ), tr( "No" ) ); + if ( choice == 1 ) + { + ret = FormatingPartition( tr( "Formatting, please wait..." ), entry ); + if ( ret < 0 ) + { + WindowPrompt( tr( "Error !" ), tr( "Failed formating" ), tr( "Return" ) ); + menu = MENU_SETTINGS; + } + else + { + sleep( 1 ); + ret = WBFS_Open(); + sprintf( text, "%s %s", text, tr( "formatted!" ) ); + WindowPrompt( tr( "Success:" ), text, tr( "OK" ) ); + if ( ret < 0 ) + { + WindowPrompt( tr( "ERROR" ), tr( "Failed to open partition" ), tr( "OK" ) ); + Sys_LoadMenu(); + } + menu = MENU_DISCLIST; + } + } + } + } + else if ( Settings.godmode == 0 ) + { + mainWindow->Remove( &optionBrowser ); char entered[20] = ""; - int result = OnScreenKeyboard(entered, 20,0); - mainWindow->Append(&optionBrowser); - if ( result == 1 ) { - if (!strcmp(entered, Settings.unlockCode)) { //if password correct - if (Settings.godmode == 0) { - WindowPrompt(tr("Correct Password"),tr("All the features of USB Loader GX are unlocked."),tr("OK")); + int result = OnScreenKeyboard( entered, 20, 0 ); + mainWindow->Append( &optionBrowser ); + if ( result == 1 ) + { + if ( !strcmp( entered, Settings.unlockCode ) ) //if password correct + { + if ( Settings.godmode == 0 ) + { + WindowPrompt( tr( "Correct Password" ), tr( "All the features of USB Loader GX are unlocked." ), tr( "OK" ) ); Settings.godmode = 1; } - } 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" ) ); } } } } } - if (shutdown == 1) + if ( shutdown == 1 ) Sys_Shutdown(); - if (reset == 1) + if ( reset == 1 ) Sys_Reboot(); - if (poweroffBtn.GetState() == STATE_CLICKED) { - choice = WindowPrompt (tr("Shutdown System"),tr("Are you sure?"),tr("Yes"),tr("No")); - if (choice == 1) { + if ( poweroffBtn.GetState() == STATE_CLICKED ) + { + choice = WindowPrompt ( tr( "Shutdown System" ), tr( "Are you sure?" ), tr( "Yes" ), tr( "No" ) ); + if ( choice == 1 ) + { Sys_Shutdown(); } - } else if (exitBtn.GetState() == STATE_CLICKED) { - choice = WindowPrompt (tr("Return to Wii Menu"),tr("Are you sure?"),tr("Yes"),tr("No")); - if (choice == 1) { + } + else if ( exitBtn.GetState() == STATE_CLICKED ) + { + choice = WindowPrompt ( tr( "Return to Wii Menu" ), tr( "Are you sure?" ), tr( "Yes" ), tr( "No" ) ); + if ( choice == 1 ) + { Sys_LoadMenu(); } } @@ -176,8 +205,8 @@ int MenuFormat() { 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 e416180a..dbcddb8b 100644 --- a/source/menu/menu_install.cpp +++ b/source/menu/menu_install.cpp @@ -12,146 +12,165 @@ float gamesize; * MenuInstall ***************************************************************************/ -int MenuInstall() { - gprintf("\nMenuInstall()"); +int MenuInstall() +{ + gprintf( "\nMenuInstall()" ); int menu = MENU_NONE; - static struct discHdr headerdisc ATTRIBUTE_ALIGN(32); + 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", CFG.theme_path); - GuiImageData battery(imgPath, battery_png); - snprintf(imgPath, sizeof(imgPath), "%sbattery_bar.png", CFG.theme_path); - GuiImageData batteryBar(imgPath, battery_bar_png); - snprintf(imgPath, sizeof(imgPath), "%sbattery_red.png", CFG.theme_path); - GuiImageData batteryRed(imgPath, battery_red_png); - snprintf(imgPath, sizeof(imgPath), "%sbattery_bar_red.png", CFG.theme_path); - GuiImageData batteryBarRed(imgPath, battery_bar_red_png); + snprintf( imgPath, sizeof( imgPath ), "%sbattery.png", CFG.theme_path ); + GuiImageData battery( imgPath, battery_png ); + snprintf( imgPath, sizeof( imgPath ), "%sbattery_bar.png", CFG.theme_path ); + GuiImageData batteryBar( imgPath, battery_bar_png ); + snprintf( imgPath, sizeof( imgPath ), "%sbattery_red.png", CFG.theme_path ); + GuiImageData batteryRed( imgPath, battery_red_png ); + snprintf( imgPath, sizeof( imgPath ), "%sbattery_bar_red.png", CFG.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 (); - ret = DiscWait(tr("Insert Disk"),tr("Waiting..."),tr("Cancel"),0,0); - if (ret < 0) { - WindowPrompt (tr("Error reading Disc"),0,tr("Back")); + ret = DiscWait( tr( "Insert Disk" ), tr( "Waiting..." ), tr( "Cancel" ), 0, 0 ); + if ( ret < 0 ) + { + WindowPrompt ( tr( "Error reading Disc" ), 0, tr( "Back" ) ); menu = MENU_DISCLIST; break; } ret = Disc_Open(); - if (ret < 0) { - WindowPrompt (tr("Could not open Disc"),0,tr("Back")); + if ( ret < 0 ) + { + WindowPrompt ( tr( "Could not open Disc" ), 0, tr( "Back" ) ); menu = MENU_DISCLIST; break; } ret = Disc_IsWii(); - if (ret < 0) { - choice = WindowPrompt (tr("Not a Wii Disc"),tr("Insert a Wii Disc!"),tr("OK"),tr("Back")); + if ( ret < 0 ) + { + 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 + } + 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) { - WindowPrompt (tr("Game is already installed:"),name,tr("Back")); + ret = WBFS_CheckGame( headerdisc.id ); + if ( ret ) + { + WindowPrompt ( tr( "Game is already installed:" ), name, tr( "Back" ) ); menu = MENU_DISCLIST; break; } f32 freespace, used; - WBFS_DiskSpace(&used, &freespace); - gamesize = WBFS_EstimeGameSize()/GB_SIZE; + 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); + } + else + { + USBStorage2_Watchdog( 0 ); + SetupGameInstallProgress( gametxt, name ); ret = WBFS_AddGame(); ProgressStop(); - USBStorage2_Watchdog(1); - wiilight(0); - if (ret != 0) { - WindowPrompt(tr("Install Error!"),0,tr("Back")); + USBStorage2_Watchdog( 1 ); + wiilight( 0 ); + if ( ret != 0 ) + { + WindowPrompt( tr( "Install Error!" ), 0, tr( "Back" ) ); menu = MENU_DISCLIST; break; - } else { + } + else + { gameList.ReadGameList(); //get the entries again 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->Play(); - WindowPrompt (tr("Successfully installed:"),name,tr("OK")); - instsuccess->Stop(); - delete instsuccess; - bgMusic->Resume(); + GuiSound * instsuccess = NULL; + bgMusic->Pause(); + instsuccess = new GuiSound( success_ogg, success_ogg_size, Settings.sfxvolume ); + instsuccess->SetVolume( Settings.sfxvolume ); + instsuccess->SetLoop( 0 ); + instsuccess->Play(); + WindowPrompt ( tr( "Successfully installed:" ), name, tr( "OK" ) ); + instsuccess->Stop(); + delete instsuccess; + bgMusic->Resume(); menu = MENU_DISCLIST; break; } } - } else { + } + else + { menu = MENU_DISCLIST; break; } - if (shutdown == 1) { - wiilight(0); + if ( shutdown == 1 ) + { + wiilight( 0 ); Sys_Shutdown(); } - if (reset == 1) { - wiilight(0); + if ( reset == 1 ) + { + 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 9c8f11f9..07529582 100644 --- a/source/mload/dip_plugin.c +++ b/source/mload/dip_plugin.c @@ -1,374 +1,375 @@ #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 27b5a072..6ea44c64 100644 --- a/source/mload/fatffs_util.c +++ b/source/mload/fatffs_util.c @@ -1,22 +1,22 @@ -/* - From Custom IOS Module (FAT) - - Copyright (C) 2009 Waninkoko. - Copyright (C) 2010 Hermes. +/* + From Custom IOS Module (FAT) - 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. + Copyright (C) 2009 Waninkoko. + Copyright (C) 2010 Hermes. - 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 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. - 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 */ @@ -31,261 +31,264 @@ extern u32 nand_mode; -s32 FAT_DeleteDir(const char *dirpath) +s32 FAT_DeleteDir( const char *dirpath ) { - DIR_ITER *dir; + DIR_ITER *dir; - s32 ret; + s32 ret; - /* Open directory */ - dir = diropen(dirpath); - if (!dir) - return -1; + /* Open directory */ + dir = diropen( dirpath ); + if ( !dir ) + return -1; - /* Read entries */ - for (;;) { - char filename[256], newpath[256]; - struct stat filestat; + /* Read entries */ + for ( ;; ) + { + char filename[256], newpath[256]; + struct stat filestat; - /* Read entry */ - if (dirnext(dir, filename, &filestat)) - break; + /* Read entry */ + if ( dirnext( dir, filename, &filestat ) ) + break; - /* Non valid entry */ - if (filename[0]=='.') - continue; + /* Non valid entry */ + if ( filename[0] == '.' ) + continue; - /* Generate entry path */ - strcpy(newpath, dirpath); - strcat(newpath, "/"); - strcat(newpath, filename); + /* Generate entry path */ + strcpy( newpath, dirpath ); + strcat( newpath, "/" ); + strcat( newpath, filename ); - /* Delete directory contents */ - if (filestat.st_mode & S_IFDIR) - FAT_DeleteDir(newpath); + /* Delete directory contents */ + if ( filestat.st_mode & S_IFDIR ) + FAT_DeleteDir( newpath ); - /* Delete object */ - ret = remove(newpath); + /* Delete object */ + ret = remove( newpath ); - /* Error */ - if (ret != 0) - break; - } + /* Error */ + if ( ret != 0 ) + break; + } - /* Close directory */ - dirclose(dir); + /* Close directory */ + dirclose( dir ); - return 0; + return 0; } -static int global_error=0; +static int global_error = 0; -static char temp_read_buffer[16384] ATTRIBUTE_ALIGN(32); +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; -int pos=0; -char *list; -s32 ret; + int n; + u32 blocks, ionodes; + int pos = 0; + char *list; + s32 ret; -u32 ionodes_temp; + 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 ( ISFS_ReadDir( ffsdirpath, list , &ionodes ) ) {free( list ); global_error = -3; return -3;} - if(ionodes) mkdir(fatdirpath, S_IRWXO | S_IRWXG | S_IRWXU); + if ( ionodes ) mkdir( fatdirpath, S_IRWXO | S_IRWXG | S_IRWXU ); - /* Read entries */ - for (n=0;n0) - { - 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) - { - global_error=-8; - break; - } - len-=ret; - } - - fclose(fp); - ISFS_Close(fd); + else // copy the file + { + int fd; + FILE *fp; + fd = ISFS_Open( newffspath, ISFS_OPEN_READ ); + if ( fd < 0 ) + { + global_error = -4; + 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;} - if(global_error) {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 ) + { + global_error = -8; + break; + } + len -= ret; + } - free(list); - return 0; + fclose( fp ); + ISFS_Close( fd ); + + if ( global_error ) {free( list ); return global_error;} + } + } + + } + + 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; + u32 blocks, ionodes; + int ret; -char create_dir[256]; + char create_dir[256]; - ISFS_Initialize(); + ISFS_Initialize(); - ret=ISFS_GetUsage(ffsdirpath, &blocks, &ionodes); + ret = ISFS_GetUsage( ffsdirpath, &blocks, &ionodes ); - if(ret==0) - { - int n=0; + if ( ret == 0 ) + { + int n = 0; - // creating the path directory + // 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) - { - if(create_dir[n]=='/') - { - create_dir[n]=0; - mkdir(create_dir, S_IRWXO | S_IRWXG | S_IRWXU); - create_dir[n]='/'; - } - n++; - } - global_error=0; - // copy files - _FFS_to_FAT_Copy(ffsdirpath, fatdirpath); + while ( create_dir[n] != 0 ) + { + if ( create_dir[n] == '/' ) + { + create_dir[n] = 0; + mkdir( create_dir, S_IRWXO | S_IRWXG | S_IRWXU ); + create_dir[n] = '/'; + } + n++; + } + global_error = 0; + // copy files + _FFS_to_FAT_Copy( ffsdirpath, fatdirpath ); - ret=global_error=0; - } - else ret=-101; + ret = global_error = 0; + } + else ret = -101; - ISFS_Deinitialize(); + ISFS_Deinitialize(); -return ret; - + 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 + 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 + 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_ITER * dir = NULL; - dir= diropen(directory); - - if(dir) {dirclose(dir);return 1;} + dir = diropen( directory ); -return 0; + if ( dir ) {dirclose( dir ); return 1;} + + return 0; } -char *get_FAT_directory1(void) +char *get_FAT_directory1( void ) { - return temp_cad+64; + return temp_cad + 64; } -char *get_FAT_directory2(void) +char *get_FAT_directory2( void ) { - return temp_cad+128; + return temp_cad + 128; } -char *get_FFS_directory1(void) +char *get_FFS_directory1( void ) { - return temp_cad+256; + return temp_cad + 256; } -char *get_FFS_directory2(void) +char *get_FFS_directory2( void ) { - return temp_cad+384; + return temp_cad + 384; } diff --git a/source/mload/fatffs_util.h b/source/mload/fatffs_util.h index c438776b..92fd7995 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 709b5067..47c18b5b 100644 --- a/source/mload/mload.c +++ b/source/mload/mload.c @@ -1,4 +1,4 @@ -/* mload.c (for PPC) (c) 2009, Hermes +/* mload.c (for PPC) (c) 2009, Hermes This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -21,7 +21,7 @@ #include "gecko.h" -static const char mload_fs[] ATTRIBUTE_ALIGN(32) = "/dev/mload"; +static const char mload_fs[] ATTRIBUTE_ALIGN( 32 ) = "/dev/mload"; //static u32 patch_datas[8] ATTRIBUTE_ALIGN(32); static s32 mload_fd = -1; @@ -37,45 +37,45 @@ static s32 hid = -1; int mload_init() { -int n; + int n; - if(hid<0) hid = iosCreateHeap(0x800); + if ( hid < 0 ) hid = iosCreateHeap( 0x800 ); - if(hid<0) - { - if(mload_fd>=0) - IOS_Close(mload_fd); + if ( hid < 0 ) + { + if ( mload_fd >= 0 ) + IOS_Close( mload_fd ); - mload_fd=-1; + mload_fd = -1; - return hid; - } + return hid; + } - if(mload_fd>=0) - { - return 0; - } + if ( mload_fd >= 0 ) + { + return 0; + } - for(n=0;n<20;n++) // try 5 seconds - { - mload_fd=IOS_Open(mload_fs, 0); - - if(mload_fd>=0) break; + for ( n = 0; n < 20; n++ ) // try 5 seconds + { + mload_fd = IOS_Open( mload_fs, 0 ); - usleep(250*1000); - } + if ( mload_fd >= 0 ) break; - if(mload_fd<0) - { - - if(hid>=0) - { - iosDestroyHeap(hid); - hid=-1; - } - } + usleep( 250*1000 ); + } -return mload_fd; + if ( mload_fd < 0 ) + { + + if ( hid >= 0 ) + { + iosDestroyHeap( hid ); + hid = -1; + } + } + + return mload_fd; } /*--------------------------------------------------------------------------------------------------------------*/ @@ -84,21 +84,21 @@ return mload_fd; int mload_close() { -int ret; + int ret; - if(hid>=0) - { - iosDestroyHeap(hid); - hid=-1; - } + if ( hid >= 0 ) + { + iosDestroyHeap( hid ); + hid = -1; + } - if(mload_fd<0) return -1; - - ret=IOS_Close(mload_fd); - - mload_fd=-1; + if ( mload_fd < 0 ) return -1; -return ret; + ret = IOS_Close( mload_fd ); + + mload_fd = -1; + + return ret; } /*--------------------------------------------------------------------------------------------------------------*/ @@ -107,13 +107,13 @@ return ret; int mload_get_thread_id() { -int ret; + int ret; - if(mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_MLOAD_THREAD_ID, ":"); + if ( mload_init() < 0 ) return -1; -return ret; + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_MLOAD_THREAD_ID, ":" ); + + return ret; } @@ -121,15 +121,15 @@ return ret; // 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; + int ret; - if(mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GET_LOAD_BASE, ":ii",starlet_base, size); + if ( mload_init() < 0 ) return -1; -return ret; + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_GET_LOAD_BASE, ":ii", starlet_base, size ); + + return ret; } @@ -138,47 +138,47 @@ return ret; // 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; + int ret; + void *buf = NULL; - if(mload_init()<0) return -1; + if ( mload_init() < 0 ) return -1; - if(hid>=0) - { - iosDestroyHeap(hid); - hid=-1; - } + if ( hid >= 0 ) + { + iosDestroyHeap( hid ); + hid = -1; + } - hid = iosCreateHeap(len+0x800); - - if(hid<0) return hid; + hid = iosCreateHeap( len + 0x800 ); - buf= iosAlloc(hid, len); + if ( hid < 0 ) return hid; - if(!buf) {ret= -1;goto out;} + buf = iosAlloc( hid, len ); - - memcpy(buf, addr,len); + if ( !buf ) {ret = -1; goto out;} - 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, ":"); + memcpy( buf, addr, len ); + + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_LOAD_MODULE, ":d", buf, len ); + + if ( ret < 0 ) goto out; + + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_RUN_MODULE, ":" ); + + if ( ret < 0 ) {ret = -666; goto out;} - if(ret<0) {ret= -666;goto out;} - out: - if(hid>=0) - { - iosDestroyHeap(hid); - hid=-1; - } - -return ret; + if ( hid >= 0 ) + { + iosDestroyHeap( hid ); + hid = -1; + } + + return ret; } @@ -187,103 +187,102 @@ return ret; // 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; + int n, m; + int p; + u8 *adr; + u32 elf = ( u32 ) my_elf; -if(elf & 3) return -1; // aligned to 4 please! + if ( elf & 3 ) return -1; // aligned to 4 please! -elfheader *head=(void *) elf; -elfphentry *entries; + elfheader *head = ( void * ) elf; + elfphentry *entries; -if(head->ident0!=0x7F454C46) return -1; -if(head->ident1!=0x01020161) return -1; -if(head->ident2!=0x01000000) return -1; + if ( head->ident0 != 0x7F454C46 ) return -1; + if ( head->ident1 != 0x01020161 ) return -1; + if ( head->ident2 != 0x01000000 ) return -1; -p=head->phoff; + p = head->phoff; -data_elf->start=(void *) head->entry; + data_elf->start = ( void * ) head->entry; -for(n=0; nphnum; n++) - { - entries=(void *) (elf+p); - p+=sizeof(elfphentry); + for ( n = 0; n < head->phnum; n++ ) + { + entries = ( void * ) ( elf + p ); + p += sizeof( elfphentry ); - if(entries->type == 4) - { - adr=(void *) (elf + entries->offset); + if ( entries->type == 4 ) + { + adr = ( void * ) ( elf + entries->offset ); - if(getbe32(0)!=0) return -2; // bad info (sure) + if ( getbe32( 0 ) != 0 ) return -2; // bad info (sure) - for(m=4; m < entries->memsz; m+=8) - { - switch(getbe32(m)) - { - case 0x9: - data_elf->start= (void *) getbe32(m+4); - break; - case 0x7D: - data_elf->prio= getbe32(m+4); - break; - case 0x7E: - data_elf->size_stack= getbe32(m+4); - break; - case 0x7F: - data_elf->stack= (void *) (getbe32(m+4)); - break; - - } + for ( m = 4; m < entries->memsz; m += 8 ) + { + switch ( getbe32( m ) ) + { + case 0x9: + data_elf->start = ( void * ) getbe32( m + 4 ); + break; + case 0x7D: + data_elf->prio = getbe32( m + 4 ); + break; + case 0x7E: + data_elf->size_stack = getbe32( m + 4 ); + break; + case 0x7F: + data_elf->stack = ( void * ) ( getbe32( m + 4 ) ); + break; - } + } - } - else - if(entries->type == 1 && entries->memsz != 0 && entries->vaddr!=0) - { + } - 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; - - } - } + } + else if ( entries->type == 1 && entries->memsz != 0 && entries->vaddr != 0 ) + { -return 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; + + } + } + + return 0; } /*--------------------------------------------------------------------------------------------------------------*/ // run one thread (you can use to load modules or binary files) -int mload_run_thread(void *starlet_addr, void *starlet_top_stack, int stack_size, int priority) +int mload_run_thread( void *starlet_addr, void *starlet_top_stack, int stack_size, int priority ) { -int ret; + int ret; - if(mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_RUN_THREAD, "iiii:", starlet_addr,starlet_top_stack, stack_size, priority); + if ( mload_init() < 0 ) return -1; + + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_RUN_THREAD, "iiii:", starlet_addr, starlet_top_stack, stack_size, priority ); -return ret; + return ret; } /*--------------------------------------------------------------------------------------------------------------*/ // stops one starlet thread -int mload_stop_thread(int id) +int mload_stop_thread( int id ) { -int ret; + int ret; - if(mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_STOP_THREAD, "i:", id); + if ( mload_init() < 0 ) return -1; -return ret; + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_STOP_THREAD, "i:", id ); + + return ret; } @@ -291,64 +290,64 @@ return ret; // continue one stopped starlet thread -int mload_continue_thread(int id) +int mload_continue_thread( int id ) { -int ret; + int ret; - if(mload_init()<0) return -1; + if ( mload_init() < 0 ) return -1; - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_CONTINUE_THREAD, "i:", id); - -return ret; + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_CONTINUE_THREAD, "i:", id ); + + return ret; } /*--------------------------------------------------------------------------------------------------------------*/ // fix starlet address to read/write (uses SEEK_SET, etc as mode) -int mload_seek(int offset, int mode) +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; + int ret; - if(mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_MEMSET, "iii:", starlet_addr, set, len); + if ( mload_init() < 0 ) return -1; + + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_MEMSET, "iii:", starlet_addr, set, len ); -return ret; + return ret; } /*--------------------------------------------------------------------------------------------------------------*/ @@ -357,97 +356,97 @@ return ret; void * mload_get_ehci_data() { -int ret; + int ret; - if(mload_init()<0) return NULL; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GET_EHCI_DATA, ":"); - if(ret<0) return NULL; + if ( mload_init() < 0 ) return NULL; -return (void *) ret; + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_GET_EHCI_DATA, ":" ); + if ( ret < 0 ) return NULL; + + 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; + int ret; - if(mload_init()<0) return -1; + if ( mload_init() < 0 ) return -1; - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_SET_ES_IOCTLV, "i:", starlet_addr); - -return ret; + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_SET_ES_IOCTLV, "i:", starlet_addr ); + + return ret; } -int mload_getw(const void * addr, u32 *dat) +int mload_getw( const void * addr, u32 *dat ) { -int ret; + int ret; - if(mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GETW, "i:i", addr, dat); + if ( mload_init() < 0 ) return -1; -return ret; + 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; + int ret; - if(mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GETH, "i:h", addr, dat); - -return ret; + if ( mload_init() < 0 ) return -1; + + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_GETH, "i:h", addr, dat ); + + return ret; } -int mload_getb(const void * addr, u8 *dat) +int mload_getb( const void * addr, u8 *dat ) { -int ret; + int ret; - if(mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GETB, "i:b", addr, dat); - -return ret; + if ( mload_init() < 0 ) return -1; + + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_GETB, "i:b", addr, dat ); + + return ret; } -int mload_setw(const void * addr, u32 dat) +int mload_setw( const void * addr, u32 dat ) { -int ret; + int ret; - if(mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_SETW, "ii:", addr, dat); - -return ret; + if ( mload_init() < 0 ) return -1; + + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_SETW, "ii:", addr, dat ); + + return ret; } -int mload_seth(const void * addr, u16 dat) +int mload_seth( const void * addr, u16 dat ) { -int ret; + int ret; - if(mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_SETH, "ih:", addr, dat); + if ( mload_init() < 0 ) return -1; -return ret; + 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; + int ret; - if(mload_init()<0) return -1; + if ( mload_init() < 0 ) return -1; - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_SETB, "ib:", addr, dat); + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_SETB, "ib:", addr, dat ); -return ret; + return ret; } /*--------------------------------------------------------------------------------------------------------------*/ @@ -457,13 +456,13 @@ return ret; int mload_get_log() { -int ret; + int ret; - if(mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GET_LOG, ":"); + if ( mload_init() < 0 ) return -1; -return ret; + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_GET_LOG, ":" ); + + return ret; } @@ -474,116 +473,116 @@ return ret; int mload_get_IOS_base() { -int ret; + int ret; - if(mload_init()<0) return -1; - - ret= IOS_IoctlvFormat(hid, mload_fd, MLOAD_GET_IOS_BASE, ":"); + if ( mload_init() < 0 ) return -1; -return ret; + ret = IOS_IoctlvFormat( hid, mload_fd, MLOAD_GET_IOS_BASE, ":" ); + + return ret; } /* int load_ehc_module() { - int is_ios=0; - FILE *fp; + 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;} - - fclose(fp); - } - } - } - - 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(fread(external_ehcmodule,1, size_external_ehcmodule ,fp)!=size_external_ehcmodule) + {free(external_ehcmodule); external_ehcmodule=NULL;} - // 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; - } + fclose(fp); + } + } + } - 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); + if(!external_ehcmodule) + { + if(mload_init()<0) return -1; - // enables DIP plugin - mload_seek(0x20209040, SEEK_SET); - mload_write(ios_36, 4); - - } - if(is_ios==38) - { - // IOS 38 + 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); - 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); - // enables DIP plugin - mload_seek(0x20208030, SEEK_SET); - mload_write(ios_38, 4); + // 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 - mload_close(); + mload_seek(0x1377E000, SEEK_SET); // copy dip_plugin in the starlet + mload_write(dip_plugin,size_dip_plugin); + + // enables DIP plugin + mload_seek(0x20209040, SEEK_SET); + mload_write(ios_36, 4); + + } + if(is_ios==38) + { + // IOS 38 + + 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); + + // enables DIP plugin + mload_seek(0x20208030, SEEK_SET); + mload_write(ios_38, 4); + + } + + mload_close(); return 0; } diff --git a/source/mload/mload.h b/source/mload/mload.h index b360faf6..faf5efa3 100644 --- a/source/mload/mload.h +++ b/source/mload/mload.h @@ -1,4 +1,4 @@ -/* mload.c (for PPC) (c) 2009, Hermes +/* mload.c (for PPC) (c) 2009, Hermes This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -26,32 +26,33 @@ #include #include "unistd.h" -#define MLOAD_MLOAD_THREAD_ID 0x4D4C4400 -#define MLOAD_GET_IOS_BASE 0x4D4C4401 -#define MLOAD_LOAD_MODULE 0x4D4C4480 -#define MLOAD_RUN_MODULE 0x4D4C4481 +#define MLOAD_MLOAD_THREAD_ID 0x4D4C4400 +#define MLOAD_GET_IOS_BASE 0x4D4C4401 +#define MLOAD_LOAD_MODULE 0x4D4C4480 +#define MLOAD_RUN_MODULE 0x4D4C4481 #define MLOAD_RUN_THREAD 0x4D4C4482 -#define MLOAD_STOP_THREAD 0x4D4C4484 +#define MLOAD_STOP_THREAD 0x4D4C4484 #define MLOAD_CONTINUE_THREAD 0x4D4C4485 #define MLOAD_GET_LOAD_BASE 0x4D4C4490 -#define MLOAD_MEMSET 0x4D4C4491 +#define MLOAD_MEMSET 0x4D4C4491 -#define MLOAD_GET_EHCI_DATA 0x4D4C44A0 -#define MLOAD_GET_LOG 0x4D4C44A1 +#define MLOAD_GET_EHCI_DATA 0x4D4C44A0 +#define MLOAD_GET_LOG 0x4D4C44A1 -#define MLOAD_SET_ES_IOCTLV 0x4D4C44B0 +#define MLOAD_SET_ES_IOCTLV 0x4D4C44B0 -#define MLOAD_GETW 0x4D4C44C0 -#define MLOAD_GETH 0x4D4C44C1 -#define MLOAD_GETB 0x4D4C44C2 -#define MLOAD_SETW 0x4D4C44C3 -#define MLOAD_SETH 0x4D4C44C4 -#define MLOAD_SETB 0x4D4C44C5 +#define MLOAD_GETW 0x4D4C44C0 +#define MLOAD_GETH 0x4D4C44C1 +#define MLOAD_GETB 0x4D4C44C2 +#define MLOAD_SETW 0x4D4C44C3 +#define MLOAD_SETH 0x4D4C44C4 +#define MLOAD_SETB 0x4D4C44C5 #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif @@ -59,169 +60,169 @@ extern "C" { #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; + typedef struct + { + u32 ident0; + u32 ident1; + u32 ident2; + u32 ident3; + u32 machinetype; + u32 version; + u32 entry; u32 phoff; u32 shoff; - u32 flags; + u32 flags; u16 ehsize; u16 phentsize; u16 phnum; u16 shentsize; u16 shnum; u16 shtrndx; -} elfheader; + } elfheader; -typedef struct -{ - u32 type; - u32 offset; - u32 vaddr; - u32 paddr; - u32 filesz; - u32 memsz; - u32 flags; - u32 align; -} elfphentry; + typedef struct + { + u32 type; + u32 offset; + u32 vaddr; + u32 paddr; + u32 filesz; + u32 memsz; + u32 flags; + u32 align; + } elfphentry; -typedef struct -{ - void *start; - int prio; - void *stack; - int size_stack; -} data_elf; + typedef struct + { + void *start; + int prio; + void *stack; + int size_stack; + } data_elf; -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // to init/test if the device is running -int mload_init(); + int mload_init(); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // to close the device (remember call it when rebooting the IOS!) -int mload_close(); + int mload_close(); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // to get the thread id of mload -int mload_get_thread_id(); + int mload_get_thread_id(); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // get the base and the size of the memory readable/writable to load modules -int mload_get_load_base(u32 *starlet_base, int *size); + int mload_get_load_base( u32 *starlet_base, int *size ); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // load and run a module from starlet (it need to allocate MEM2 to send the elf file) // the module must be a elf made with stripios -int mload_module(void *addr, int len); + int mload_module( void *addr, int len ); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // load a module from the PPC // the module must be a elf made with stripios -int mload_elf(void *my_elf, data_elf *data_elf); + int mload_elf( void *my_elf, data_elf *data_elf ); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // run one thread (you can use to load modules or binary files) -int mload_run_thread(void *starlet_addr, void *starlet_top_stack, int stack_size, int priority); + int mload_run_thread( void *starlet_addr, void *starlet_top_stack, int stack_size, int priority ); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // stops one starlet thread -int mload_stop_thread(int id); + int mload_stop_thread( int id ); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // continue one stopped starlet thread -int mload_continue_thread(int id); + int mload_continue_thread( int id ); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // fix starlet address to read/write (uses SEEK_SET, etc as mode) -int mload_seek(int offset, int mode); + int mload_seek( int offset, int mode ); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // read bytes from starlet (it update the offset) -int mload_read(void* buf, u32 size); + int mload_read( void* buf, u32 size ); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // write bytes from starlet (it update the offset) -int mload_write(const void * buf, u32 size); + int mload_write( const void * buf, u32 size ); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // fill a block (similar to memset) -int mload_memset(void *starlet_addr, int set, int len); + int mload_memset( void *starlet_addr, int set, int len ); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // get the ehci datas ( ehcmodule.elf uses this address) -void * mload_get_ehci_data(); + void * mload_get_ehci_data(); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // set the dev/es ioctlv in routine -int mload_set_ES_ioctlv_vector(void *starlet_addr); + int mload_set_ES_ioctlv_vector( void *starlet_addr ); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // to get log buffer // this function return the size of the log buffer and prepare it to read with mload_read() the datas -int mload_get_log(); + int mload_get_log(); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ // to get IOS base for dev/es to create the cIOS -int mload_get_IOS_base(); + int mload_get_IOS_base(); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ -int mload_getw(const void * addr, u32 *dat); -int mload_geth(const void * addr, u16 *dat); -int mload_getb(const void * addr, u8 *dat); + int mload_getw( const void * addr, u32 *dat ); + int mload_geth( const void * addr, u16 *dat ); + int mload_getb( const void * addr, u8 *dat ); -int mload_setw(const void * addr, u32 dat); -int mload_seth(const void * addr, u16 dat); -int mload_setb(const void * addr, u8 dat); + int mload_setw( const void * addr, u32 dat ); + int mload_seth( const void * addr, u16 dat ); + int mload_setb( const void * addr, u8 dat ); -/*--------------------------------------------------------------------------------------------------------------*/ + /*--------------------------------------------------------------------------------------------------------------*/ #ifdef __cplusplus - } +} #endif diff --git a/source/mload/mload_modules.c b/source/mload/mload_modules.c index a1090d51..d0352fe9 100644 --- a/source/mload/mload_modules.c +++ b/source/mload/mload_modules.c @@ -9,492 +9,505 @@ /* Used for Hermes NAND emulation */ int global_mount; -int sd_ok=0; -int ud_ok=0; +int sd_ok = 0; +int ud_ok = 0; -static u32 ios_36[16] ATTRIBUTE_ALIGN(32)= +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) + 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)= +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) + 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)= +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) + 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)= +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) + 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)= +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) + 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); +u32 patch_datas[8] ATTRIBUTE_ALIGN( 32 ); data_elf my_data_elf; -void *external_ehcmodule= NULL; -int size_external_ehcmodule=0; +void *external_ehcmodule = NULL; +int size_external_ehcmodule = 0; -static int my_thread_id=0; +static int my_thread_id = 0; int load_ehc_module() { -int is_ios=0; + int is_ios = 0; #if 0 -FILE *fp; + FILE *fp; // WARNING!!!: load external module suspended -if(sd_ok && !external_ehcmodule) - { + 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/usbloader_gx/ehcmodule.elf", "rb" ); + if ( fp == NULL ) + fp = fopen( "sd:/apps/usbloadergx/ehcmodule.elf", "rb" ); - if(fp!=0) - { - 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 ( fp != 0 ) + { + 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;} - - fclose(fp); - } - } - } + if ( fread( external_ehcmodule, 1, size_external_ehcmodule , fp ) != size_external_ehcmodule ) + {free( external_ehcmodule ); external_ehcmodule = NULL;} + + fclose( fp ); + } + } + } #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(!external_ehcmodule) - { + /* + 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 ) + { #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); - } else if (IOS_GetRevision() == 65535) { + mload_elf( ( void * ) ehcmodule_frag_v4_bin, &my_data_elf ); + } + 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); - } else { - return -2; - } -// mload_elf((void *) ehcmodule, &my_data_elf); + mload_elf( ( void * ) ehcmodule_frag_v5_bin, &my_data_elf ); + } + else + { + return -2; + } +// 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; - //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; - } - usleep(350*1000); - + 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; + } + usleep( 350*1000 ); - // Test for IOS - #if 0 - mload_seek(0x20207c84, SEEK_SET); - mload_read(patch_datas, 32); - if(patch_datas[0]==0x6e657665 ) - { - is_ios=38; - } - else - { - is_ios=36; - } + // Test for IOS + +#if 0 + mload_seek( 0x20207c84, SEEK_SET ); + mload_read( patch_datas, 32 ); + if ( patch_datas[0] == 0x6e657665 ) + { + is_ios = 38; + } + else + { + is_ios = 36; + } #endif - is_ios=mload_get_IOS_base(); - - switch(is_ios) - { + is_ios = mload_get_IOS_base(); - 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 - - mload_seek(0x1377E000, SEEK_SET); // copy dip_plugin in the starlet - mload_write(dip_plugin,size_dip_plugin); + switch ( is_ios ) + { - // enables DIP plugin - mload_seek(0x20209040, SEEK_SET); - mload_write(ios_36, 4); - break; - - case 37: + case 36: - 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); + memcpy( ios_36, dip_plugin, 4 ); // copy the entry_point + memcpy( dip_plugin, ios_36, 4*10 ); // copy the adresses from the array - // enables DIP plugin - mload_seek(0x20209030, SEEK_SET); - mload_write(ios_37, 4); - break; + mload_seek( 0x1377E000, SEEK_SET ); // copy dip_plugin in the starlet + mload_write( dip_plugin, size_dip_plugin ); - case 38: + // enables DIP plugin + mload_seek( 0x20209040, SEEK_SET ); + mload_write( ios_36, 4 ); + break; - 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); + case 37: - // enables DIP plugin - mload_seek(0x20208030, SEEK_SET); - mload_write(ios_38, 4); - break; + memcpy( ios_37, dip_plugin, 4 ); // copy the entry_point + memcpy( dip_plugin, ios_37, 4*10 ); // copy the adresses from the array - case 57: + mload_seek( 0x1377E000, SEEK_SET ); // copy dip_plugin in the starlet + mload_write( dip_plugin, size_dip_plugin ); - 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); + // enables DIP plugin + mload_seek( 0x20209030, SEEK_SET ); + mload_write( ios_37, 4 ); + break; - // enables DIP plugin - mload_seek(0x20208030, SEEK_SET); - mload_write(ios_57, 4); - break; - - case 60: + case 38: - 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); + memcpy( ios_38, dip_plugin, 4 ); // copy the entry_point + memcpy( dip_plugin, ios_38, 4*10 ); // copy the adresses from the array - // enables DIP plugin - mload_seek(0x20208030, SEEK_SET); - mload_write(ios_60, 4); - break; + 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 ); + break; - mload_close(); + case 57: -return 0; + 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 ); + + // enables DIP plugin + 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 + + 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 ); + break; + + } + + mload_close(); + + return 0; } -#define IOCTL_FAT_MOUNTSD 0xF0 -#define IOCTL_FAT_UMOUNTSD 0xF1 -#define IOCTL_FAT_MOUNTUSB 0xF2 -#define IOCTL_FAT_UMOUNTUSB 0xF3 +#define IOCTL_FAT_MOUNTSD 0xF0 +#define IOCTL_FAT_UMOUNTSD 0xF1 +#define IOCTL_FAT_MOUNTUSB 0xF2 +#define IOCTL_FAT_UMOUNTUSB 0xF3 -#define IOCTL_FFS_MODE 0x80 +#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:"; - int n; - char *p; - s32 ret; + static char fs[] ATTRIBUTE_ALIGN( 32 ) = "fat"; + s32 hid = -1, fd = -1; + static char file_name[256] ALIGNED( 0x20 ) = "SD:"; + int n; + char *p; + s32 ret; - p=&file_name[0]; + 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; + global_mount &= ~0xc; - if(discid) - { - sd_ok=ud_ok=1; - - /* Function get_fat_name not implemented, this should return the path to the save file */ - // p=get_fat_name(discid); - p = NULL; - - sd_ok=ud_ok=0; - - if(!p) return -1; + if ( discid ) + { + sd_ok = ud_ok = 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);} + /* Function get_fat_name not implemented, this should return the path to the save file */ + // p=get_fat_name(discid); + p = NULL; - // 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_close(); + sd_ok = ud_ok = 0; - - } - else - { - if((global_mount & 3)==0) return 0; - if(global_mount & 1) p[0]='s'; - if(global_mount & 2) p[0]='u'; - } - usleep(350*1000); + if ( !p ) return -1; - /* Create heap */ - if (hid < 0) { - hid = iosCreateHeap(0x100); - if (hid < 0) - return -1; - } + global_mount &= ~0xf; - /* Open USB device */ - fd = IOS_Open(fs, 0); - - if (fd < 0) - { - if(hid>=0) - { - iosDestroyHeap(hid); - hid=-1; - } - return -1; - } - - n=30; // try 20 times - 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 & 7)==3 && ret==0) - {ret=IOS_IoctlvFormat(hid, fd, IOCTL_FAT_MOUNTSD, ":");if(ret==0) global_mount|=4;} + // 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((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); - n--; - } + // 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_close(); - if (fd >= 0) { - IOS_Close(fd); - fd = -1; - } - if(hid>=0) - { - iosDestroyHeap(hid); - hid=-1; - } - - if(n==0) return -1; + } + else + { + if ( ( global_mount & 3 ) == 0 ) return 0; + if ( global_mount & 1 ) p[0] = 's'; + if ( global_mount & 2 ) p[0] = 'u'; + } + usleep( 350*1000 ); -return 0; + /* Create heap */ + if ( hid < 0 ) + { + hid = iosCreateHeap( 0x100 ); + if ( hid < 0 ) + return -1; + } + + /* Open USB device */ + fd = IOS_Open( fs, 0 ); + + if ( fd < 0 ) + { + if ( hid >= 0 ) + { + iosDestroyHeap( hid ); + hid = -1; + } + return -1; + } + + n = 30; // try 20 times + 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 & 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;} + else ret = -1; + + //ret=IOS_IoctlvFormat(hid, fd, IOCTL_FAT_MOUNTSD, ":"); + //if(ret==0) break; + usleep( 500*1000 ); + n--; + } + + if ( fd >= 0 ) + { + IOS_Close( fd ); + fd = -1; + } + + if ( hid >= 0 ) + { + iosDestroyHeap( hid ); + hid = -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; + static char fs[] ATTRIBUTE_ALIGN( 32 ) = "fat"; + s32 hid = -1, fd = -1; + s32 ret; - /* Create heap */ - if (hid < 0) { - hid = iosCreateHeap(0x100); - if (hid < 0) - return -1; - } + /* Create heap */ + if ( hid < 0 ) + { + hid = iosCreateHeap( 0x100 ); + if ( hid < 0 ) + return -1; + } - /* Open USB device */ - fd = IOS_Open(fs, 0); - - if (fd < 0) - { - if(hid>=0) - { - iosDestroyHeap(hid); - hid=-1; - } - return -1; - } + /* Open USB device */ + fd = IOS_Open( fs, 0 ); + + if ( fd < 0 ) + { + if ( hid >= 0 ) + { + iosDestroyHeap( hid ); + hid = -1; + } + return -1; + } - ret=IOS_IoctlvFormat(hid, fd, IOCTL_FFS_MODE, "i:", mode); - - - if (fd >= 0) { - IOS_Close(fd); - fd = -1; - } - - if(hid>=0) - { - iosDestroyHeap(hid); - hid=-1; - } - + ret = IOS_IoctlvFormat( hid, fd, IOCTL_FFS_MODE, "i:", mode ); -return ret; + if ( fd >= 0 ) + { + IOS_Close( fd ); + fd = -1; + } + + if ( hid >= 0 ) + { + 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_close(); + // 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_close(); } -u8 *search_for_ehcmodule_cfg(u8 *p, int size) +u8 *search_for_ehcmodule_cfg( u8 *p, int size ) { - int n; + int n; - for(n=0;n #include #include @@ -43,49 +43,49 @@ 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()) + if ( !IsNetworkInit() ) return false; - struct block file = downloadfile(url); + struct block file = downloadfile( url ); - if (!file.data || !file.size) + 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) + if ( !HTML_File ) return NULL; - while((u32) position < filesize) + while ( ( u32 ) position < filesize ) { - if(htmlstringcompare(HTML_File, string, position) == 0) + if ( htmlstringcompare( HTML_File, string, position ) == 0 ) break; position++; @@ -94,56 +94,56 @@ 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) + if ( !HTML_File ) return NULL; - while((u32) position < filesize) + while ( ( u32 ) position < filesize ) { - if(htmlstringcompare(HTML_File, string, position) == 0) + 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) + if ( !stopat || !HTML_File ) return NULL; u32 blocksize = 1024; u32 counter = 0; u32 allocatedsize = 0; - char * outtext = (char*) malloc(blocksize); - if(!outtext) + 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 +156,17 @@ 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) + if ( !HTML_File ) return -1; - switch(origin) + switch ( origin ) { case SEEK_SET: position = pos; @@ -175,7 +175,7 @@ int HTML_Stream::Seek(u32 pos, int origin) position += pos; break; case SEEK_END: - position = filesize+pos; + position = filesize + pos; break; } @@ -184,7 +184,7 @@ int HTML_Stream::Seek(u32 pos, int origin) void HTML_Stream::Rewind() { - if(!HTML_File) + if ( !HTML_File ) return; position = 0; diff --git a/source/network/HTML_Stream.h b/source/network/HTML_Stream.h index e696ce0c..d2647938 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 0f9cf83b..446480fe 100644 --- a/source/network/URL_List.cpp +++ b/source/network/URL_List.cpp @@ -11,18 +11,21 @@ #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; } @@ -30,62 +33,70 @@ URL_List::URL_List(const char * url) { u32 cnt = 0; char temp[1024]; - Links = (Link_Info *) malloc(sizeof(Link_Info)); - if (!Links) { - free(file.data); + Links = ( Link_Info * ) malloc( sizeof( Link_Info ) ); + if ( !Links ) + { + 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++; cnt++; } 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) { - for (int i = 0; i == urlcount; i++) { + if ( !Links ) + { + 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]; - if (!Links[urlcount].URL) { - for (int i = 0; i == urlcount; i++) { + if ( !Links[urlcount].URL ) + { + 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; @@ -95,38 +106,45 @@ URL_List::URL_List(const char * url) { cnt++; } - free(file.data); + free( file.data ); } -URL_List::~URL_List() { - for (int i = 0; i == urlcount; i++) { +URL_List::~URL_List() +{ + for ( int i = 0; i == urlcount; i++ ) + { delete Links[i].URL; Links[i].URL = NULL; } - if (Links != NULL) { - free(Links); + if ( Links != NULL ) + { + free( Links ); Links = NULL; } } -char * URL_List::GetURL(int ind) { - if (ind > urlcount || ind < 0 || !Links || urlcount <= 0) +char * URL_List::GetURL( int ind ) +{ + if ( ind > urlcount || ind < 0 || !Links || urlcount <= 0 ) return NULL; else return Links[ind].URL; } -int URL_List::GetURLCount() { +int URL_List::GetURLCount() +{ return urlcount; } -static int ListCompare(const void *a, const void *b) { - Link_Info *ab = (Link_Info*) a; - Link_Info *bb = (Link_Info*) b; +static int ListCompare( const void *a, const void *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); +void URL_List::SortList() +{ + qsort( Links, urlcount, sizeof( Link_Info ), ListCompare ); } diff --git a/source/network/URL_List.h b/source/network/URL_List.h index 79caee7c..08cd2977 100644 --- a/source/network/URL_List.h +++ b/source/network/URL_List.h @@ -9,30 +9,32 @@ #include "network/networkops.h" #include "network/http.h" -typedef struct { +typedef struct +{ char *URL; bool direct; } Link_Info; -class URL_List { -public: - //!Constructor - //!\param url from where to get the list of links - URL_List(const char *url); - //!Destructor - ~URL_List(); - //! Get the a filepath of the list - //!\param list index - char * GetURL(int index); - //! Is it a direct URL or just a file or path under the main url - bool IsDirectURL(int index); - //! Get the number of links counted - int GetURLCount(); - //! Sort list - void SortList(); -protected: - int urlcount; - Link_Info *Links; +class URL_List +{ + public: + //!Constructor + //!\param url from where to get the list of links + URL_List( const char *url ); + //!Destructor + ~URL_List(); + //! Get the a filepath of the list + //!\param list index + char * GetURL( int index ); + //! Is it a direct URL or just a file or path under the main url + bool IsDirectURL( int index ); + //! Get the number of links counted + int GetURLCount(); + //! Sort list + void SortList(); + protected: + int urlcount; + Link_Info *Links; }; #endif diff --git a/source/network/dns.c b/source/network/dns.c index 07d15288..dd3bbf5e 100644 --- a/source/network/dns.c +++ b/source/network/dns.c @@ -8,17 +8,19 @@ * @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; } @@ -30,7 +32,8 @@ u32 getipbyname(char *domain) { //The cache is defined as a linked list, //The last resolved domain name will always be at the front //This will allow heavily used domainnames to always stay cached -struct dnsentry { +struct dnsentry +{ char *domain; u32 ip; struct dnsentry *nextnode; @@ -43,18 +46,21 @@ 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) { - if (strcmp(node->domain, domain) == 0) { + while ( node != NULL ) + { + if ( strcmp( node->domain, domain ) == 0 ) + { //DNS node found in the cache, move it to the front of the list - if (previousnode != NULL) + if ( previousnode != NULL ) previousnode->nextnode = node->nextnode; - if (node != firstdnsentry) + if ( node != firstdnsentry ) node->nextnode = firstdnsentry; firstdnsentry = node; @@ -64,48 +70,57 @@ 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) { - free(newnode); + newnode->domain = malloc( strlen( domain ) + 1 ); + if ( newnode->domain == NULL ) + { + 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) { - printf("Configuration error, MAX_DNS_ENTRIES reached while the list is empty\n"); - exit(1); - } else if (previousnode == NULL) { + if ( node == NULL ) + { + printf( "Configuration error, MAX_DNS_ENTRIES reached while the list is empty\n" ); + exit( 1 ); + } + else if ( previousnode == NULL ) + { firstdnsentry = NULL; - } else { + } + else + { 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 b9313a0e..5e6dc9bf 100644 --- a/source/network/dns.h +++ b/source/network/dns.h @@ -9,11 +9,12 @@ #include //usleep #ifdef __cplusplus -extern "C" { +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 34ea7009..a107c9ce 100644 --- a/source/network/http.c +++ b/source/network/http.c @@ -14,16 +14,23 @@ const struct block emptyblock = {0, NULL}; #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) { - if ((bytes_transferred = net_write(server, msg, remaining > NET_BUFFER_SIZE ? NET_BUFFER_SIZE : remaining)) > 0) { + s32 remaining = strlen( msg ); + while ( remaining ) + { + if ( ( bytes_transferred = net_write( server, msg, remaining > NET_BUFFER_SIZE ? NET_BUFFER_SIZE : remaining ) ) > 0 ) + { remaining -= bytes_transferred; - usleep (20 * 1000); - } else if (bytes_transferred < 0) { + usleep ( 20 * 1000 ); + } + else if ( bytes_transferred < 0 ) + { return bytes_transferred; - } else { + } + else + { return -ENODATA; } } @@ -37,22 +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; + 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) { - net_close(connection); + if ( net_connect( connection, ( struct sockaddr* )&connect_addr, sizeof( connect_addr ) ) == -1 ) + { + net_close( connection ); return -1; } return connection; @@ -73,33 +82,38 @@ 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; } //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; } //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; } @@ -107,11 +121,13 @@ 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; } } @@ -121,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; } @@ -130,106 +146,118 @@ 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 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++) { - if (response.data[i] == '\n' && + 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') { + response.data[i-3] == '\r' ) + { filestart = response.data + i + 1; filesize = response.size - i - 1; break; } } - 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 6031e7ec..6eb3f3de 100644 --- a/source/network/http.h +++ b/source/network/http.h @@ -7,7 +7,8 @@ #include #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #include "dns.h" @@ -15,15 +16,16 @@ extern "C" { /** * A simple structure to keep track of the size of a malloc()ated block of memory */ - struct block { + struct block + { 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 7c0837d7..ecc29dcb 100644 --- a/source/network/networkops.cpp +++ b/source/network/networkops.cpp @@ -43,18 +43,22 @@ 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; - } else { + } + else + { networkinitialized = true; return; } @@ -63,45 +67,52 @@ void Initialize_Network(void) { /**************************************************************************** * Check if network was initialised ***************************************************************************/ -bool IsNetworkInit(void) { +bool IsNetworkInit( void ) +{ return networkinitialized; } /**************************************************************************** * Get network IP ***************************************************************************/ -char * GetNetworkIP(void) { +char * GetNetworkIP( void ) +{ return IP; } /**************************************************************************** * Get incomming IP ***************************************************************************/ -char * GetIncommingIP(void) { +char * GetIncommingIP( void ) +{ return incommingIP; } /**************************************************************************** * Get network IP ***************************************************************************/ -bool ShutdownWC24() { +bool ShutdownWC24() +{ bool onlinefix = IsNetworkInit(); - if (onlinefix) { + if ( onlinefix ) + { s32 kd_fd, ret; - STACK_ALIGN(u8, kd_buf, 0x20, 32); + STACK_ALIGN( u8, kd_buf, 0x20, 32 ); - 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) + 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); + 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; @@ -109,32 +120,32 @@ s32 network_request(const char * request, char * filename) { s32 ret; /* Send request */ - ret = net_send(connection, request, strlen(request), 0); - if (ret < 0) + 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) + 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")) + 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'; @@ -143,27 +154,29 @@ s32 network_request(const char * request, char * filename) { } /* Retrieve content size */ - ptr = strstr(buf, "Content-Length:"); - if (!ptr) + 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) + ret = net_read( connection, buf + read, len - read ); + if ( ret < 0 ) return ret; /* Read finished */ - if (!ret) + if ( !ret ) break; /* Increment read variable */ @@ -176,51 +189,58 @@ 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; } -void CloseConnection() { +void CloseConnection() +{ - net_close(connection); + net_close( connection ); - if (waitforanswer) { - net_close(socket); + if ( waitforanswer ) + { + net_close( socket ); waitforanswer = false; } } @@ -228,58 +248,66 @@ void CloseConnection() { /**************************************************************************** * NetworkWait ***************************************************************************/ -int NetworkWait() { +int NetworkWait() +{ - if (!checkincomming) + 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; } sin.sin_family = AF_INET; - sin.sin_port = htons(PORT); - sin.sin_addr.s_addr = htonl(INADDR_ANY); + sin.sin_port = htons( PORT ); + sin.sin_addr.s_addr = htonl( INADDR_ANY ); - if (net_bind(socket, (struct sockaddr*)&sin, sizeof(sin)) < 0) { - net_close(socket); + if ( net_bind( socket, ( struct sockaddr* )&sin, sizeof( sin ) ) < 0 ) + { + net_close( socket ); return -1; } - if (net_listen(socket, 3) < 0) { - net_close(socket); + if ( net_listen( socket, 3 ) < 0 ) + { + 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) { - net_close(connection); - net_close(socket); + if ( connection < 0 ) + { + net_close( connection ); + net_close( socket ); return -4; - } else { + } + else + { unsigned char haxx[9]; //skip haxx - net_read(connection, &haxx, 8); - wiiloadVersion[0] = haxx[4]; - wiiloadVersion[1] = haxx[5]; + 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) { - net_read(connection, &uncfilesize, 4); // Compressed protocol, read another 4 bytes - } + if ( haxx[4] > 0 || haxx[5] > 4 ) + { + net_read( connection, &uncfilesize, 4 ); // Compressed protocol, read another 4 bytes + } waitforanswer = true; checkincomming = false; networkHalt = true; @@ -291,34 +319,39 @@ int NetworkWait() { /**************************************************************************** * Update check ***************************************************************************/ -int CheckUpdate() { - if (!networkinitialized) +int CheckUpdate() +{ + if ( !networkinitialized ) return -1; int revnumber = 0; - int currentrev = atoi(GetRev()); + int currentrev = atoi( GetRev() ); - if (Settings.beta_upgrades) { - revnumber = CheckForBetaUpdate(); - } else { + if ( Settings.beta_upgrades ) + { + revnumber = CheckForBetaUpdate(); + } + else + { #ifdef FULLCHANNEL - struct block file = downloadfile("http://www.techjawa.com/usbloadergx/wadrev.txt"); + struct block file = downloadfile( "http://www.techjawa.com/usbloadergx/wadrev.txt" ); #else - struct block file = downloadfile("http://www.techjawa.com/usbloadergx/rev.txt"); + struct block file = downloadfile( "http://www.techjawa.com/usbloadergx/rev.txt" ); #endif - char revtxt[10]; + char revtxt[10]; - u8 i; - if (file.data != NULL) { - for (i=0; i<9 || i < file.size; i++) - revtxt[i] = file.data[i]; - revtxt[i] = 0; - revnumber = atoi(revtxt); - free(file.data); - } - } + u8 i; + if ( file.data != NULL ) + { + for ( i = 0; i < 9 || i < file.size; i++ ) + revtxt[i] = file.data[i]; + revtxt[i] = 0; + revnumber = atoi( revtxt ); + free( file.data ); + } + } - if (revnumber > currentrev) + if ( revnumber > currentrev ) return revnumber; else return -1; @@ -327,52 +360,58 @@ int CheckUpdate() { /**************************************************************************** * HaltNetwork ***************************************************************************/ -void HaltNetworkThread() { +void HaltNetworkThread() +{ networkHalt = true; checkincomming = false; - if (waitforanswer) + if ( waitforanswer ) CloseConnection(); // wait for thread to finish - while (!LWP_ThreadIsSuspended(networkthread)) - usleep(100); + while ( !LWP_ThreadIsSuspended( networkthread ) ) + usleep( 100 ); } /**************************************************************************** * ResumeNetworkThread ***************************************************************************/ -void ResumeNetworkThread() { +void ResumeNetworkThread() +{ networkHalt = false; - LWP_ResumeThread(networkthread); + LWP_ResumeThread( networkthread ); } /**************************************************************************** * Resume NetworkWait ***************************************************************************/ -void ResumeNetworkWait() { +void ResumeNetworkWait() +{ networkHalt = true; checkincomming = true; 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) { - while (1) { +static void * networkinitcallback( void *arg ) +{ + 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) + if ( CheckUpdate() > 0 ) updateavailable = true; //suspend thread @@ -381,7 +420,7 @@ static void * networkinitcallback(void *arg) { checkincomming = false; } - if (checkincomming) + if ( checkincomming ) NetworkWait(); } return NULL; @@ -390,14 +429,16 @@ static void * networkinitcallback(void *arg) { /**************************************************************************** * InitNetworkThread with priority 0 (idle) ***************************************************************************/ -void InitNetworkThread() { - LWP_CreateThread (&networkthread, networkinitcallback, NULL, NULL, 16384, 0); +void InitNetworkThread() +{ + LWP_CreateThread ( &networkthread, networkinitcallback, NULL, NULL, 16384, 0 ); } /**************************************************************************** * ShutdownThread ***************************************************************************/ -void ShutdownNetworkThread() { - LWP_JoinThread (networkthread, NULL); +void ShutdownNetworkThread() +{ + LWP_JoinThread ( networkthread, NULL ); networkthread = LWP_THREAD_NULL; } diff --git a/source/network/networkops.h b/source/network/networkops.h index 0d7538dc..b71387f6 100644 --- a/source/network/networkops.h +++ b/source/network/networkops.h @@ -10,14 +10,14 @@ #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 eb49758d..7edefeb9 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,39 @@ 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 8283c8cc..5ab60317 100644 --- a/source/network/update.h +++ b/source/network/update.h @@ -1,34 +1,34 @@ - /*************************************************************************** - * Copyright (C) 2009 - * by Dimok - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any - * damages arising from the use of this software. - * - * Permission is granted to anyone to use this software for any - * purpose, including commercial applications, and to alter it and - * redistribute it freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you use - * this software in a product, an acknowledgment in the product - * documentation would be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and - * must not be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - * update.h - * - * Update operations - * for Wii-Xplorer 2009 - ***************************************************************************/ -#ifndef _UPDATEOPS_H_ +/*************************************************************************** +* Copyright (C) 2009 +* by Dimok +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any +* damages arising from the use of this software. +* +* Permission is granted to anyone to use this software for any +* purpose, including commercial applications, and to alter it and +* redistribute it freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you +* must not claim that you wrote the original software. If you use +* this software in a product, an acknowledgment in the product +* documentation would be appreciated but is not required. +* +* 2. Altered source versions must be plainly marked as such, and +* must not be misrepresented as being the original software. +* +* 3. This notice may not be removed or altered from any source +* distribution. +* +* update.h +* +* Update operations +* for Wii-Xplorer 2009 +***************************************************************************/ +#ifndef _UPDATEOPS_H_ #define _UPDATEOPS_H_ int CheckForBetaUpdate(); -#endif +#endif diff --git a/source/patches/codehandler.h b/source/patches/codehandler.h index a5a80be1..73715fd2 100644 --- a/source/patches/codehandler.h +++ b/source/patches/codehandler.h @@ -3,275 +3,276 @@ 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 d125bae7..7fc7c52b 100644 --- a/source/patches/codehandleronly.h +++ b/source/patches/codehandleronly.h @@ -3,178 +3,179 @@ 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 131c86db..66407226 100644 --- a/source/patches/dolpatcher.c +++ b/source/patches/dolpatcher.c @@ -1,19 +1,19 @@ #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; + 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; } - return false; + return false; } diff --git a/source/patches/dolpatcher.h b/source/patches/dolpatcher.h index 09eb3190..df7c1ccf 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 0d012392..7b355b6e 100644 --- a/source/patches/dvd_broadway.c +++ b/source/patches/dvd_broadway.c @@ -26,56 +26,56 @@ #include #include #include -#include - +#include + #include "dvd_broadway.h" - -#define DI_CMDCTX_CNT 4 - -#define DVD_DISKIDSIZE 0x20 -#define DVD_DRVINFSIZE 0x20 - -#define IOCTL_DI_INQUIRY 0x12 -#define IOCTL_DI_READID 0x70 -#define IOCTL_DI_READ 0x71 -#define IOCTL_DI_WAITCVRCLOSE 0x79 -#define IOCTL_DI_COVER 0x7A -#define IOCTL_DI_RESETNOTIFY 0x7E -#define IOCTL_DI_RESET 0x8A -#define IOCTL_DI_OPENPART 0x8B -#define IOCTL_DI_CLOSEPART 0x8C -#define IOCTL_DI_UNENCREAD 0x8D -#define IOCTL_DI_ENABLE_DVD 0x8E -#define IOCTL_DI_SEEK 0xAB -#define IOCTL_DI_READ_DVDVIDEO 0xD0 -#define IOCTL_DI_STOPLASER 0xD2 -#define IOCTL_DI_OFFSET 0xD9 -#define IOCTL_DI_REQERROR 0xE0 -#define IOCTL_DI_STOPMOTOR 0xE3 -#define IOCTL_DI_SETOFFBASE 0xF0 -#define IOCTL_DI_GETOFFBASE 0xF1 -#define IOCTL_DI_SETCRYPTMODE 0xF2 -#define IOCTL_DI_GETCRYPTMODE 0xF3 -#define IOCTL_DI_SETDVDROMMODE 0xF4 -#define IOCTL_DI_GETDVDROMMODE 0xF5 - -#define _SHIFTL(v, s, w) \ + +#define DI_CMDCTX_CNT 4 + +#define DVD_DISKIDSIZE 0x20 +#define DVD_DRVINFSIZE 0x20 + +#define IOCTL_DI_INQUIRY 0x12 +#define IOCTL_DI_READID 0x70 +#define IOCTL_DI_READ 0x71 +#define IOCTL_DI_WAITCVRCLOSE 0x79 +#define IOCTL_DI_COVER 0x7A +#define IOCTL_DI_RESETNOTIFY 0x7E +#define IOCTL_DI_RESET 0x8A +#define IOCTL_DI_OPENPART 0x8B +#define IOCTL_DI_CLOSEPART 0x8C +#define IOCTL_DI_UNENCREAD 0x8D +#define IOCTL_DI_ENABLE_DVD 0x8E +#define IOCTL_DI_SEEK 0xAB +#define IOCTL_DI_READ_DVDVIDEO 0xD0 +#define IOCTL_DI_STOPLASER 0xD2 +#define IOCTL_DI_OFFSET 0xD9 +#define IOCTL_DI_REQERROR 0xE0 +#define IOCTL_DI_STOPMOTOR 0xE3 +#define IOCTL_DI_SETOFFBASE 0xF0 +#define IOCTL_DI_GETOFFBASE 0xF1 +#define IOCTL_DI_SETCRYPTMODE 0xF2 +#define IOCTL_DI_GETCRYPTMODE 0xF3 +#define IOCTL_DI_SETDVDROMMODE 0xF4 +#define IOCTL_DI_GETDVDROMMODE 0xF5 + +#define _SHIFTL(v, s, w) \ ((u32) (((u32)(v) & ((0x01 << (w)) - 1)) << (s))) -#define _SHIFTR(v, s, w) \ +#define _SHIFTR(v, s, w) \ ((u32)(((u32)(v) >> (s)) & ((0x01 << (w)) - 1))) - + struct dicommand { - u32 diReg[8]; + u32 diReg[8]; }; - + struct dicontext { - lwp_node node; - dvdcallbacklow cb; - struct dicommand *cmd; + lwp_node node; + dvdcallbacklow cb; + struct dicommand *cmd; }; - + static s32 __dvd_fd = -1; static u32 __dvd_spinupval = 1; static lwp_queue __di_contextq; @@ -85,529 +85,535 @@ static u32 __dvd_reqinprogress = 0; static u32 __dvd_lowinitcalled = 0; static struct dicommand *__di_commands = NULL; static struct dicontext __di_contexts[DI_CMDCTX_CNT]; -static u32 __di_regbuffer[0x08] ATTRIBUTE_ALIGN(32); -static u32 __di_regvalcache[0x08] ATTRIBUTE_ALIGN(32); -static u32 __di_lastticketerror[0x08] ATTRIBUTE_ALIGN(32); -static ioctlv __di_iovector[0x08] ATTRIBUTE_ALIGN(32); -static char __di_fs[] ATTRIBUTE_ALIGN(32) = "/dev/di"; - +static u32 __di_regbuffer[0x08] ATTRIBUTE_ALIGN( 32 ); +static u32 __di_regvalcache[0x08] ATTRIBUTE_ALIGN( 32 ); +static u32 __di_lastticketerror[0x08] ATTRIBUTE_ALIGN( 32 ); +static ioctlv __di_iovector[0x08] ATTRIBUTE_ALIGN( 32 ); +static char __di_fs[] ATTRIBUTE_ALIGN( 32 ) = "/dev/di"; + extern u32 __IPC_ClntInit(); - -static __inline__ lwp_node* __lwp_queue_head(lwp_queue *queue) + +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->perm_null = NULL; - queue->last = __lwp_queue_head(queue); + queue->first = __lwp_queue_tail( queue ); + queue->perm_null = NULL; + 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; - - return ctx; + struct dicontext *ctx; + + ctx = ( struct dicontext* )__lwp_queue_get( &__di_contextq ); + if ( ctx != NULL ) ctx->cb = cb; + + return ctx; } - -static s32 __dvd_iostransactionCB(s32 result,void *usrdata) + +static s32 __dvd_iostransactionCB( s32 result, void *usrdata ) { - struct dicontext *ctx = (struct dicontext*)usrdata; - - __dvd_reqinprogress = 0; - - if(ctx->cb!=NULL) { - __dvd_cbinprogress = 1; - if(result!=0) __dvd_readlength = 0; - ctx->cb(result); - __dvd_cbinprogress = 0; - } - __lwp_queue_append(&__di_contextq,&ctx->node); - - return 0; + struct dicontext *ctx = ( struct dicontext* )usrdata; + + __dvd_reqinprogress = 0; + + if ( ctx->cb != NULL ) + { + __dvd_cbinprogress = 1; + if ( result != 0 ) __dvd_readlength = 0; + ctx->cb( result ); + __dvd_cbinprogress = 0; + } + __lwp_queue_append( &__di_contextq, &ctx->node ); + + return 0; } - -static s32 __dvd_ioscoverregisterCB(s32 result,void *usrdata) + +static s32 __dvd_ioscoverregisterCB( s32 result, void *usrdata ) { - struct dicontext *ctx = (struct dicontext*)usrdata; - - __dvd_reqinprogress = 0; - __di_regvalcache[1] = __di_regbuffer[0]; - - if(ctx->cb!=NULL) { - __dvd_cbinprogress = 1; - ctx->cb(result); - __dvd_cbinprogress = 0; - } - __lwp_queue_append(&__di_contextq,&ctx->node); - - return 0; + struct dicontext *ctx = ( struct dicontext* )usrdata; + + __dvd_reqinprogress = 0; + __di_regvalcache[1] = __di_regbuffer[0]; + + if ( ctx->cb != NULL ) + { + __dvd_cbinprogress = 1; + ctx->cb( result ); + __dvd_cbinprogress = 0; + } + __lwp_queue_append( &__di_contextq, &ctx->node ); + + return 0; } - -static s32 __dvd_ioscovercloseCB(s32 result,void *usrdata) + +static s32 __dvd_ioscovercloseCB( s32 result, void *usrdata ) { - struct dicontext *ctx = (struct dicontext*)usrdata; - - __dvd_reqinprogress = 0; - - if(ctx->cb!=NULL) { - __dvd_cbinprogress = 1; - ctx->cb(result); - __dvd_cbinprogress = 0; - } - __lwp_queue_append(&__di_contextq,&ctx->node); - - return 0; + struct dicontext *ctx = ( struct dicontext* )usrdata; + + __dvd_reqinprogress = 0; + + if ( ctx->cb != NULL ) + { + __dvd_cbinprogress = 1; + ctx->cb( result ); + __dvd_cbinprogress = 0; + } + __lwp_queue_append( &__di_contextq, &ctx->node ); + + return 0; } - + s32 bwDVD_LowInit() { - s32 i,ret = 0; - u32 ipclo,ipchi; - lwp_queue inactives; - struct dicontext *ctx; - - if(__dvd_lowinitcalled==0) { - ret = __IPC_ClntInit(); - if(ret<0) return ret; - - ipclo = (((u32)IPC_GetBufferLo()+0x1f)&~0x1f); - ipchi = (u32)IPC_GetBufferHi(); - if(ipchi>=(ipclo+(sizeof(struct dicommand)*DI_CMDCTX_CNT))) { - __di_commands = (struct dicommand*)ipclo; - IPC_SetBufferLo((void*)(ipclo+(sizeof(struct dicommand)*DI_CMDCTX_CNT))); - - memset(__di_commands,0,(sizeof(struct dicommand)*DI_CMDCTX_CNT)); - - i = 0; - __lwp_queue_init_empty(&__di_contextq); - __lwp_queue_initialize(&inactives,__di_contexts,DI_CMDCTX_CNT,sizeof(struct dicontext)); - while((ctx=(struct dicontext*)__lwp_queue_get(&inactives))!=NULL) { - ctx->cmd = &__di_commands[i]; - ctx->cb = NULL; - __lwp_queue_append(&__di_contextq,&ctx->node); - - i++; - } - } - - ret = IOS_Open(__di_fs,0); - if(ret<0) return ret; - - __dvd_fd = ret; -// __dvd_lowinitcalled = 1; - - // printf("DVD_LowInit(%d)\n",ret); - } - return 0; -} - -s32 bwDVD_LowInquiry(dvddrvinfo *info,dvdcallbacklow cb) -{ - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_INQUIRY<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_INQUIRY,cmd->diReg,sizeof(struct dicommand),info,DVD_DRVINFSIZE,__dvd_iostransactionCB,ctx); - - return ret; -} - -s32 bwDVD_LowReadID(dvddiskid *diskID,dvdcallbacklow cb) -{ - s32 ret = 0; - struct dicontext *ctx; - struct dicommand *cmd; - -// printf("DVD_LowReadID()\n"); - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_READID<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_READID,cmd->diReg,sizeof(struct dicommand),diskID,DVD_DISKIDSIZE,__dvd_iostransactionCB,ctx); - -// printf("DVD_LowReadID(%d)\n",ret); - return ret; + s32 i, ret = 0; + u32 ipclo, ipchi; + lwp_queue inactives; + struct dicontext *ctx; + + if ( __dvd_lowinitcalled == 0 ) + { + ret = __IPC_ClntInit(); + if ( ret < 0 ) return ret; + + ipclo = ( ( ( u32 )IPC_GetBufferLo() + 0x1f )&~0x1f ); + ipchi = ( u32 )IPC_GetBufferHi(); + if ( ipchi >= ( ipclo + ( sizeof( struct dicommand )*DI_CMDCTX_CNT ) ) ) + { + __di_commands = ( struct dicommand* )ipclo; + IPC_SetBufferLo( ( void* )( ipclo + ( sizeof( struct dicommand )*DI_CMDCTX_CNT ) ) ); + + memset( __di_commands, 0, ( sizeof( struct dicommand )*DI_CMDCTX_CNT ) ); + + i = 0; + __lwp_queue_init_empty( &__di_contextq ); + __lwp_queue_initialize( &inactives, __di_contexts, DI_CMDCTX_CNT, sizeof( struct dicontext ) ); + while ( ( ctx = ( struct dicontext* )__lwp_queue_get( &inactives ) ) != NULL ) + { + ctx->cmd = &__di_commands[i]; + ctx->cb = NULL; + __lwp_queue_append( &__di_contextq, &ctx->node ); + + i++; + } + } + + ret = IOS_Open( __di_fs, 0 ); + if ( ret < 0 ) return ret; + + __dvd_fd = ret; +// __dvd_lowinitcalled = 1; + + // printf("DVD_LowInit(%d)\n",ret); + } + return 0; } - -s32 bwDVD_LowRead(void *buf,u32 len,u32 offset,dvdcallbacklow cb) +s32 bwDVD_LowInquiry( dvddrvinfo *info, dvdcallbacklow cb ) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - if(buf==NULL || ((u32)buf%32)!=0) return -1; - - __dvd_reqinprogress = 1; - __dvd_readlength = len; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_READ<<24); - cmd->diReg[1] = len; - cmd->diReg[2] = offset; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_READ,cmd->diReg,sizeof(struct dicommand),buf,len,__dvd_iostransactionCB,ctx); - - return ret; + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_INQUIRY << 24 ); + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_INQUIRY, cmd->diReg, sizeof( struct dicommand ), info, DVD_DRVINFSIZE, __dvd_iostransactionCB, ctx ); + + return ret; +} + +s32 bwDVD_LowReadID( dvddiskid *diskID, dvdcallbacklow cb ) +{ + s32 ret = 0; + struct dicontext *ctx; + struct dicommand *cmd; + +// printf("DVD_LowReadID()\n"); + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_READID << 24 ); + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_READID, cmd->diReg, sizeof( struct dicommand ), diskID, DVD_DISKIDSIZE, __dvd_iostransactionCB, ctx ); + +// printf("DVD_LowReadID(%d)\n",ret); + return ret; +} + + +s32 bwDVD_LowRead( void *buf, u32 len, u32 offset, dvdcallbacklow cb ) +{ + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + if ( buf == NULL || ( ( u32 )buf % 32 ) != 0 ) return -1; + + __dvd_reqinprogress = 1; + __dvd_readlength = len; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_READ << 24 ); + cmd->diReg[1] = len; + cmd->diReg[2] = offset; + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_READ, cmd->diReg, sizeof( struct dicommand ), buf, len, __dvd_iostransactionCB, ctx ); + + return ret; } // 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; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - __dvd_readlength = len; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_READ_DVDVIDEO<<24); - cmd->diReg[1] = len; - cmd->diReg[2] = offset; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_READ_DVDVIDEO,cmd->diReg,sizeof(struct dicommand),buf,len,__dvd_iostransactionCB,ctx); - - return ret; + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + __dvd_readlength = len; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_READ_DVDVIDEO << 24 ); + cmd->diReg[1] = len; + cmd->diReg[2] = offset; + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_READ_DVDVIDEO, cmd->diReg, sizeof( struct dicommand ), buf, len, __dvd_iostransactionCB, ctx ); + + return ret; } - -s32 bwDVD_LowStopLaser(dvdcallbacklow cb) + +s32 bwDVD_LowStopLaser( dvdcallbacklow cb ) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_STOPLASER<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_STOPLASER,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_STOPLASER << 24 ); + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_STOPLASER, cmd->diReg, sizeof( struct dicommand ), __di_regvalcache, 0x20, __dvd_iostransactionCB, ctx ); + + return ret; } // never got this function working, probably removed from wii -s32 bwDVD_EnableVideo(dvdcallbacklow cb) +s32 bwDVD_EnableVideo( dvdcallbacklow cb ) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_ENABLE_DVD<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_ENABLE_DVD,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_ENABLE_DVD << 24 ); + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_ENABLE_DVD, cmd->diReg, sizeof( struct dicommand ), __di_regvalcache, 0x20, __dvd_iostransactionCB, ctx ); + + return ret; } - -s32 bwDVD_LowSeek(u32 offset,dvdcallbacklow cb) + +s32 bwDVD_LowSeek( u32 offset, dvdcallbacklow cb ) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_SEEK<<24); - cmd->diReg[1] = offset; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_SEEK,cmd->diReg,sizeof(struct dicommand),NULL,0,__dvd_iostransactionCB,ctx); - - return ret; + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_SEEK << 24 ); + cmd->diReg[1] = offset; + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_SEEK, cmd->diReg, sizeof( struct dicommand ), NULL, 0, __dvd_iostransactionCB, ctx ); + + return ret; } - -s32 bwDVD_LowOffset(u64 offset,dvdcallbacklow cb) + +s32 bwDVD_LowOffset( u64 offset, dvdcallbacklow cb ) { - s32 ret; - //u32 *off = (u32*)(void*)(&offset); - union { u64 off64; u32 off32[2]; } off;off.off64 = offset; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_OFFSET<<24); - cmd->diReg[1] = 0; - if(off.off32[0]) cmd->diReg[1] = 1; - cmd->diReg[2] = off.off32[1]; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_OFFSET,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; + s32 ret; + //u32 *off = (u32*)(void*)(&offset); + union { u64 off64; u32 off32[2]; } off; off.off64 = offset; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_OFFSET << 24 ); + cmd->diReg[1] = 0; + if ( off.off32[0] ) cmd->diReg[1] = 1; + cmd->diReg[2] = off.off32[1]; + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_OFFSET, cmd->diReg, sizeof( struct dicommand ), __di_regvalcache, 0x20, __dvd_iostransactionCB, ctx ); + + return ret; } - -s32 bwDVD_LowPrepareCoverRegister(dvdcallbacklow cb) + +s32 bwDVD_LowPrepareCoverRegister( dvdcallbacklow cb ) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_COVER<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_COVER,cmd->diReg,sizeof(struct dicommand),__di_regbuffer,0x20,__dvd_ioscoverregisterCB,ctx); - - return ret; + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_COVER << 24 ); + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_COVER, cmd->diReg, sizeof( struct dicommand ), __di_regbuffer, 0x20, __dvd_ioscoverregisterCB, ctx ); + + return ret; } - -s32 bwDVD_LowOpenPartition(u32 offset,void *eticket,u32 certin_len,void *certificate_in,void *certificate_out,dvdcallbacklow cb) + +s32 bwDVD_LowOpenPartition( u32 offset, void *eticket, u32 certin_len, void *certificate_in, void *certificate_out, dvdcallbacklow cb ) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - if(eticket!=NULL && ((u32)eticket%32)!=0) return -1; - if(certificate_in!=NULL && ((u32)certificate_in%32)!=0) return -1; - if(certificate_out!=NULL && ((u32)certificate_out%32)!=0) return -1; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_OPENPART<<24); - cmd->diReg[1] = offset; - - __di_iovector[0].data = cmd; - __di_iovector[0].len = sizeof(struct dicommand); - - __di_iovector[1].data = eticket; - if(eticket==NULL) __di_iovector[1].len = 0; - else __di_iovector[1].len = 676; - - __di_iovector[2].data = certificate_in; - if(certificate_in==NULL) __di_iovector[2].len = 0; - else __di_iovector[2].len = certin_len; - - __di_iovector[3].data = certificate_out; - __di_iovector[3].len = 18916; - __di_iovector[4].data = __di_lastticketerror; - __di_iovector[4].len = 0x20; - ret = IOS_IoctlvAsync(__dvd_fd,IOCTL_DI_OPENPART,3,2,__di_iovector,__dvd_iostransactionCB,ctx); - - return ret; + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + if ( eticket != NULL && ( ( u32 )eticket % 32 ) != 0 ) return -1; + if ( certificate_in != NULL && ( ( u32 )certificate_in % 32 ) != 0 ) return -1; + if ( certificate_out != NULL && ( ( u32 )certificate_out % 32 ) != 0 ) return -1; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_OPENPART << 24 ); + cmd->diReg[1] = offset; + + __di_iovector[0].data = cmd; + __di_iovector[0].len = sizeof( struct dicommand ); + + __di_iovector[1].data = eticket; + if ( eticket == NULL ) __di_iovector[1].len = 0; + else __di_iovector[1].len = 676; + + __di_iovector[2].data = certificate_in; + if ( certificate_in == NULL ) __di_iovector[2].len = 0; + else __di_iovector[2].len = certin_len; + + __di_iovector[3].data = certificate_out; + __di_iovector[3].len = 18916; + __di_iovector[4].data = __di_lastticketerror; + __di_iovector[4].len = 0x20; + ret = IOS_IoctlvAsync( __dvd_fd, IOCTL_DI_OPENPART, 3, 2, __di_iovector, __dvd_iostransactionCB, ctx ); + + return ret; } - -s32 bwDVD_LowClosePartition(dvdcallbacklow cb) + +s32 bwDVD_LowClosePartition( dvdcallbacklow cb ) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_CLOSEPART<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_CLOSEPART,cmd->diReg,sizeof(struct dicommand),NULL,0,__dvd_iostransactionCB,ctx); - - return ret; + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_CLOSEPART << 24 ); + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_CLOSEPART, cmd->diReg, sizeof( struct dicommand ), NULL, 0, __dvd_iostransactionCB, ctx ); + + return ret; } - -s32 bwDVD_LowUnencryptedRead(void *buf,u32 len,u32 offset,dvdcallbacklow cb) + +s32 bwDVD_LowUnencryptedRead( void *buf, u32 len, u32 offset, dvdcallbacklow cb ) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - __dvd_readlength = len; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_UNENCREAD<<24); - cmd->diReg[1] = len; - cmd->diReg[2] = offset; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_UNENCREAD,cmd->diReg,sizeof(struct dicommand),buf,len,__dvd_iostransactionCB,ctx); - - return ret; + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + __dvd_readlength = len; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_UNENCREAD << 24 ); + cmd->diReg[1] = len; + cmd->diReg[2] = offset; + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_UNENCREAD, cmd->diReg, sizeof( struct dicommand ), buf, len, __dvd_iostransactionCB, ctx ); + + return ret; } - -s32 bwDVD_LowWaitCoverClose(dvdcallbacklow cb) + +s32 bwDVD_LowWaitCoverClose( dvdcallbacklow cb ) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_WAITCVRCLOSE<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_WAITCVRCLOSE,cmd->diReg,sizeof(struct dicommand),NULL,0,__dvd_ioscovercloseCB,ctx); - - return ret; + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_WAITCVRCLOSE << 24 ); + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_WAITCVRCLOSE, cmd->diReg, sizeof( struct dicommand ), NULL, 0, __dvd_ioscovercloseCB, ctx ); + + return ret; } - + s32 bwDVD_LowResetNotify() { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - if(__dvd_cbinprogress==1) return -1; - - ctx = __dvd_getcontext(NULL); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_RESETNOTIFY<<24); - ret = IOS_Ioctl(__dvd_fd,IOCTL_DI_RESETNOTIFY,cmd->diReg,sizeof(struct dicommand),NULL,0); - - return ret; + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + if ( __dvd_cbinprogress == 1 ) return -1; + + ctx = __dvd_getcontext( NULL ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_RESETNOTIFY << 24 ); + ret = IOS_Ioctl( __dvd_fd, IOCTL_DI_RESETNOTIFY, cmd->diReg, sizeof( struct dicommand ), NULL, 0 ); + + return ret; } - -s32 bwDVD_LowReset(dvdcallbacklow cb) + +s32 bwDVD_LowReset( dvdcallbacklow cb ) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - -// printf("DVD_LowReset()\n"); - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_RESET<<24); - cmd->diReg[1] = __dvd_spinupval; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_RESET,cmd->diReg,sizeof(struct dicommand),NULL,0,__dvd_iostransactionCB,ctx); - -// printf("DVD_LowReset(%d)\n",ret); - return ret; + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + +// printf("DVD_LowReset()\n"); + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_RESET << 24 ); + cmd->diReg[1] = __dvd_spinupval; + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_RESET, cmd->diReg, sizeof( struct dicommand ), NULL, 0, __dvd_iostransactionCB, ctx ); + +// 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; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_STOPMOTOR<<24); - cmd->diReg[1] = (stop1<<24); - cmd->diReg[2] = (stop2<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_STOPMOTOR,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; - + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_STOPMOTOR << 24 ); + cmd->diReg[1] = ( stop1 << 24 ); + cmd->diReg[2] = ( stop2 << 24 ); + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_STOPMOTOR, cmd->diReg, sizeof( struct dicommand ), __di_regvalcache, 0x20, __dvd_iostransactionCB, ctx ); + + return ret; + } - -s32 bwDVD_LowRequestError(dvdcallbacklow cb) + +s32 bwDVD_LowRequestError( dvdcallbacklow cb ) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_REQERROR<<24); - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_REQERROR,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_REQERROR << 24 ); + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_REQERROR, cmd->diReg, sizeof( struct dicommand ), __di_regvalcache, 0x20, __dvd_iostransactionCB, ctx ); + + return ret; } -s32 bwDVD_SetDecryption(s32 mode, dvdcallbacklow cb) +s32 bwDVD_SetDecryption( s32 mode, dvdcallbacklow cb ) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_SETCRYPTMODE<<24); - cmd->diReg[1] = mode; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_SETCRYPTMODE,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; - + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_SETCRYPTMODE << 24 ); + cmd->diReg[1] = mode; + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_SETCRYPTMODE, cmd->diReg, sizeof( struct dicommand ), __di_regvalcache, 0x20, __dvd_iostransactionCB, ctx ); + + return ret; + } -s32 bwDVD_SetOffset(u32 offset, dvdcallbacklow cb) +s32 bwDVD_SetOffset( u32 offset, dvdcallbacklow cb ) { - s32 ret; - struct dicontext *ctx; - struct dicommand *cmd; - - __dvd_reqinprogress = 1; - - ctx = __dvd_getcontext(cb); - if(ctx==NULL) return IPC_ENOMEM; - - cmd = ctx->cmd; - cmd->diReg[0] = (IOCTL_DI_SETOFFBASE<<24); - cmd->diReg[1] = offset; - ret = IOS_IoctlAsync(__dvd_fd,IOCTL_DI_SETOFFBASE,cmd->diReg,sizeof(struct dicommand),__di_regvalcache,0x20,__dvd_iostransactionCB,ctx); - - return ret; - + s32 ret; + struct dicontext *ctx; + struct dicommand *cmd; + + __dvd_reqinprogress = 1; + + ctx = __dvd_getcontext( cb ); + if ( ctx == NULL ) return IPC_ENOMEM; + + cmd = ctx->cmd; + cmd->diReg[0] = ( IOCTL_DI_SETOFFBASE << 24 ); + cmd->diReg[1] = offset; + ret = IOS_IoctlAsync( __dvd_fd, IOCTL_DI_SETOFFBASE, cmd->diReg, sizeof( struct dicommand ), __di_regvalcache, 0x20, __dvd_iostransactionCB, ctx ); + + return ret; + } diff --git a/source/patches/dvd_broadway.h b/source/patches/dvd_broadway.h index e36361d2..f91f35b0 100644 --- a/source/patches/dvd_broadway.h +++ b/source/patches/dvd_broadway.h @@ -21,33 +21,34 @@ #ifndef __DVD_BROADWAY_H__ #define __DVD_BROADWAY_H__ - + #include #include #include - -#ifdef __cplusplus - extern "C" { -#endif /* __cplusplus */ - -typedef void (*dvdcallbacklow)(s32 result); - -s32 bwDVD_LowInit(); -s32 bwDVD_LowInquiry(dvddrvinfo *info,dvdcallbacklow cb); -s32 bwDVD_LowReadID(dvddiskid *diskID,dvdcallbacklow cb); -s32 bwDVD_LowClosePartition(dvdcallbacklow cb); -s32 bwDVD_LowOpenPartition(u32 offset,void *eticket,u32 certin_len,void *certificate_in,void *certificate_out,dvdcallbacklow cb); -s32 bwDVD_LowUnencryptedRead(void *buf,u32 len,u32 offset,dvdcallbacklow cb); -s32 bwDVD_LowReset(dvdcallbacklow cb); -s32 bwDVD_LowWaitCoverClose(dvdcallbacklow cb); -s32 bwDVD_LowRead(void *buf,u32 len,u32 offset,dvdcallbacklow cb); -s32 bwDVD_EnableVideo(dvdcallbacklow cb); -s32 bwDVD_LowReadVideo(void *buf,u32 len,u32 offset,dvdcallbacklow cb); -s32 bwDVD_SetDecryption(s32 mode, dvdcallbacklow cb); -s32 bwDVD_SetOffset(u32 offset, dvdcallbacklow cb); #ifdef __cplusplus - } +extern "C" +{ #endif /* __cplusplus */ - + + typedef void ( *dvdcallbacklow )( s32 result ); + + s32 bwDVD_LowInit(); + s32 bwDVD_LowInquiry( dvddrvinfo *info, dvdcallbacklow cb ); + s32 bwDVD_LowReadID( dvddiskid *diskID, dvdcallbacklow cb ); + s32 bwDVD_LowClosePartition( dvdcallbacklow cb ); + s32 bwDVD_LowOpenPartition( u32 offset, void *eticket, u32 certin_len, void *certificate_in, void *certificate_out, dvdcallbacklow cb ); + s32 bwDVD_LowUnencryptedRead( void *buf, u32 len, u32 offset, dvdcallbacklow cb ); + s32 bwDVD_LowReset( dvdcallbacklow cb ); + s32 bwDVD_LowWaitCoverClose( dvdcallbacklow cb ); + s32 bwDVD_LowRead( void *buf, u32 len, u32 offset, dvdcallbacklow cb ); + s32 bwDVD_EnableVideo( dvdcallbacklow cb ); + s32 bwDVD_LowReadVideo( void *buf, u32 len, u32 offset, dvdcallbacklow cb ); + s32 bwDVD_SetDecryption( s32 mode, dvdcallbacklow cb ); + s32 bwDVD_SetOffset( u32 offset, dvdcallbacklow cb ); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + #endif diff --git a/source/patches/fst.c b/source/patches/fst.c index d243a503..06a089ca 100644 --- a/source/patches/fst.c +++ b/source/patches/fst.c @@ -46,11 +46,11 @@ #define FSTDIRTYPE 1 #define FSTFILETYPE 0 #define ENTRYSIZE 0xC -//#define FILEDIR "fat0:/codes" -//#define FILEDIR "sd:/codes" -#define FILEDIR "/codes" +//#define FILEDIR "fat0:/codes" +//#define FILEDIR "sd:/codes" +#define FILEDIR "/codes" -#define MAX_FILENAME_LEN 128 +#define MAX_FILENAME_LEN 128 static u8 *codelistend; void *codelist; @@ -74,564 +74,568 @@ extern const u32 wpadbuttonsdown2hooks[4]; //static vu32 dvddone = 0; //--------------------------------------------------------------------------------- -void app_loadgameconfig(char *discid) +void app_loadgameconfig( char *discid ) //--------------------------------------------------------------------------------- { - gameconfsize = 0; + gameconfsize = 0; - if (gameconf == NULL) - { - gameconf = malloc(65536); - if (gameconf == NULL) - { - //TODO for oggzee - //print_status("Out of memory"); - return; - } - } - - FILE* fp; - u32 ret; - u32 filesize; - s32 gameidmatch, maxgameidmatch = -1, maxgameidmatch2 = -1; - u32 i, numnonascii, parsebufpos; - u32 codeaddr, codeval, codeaddr2, codeval2, codeoffset; - u32 temp, tempoffset = 0; - char parsebuffer[18]; - - //if (config_bytes[2] == 8) - // hookset = 1; - - u8 *tempgameconf; - u32 tempgameconfsize = 0; - - //memcpy(tempgameconf, defaultgameconfig, defaultgameconfig_size); - //tempgameconf[defaultgameconfig_size] = '\n'; - //tempgameconfsize = defaultgameconfig_size + 1; - - char filepath[200]; - snprintf(filepath, sizeof(filepath), "%s/gameconfig.txt", Settings.Cheatcodespath); - - fp = fopen(filepath, "rb"); - - if (!fp) - { - snprintf(filepath, sizeof(filepath), "SD:/gameconfig.txt"); - fp = fopen(filepath, "rb"); - if(!fp) + if ( gameconf == NULL ) + { + gameconf = malloc( 65536 ); + if ( gameconf == NULL ) { - snprintf(filepath, sizeof(filepath), "USB:/gameconfig.txt"); - fp = fopen(filepath, "rb"); + //TODO for oggzee + //print_status("Out of memory"); + return; } - } + } - if (fp) { - fseek(fp, 0, SEEK_END); - filesize = ftell(fp); - fseek(fp, 0, SEEK_SET); + FILE* fp; + u32 ret; + u32 filesize; + s32 gameidmatch, maxgameidmatch = -1, maxgameidmatch2 = -1; + u32 i, numnonascii, parsebufpos; + u32 codeaddr, codeval, codeaddr2, codeval2, codeoffset; + u32 temp, tempoffset = 0; + char parsebuffer[18]; - tempgameconf = malloc(filesize); - if (tempgameconf == NULL) - { - //TODO for oggzee - //print_status("Out of memory"); - //wait(4); - return; - } + //if (config_bytes[2] == 8) + // hookset = 1; - ret = fread((void*)tempgameconf, 1, filesize, fp); - fclose(fp); - if (ret != filesize) - { - //TODO for oggzee - //print_status("Error reading gameconfig.txt"); - //wait(4); - return; - } - tempgameconfsize = filesize; - } - else - { - return; - } + u8 *tempgameconf; + u32 tempgameconfsize = 0; - // Remove non-ASCII characters - numnonascii = 0; - for (i = 0; i < tempgameconfsize; i++) - { - if (tempgameconf[i] < 9 || tempgameconf[i] > 126) - numnonascii++; - else - tempgameconf[i-numnonascii] = tempgameconf[i]; - } - tempgameconfsize -= numnonascii; + //memcpy(tempgameconf, defaultgameconfig, defaultgameconfig_size); + //tempgameconf[defaultgameconfig_size] = '\n'; + //tempgameconfsize = defaultgameconfig_size + 1; - *(tempgameconf + tempgameconfsize) = 0; - //gameconf = (tempgameconf + tempgameconfsize) + (4 - (((u32) (tempgameconf + tempgameconfsize)) % 4)); + char filepath[200]; + snprintf( filepath, sizeof( filepath ), "%s/gameconfig.txt", Settings.Cheatcodespath ); - for (maxgameidmatch = 0; maxgameidmatch <= 6; maxgameidmatch++) - { - i = 0; - while (i < tempgameconfsize) - { - maxgameidmatch2 = -1; - 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++; - parsebufpos = 0; - gameidmatch = 0; - while (tempgameconf[i] != ':') - { - if (tempgameconf[i] == '?') - { - parsebuffer[parsebufpos] = discid[parsebufpos]; - parsebufpos++; - gameidmatch--; - i++; - } - else if (tempgameconf[i] != 0 && tempgameconf[i] != ' ') - parsebuffer[parsebufpos++] = tempgameconf[i++]; - else if (tempgameconf[i] == ' ') - break; - else - i++; - if (parsebufpos == 8) break; - } - parsebuffer[parsebufpos] = 0; - if (strncasecmp("DEFAULT", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 7) - { - gameidmatch = 0; - goto idmatch; - } - if (strncmp(discid, parsebuffer, strlen(parsebuffer)) == 0) - { - gameidmatch += strlen(parsebuffer); - idmatch: - if (gameidmatch > maxgameidmatch2) - { - maxgameidmatch2 = gameidmatch; - } - } - while ((i != tempgameconfsize) && (tempgameconf[i] != 10 && tempgameconf[i] != 13)) i++; - } - while (i != tempgameconfsize && tempgameconf[i] != ':') - { - parsebufpos = 0; - while ((i != tempgameconfsize) && (tempgameconf[i] != 10 && tempgameconf[i] != 13)) - { - if (tempgameconf[i] != 0 && tempgameconf[i] != ' ' && tempgameconf[i] != '(' && tempgameconf[i] != ':') - parsebuffer[parsebufpos++] = tempgameconf[i++]; - else if (tempgameconf[i] == ' ' || tempgameconf[i] == '(' || tempgameconf[i] == ':') - break; - else - i++; - if (parsebufpos == 17) break; - } - parsebuffer[parsebufpos] = 0; - //if (!autobootcheck) - { - //if (strncasecmp("addtocodelist(", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 14) - //{ - // ret = sscanf(tempgameconf + i, "%x %x", &codeaddr, &codeval); - // if (ret == 2) - // addtocodelist(codeaddr, codeval); - //} - if (strncasecmp("codeliststart", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 13) - { - sscanf((char *)(tempgameconf + i), " = %x", (unsigned int *)&codelist); - } - if (strncasecmp("codelistend", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 11) - { - sscanf((char *)(tempgameconf + i), " = %x", (unsigned int *)&codelistend); - } - /* - 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) - { - ret = sscanf((char *)tempgameconf + i, "( %x , %x", &codeaddr, &codeval); - if (ret == 2) - { - *(gameconf + (gameconfsize / 4)) = 0; - gameconfsize += 4; - *(gameconf + (gameconfsize / 4)) = 0; - gameconfsize += 8; - *(gameconf + (gameconfsize / 4)) = codeaddr; - gameconfsize += 4; - *(gameconf + (gameconfsize / 4)) = codeval; - gameconfsize += 4; - DCFlushRange((void *) (gameconf + (gameconfsize / 4) - 5), 20); - } - } - 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) - { - *(gameconf + (gameconfsize / 4)) = 0; - gameconfsize += 4; - *(gameconf + (gameconfsize / 4)) = codeaddr; - gameconfsize += 4; - *(gameconf + (gameconfsize / 4)) = codeval; - gameconfsize += 4; - *(gameconf + (gameconfsize / 4)) = codeaddr2; - gameconfsize += 4; - *(gameconf + (gameconfsize / 4)) = codeval2; - gameconfsize += 4; - DCFlushRange((void *) (gameconf + (gameconfsize / 4) - 5), 20); - } - } - if (strncasecmp("searchandpoke", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 13) - { - ret = sscanf((char *)(tempgameconf + i), "( %x%n", &codeval, &tempoffset); - if (ret == 1) - { - gameconfsize += 4; - temp = 0; - while (ret == 1) - { - *(gameconf + (gameconfsize / 4)) = codeval; - gameconfsize += 4; - temp++; - i += 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)) = codeaddr; - gameconfsize += 4; - *(gameconf + (gameconfsize / 4)) = codeaddr2; - gameconfsize += 4; - *(gameconf + (gameconfsize / 4)) = codeoffset; - gameconfsize += 4; - *(gameconf + (gameconfsize / 4)) = codeval2; - gameconfsize += 4; - DCFlushRange((void *) (gameconf + (gameconfsize / 4) - temp - 5), temp * 4 + 20); - } - else - gameconfsize -= temp * 4 + 4; - } + fp = fopen( filepath, "rb" ); - } - /* - 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 ( !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" ); + } + } - 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 ( fp ) + { + fseek( fp, 0, SEEK_END ); + filesize = ftell( fp ); + fseek( fp, 0, SEEK_SET ); - }*/ - if (tempgameconf[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--; - } - } + tempgameconf = malloc( filesize ); + if ( tempgameconf == NULL ) + { + //TODO for oggzee + //print_status("Out of memory"); + //wait(4); + return; + } - free(tempgameconf); - //tempcodelist = ((u8 *) gameconf) + gameconfsize; + ret = fread( ( void* )tempgameconf, 1, filesize, fp ); + fclose( fp ); + if ( ret != filesize ) + { + //TODO for oggzee + //print_status("Error reading gameconfig.txt"); + //wait(4); + return; + } + tempgameconfsize = filesize; + } + else + { + return; + } + + // Remove non-ASCII characters + numnonascii = 0; + for ( i = 0; i < tempgameconfsize; i++ ) + { + if ( tempgameconf[i] < 9 || tempgameconf[i] > 126 ) + numnonascii++; + else + tempgameconf[i-numnonascii] = tempgameconf[i]; + } + tempgameconfsize -= numnonascii; + + *( tempgameconf + tempgameconfsize ) = 0; + //gameconf = (tempgameconf + tempgameconfsize) + (4 - (((u32) (tempgameconf + tempgameconfsize)) % 4)); + + for ( maxgameidmatch = 0; maxgameidmatch <= 6; maxgameidmatch++ ) + { + i = 0; + while ( i < tempgameconfsize ) + { + maxgameidmatch2 = -1; + 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++; + parsebufpos = 0; + gameidmatch = 0; + while ( tempgameconf[i] != ':' ) + { + if ( tempgameconf[i] == '?' ) + { + parsebuffer[parsebufpos] = discid[parsebufpos]; + parsebufpos++; + gameidmatch--; + i++; + } + else if ( tempgameconf[i] != 0 && tempgameconf[i] != ' ' ) + parsebuffer[parsebufpos++] = tempgameconf[i++]; + else if ( tempgameconf[i] == ' ' ) + break; + else + i++; + if ( parsebufpos == 8 ) break; + } + parsebuffer[parsebufpos] = 0; + if ( strncasecmp( "DEFAULT", parsebuffer, strlen( parsebuffer ) ) == 0 && strlen( parsebuffer ) == 7 ) + { + gameidmatch = 0; + goto idmatch; + } + if ( strncmp( discid, parsebuffer, strlen( parsebuffer ) ) == 0 ) + { + gameidmatch += strlen( parsebuffer ); +idmatch: + if ( gameidmatch > maxgameidmatch2 ) + { + maxgameidmatch2 = gameidmatch; + } + } + while ( ( i != tempgameconfsize ) && ( tempgameconf[i] != 10 && tempgameconf[i] != 13 ) ) i++; + } + while ( i != tempgameconfsize && tempgameconf[i] != ':' ) + { + parsebufpos = 0; + while ( ( i != tempgameconfsize ) && ( tempgameconf[i] != 10 && tempgameconf[i] != 13 ) ) + { + if ( tempgameconf[i] != 0 && tempgameconf[i] != ' ' && tempgameconf[i] != '(' && tempgameconf[i] != ':' ) + parsebuffer[parsebufpos++] = tempgameconf[i++]; + else if ( tempgameconf[i] == ' ' || tempgameconf[i] == '(' || tempgameconf[i] == ':' ) + break; + else + i++; + if ( parsebufpos == 17 ) break; + } + parsebuffer[parsebufpos] = 0; + //if (!autobootcheck) + { + //if (strncasecmp("addtocodelist(", parsebuffer, strlen(parsebuffer)) == 0 && strlen(parsebuffer) == 14) + //{ + // ret = sscanf(tempgameconf + i, "%x %x", &codeaddr, &codeval); + // if (ret == 2) + // addtocodelist(codeaddr, codeval); + //} + if ( strncasecmp( "codeliststart", parsebuffer, strlen( parsebuffer ) ) == 0 && strlen( parsebuffer ) == 13 ) + { + sscanf( ( char * )( tempgameconf + i ), " = %x", ( unsigned int * )&codelist ); + } + if ( strncasecmp( "codelistend", parsebuffer, strlen( parsebuffer ) ) == 0 && strlen( parsebuffer ) == 11 ) + { + sscanf( ( char * )( tempgameconf + i ), " = %x", ( unsigned int * )&codelistend ); + } + /* + 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 ) + { + ret = sscanf( ( char * )tempgameconf + i, "( %x , %x", &codeaddr, &codeval ); + if ( ret == 2 ) + { + *( gameconf + ( gameconfsize / 4 ) ) = 0; + gameconfsize += 4; + *( gameconf + ( gameconfsize / 4 ) ) = 0; + gameconfsize += 8; + *( gameconf + ( gameconfsize / 4 ) ) = codeaddr; + gameconfsize += 4; + *( gameconf + ( gameconfsize / 4 ) ) = codeval; + gameconfsize += 4; + DCFlushRange( ( void * ) ( gameconf + ( gameconfsize / 4 ) - 5 ), 20 ); + } + } + 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 ) + { + *( gameconf + ( gameconfsize / 4 ) ) = 0; + gameconfsize += 4; + *( gameconf + ( gameconfsize / 4 ) ) = codeaddr; + gameconfsize += 4; + *( gameconf + ( gameconfsize / 4 ) ) = codeval; + gameconfsize += 4; + *( gameconf + ( gameconfsize / 4 ) ) = codeaddr2; + gameconfsize += 4; + *( gameconf + ( gameconfsize / 4 ) ) = codeval2; + gameconfsize += 4; + DCFlushRange( ( void * ) ( gameconf + ( gameconfsize / 4 ) - 5 ), 20 ); + } + } + if ( strncasecmp( "searchandpoke", parsebuffer, strlen( parsebuffer ) ) == 0 && strlen( parsebuffer ) == 13 ) + { + ret = sscanf( ( char * )( tempgameconf + i ), "( %x%n", &codeval, &tempoffset ); + if ( ret == 1 ) + { + gameconfsize += 4; + temp = 0; + while ( ret == 1 ) + { + *( gameconf + ( gameconfsize / 4 ) ) = codeval; + gameconfsize += 4; + temp++; + i += 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 ) ) = codeaddr; + gameconfsize += 4; + *( gameconf + ( gameconfsize / 4 ) ) = codeaddr2; + gameconfsize += 4; + *( gameconf + ( gameconfsize / 4 ) ) = codeoffset; + gameconfsize += 4; + *( gameconf + ( gameconfsize / 4 ) ) = codeval2; + gameconfsize += 4; + DCFlushRange( ( void * ) ( gameconf + ( gameconfsize / 4 ) - temp - 5 ), temp * 4 + 20 ); + } + 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; + } + */ + } + /*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 ( tempgameconf[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--; + } + } + + 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]; + char filepath[150]; - gprintf("Ocarina: Searching codes..."); - gprintf("\n"); + gprintf( "Ocarina: Searching codes..." ); + gprintf( "\n" ); - sprintf(filepath, "%s%s", Settings.Cheatcodespath, (char *) id); - filepath[strlen(Settings.Cheatcodespath)+6] = 0x2E; - filepath[strlen(Settings.Cheatcodespath)+7] = 0x67; - filepath[strlen(Settings.Cheatcodespath)+8] = 0x63; - filepath[strlen(Settings.Cheatcodespath)+9] = 0x74; - filepath[strlen(Settings.Cheatcodespath)+10] = 0; + sprintf( filepath, "%s%s", Settings.Cheatcodespath, ( char * ) id ); + filepath[strlen( Settings.Cheatcodespath )+6] = 0x2E; + filepath[strlen( Settings.Cheatcodespath )+7] = 0x67; + filepath[strlen( Settings.Cheatcodespath )+8] = 0x63; + filepath[strlen( Settings.Cheatcodespath )+9] = 0x74; + filepath[strlen( Settings.Cheatcodespath )+10] = 0; - FILE * fp = fopen(filepath, "rb"); - if(!fp) { - gprintf("Ocarina: No codes found"); - printf("\n"); - return 0; - } + FILE * fp = fopen( filepath, "rb" ); + if ( !fp ) + { + 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) { - gprintf("Ocarina: No codes found"); - printf("\n"); - fclose(fp); - return 0; - } + code_buf = ( u8* ) malloc( filesize ); + if ( !code_buf ) + { + gprintf( "Ocarina: No codes found" ); + printf( "\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) { - gprintf("Ocarina: could not read file."); - gprintf("\n"); - free(code_buf); - code_buf = NULL; - code_size = 0; - return 0; - } + if ( code_size <= 0 ) + { + gprintf( "Ocarina: could not read file." ); + gprintf( "\n" ); + free( code_buf ); + code_buf = NULL; + code_size = 0; + return 0; + } - if (code_size > (u32)codelistend - (u32)codelist) - { - gprintf("Ocarina: Too many codes found"); - gprintf("\n"); - free(code_buf); - code_buf = NULL; - code_size = 0; - return 0; - } + if ( code_size > ( u32 )codelistend - ( u32 )codelist ) + { + gprintf( "Ocarina: Too many codes found" ); + gprintf( "\n" ); + free( code_buf ); + code_buf = NULL; + code_size = 0; + return 0; + } - gprintf("Ocarina: Codes found."); - gprintf("\n"); + gprintf( "Ocarina: Codes found." ); + gprintf( "\n" ); - return code_size; + return code_size; } //--------------------------------------------------------------------------------- void app_pokevalues() //--------------------------------------------------------------------------------- { - u32 i, *codeaddr, *codeaddr2, *addrfound = NULL; + u32 i, *codeaddr, *codeaddr2, *addrfound = NULL; - if (gameconfsize != 0) - { - for (i = 0; i < gameconfsize/4; i++) - { - if (*(gameconf + i) == 0) - { - 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); - } - i += 4; - } - else - { - 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) - { - i += *(gameconf + i) + 4; - continue; - } - if (codeaddr2 == 0) - codeaddr2 = codeaddr + *(gameconf + i); - addrfound = NULL; - while (codeaddr <= (codeaddr2 - *(gameconf + i))) - { - 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++; - } - i += *(gameconf + i) + 4; - } - } - } + if ( gameconfsize != 0 ) + { + for ( i = 0; i < gameconfsize / 4; i++ ) + { + if ( *( gameconf + i ) == 0 ) + { + 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 ); + } + i += 4; + } + else + { + 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 ) + { + i += *( gameconf + i ) + 4; + continue; + } + if ( codeaddr2 == 0 ) + codeaddr2 = codeaddr + *( gameconf + i ); + addrfound = NULL; + while ( codeaddr <= ( codeaddr2 - *( gameconf + i ) ) ) + { + 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++; + } + i += *( gameconf + i ) + 4; + } + } + } } @@ -639,200 +643,207 @@ void app_pokevalues() void load_handler() //--------------------------------------------------------------------------------- { - if (hooktype != 0x00) - { - if (debuggerselect == 0x01) - { - /*switch(gecko_channel) - { - case 0: // Slot A + if ( hooktype != 0x00 ) + { + if ( debuggerselect == 0x01 ) + { + /*switch(gecko_channel) + { + 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); - //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); - /* break; + 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 ); + /* 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); - } - // Load multidol handler - 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); - break; - case 0x02: - 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); - break; - case 0x04: - 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); - break; - case 0x06: - 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); - break; - case 0x08: - //if (customhooksize == 16) - //{ - // memcpy((void*)0x8000119C,customhook,12); - // memcpy((void*)0x80001198,customhook+3,4); - //} - break; - case 0x09: - //memcpy((void*)0x8000119C,wpadbuttonsdownhooks,12); - //memcpy((void*)0x80001198,wpadbuttonsdownhooks+3,4); - break; - case 0x0A: - //memcpy((void*)0x8000119C,wpadbuttonsdown2hooks,12); - //memcpy((void*)0x80001198,wpadbuttonsdown2hooks+3,4); - break; - } - DCFlushRange((void*)0x80001198,16); - } - memcpy((void *)0x80001800, (void*)0x80000000, 6); + 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 ); + } + // Load multidol handler + 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 ); + break; + case 0x02: + 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 ); + break; + case 0x04: + 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 ); + break; + case 0x06: + 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 ); + break; + case 0x08: + //if (customhooksize == 16) + //{ + // memcpy((void*)0x8000119C,customhook,12); + // memcpy((void*)0x80001198,customhook+3,4); + //} + break; + case 0x09: + //memcpy((void*)0x8000119C,wpadbuttonsdownhooks,12); + //memcpy((void*)0x80001198,wpadbuttonsdownhooks+3,4); + break; + case 0x0A: + //memcpy((void*)0x8000119C,wpadbuttonsdown2hooks,12); + //memcpy((void*)0x80001198,wpadbuttonsdown2hooks+3,4); + break; + } + DCFlushRange( ( void* )0x80001198, 16 ); + } + memcpy( ( void * )0x80001800, ( void* )0x80000000, 6 ); } int ocarina_do_code() { - if (!code_buf) { - return 0; - } + if ( !code_buf ) + { + return 0; + } - memset((void *)0x80001800, 0, 0x1800); + memset( ( void * )0x80001800, 0, 0x1800 ); - load_handler(); - memset(codelist, 0, (u32)codelistend - (u32)codelist); + load_handler(); + memset( codelist, 0, ( u32 )codelistend - ( u32 )codelist ); - //Copy the codes - if (code_size > 0) - { - memcpy(codelist, code_buf, code_size); - DCFlushRange(codelist, (u32)codelistend - (u32)codelist); - free(code_buf); - code_buf = NULL; - } + //Copy the codes + if ( code_size > 0 ) + { + memcpy( codelist, code_buf, code_size ); + DCFlushRange( codelist, ( u32 )codelistend - ( u32 )codelist ); + free( code_buf ); + code_buf = NULL; + } - // TODO What's this??? - // enable flag - //*(vu8*)0x80001807 = 0x01; + // TODO What's this??? + // enable flag + //*(vu8*)0x80001807 = 0x01; - //This needs to be done after loading the .dol into memory - app_pokevalues(); + //This needs to be done after loading the .dol into memory + app_pokevalues(); - // hooks are patched in dogamehooks() - return 1; + // hooks are patched in dogamehooks() + return 1; } -u32 do_bca_code(u8 *gameid) +u32 do_bca_code( u8 *gameid ) { - if (IOS_GetVersion() == 222 || IOS_GetVersion() == 223) - { - FILE *fp; - u32 filesize; - char filepath[150]; - memset(filepath, 0, 150); - u8 bcaCode[64] ATTRIBUTE_ALIGN(32); + if ( IOS_GetVersion() == 222 || IOS_GetVersion() == 223 ) + { + FILE *fp; + u32 filesize; + char filepath[150]; + memset( filepath, 0, 150 ); + u8 bcaCode[64] ATTRIBUTE_ALIGN( 32 ); - sprintf(filepath, "%s%6s", Settings.BcaCodepath, gameid); - filepath[strlen(Settings.BcaCodepath)+6] = '.'; - filepath[strlen(Settings.BcaCodepath)+7] = 'b'; - filepath[strlen(Settings.BcaCodepath)+8] = 'c'; - filepath[strlen(Settings.BcaCodepath)+9] = 'a'; + sprintf( filepath, "%s%6s", Settings.BcaCodepath, gameid ); + filepath[strlen( Settings.BcaCodepath )+6] = '.'; + filepath[strlen( Settings.BcaCodepath )+7] = 'b'; + filepath[strlen( Settings.BcaCodepath )+8] = 'c'; + filepath[strlen( Settings.BcaCodepath )+9] = 'a'; - fp = fopen(filepath, "rb"); - if (!fp) { - memset(filepath, 0, 150); - sprintf(filepath, "%s%3s", Settings.BcaCodepath, gameid + 1); - filepath[strlen(Settings.BcaCodepath)+3] = '.'; - filepath[strlen(Settings.BcaCodepath)+4] = 'b'; - filepath[strlen(Settings.BcaCodepath)+5] = 'c'; - filepath[strlen(Settings.BcaCodepath)+6] = 'a'; - fp = fopen(filepath, "rb"); + fp = fopen( filepath, "rb" ); + if ( !fp ) + { + memset( filepath, 0, 150 ); + sprintf( filepath, "%s%3s", Settings.BcaCodepath, gameid + 1 ); + filepath[strlen( Settings.BcaCodepath )+3] = '.'; + filepath[strlen( Settings.BcaCodepath )+4] = 'b'; + filepath[strlen( Settings.BcaCodepath )+5] = 'c'; + filepath[strlen( Settings.BcaCodepath )+6] = 'a'; + fp = fopen( filepath, "rb" ); - if (!fp) { - // Set default bcaCode - memset(bcaCode, 0, 64); - bcaCode[0x33] = 1; - } - } + if ( !fp ) + { + // Set default bcaCode + memset( bcaCode, 0, 64 ); + bcaCode[0x33] = 1; + } + } - if (fp) { - u32 ret = 0; + if ( fp ) + { + u32 ret = 0; - fseek(fp, 0, SEEK_END); - filesize = ftell(fp); + fseek( fp, 0, SEEK_END ); + filesize = ftell( fp ); - if (filesize == 64) { - fseek(fp, 0, SEEK_SET); - ret = fread(bcaCode, 1, 64, fp); - } - fclose(fp); + if ( filesize == 64 ) + { + fseek( fp, 0, SEEK_SET ); + ret = fread( bcaCode, 1, 64, fp ); + } + fclose( fp ); - if (ret != 64) { - // Set default bcaCode - memset(bcaCode, 0, 64); - bcaCode[0x33] = 1; - } - } + if ( ret != 64 ) + { + // Set default bcaCode + memset( bcaCode, 0, 64 ); + bcaCode[0x33] = 1; + } + } - mload_seek(*((u32 *) (dip_plugin+15*4)), SEEK_SET); // offset 15 (bca_data area) - mload_write(bcaCode, 64); - mload_close(); - } - return 0; + 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 73126e90..8ff424e0 100644 --- a/source/patches/fst.h +++ b/source/patches/fst.h @@ -23,16 +23,17 @@ #define __FST_H__ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif //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); -int ocarina_do_code(); + u32 do_bca_code( u8 *gameid ); + int ocarina_load_code( u8 *id ); + int ocarina_do_code(); #ifdef __cplusplus } diff --git a/source/patches/fwrite_patch.h b/source/patches/fwrite_patch.h index 54fedcc4..cd180104 100644 --- a/source/patches/fwrite_patch.h +++ b/source/patches/fwrite_patch.h @@ -1,15 +1,16 @@ -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 026562d6..18df024e 100644 --- a/source/patches/gamepatches.c +++ b/source/patches/gamepatches.c @@ -5,52 +5,52 @@ #include "wip.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) - { - 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)); + 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 ) ); - } - 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)); - } - return false; + } + 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 ) ); + } + 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)); + 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; + return false; } @@ -60,7 +60,8 @@ bool PoPPatch() #if 0 /** Isn't used right now **/ -static GXRModeObj* vmodes[] = { +static GXRModeObj* vmodes[] = +{ &TVNtsc240Ds, &TVNtsc240DsAa, &TVNtsc240Int, @@ -91,78 +92,84 @@ 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* 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 bool compare_videomodes(GXRModeObj* mode1, GXRModeObj* mode2) +static GXRModeObj* PAL2NTSC[] = { - if (mode1->viTVMode != mode2->viTVMode || mode1->fbWidth != mode2->fbWidth || mode1->efbHeight != mode2->efbHeight || mode1->xfbHeight != mode2->xfbHeight || + &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* 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 ) +{ + 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[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[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] ) { + 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; - } else { + } + else + { return true; } } -static void patch_videomode(GXRModeObj* mode1, GXRModeObj* mode2) +static void patch_videomode( GXRModeObj* mode1, GXRModeObj* mode2 ) { mode1->viTVMode = mode2->viTVMode; mode1->fbWidth = mode2->fbWidth; @@ -208,23 +215,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; } } @@ -237,33 +246,37 @@ static bool Search_and_patch_Video_Modes(u8 * Address, u32 Size, GXRModeObj* Tab 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 + GXRModeObj** table = NULL; + if ( videoSelected == 5 ) // patch { - switch (CONF_GetVideo()) { - case CONF_VIDEO_PAL: - if (CONF_GetEuRGB60() > 0) { - table = NTSC2PAL60; - } else { + switch ( CONF_GetVideo() ) + { + case CONF_VIDEO_PAL: + if ( CONF_GetEuRGB60() > 0 ) + { + table = NTSC2PAL60; + } + else + { + table = NTSC2PAL; + } + break; + + case CONF_VIDEO_MPAL: + + + table = NTSC2PAL; - } - break; - - case CONF_VIDEO_MPAL: + break; - - table = NTSC2PAL; - break; - - - default: - table = PAL2NTSC; - break; + default: + table = PAL2NTSC; + break; } - Search_and_patch_Video_Modes(dst, len, table); + Search_and_patch_Video_Modes( dst, len, table ); } } diff --git a/source/patches/gamepatches.h b/source/patches/gamepatches.h index ef8baa54..fbe6f3a8 100644 --- a/source/patches/gamepatches.h +++ b/source/patches/gamepatches.h @@ -3,10 +3,10 @@ #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 Search_and_patch_Video_Modes( u8 * Address, u32 Size, GXRModeObj* Table[] ); +void VideoModePatcher( u8 * dst, int len, u8 videoSelected ); #endif diff --git a/source/patches/geckomenu.h b/source/patches/geckomenu.h index 76430e44..45068415 100644 --- a/source/patches/geckomenu.h +++ b/source/patches/geckomenu.h @@ -32,7 +32,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 +48,13 @@ 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 bc3d0ed1..6a173005 100644 --- a/source/patches/kenobiwii.h +++ b/source/patches/kenobiwii.h @@ -3,262 +3,263 @@ 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 eada5c26..2a52520e 100644 --- a/source/patches/multidol.c +++ b/source/patches/multidol.c @@ -3,34 +3,35 @@ 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 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 int multidol_size = sizeof( multidol ); diff --git a/source/patches/patchcode.c b/source/patches/patchcode.c index f40ee279..ee96767f 100644 --- a/source/patches/patchcode.c +++ b/source/patches/patchcode.c @@ -34,323 +34,354 @@ //#include "fwrite_patch_slota.h" //#include "main.h" -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 +// 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 ) //--------------------------------------------------------------------------------- { //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", Settings.Cheatcodespath, GameId); + sprintf( filepath, "%s%s.gct", Settings.Cheatcodespath, GameId ); - if(!checkfile(filepath)) + if ( !checkfile( filepath ) ) return false; - //TODO for oggzee: when using Ocarina check if a hook as patched + //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 - */ + 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 + */ - void *addr_start = addr; - void *addr_end = addr+len; - bool hookpatched = false; + void *addr_start = addr; + void *addr_end = addr + len; + bool hookpatched = false; - while(addr_start < addr_end) - { - switch(hooktype) - { + while ( addr_start < addr_end ) + { + switch ( hooktype ) + { - case 0x00: - hookpatched = true; - break; + case 0x00: + hookpatched = true; + break; - case 0x01: - if(memcmp(addr_start, viwiihooks, sizeof(viwiihooks))==0) - { - patchhook((u32)addr_start, len); - hookpatched = true; - } - if(memcmp(addr_start, multidolhooks, sizeof(multidolhooks))==0) - { - multidolhook((u32)addr_start+sizeof(multidolhooks)-4); - hookpatched = true; - } - break; + case 0x01: + if ( memcmp( addr_start, viwiihooks, sizeof( viwiihooks ) ) == 0 ) + { + patchhook( ( u32 )addr_start, len ); + hookpatched = true; + } + if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + { + multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + hookpatched = true; + } + break; - case 0x02: + case 0x02: - if(memcmp(addr_start, kpadhooks, sizeof(kpadhooks))==0) - { - patchhook((u32)addr_start, len); - hookpatched = true; - } + if ( memcmp( addr_start, kpadhooks, sizeof( kpadhooks ) ) == 0 ) + { + patchhook( ( u32 )addr_start, len ); + hookpatched = true; + } - if(memcmp(addr_start, kpadoldhooks, sizeof(kpadoldhooks))==0) - { - patchhook((u32)addr_start, len); - hookpatched = true; - } - if(memcmp(addr_start, multidolhooks, sizeof(multidolhooks))==0) - { - multidolhook((u32)addr_start+sizeof(multidolhooks)-4); - hookpatched = true; - } - break; + if ( memcmp( addr_start, kpadoldhooks, sizeof( kpadoldhooks ) ) == 0 ) + { + patchhook( ( u32 )addr_start, len ); + hookpatched = true; + } + if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + { + multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + hookpatched = true; + } + break; - case 0x03: + case 0x03: - if(memcmp(addr_start, joypadhooks, sizeof(joypadhooks))==0) - { - patchhook((u32)addr_start, len); - hookpatched = true; - } - if(memcmp(addr_start, multidolhooks, sizeof(multidolhooks))==0) - { - multidolhook((u32)addr_start+sizeof(multidolhooks)-4); - hookpatched = true; - } - break; + if ( memcmp( addr_start, joypadhooks, sizeof( joypadhooks ) ) == 0 ) + { + patchhook( ( u32 )addr_start, len ); + hookpatched = true; + } + if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + { + multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + hookpatched = true; + } + break; - case 0x04: + case 0x04: - if(memcmp(addr_start, gxdrawhooks, sizeof(gxdrawhooks))==0) - { - patchhook((u32)addr_start, len); - hookpatched = true; - } - if(memcmp(addr_start, multidolhooks, sizeof(multidolhooks))==0) - { - multidolhook((u32)addr_start+sizeof(multidolhooks)-4); - hookpatched = true; - } - break; + if ( memcmp( addr_start, gxdrawhooks, sizeof( gxdrawhooks ) ) == 0 ) + { + patchhook( ( u32 )addr_start, len ); + hookpatched = true; + } + if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + { + multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + hookpatched = true; + } + break; - case 0x05: + case 0x05: - if(memcmp(addr_start, gxflushhooks, sizeof(gxflushhooks))==0) - { - patchhook((u32)addr_start, len); - hookpatched = true; - } - if(memcmp(addr_start, multidolhooks, sizeof(multidolhooks))==0) - { - multidolhook((u32)addr_start+sizeof(multidolhooks)-4); - hookpatched = true; - } - break; + if ( memcmp( addr_start, gxflushhooks, sizeof( gxflushhooks ) ) == 0 ) + { + patchhook( ( u32 )addr_start, len ); + hookpatched = true; + } + if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + { + multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + hookpatched = true; + } + break; - case 0x06: + case 0x06: - if(memcmp(addr_start, ossleepthreadhooks, sizeof(ossleepthreadhooks))==0) - { - patchhook((u32)addr_start, len); - hookpatched = true; - } - if(memcmp(addr_start, multidolhooks, sizeof(multidolhooks))==0) - { - multidolhook((u32)addr_start+sizeof(multidolhooks)-4); - hookpatched = true; - } - break; + if ( memcmp( addr_start, ossleepthreadhooks, sizeof( ossleepthreadhooks ) ) == 0 ) + { + patchhook( ( u32 )addr_start, len ); + hookpatched = true; + } + if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + { + multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + hookpatched = true; + } + break; - case 0x07: + case 0x07: - if(memcmp(addr_start, axnextframehooks, sizeof(axnextframehooks))==0) - { - patchhook((u32)addr_start, len); - hookpatched = true; - } - if(memcmp(addr_start, multidolhooks, sizeof(multidolhooks))==0) - { - multidolhook((u32)addr_start+sizeof(multidolhooks)-4); - hookpatched = true; - } - break; + if ( memcmp( addr_start, axnextframehooks, sizeof( axnextframehooks ) ) == 0 ) + { + patchhook( ( u32 )addr_start, len ); + hookpatched = true; + } + if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + { + multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + hookpatched = true; + } + break; - case 0x08: + case 0x08: - //if(memcmp(addr_start, customhook, customhooksize)==0) - //{ - // patchhook((u32)addr_start, len); - // hookpatched = true; - //} - if(memcmp(addr_start, multidolhooks, sizeof(multidolhooks))==0) - { - multidolhook((u32)addr_start+sizeof(multidolhooks)-4); - hookpatched = true; - } - break; - } - addr_start += 4; - } - return hookpatched; + //if(memcmp(addr_start, customhook, customhooksize)==0) + //{ + // patchhook((u32)addr_start, len); + // hookpatched = true; + //} + if ( memcmp( addr_start, multidolhooks, sizeof( multidolhooks ) ) == 0 ) + { + multidolhook( ( u32 )addr_start + sizeof( multidolhooks ) - 4 ); + hookpatched = true; + } + break; + } + addr_start += 4; + } + return hookpatched; } // Not used yet, for patching DOL once loaded into memory and befor execution @@ -358,72 +389,75 @@ bool dogamehooks(void *addr, u32 len) void patchdol(void *addr, u32 len) { - void *addr_start = addr; - void *addr_end = addr+len; + void *addr_start = addr; + void *addr_end = addr+len; - while(addr_start < addr_end) - { - if(memcmp(addr_start, wpadlibogc, sizeof(wpadlibogc))==0) { - // printf("\n\n\n"); - // printf("found at address %x\n", addr_start); - // sleep(10); - // patchhookdol((u32)addr_start, len); - patched = 1; - break; - } - addr_start += 4; - } + while(addr_start < addr_end) + { + if(memcmp(addr_start, wpadlibogc, sizeof(wpadlibogc))==0) { + // printf("\n\n\n"); + // printf("found at address %x\n", addr_start); + // sleep(10); + // patchhookdol((u32)addr_start, len); + patched = 1; + break; + } + addr_start += 4; + } } */ -void langpatcher(void *addr, u32 len) +void langpatcher( void *addr, u32 len ) { - void *addr_start = addr; - void *addr_end = addr+len; + void *addr_start = addr; + void *addr_end = addr + len; - while(addr_start < addr_end) - { + while ( addr_start < addr_end ) + { - if(memcmp(addr_start, langpatch, sizeof(langpatch))==0) { - if(configbytes[0] != 0xCD){ - langvipatch((u32)addr_start, len, configbytes[0]); - } - } - addr_start += 4; - } + if ( memcmp( addr_start, langpatch, sizeof( langpatch ) ) == 0 ) + { + if ( configbytes[0] != 0xCD ) + { + langvipatch( ( u32 )addr_start, len, configbytes[0] ); + } + } + addr_start += 4; + } } /* void patchdebug(void *addr, u32 len) { - void *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; - } + memcpy(addr_start,fwrite_patch_bin,fwrite_patch_bin_len); + // apply patch + } + addr_start += 4; + } } */ -void vidolpatcher(void *addr, u32 len) +void vidolpatcher( void *addr, u32 len ) { - void *addr_start = addr; - void *addr_end = addr+len; + void *addr_start = addr; + void *addr_end = addr + len; - while(addr_start < addr_end) - { - if(memcmp(addr_start, vipatchcode, sizeof(vipatchcode))==0) { - vipatch((u32)addr_start, len); - } - addr_start += 4; - } + while ( addr_start < addr_end ) + { + if ( memcmp( addr_start, vipatchcode, sizeof( vipatchcode ) ) == 0 ) + { + vipatch( ( u32 )addr_start, len ); + } + addr_start += 4; + } } diff --git a/source/patches/patchcode.h b/source/patches/patchcode.h index a67b6fda..a769c333 100644 --- a/source/patches/patchcode.h +++ b/source/patches/patchcode.h @@ -23,19 +23,20 @@ #define __PATCHCODE_H__ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif // Globals -u32 hooktype; -int patched; -u8 configbytes[2]; -u32 regionfree; + u32 hooktype; + int patched; + u8 configbytes[2]; + u32 regionfree; // Function prototypes -bool dogamehooks(void *addr, u32 len); -void langpatcher(void *addr, u32 len); -void vidolpatcher(void *addr, u32 len); -void patchdebug(void *addr, u32 len); + 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 ae90eb10..7448cb7b 100644 --- a/source/patches/ppc.h +++ b/source/patches/ppc.h @@ -2,82 +2,82 @@ /* Condition Register Bit Fields */ -#define cr0 0 -#define cr1 1 -#define cr2 2 -#define cr3 3 -#define cr4 4 -#define cr5 5 -#define cr6 6 -#define cr7 7 +#define cr0 0 +#define cr1 1 +#define cr2 2 +#define cr3 3 +#define cr4 4 +#define cr5 5 +#define cr6 6 +#define cr7 7 /* General Purpose Registers */ -#define r0 0 -#define r1 1 -#define r2 2 -#define r3 3 -#define r4 4 -#define r5 5 -#define r6 6 -#define r7 7 -#define r8 8 -#define r9 9 -#define r10 10 -#define r11 11 -#define r12 12 -#define r13 13 -#define r14 14 -#define r15 15 -#define r16 16 -#define r17 17 -#define r18 18 -#define r19 19 -#define r20 20 -#define r21 21 -#define r22 22 -#define r23 23 -#define r24 24 -#define r25 25 -#define r26 26 -#define r27 27 -#define r28 28 -#define r29 29 -#define r30 30 -#define r31 31 +#define r0 0 +#define r1 1 +#define r2 2 +#define r3 3 +#define r4 4 +#define r5 5 +#define r6 6 +#define r7 7 +#define r8 8 +#define r9 9 +#define r10 10 +#define r11 11 +#define r12 12 +#define r13 13 +#define r14 14 +#define r15 15 +#define r16 16 +#define r17 17 +#define r18 18 +#define r19 19 +#define r20 20 +#define r21 21 +#define r22 22 +#define r23 23 +#define r24 24 +#define r25 25 +#define r26 26 +#define r27 27 +#define r28 28 +#define r29 29 +#define r30 30 +#define r31 31 /* Define Floating Point Registers */ -#define f0 0 -#define f1 1 -#define f2 2 -#define f3 3 -#define f4 4 -#define f5 5 -#define f6 6 -#define f7 7 -#define f8 8 -#define f9 9 -#define f10 10 -#define f11 11 -#define f12 12 -#define f13 13 -#define f14 14 -#define f15 15 -#define f16 16 -#define f17 17 -#define f18 18 -#define f19 19 -#define f20 20 -#define f21 21 -#define f22 22 -#define f23 23 -#define f24 24 -#define f25 25 -#define f26 26 -#define f27 27 -#define f28 28 -#define f29 29 -#define f30 30 -#define f31 31 +#define f0 0 +#define f1 1 +#define f2 2 +#define f3 3 +#define f4 4 +#define f5 5 +#define f6 6 +#define f7 7 +#define f8 8 +#define f9 9 +#define f10 10 +#define f11 11 +#define f12 12 +#define f13 13 +#define f14 14 +#define f15 15 +#define f16 16 +#define f17 17 +#define f18 18 +#define f19 19 +#define f20 20 +#define f21 21 +#define f22 22 +#define f23 23 +#define f24 24 +#define f25 25 +#define f26 26 +#define f27 27 +#define f28 28 +#define f29 29 +#define f30 30 +#define f31 31 diff --git a/source/patches/wip.c b/source/patches/wip.c index a6e8af9b..059b166a 100644 --- a/source/patches/wip.c +++ b/source/patches/wip.c @@ -12,12 +12,12 @@ 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) + if ( !CodeList ) return; - if(Counter < 3) + if ( Counter < 3 ) { Counter++; return; @@ -27,24 +27,24 @@ 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; + offset = CodeList[i].offset + n - ProcessedLength; - if(offset < 0 || offset >= len) + 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 +56,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 +77,63 @@ 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); + 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 ); - 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"); - } - 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"); - } + 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" ); + } + 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" ); + } - if (!fp) + 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 +145,8 @@ int load_wip_code(u8 *gameid) CodeList[CodesCount].dstaddress = dstaddress; CodesCount++; } - fclose(fp); - gprintf("\n"); + fclose( fp ); + gprintf( "\n" ); - return 0; + return 0; } diff --git a/source/patches/wip.h b/source/patches/wip.h index 395244ea..a7abdbee 100644 --- a/source/patches/wip.h +++ b/source/patches/wip.h @@ -10,9 +10,9 @@ typedef struct 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); +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(); diff --git a/source/prompts/DiscBrowser.cpp b/source/prompts/DiscBrowser.cpp index 6ae60e43..9ff221e2 100644 --- a/source/prompts/DiscBrowser.cpp +++ b/source/prompts/DiscBrowser.cpp @@ -33,80 +33,89 @@ extern u8 mountMethod; /******************************************************************************** *Disk Browser *********************************************************************************/ -int DiscBrowse(struct discHdr * header) { - gprintf("\nDiscBrowser() started"); +int DiscBrowse( struct discHdr * header ) +{ + gprintf( "\nDiscBrowser() started" ); bool exit = false; int ret, choice; u64 offset; - HaltGui(); - if (!mountMethod) - { - ret = Disc_SetUSB(header->id); - if (ret < 0) { - ResumeGui(); - WindowPrompt(tr("ERROR:"), tr("Could not set USB."), tr("OK")); - return ret; - } - } - - ret = Disc_Open(); - if (ret < 0) { - ResumeGui(); - WindowPrompt(tr("ERROR:"), tr("Could not open Disc"), tr("OK")); + HaltGui(); + if ( !mountMethod ) + { + ret = Disc_SetUSB( header->id ); + if ( ret < 0 ) + { + ResumeGui(); + WindowPrompt( tr( "ERROR:" ), tr( "Could not set USB." ), tr( "OK" ) ); + return ret; + } + } + + ret = Disc_Open(); + if ( ret < 0 ) + { + ResumeGui(); + WindowPrompt( tr( "ERROR:" ), tr( "Could not open Disc" ), tr( "OK" ) ); return ret; } - ret = __Disc_FindPartition(&offset); - if (ret < 0) { - ResumeGui(); - WindowPrompt(tr("ERROR:"), tr("Could not find a WBFS partition."), tr("OK")); + ret = __Disc_FindPartition( &offset ); + if ( ret < 0 ) + { + ResumeGui(); + WindowPrompt( tr( "ERROR:" ), tr( "Could not find a WBFS partition." ), tr( "OK" ) ); return ret; } - ret = WDVD_OpenPartition(offset); - if (ret < 0) { - ResumeGui(); - WindowPrompt(tr("ERROR:"), tr("Could not open WBFS partition"), tr("OK")); + ret = WDVD_OpenPartition( offset ); + if ( ret < 0 ) + { + ResumeGui(); + WindowPrompt( tr( "ERROR:" ), tr( "Could not open WBFS partition" ), tr( "OK" ) ); return ret; } - - int *buffer = (int*)allocate_memory(0x20); - if (buffer == NULL) { - ResumeGui(); - WindowPrompt(tr("ERROR:"), tr("Not enough free memory."), tr("OK")); + int *buffer = ( int* )allocate_memory( 0x20 ); + + if ( buffer == NULL ) + { + ResumeGui(); + WindowPrompt( tr( "ERROR:" ), tr( "Not enough free memory." ), tr( "OK" ) ); return -1; } - ret = WDVD_Read(buffer, 0x20, 0x420); - if (ret < 0) { - ResumeGui(); - WindowPrompt(tr("ERROR:"), tr("Could not read the disc."), tr("OK")); + ret = WDVD_Read( buffer, 0x20, 0x420 ); + if ( ret < 0 ) + { + ResumeGui(); + 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; - if (fst == NULL) { - ResumeGui(); - WindowPrompt(tr("ERROR:"), tr("Not enough free memory."), tr("OK")); - free(buffer); + void *fstbuffer = allocate_memory( buffer[2] * 4 ); + FST_ENTRY *fst = ( FST_ENTRY * )fstbuffer; + + if ( fst == NULL ) + { + ResumeGui(); + 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) { - ResumeGui(); - WindowPrompt(tr("ERROR:"), tr("Could not read the disc."), tr("OK")); - free(buffer); - free(fstbuffer); + if ( ret < 0 ) + { + ResumeGui(); + WindowPrompt( tr( "ERROR:" ), tr( "Could not read the disc." ), tr( "OK" ) ); + free( buffer ); + free( fstbuffer ); return ret; } - ResumeGui(); - free(buffer); + ResumeGui(); + free( buffer ); WDVD_Reset(); //Disc_SetUSB(NULL); @@ -116,374 +125,403 @@ 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') { - options3.SetName(i, "%i", i); - options3.SetValue(i, fstfiles(fst, i)); + 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, fstfiles(fst, i)); dolfilecount++; } } - gprintf("\n%i alt dols found",dolfilecount); - if (dolfilecount <= 0) { - WindowPrompt(tr("ERROR"), tr("No DOL file found on disc."), tr("OK")); - free(fstbuffer); + gprintf( "\n%i alt dols found", dolfilecount ); + if ( dolfilecount <= 0 ) + { + 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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sgamesettings_background.png", CFG.theme_path); - GuiImageData settingsbg(imgPath, settings_background_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sgamesettings_background.png", CFG.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) { - cancelBtnTxt.SetWidescreen(CFG.widescreen); - cancelBtnImg.SetWidescreen(CFG.widescreen); + GuiText cancelBtnTxt( tr( "Back" ), 22, THEME.prompttext ); + cancelBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); + GuiImage cancelBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + cancelBtnTxt.SetWidescreen( CFG.widescreen ); + cancelBtnImg.SetWidescreen( CFG.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) + if ( dolfilecount > 9 ) scrollbaron = 1; - GuiCustomOptionBrowser optionBrowser3(396, 280, &options3, CFG.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, CFG.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) + if ( shutdown == 1 ) Sys_Shutdown(); - if (reset == 1) + 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)); - exit = true; + strlcpy( alternatedname, temp, sizeof( alternatedname ) ); + exit = true; } } - if (cancelBtn.GetState() == STATE_CLICKED) { - ret = 696969; - exit = true; + if ( cancelBtn.GetState() == STATE_CLICKED ) + { + ret = 696969; + exit = true; } } 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) { - gprintf("\nautoSelectDol() started"); +int autoSelectDol( const char *id, bool force ) +{ + gprintf( "\nautoSelectDol() started" ); + + char id4[10]; + sprintf( id4, "%c%c%c%c", id[0], id[1], id[2], id[3] ); - char id4[10]; - sprintf(id4,"%c%c%c%c",id[0],id[1],id[2],id[3]); - ////// games that can be forced (always need alt dol) - //Boogie - 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 - - //Madden NFL07 - if (strcmp(id,"RMDP69") == 0) return 39;//from isostar - - //Madden NFL08 - if (strcmp(id,"RNFP69") == 0) return 1079;//from isostar - - //Medal of Honor: Heroes 2 - if (strcmp(id,"RM2X69") == 0)return 601;//dj_skual - if (strcmp(id,"RM2P69") == 0)return 517;//MZottel - if (strcmp(id,"RM2E69") == 0) return 492;//Old8oy - - //Mortal Kombat - if (strcmp(id,"RKMP5D") == 0) return 290;//from isostar - if (strcmp(id,"RKME5D") == 0) return 290;//starstremr + //Boogie + if ( strcmp( id, "RBOP69" ) == 0 ) return 675;//previous value was 657 + if ( strcmp( id, "RBOE69" ) == 0 ) return 675;//starstremr - //NBA 08 - if (strcmp(id,"RNBX69") == 0) return 964;//from isostar + //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 - //Pangya! Golf with Style - 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 + //Madden NFL07 + if ( strcmp( id, "RMDP69" ) == 0 ) return 39;//from isostar + + //Madden NFL08 + if ( strcmp( id, "RNFP69" ) == 0 ) return 1079;//from isostar + + //Medal of Honor: Heroes 2 + if ( strcmp( id, "RM2X69" ) == 0 )return 601;//dj_skual + if ( strcmp( id, "RM2P69" ) == 0 )return 517;//MZottel + if ( strcmp( id, "RM2E69" ) == 0 ) return 492;//Old8oy + + //Mortal Kombat + 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 + + //Pangya! Golf with Style + 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 + + //SSX + if ( strcmp( id, "RSXP69" ) == 0 ) return 377;//previous value was 337 + if ( strcmp( id, "RSXE69" ) == 0 ) return 377;//previous value was 337 + + //Wii Sports Resort, needs alt dol one time only, to show the Motion Plus video + //if (strcmp(id,"RZTP01") == 0 && CheckForSave(id4)==0) return 952;//from isostar + //if (strcmp(id,"RZTE01") == 0 && CheckForSave(id4)==0) return 674;//from starstremr + //as well as Grand Slam Tennis, Tiger Woods 10, Virtual Tennis 2009 - //SSX - if (strcmp(id,"RSXP69") == 0) return 377;//previous value was 337 - if (strcmp(id,"RSXE69") == 0) return 377;//previous value was 337 - - //Wii Sports Resort, needs alt dol one time only, to show the Motion Plus video - //if (strcmp(id,"RZTP01") == 0 && CheckForSave(id4)==0) return 952;//from isostar - //if (strcmp(id,"RZTE01") == 0 && CheckForSave(id4)==0) return 674;//from starstremr - //as well as Grand Slam Tennis, Tiger Woods 10, Virtual Tennis 2009 - ///// games that can't be forced (alt dol is not always needed) - if (!force) { - - //Grand Slam Tennis - if (strcmp(id,"R5TP69") == 0) return 1493;//from isostar - if (strcmp(id,"R5TE69") == 0) return 1493;//starstremr - - //Medal of Honor Heroes - if (strcmp(id,"RMZX69") == 0) return 492;//from isostar - if (strcmp(id,"RMZP69") == 0) return 492;//from isostar - if (strcmp(id,"RMZE69") == 0) return 492;//starstremr - - //Tiger Woods 10 - if (strcmp(id,"R9OP69") == 0) return 1991;//from isostar - if (strcmp(id,"R9OE69") == 0) return 1973;//starstremr - - //Virtual Tennis 2009 - if (strcmp(id,"RVUP8P") == 0) return 16426;//from isostar - if (strcmp(id,"RVUE8P") == 0) return 16405;//from isostar - - //Wii Sports Resort - if (strcmp(id,"RZTP01") == 0) return 952;//from isostar - if (strcmp(id,"RZTE01") == 0) return 674;//from starstremr - } - + if ( !force ) + { + + //Grand Slam Tennis + if ( strcmp( id, "R5TP69" ) == 0 ) return 1493;//from isostar + if ( strcmp( id, "R5TE69" ) == 0 ) return 1493;//starstremr + + //Medal of Honor Heroes + if ( strcmp( id, "RMZX69" ) == 0 ) return 492;//from isostar + if ( strcmp( id, "RMZP69" ) == 0 ) return 492;//from isostar + if ( strcmp( id, "RMZE69" ) == 0 ) return 492;//starstremr + + //Tiger Woods 10 + if ( strcmp( id, "R9OP69" ) == 0 ) return 1991;//from isostar + if ( strcmp( id, "R9OE69" ) == 0 ) return 1973;//starstremr + + //Virtual Tennis 2009 + if ( strcmp( id, "RVUP8P" ) == 0 ) return 16426;//from isostar + if ( strcmp( id, "RVUE8P" ) == 0 ) return 16405;//from isostar + + //Wii Sports Resort + if ( strcmp( id, "RZTP01" ) == 0 ) return 952;//from isostar + if ( strcmp( id, "RZTE01" ) == 0 ) return 674;//from starstremr + } + return -1; } -int autoSelectDolMenu(const char *id, bool force) { +int autoSelectDolMenu( const char *id, bool force ) +{ - /* - char id4[10]; - sprintf(id4,"%c%c%c%c",id[0],id[1],id[2],id[3]); - - switch (CheckForSave(id4)) { - case 0: - WindowPrompt(tr("NO save"),0,tr("OK")); - break; - case 1: - WindowPrompt(tr("save"),0,tr("OK")); - break; - default: - char test[10]; - sprintf(test,"%d",CheckForSave(id4)); - WindowPrompt(test,0,tr("OK")); + /* + char id4[10]; + sprintf(id4,"%c%c%c%c",id[0],id[1],id[2],id[3]); + + switch (CheckForSave(id4)) { + case 0: + WindowPrompt(tr("NO save"),0,tr("OK")); break; - } - return -1; - */ - - //Indiana Jones and the Staff of Kings (Fate of Atlantis) - if (strcmp(id,"RJ8E64") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "Fate of Atlantis", tr("Default")); - switch (choice) { - case 1: - choice = 8; //from starstremr - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } - if (strcmp(id,"RJ8P64") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "Fate of Atlantis", tr("Default")); - switch (choice) { - case 1: - choice = 8; //from isostar - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } - - //Metal Slug Anthology (Metal Slug 6) - if (strcmp(id,"RMLEH4") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "Metal Slug 6", tr("Default")); - switch (choice) { - case 1: - choice = 54; //from lustar - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } - if (strcmp(id,"RMLP7U") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "Metal Slug 6", tr("Default")); - switch (choice) { - case 1: - choice = 56; //from isostar - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } - - //Metroid Prime Trilogy - if (strcmp(id,"R3ME01") == 0) { - //do not use any alt dol if there is no save game in the nand - /* - if (CheckForSave(id4)==0 && force) { - WindowPrompt(0,tr("You need to start this game one time to create a save file, then exit and start it again."),tr("OK")); - return -1; - } - */ - int choice = WindowPrompt(tr("Select a DOL"), 0, "Metroid Prime", "Metroid Prime 2", "Metroid Prime 3", tr("Default")); - switch (choice) { + case 1: + WindowPrompt(tr("save"),0,tr("OK")); + break; + default: + char test[10]; + sprintf(test,"%d",CheckForSave(id4)); + WindowPrompt(test,0,tr("OK")); + break; + } + return -1; + */ + + //Indiana Jones and the Staff of Kings (Fate of Atlantis) + if ( strcmp( id, "RJ8E64" ) == 0 ) + { + int choice = WindowPrompt( tr( "Select a DOL" ), 0, "Fate of Atlantis", tr( "Default" ) ); + switch ( choice ) + { case 1: - choice = 780; - break; - case 2: - choice = 781; - break; - case 3: - choice = 782; + choice = 8; //from starstremr break; default: // no alt dol - choice = 0; + choice = 0; break; - } - return choice; - } - if (strcmp(id,"R3MP01") == 0) { - /* - if (CheckForSave(id4)==0 && force) { - WindowPrompt(0,tr("You need to start this game one time to create a save file, then exit and start it again."),tr("OK")); - return -1; - } - */ - int choice = WindowPrompt(tr("Select a DOL"), 0, "Metroid Prime", "Metroid Prime 2", "Metroid Prime 3", tr("Default")); - switch (choice) { + } + return choice; + } + if ( strcmp( id, "RJ8P64" ) == 0 ) + { + int choice = WindowPrompt( tr( "Select a DOL" ), 0, "Fate of Atlantis", tr( "Default" ) ); + switch ( choice ) + { case 1: - choice = 782; - break; - case 2: - choice = 783; - break; - case 3: - choice = 784; + choice = 8; //from isostar break; default: // no alt dol - choice = 0; - break; - } - return choice; - } - - //Rampage: Total Destruction (M1.dol=Rampage, jarvos.dol=Rampage World Tour) - if (strcmp(id,"RPGP5D") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "Rampage", "World Tour", tr("Default")); - switch (choice) { + choice = 0; + break; + } + return choice; + } + + //Metal Slug Anthology (Metal Slug 6) + if ( strcmp( id, "RMLEH4" ) == 0 ) + { + int choice = WindowPrompt( tr( "Select a DOL" ), 0, "Metal Slug 6", tr( "Default" ) ); + switch ( choice ) + { case 1: - choice = 369; //from Ramzee - break; - case 2: - choice = 368; //from Ramzee - break; + choice = 54; //from lustar + break; default: // no alt dol - choice = 0; - break; - } - return choice; - } - - //The House Of The Dead 2 & 3 Return (only to play 2) - if (strcmp(id,"RHDE8P") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "HotD 2", tr("Default")); - switch (choice) { - case 1: - choice = 149; //from starstremr - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } - if (strcmp(id,"RHDP8P") == 0) { - int choice = WindowPrompt(tr("Select a DOL"), 0, "HotD 2", tr("Default")); - switch (choice) { - case 1: - choice = 149; //from isostar - break; - default: // no alt dol - choice = 0; - break; - } - return choice; - } + choice = 0; + break; + } + return choice; + } + if ( strcmp( id, "RMLP7U" ) == 0 ) + { + int choice = WindowPrompt( tr( "Select a DOL" ), 0, "Metal Slug 6", tr( "Default" ) ); + switch ( choice ) + { + case 1: + choice = 56; //from isostar + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } + + //Metroid Prime Trilogy + if ( strcmp( id, "R3ME01" ) == 0 ) + { + //do not use any alt dol if there is no save game in the nand + /* + if (CheckForSave(id4)==0 && force) { + WindowPrompt(0,tr("You need to start this game one time to create a save file, then exit and start it again."),tr("OK")); + return -1; + } + */ + int choice = WindowPrompt( tr( "Select a DOL" ), 0, "Metroid Prime", "Metroid Prime 2", "Metroid Prime 3", tr( "Default" ) ); + switch ( choice ) + { + case 1: + choice = 780; + break; + case 2: + choice = 781; + break; + case 3: + choice = 782; + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } + if ( strcmp( id, "R3MP01" ) == 0 ) + { + /* + if (CheckForSave(id4)==0 && force) { + WindowPrompt(0,tr("You need to start this game one time to create a save file, then exit and start it again."),tr("OK")); + return -1; + } + */ + int choice = WindowPrompt( tr( "Select a DOL" ), 0, "Metroid Prime", "Metroid Prime 2", "Metroid Prime 3", tr( "Default" ) ); + switch ( choice ) + { + case 1: + choice = 782; + break; + case 2: + choice = 783; + break; + case 3: + choice = 784; + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } + + //Rampage: Total Destruction (M1.dol=Rampage, jarvos.dol=Rampage World Tour) + if ( strcmp( id, "RPGP5D" ) == 0 ) + { + int choice = WindowPrompt( tr( "Select a DOL" ), 0, "Rampage", "World Tour", tr( "Default" ) ); + switch ( choice ) + { + case 1: + choice = 369; //from Ramzee + break; + case 2: + choice = 368; //from Ramzee + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } + + //The House Of The Dead 2 & 3 Return (only to play 2) + if ( strcmp( id, "RHDE8P" ) == 0 ) + { + int choice = WindowPrompt( tr( "Select a DOL" ), 0, "HotD 2", tr( "Default" ) ); + switch ( choice ) + { + case 1: + choice = 149; //from starstremr + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } + if ( strcmp( id, "RHDP8P" ) == 0 ) + { + int choice = WindowPrompt( tr( "Select a DOL" ), 0, "HotD 2", tr( "Default" ) ); + switch ( choice ) + { + case 1: + choice = 149; //from isostar + break; + default: // no alt dol + choice = 0; + break; + } + return choice; + } return -1; @@ -494,41 +532,43 @@ int autoSelectDolMenu(const char *id, bool force) { * 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; + dvddone = result; } -u8 DiscMount(discHdr *header) { - gprintf("\nDiscMount() "); +u8 DiscMount( discHdr *header ) +{ + 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 + HaltGui(); - ret = bwDVD_LowInit(); - dvddone = 0; - ret = bwDVD_LowReset(__dvd_readidcb); - while(ret>=0 && dvddone==0); - - dvddone = 0; - ret = bwDVD_LowReadID(g_diskID, __dvd_readidcb); // Leave this one here, or you'll get an IOCTL error - while(ret>=0 && dvddone==0); + u8 *tmpBuff = ( u8 * ) malloc( 0x60 ); + memcpy( tmpBuff, g_diskID, 0x60 ); // Make a backup of the first 96 bytes at 0x80000000 - 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_LowInit(); + dvddone = 0; + ret = bwDVD_LowReset( __dvd_readidcb ); + while ( ret >= 0 && dvddone == 0 ); - - ResumeGui(); - if (dvddone != 1) { - return 0; - } - return (header->magic == 0x5D1C9EA3) ? 1 : 2; // Don't check gamecube magic (0xC2339F3D) + dvddone = 0; + ret = bwDVD_LowReadID( g_diskID, __dvd_readidcb ); // Leave this one here, or you'll get an IOCTL error + while ( ret >= 0 && dvddone == 0 ); + + dvddone = 0; + ret = bwDVD_LowUnencryptedRead( g_diskID, 0x60, 0x00, __dvd_readidcb ); // Overwrite the g_diskID thing + while ( ret >= 0 && dvddone == 0 ); + + memcpy( header, g_diskID, 0x60 ); + memcpy( g_diskID, tmpBuff, 0x60 ); // Put the backup back, or games won't load + free( tmpBuff ); + + + ResumeGui(); + if ( dvddone != 1 ) + { + return 0; + } + return ( header->magic == 0x5D1C9EA3 ) ? 1 : 2; // Don't check gamecube magic (0xC2339F3D) } diff --git a/source/prompts/DiscBrowser.h b/source/prompts/DiscBrowser.h index 4ea20536..947c7c9f 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 47c719c6..cf4214ee 100644 --- a/source/prompts/ProgressWindow.cpp +++ b/source/prompts/ProgressWindow.cpp @@ -48,7 +48,7 @@ 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; @@ -60,10 +60,10 @@ extern "C" void ProgressCallback(s64 done, s64 total) ***************************************************************************/ static void GameInstallProgress() { - if (gameinstalltotal <= 0) + if ( gameinstalltotal <= 0 ) return; - if (gameinstalldone > gameinstalltotal) + if ( gameinstalldone > gameinstalltotal ) gameinstalldone = gameinstalltotal; static u32 expected = 300; @@ -72,31 +72,32 @@ 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; + m = ( elapsed / 60 ) % 60; s = elapsed % 60; - progressDone = 100.0*gameinstalldone/gameinstalltotal; + 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; } @@ -104,16 +105,17 @@ static void GameInstallProgress() /**************************************************************************** * 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 ); } /**************************************************************************** @@ -123,174 +125,181 @@ 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) { - GuiWindow promptWindow(472,320); - promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - promptWindow.SetPosition(0, -10); +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 ); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", CFG.theme_path ); + GuiImageData dialogBox( imgPath, dialogue_box_png ); GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); - GuiImage dialogBoxImg(&dialogBox); - if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen(CFG.widescreen); + GuiImage dialogBoxImg( &dialogBox ); + if ( Settings.wsprompt == yes ) + { + dialogBoxImg.SetWidescreen( CFG.widescreen ); } - snprintf(imgPath, sizeof(imgPath), "%sprogressbar_outline.png", CFG.theme_path); - GuiImageData progressbarOutline(imgPath, progressbar_outline_png); + snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_outline.png", CFG.theme_path ); + GuiImageData progressbarOutline( imgPath, progressbar_outline_png ); - GuiImage progressbarOutlineImg(&progressbarOutline); - if (Settings.wsprompt == yes) { - progressbarOutlineImg.SetWidescreen(CFG.widescreen); + GuiImage progressbarOutlineImg( &progressbarOutline ); + if ( Settings.wsprompt == yes ) + { + progressbarOutlineImg.SetWidescreen( CFG.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", CFG.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", CFG.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", CFG.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", CFG.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); + 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); + 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) && (CFG.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); + if ( ( Settings.wsprompt == yes ) && ( CFG.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 ); - 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) + 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(&sizeTxt); - promptWindow.Append(&speedTxt); + 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 ); } 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 (CFG.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); + if ( CFG.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); + 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) { - sizeTxt.SetText(progressSizeLeft); - speedTxt.SetText(progressSpeed); + if ( showSize ) + { + 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(); } @@ -298,13 +307,15 @@ static void ProgressWindow(const char *title, const char *msg1, const char *msg2 * ProgressThread ***************************************************************************/ -static void * ProgressThread (void *arg) { - while (1) { - if (!showProgress) - LWP_SuspendThread (progressthread); +static void * ProgressThread ( void *arg ) +{ + while ( 1 ) + { + if ( !showProgress ) + LWP_SuspendThread ( progressthread ); - ProgressWindow(progressTitle, progressMsg1, progressMsg2); - usleep(100); + ProgressWindow( progressTitle, progressMsg1, progressMsg2 ); + usleep( 100 ); } return NULL; } @@ -312,13 +323,14 @@ static void * ProgressThread (void *arg) { /**************************************************************************** * ProgressStop ***************************************************************************/ -void ProgressStop() { +void ProgressStop() +{ showProgress = 0; gameinstalltotal = -1; // wait for thread to finish - while (!LWP_ThreadIsSuspended(progressthread)) - usleep(100); + while ( !LWP_ThreadIsSuspended( progressthread ) ) + usleep( 100 ); } /**************************************************************************** @@ -327,72 +339,76 @@ 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) + 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) + 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) { - start = time(0); + if ( !done ) + { + 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; + m = ( elapsed / 60 ) % 60; s = elapsed % 60; - if (swTime == true) { - snprintf(progressTime, sizeof(progressTime), "%s %d:%02d:%02d",tr("Time left:"),h,m,s); + if ( swTime == true ) + { + snprintf( progressTime, sizeof( progressTime ), "%s %d:%02d:%02d", tr( "Time left:" ), h, m, s ); } - 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); + 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); + 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; - progressDone = 100.0*done/total; + progressDone = 100.0 * done / total; changed = true; } @@ -401,8 +417,9 @@ void ShowProgress(const char *title, const char *msg1, char *dynmsg2, f32 done, * * Startup Progressthread in idle prio ***************************************************************************/ -void InitProgressThread() { - LWP_CreateThread(&progressthread, ProgressThread, NULL, NULL, 16384, 80); +void InitProgressThread() +{ + LWP_CreateThread( &progressthread, ProgressThread, NULL, NULL, 16384, 80 ); } /**************************************************************************** @@ -410,7 +427,8 @@ void InitProgressThread() { * * Shutdown Progressthread ***************************************************************************/ -void ExitProgressThread() { - LWP_JoinThread(progressthread, NULL); +void ExitProgressThread() +{ + LWP_JoinThread( progressthread, NULL ); progressthread = LWP_THREAD_NULL; } diff --git a/source/prompts/ProgressWindow.h b/source/prompts/ProgressWindow.h index 204bdfc7..2cb2d239 100644 --- a/source/prompts/ProgressWindow.h +++ b/source/prompts/ProgressWindow.h @@ -10,16 +10,17 @@ 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 -extern "C" { +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 f81d36e2..363f5127 100644 --- a/source/prompts/PromptWindows.cpp +++ b/source/prompts/PromptWindows.cpp @@ -67,69 +67,74 @@ 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 save = -1; +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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size,Settings.sfxvolume); + GuiSound 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 ); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.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) { - okBtnTxt.SetWidescreen(CFG.widescreen); - okBtnImg.SetWidescreen(CFG.widescreen); + GuiText okBtnTxt( tr( "OK" ), 22, THEME.prompttext ); + GuiImage okBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + okBtnTxt.SetWidescreen( CFG.widescreen ); + okBtnImg.SetWidescreen( CFG.widescreen ); } - GuiButton okBtn(&okBtnImg,&okBtnImg, 0, 4, 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(CFG.widescreen); - cancelBtnImg.SetWidescreen(CFG.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 ) + { + cancelBtnTxt.SetWidescreen( CFG.widescreen ); + cancelBtnImg.SetWidescreen( CFG.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) + else if ( cancelBtn.GetState() == STATE_CLICKED ) save = 0; } - if (save == 1) { - snprintf(var, maxlen, "%s", numpad.kbtextstr); + if ( save == 1 ) + { + 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; } @@ -139,79 +144,84 @@ 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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size,Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.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) { - okBtnTxt.SetWidescreen(CFG.widescreen); - okBtnImg.SetWidescreen(CFG.widescreen); + GuiText okBtnTxt( tr( "OK" ), 22, THEME.prompttext ); + GuiImage okBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + okBtnTxt.SetWidescreen( CFG.widescreen ); + okBtnImg.SetWidescreen( CFG.widescreen ); } - GuiButton okBtn(&okBtnImg,&okBtnImg, 0, 4, 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(CFG.widescreen); - cancelBtnImg.SetWidescreen(CFG.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 ) + { + cancelBtnTxt.SetWidescreen( CFG.widescreen ); + cancelBtnImg.SetWidescreen( CFG.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) + else if ( cancelBtn.GetState() == STATE_CLICKED ) save = 0; } - if (save) { - snprintf(var, maxlen, "%s", keyboard.kbtextstr); + if ( save ) + { + 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; } @@ -219,211 +229,213 @@ int OnScreenKeyboard(char * var, u32 maxlen, int min) { * WindowCredits * Display credits ***************************************************************************/ -void WindowCredits() { - gprintf("\nWindowCredits()"); +void WindowCredits() +{ + gprintf( "\nWindowCredits()" ); 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(CFG.widescreen); //added - starImg.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - starImg.SetPosition(505,350); + GuiImageData star( little_star_png ); + GuiImage starImg( &star ); + starImg.SetWidescreen( CFG.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 - snprintf(svnTmp,sizeof(svnTmp), "%s", GetRev()); + snprintf( svnTmp, sizeof( svnTmp ), "%s", GetRev() ); char SvnRev[30]; - snprintf(SvnRev,sizeof(SvnRev), "Rev%sc IOS%u (Rev %u)", svnTmp, IOS_GetVersion(), IOS_GetRevision()); + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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) + if ( angle > 360 ) angle = 0; - usleep(12000); - starImg.SetAngle(angle); - if (ButtonsPressed() != 0) + usleep( 12000 ); + starImg.SetAngle( angle ); + if ( ButtonsPressed() != 0 ) exit = true; } @@ -432,12 +444,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; } @@ -450,51 +463,55 @@ void WindowCredits() { * WindowScreensaver * Display screensaver ***************************************************************************/ -int WindowScreensaver() { - gprintf("\nWindowScreenSaver()"); - int i = 0; - bool exit = false; - char imgPath[100];//uncomment for themable screensaver +int WindowScreensaver() +{ + gprintf( "\nWindowScreenSaver()" ); + int i = 0; + bool exit = false; + char imgPath[100];//uncomment for themable screensaver - /* initialize random seed: */ - srand ( time(NULL) ); + /* initialize random seed: */ + srand ( time( NULL ) ); - snprintf(imgPath, sizeof(imgPath), "%sscreensaver.png", CFG.theme_path);//uncomment for themable screensaver - GuiImageData GXlogo(imgPath, gxlogo_png);//uncomment for themable screensaver - //GuiImageData GXlogo(gxlogo_png);//comment for themable screensaver - GuiImage GXlogoImg(&GXlogo); - GXlogoImg.SetPosition(172,152); - GXlogoImg.SetAlignment(ALIGN_LEFT,ALIGN_TOP); + snprintf( imgPath, sizeof( imgPath ), "%sscreensaver.png", CFG.theme_path );//uncomment for themable screensaver + GuiImageData GXlogo( imgPath, gxlogo_png );//uncomment for themable screensaver + //GuiImageData GXlogo(gxlogo_png);//comment for themable screensaver + GuiImage GXlogoImg( &GXlogo ); + GXlogoImg.SetPosition( 172, 152 ); + GXlogoImg.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - GuiImage BackgroundImg(640,480,(GXColor) {0, 0, 0, 255}); - BackgroundImg.SetPosition(0,0); - BackgroundImg.SetAlignment(ALIGN_LEFT,ALIGN_TOP); + GuiImage BackgroundImg( 640, 480, ( GXColor ) {0, 0, 0, 255} ); + BackgroundImg.SetPosition( 0, 0 ); + BackgroundImg.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); - GuiWindow screensaverWindow(screenwidth,screenheight); - screensaverWindow.Append(&BackgroundImg); - screensaverWindow.Append(&GXlogoImg); + GuiWindow screensaverWindow( screenwidth, screenheight ); + screensaverWindow.Append( &BackgroundImg ); + screensaverWindow.Append( &GXlogoImg ); - HaltGui(); - mainWindow->SetState(STATE_DISABLED); - mainWindow->Append(&screensaverWindow); - ResumeGui(); + HaltGui(); + mainWindow->SetState( STATE_DISABLED ); + mainWindow->Append( &screensaverWindow ); + ResumeGui(); - while (!exit) { + 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; } @@ -509,258 +526,296 @@ 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("\nWindowPrompt(%s, %s, %s, %s, %s, %s, %i)",title,msg,btn1Label,btn2Label, btn3Label,btn4Label,wait); + gprintf( "\nWindowPrompt(%s, %s, %s, %s, %s, %s, %i)", title, msg, btn1Label, btn2Label, btn3Label, btn4Label, wait ); - GuiWindow promptWindow(472,320); - 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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", CFG.theme_path ); + GuiImageData dialogBox( imgPath, dialogue_box_png ); GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + 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) { - dialogBoxImg.SetWidescreen(CFG.widescreen); + GuiImage dialogBoxImg( &dialogBox ); + if ( Settings.wsprompt == yes ) + { + dialogBoxImg.SetWidescreen( CFG.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) { - btn1Txt.SetWidescreen(CFG.widescreen); - btn1Img.SetWidescreen(CFG.widescreen); + GuiText btn1Txt( btn1Label, 22, THEME.prompttext ); + GuiImage btn1Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn1Txt.SetWidescreen( CFG.widescreen ); + btn1Img.SetWidescreen( CFG.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) { - btn2Txt.SetWidescreen(CFG.widescreen); - btn2Img.SetWidescreen(CFG.widescreen); + GuiText btn2Txt( btn2Label, 22, THEME.prompttext ); + GuiImage btn2Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn2Txt.SetWidescreen( CFG.widescreen ); + btn2Img.SetWidescreen( CFG.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) { - btn3Txt.SetWidescreen(CFG.widescreen); - btn3Img.SetWidescreen(CFG.widescreen); + GuiText btn3Txt( btn3Label, 22, THEME.prompttext ); + GuiImage btn3Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn3Txt.SetWidescreen( CFG.widescreen ); + btn3Img.SetWidescreen( CFG.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) { - btn4Txt.SetWidescreen(CFG.widescreen); - btn4Img.SetWidescreen(CFG.widescreen); + GuiText btn4Txt( btn4Label, 22, THEME.prompttext ); + GuiImage btn4Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn4Txt.SetWidescreen( CFG.widescreen ); + btn4Img.SetWidescreen( CFG.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) && (CFG.widescreen)) {/////////////adjust buttons for widescreen - msgTxt.SetMaxWidth(330); + if ( ( Settings.wsprompt == yes ) && ( CFG.widescreen ) ) /////////////adjust buttons for widescreen + { + msgTxt.SetMaxWidth( 330 ); - 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); - } 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); - } 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); - } 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); - } 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); + 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 ); } - } else { + 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 ); + } + 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 ); + } + 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 ); + } + 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 ); + } + } + else + { - 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); - } 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); - } 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); - } 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); - } 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); + 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 ); + } + 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 ); + } + 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 ); + } + 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 ); + } + 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 ); } } 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) { - wiilight(0); + if ( shutdown == 1 ) + { + wiilight( 0 ); Sys_Shutdown(); } - if (reset == 1) + if ( reset == 1 ) Sys_Reboot(); - if (btn1.GetState() == STATE_CLICKED) { + if ( btn1.GetState() == STATE_CLICKED ) + { choice = 1; - } else if (btn2.GetState() == STATE_CLICKED) { - if (!btn3Label) + } + else if ( btn2.GetState() == STATE_CLICKED ) + { + if ( !btn3Label ) choice = 0; else choice = 2; - } else if (btn3.GetState() == STATE_CLICKED) { - if (!btn4Label) + } + else if ( btn3.GetState() == STATE_CLICKED ) + { + if ( !btn4Label ) choice = 0; else choice = 3; - } else if (btn4.GetState() == STATE_CLICKED) { + } + else if ( btn4.GetState() == STATE_CLICKED ) + { choice = 0; - } else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tscreenShotBtn clicked"); - screenShotBtn.ResetState(); - ScreenShot(); - gprintf("...It's easy, mmmmmmKay"); - } - if (count>0)count--; - if (count==0) choice = 1; + } + else if ( screenShotBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tscreenShotBtn clicked" ); + screenShotBtn.ResetState(); + ScreenShot(); + gprintf( "...It's easy, mmmmmmKay" ); + } + if ( count > 0 )count--; + if ( count == 0 ) choice = 1; } - 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",choice); + gprintf( " = %i", choice ); return choice; } @@ -777,51 +832,51 @@ int WindowPrompt(const char *title, const char *msg, const char *btn1Label, ***************************************************************************/ int WindowExitPrompt() { - gprintf("\nWindowExitPrompt()"); + gprintf( "\nWindowExitPrompt()" ); 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); + u64 oldstub = getStubDest(); + loadStub(); + 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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiWindow promptWindow( 640, 480 ); + promptWindow.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); + promptWindow.SetPosition( 0, 0 ); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - 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", CFG.theme_path); - GuiImageData battery(imgPath, battery_white_png); - snprintf(imgPath, sizeof(imgPath), "%sbattery_bar_white.png", CFG.theme_path); - GuiImageData batteryBar(imgPath, battery_bar_white_png); - snprintf(imgPath, sizeof(imgPath), "%sbattery_red.png", CFG.theme_path); - GuiImageData batteryRed(imgPath, battery_red_png); - snprintf(imgPath, sizeof(imgPath), "%sbattery_bar_red.png", CFG.theme_path); - GuiImageData batteryBarRed(imgPath, battery_bar_red_png); + snprintf( imgPath, sizeof( imgPath ), "%sbattery_white.png", CFG.theme_path ); + GuiImageData battery( imgPath, battery_white_png ); + snprintf( imgPath, sizeof( imgPath ), "%sbattery_bar_white.png", CFG.theme_path ); + GuiImageData batteryBar( imgPath, battery_bar_white_png ); + snprintf( imgPath, sizeof( imgPath ), "%sbattery_red.png", CFG.theme_path ); + GuiImageData batteryRed( imgPath, battery_red_png ); + snprintf( imgPath, sizeof( imgPath ), "%sbattery_bar_red.png", CFG.theme_path ); + GuiImageData batteryBarRed( imgPath, battery_bar_red_png ); int i = 0, ret = 0, level; char txt[3]; @@ -830,261 +885,291 @@ 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); + GuiTrigger trigA; + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); GuiTrigger trigB; - trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); + 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) { - closeTxt.SetWidescreen(CFG.widescreen); - closeImg.SetWidescreen(CFG.widescreen); + GuiText closeTxt( tr( "Close" ), 28, ( GXColor ) {0, 0, 0, 255} ); + closeTxt.SetPosition( 10, 3 ); + GuiImage closeImg( &close ); + if ( Settings.wsprompt == yes ) + { + closeTxt.SetWidescreen( CFG.widescreen ); + closeImg.SetWidescreen( CFG.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) { - btn2Txt.SetWidescreen(CFG.widescreen); - btn2Img.SetWidescreen(CFG.widescreen); + GuiText btn2Txt( tr( "Back to Loader" ), 28, ( GXColor ) {0, 0, 0, 255} ); + GuiImage btn2Img( &button ); + if ( Settings.wsprompt == yes ) + { + btn2Txt.SetWidescreen( CFG.widescreen ); + btn2Img.SetWidescreen( CFG.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) { - btn3Txt.SetWidescreen(CFG.widescreen); - btn3Img.SetWidescreen(CFG.widescreen); + GuiText btn3Txt( tr( "Wii Menu" ), 28, ( GXColor ) {0, 0, 0, 255} ); + GuiImage btn3Img( &button ); + if ( Settings.wsprompt == yes ) + { + btn3Txt.SetWidescreen( CFG.widescreen ); + btn3Img.SetWidescreen( CFG.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) { - wiimoteImg.SetWidescreen(CFG.widescreen); + GuiImage wiimoteImg( &wiimote ); + if ( Settings.wsprompt == yes ) + { + wiimoteImg.SetWidescreen( CFG.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++) { - if (WPAD_Probe(i, NULL) == WPAD_ERR_NONE) { // controller connected - level = (userInput[i].wpad.battery_level / 100.0) * 4; - if (level > 4) level = 4; + for ( i = 0; i < 4; i++ ) + { + if ( WPAD_Probe( i, NULL ) == WPAD_ERR_NONE ) // controller connected + { + level = ( userInput[i].wpad.battery_level / 100.0 ) * 4; + if ( level > 4 ) level = 4; - if (level <= 1) { - batteryBarImg[i]->SetImage(&batteryBarRed); - batteryImg[i]->SetImage(&batteryRed); - } else { - batteryBarImg[i]->SetImage(&batteryBar); - } + if ( level <= 1 ) + { + batteryBarImg[i]->SetImage( &batteryBarRed ); + batteryImg[i]->SetImage( &batteryRed ); + } + else + { + batteryBarImg[i]->SetImage( &batteryBar ); + } - batteryImg[i]->SetTile(level); + batteryImg[i]->SetTile( level ); - batteryBtn[i]->SetAlpha(255); - } else { // controller not connected - batteryImg[i]->SetTile(0); - batteryImg[i]->SetImage(&battery); - batteryBtn[i]->SetAlpha(70); + batteryBtn[i]->SetAlpha( 255 ); + } + else // controller not connected + { + batteryImg[i]->SetTile( 0 ); + batteryImg[i]->SetImage( &battery ); + batteryBtn[i]->SetAlpha( 70 ); } } - if (shutdown == 1) { - wiilight(0); + if ( shutdown == 1 ) + { + wiilight( 0 ); Sys_Shutdown(); } - if (reset == 1) + if ( reset == 1 ) Sys_Reboot(); - if (btn1.GetState() == STATE_CLICKED) { + 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) { - wiimoteImg.SetPosition(50,165); - } else if (btn2.GetState() == STATE_CLICKED) { - ret = WindowPrompt(tr("Are you sure?"), 0, tr("Yes"), tr("No")); - if (ret == 1) { + } + else if ( btn4.GetState() == STATE_SELECTED ) + { + wiimoteImg.SetPosition( 50, 165 ); + } + else if ( btn2.GetState() == STATE_CLICKED ) + { + 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) { - ret = WindowPrompt(tr("Are you sure?"), 0, tr("Yes"), tr("No")); - if (ret == 1) { + } + else if ( btn3.GetState() == STATE_CLICKED ) + { + 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) { - 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); + } + 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 ); - 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) { - wiimoteImg.SetPosition(50,210); + } + else if ( btn4.GetState() != STATE_SELECTED ) + { + 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) { - favoritevar = game_num->favorite; - playcount = game_num->count; - } else { - favoritevar = 0; - playcount = 0; - } - favoritevar = (favorite == favoritevar) ? 0 : favorite; // Press the current rank to reset the rank - CFG_save_game_num(gameId); - return favoritevar; + struct Game_NUM * game_num = CFG_get_game_num( gameId ); + if ( game_num ) + { + favoritevar = game_num->favorite; + playcount = game_num->count; + } + else + { + favoritevar = 0; + playcount = 0; + } + favoritevar = ( favorite == favoritevar ) ? 0 : favorite; // Press the current rank to reset the rank + CFG_save_game_num( gameId ); + return favoritevar; } -void SetFavoriteImages(GuiImage *b1, GuiImage *b2, GuiImage *b3, GuiImage *b4, GuiImage *b5, GuiImageData *on, GuiImageData *off) +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 ); } /**************************************************************************** @@ -1093,7 +1178,8 @@ void SetFavoriteImages(GuiImage *b1, GuiImage *b2, GuiImage *b3, GuiImage *b4, G * Displays a prompt window to user, with information, an error message, or * presenting a user with a choice ***************************************************************************/ -int GameWindowPrompt() { +int GameWindowPrompt() +{ int choice = -1, angle = 0; f32 size = 0.0; char ID[5]; @@ -1101,566 +1187,623 @@ int GameWindowPrompt() { GuiSound * gameSound = NULL; - gprintf("\nGameWindowPrompt()"); - GuiWindow promptWindow(472,320); - promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - promptWindow.SetPosition(0, -10); - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + gprintf( "\nGameWindowPrompt()" ); + GuiWindow promptWindow( 472, 320 ); + promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); + promptWindow.SetPosition( 0, -10 ); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf(imgPath, sizeof(imgPath), "%sfavorite.png", CFG.theme_path); - GuiImageData imgFavorite(imgPath, favorite_png); - snprintf(imgPath, sizeof(imgPath), "%snot_favorite.png", CFG.theme_path); - GuiImageData imgNotFavorite(imgPath, not_favorite_png); + snprintf( imgPath, sizeof( imgPath ), "%sfavorite.png", CFG.theme_path ); + GuiImageData imgFavorite( imgPath, favorite_png ); + snprintf( imgPath, sizeof( imgPath ), "%snot_favorite.png", CFG.theme_path ); + GuiImageData imgNotFavorite( imgPath, not_favorite_png ); - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", CFG.theme_path); - GuiImageData imgLeft(imgPath, startgame_arrow_left_png); - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", CFG.theme_path); - GuiImageData imgRight(imgPath, startgame_arrow_right_png); + snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_left.png", CFG.theme_path ); + GuiImageData imgLeft( imgPath, startgame_arrow_left_png ); + snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_right.png", CFG.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 (CFG.widescreen) - snprintf(imgPath, sizeof(imgPath), "%swdialogue_box_startgame.png", CFG.theme_path); + if ( CFG.widescreen ) + snprintf( imgPath, sizeof( imgPath ), "%swdialogue_box_startgame.png", CFG.theme_path ); else - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box_startgame.png", CFG.theme_path); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box_startgame.png", CFG.theme_path ); - GuiImageData dialogBox(imgPath, CFG.widescreen ? wdialogue_box_startgame_png : dialogue_box_startgame_png); - GuiImage dialogBoxImg(&dialogBox); + GuiImageData dialogBox( imgPath, CFG.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(CFG.widescreen); - GuiText nameTxt("", 22, THEME.prompttext); - if (Settings.wsprompt == yes) - nameTxt.SetWidescreen(CFG.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( CFG.widescreen ); + GuiText nameTxt( "", 22, THEME.prompttext ); + if ( Settings.wsprompt == yes ) + nameTxt.SetWidescreen( CFG.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) { - nameBtn.SetTrigger(&trigA); + if ( Settings.godmode == 1 && !mountMethod ) + { + 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(CFG.widescreen); - diskImg.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - diskImg.SetAngle(angle); + diskImg.SetWidescreen( CFG.widescreen ); + diskImg.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); + diskImg.SetAngle( angle ); GuiDiskCover diskImg2; - diskImg2.SetWidescreen(CFG.widescreen); - diskImg2.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - diskImg2.SetPosition(0, -20); - diskImg2.SetAngle(angle); - diskImg2.SetBeta(180); + diskImg2.SetWidescreen( CFG.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) { - btn2Txt.SetWidescreen(CFG.widescreen); - btn2Img.SetWidescreen(CFG.widescreen); + GuiText btn2Txt( tr( "Back" ), 22, THEME.prompttext ); + GuiImage btn2Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn2Txt.SetWidescreen( CFG.widescreen ); + btn2Img.SetWidescreen( CFG.widescreen ); } - 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); - } else { - btn2.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - btn2.SetPosition(0, -40); + 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 ); + } + else + { + 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) { - btn3Txt.SetWidescreen(CFG.widescreen); - btn3Img.SetWidescreen(CFG.widescreen); + GuiText btn3Txt( tr( "Settings" ), 22, THEME.prompttext ); + GuiImage btn3Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn3Txt.SetWidescreen( CFG.widescreen ); + btn3Img.SetWidescreen( CFG.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(CFG.widescreen); + btnFavoriteImg1.SetWidescreen( CFG.widescreen ); GuiImage btnFavoriteImg2; - btnFavoriteImg2.SetWidescreen(CFG.widescreen); + btnFavoriteImg2.SetWidescreen( CFG.widescreen ); GuiImage btnFavoriteImg3; - btnFavoriteImg3.SetWidescreen(CFG.widescreen); + btnFavoriteImg3.SetWidescreen( CFG.widescreen ); GuiImage btnFavoriteImg4; - btnFavoriteImg4.SetWidescreen(CFG.widescreen); + btnFavoriteImg4.SetWidescreen( CFG.widescreen ); GuiImage btnFavoriteImg5; - btnFavoriteImg5.SetWidescreen(CFG.widescreen); + btnFavoriteImg5.SetWidescreen( CFG.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) { - btnLeftImg.SetWidescreen(CFG.widescreen); + GuiImage btnLeftImg( &imgLeft ); + if ( Settings.wsprompt == yes ) + { + btnLeftImg.SetWidescreen( CFG.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) { - btnRightImg.SetWidescreen(CFG.widescreen); + GuiImage btnRightImg( &imgRight ); + if ( Settings.wsprompt == yes ) + { + btnRightImg.SetWidescreen( CFG.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(&sizeTxt); - promptWindow.Append(&btnLeft); - promptWindow.Append(&btnRight); - promptWindow.Append(&btnFavorite1); - promptWindow.Append(&btnFavorite2); - promptWindow.Append(&btnFavorite3); - promptWindow.Append(&btnFavorite4); - promptWindow.Append(&btnFavorite5); - } + 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 ); + } //check if unlocked - if (Settings.godmode == 1 && mountMethod!=2 && mountMethod!=3) { - promptWindow.Append(&btn3); + if ( Settings.godmode == 1 && mountMethod != 2 && mountMethod != 3 ) + { + 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) { - if (changed == 1) { - promptWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 50); - } else if (changed == 2) { - promptWindow.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 50); - } else if (changed == 3 || changed == 4) { - if (diskCover2) + while ( changed ) + { + if ( changed == 1 ) + { + promptWindow.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 50 ); + } + else if ( changed == 2 ) + { + promptWindow.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 50 ); + } + else if ( changed == 3 || changed == 4 ) + { + if ( diskCover2 ) delete diskCover2; diskCover2 = NULL; - if (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) - { - gameSound->Stop(); - delete gameSound; - gameSound = NULL; - } - u32 gameSoundDataLen; - const u8 *gameSoundData = LoadBannerSound(header->id, &gameSoundDataLen); - if(gameSoundData) - { - gameSound = new GuiSound(gameSoundData, gameSoundDataLen, Settings.gamesoundvolume, false, true); - bgMusic->SetVolume(0); - if(Settings.gamesound == 2) - gameSound->SetLoop(1); - gameSound->Play(); - } + if ( gameSound ) + { + gameSound->Stop(); + delete gameSound; + gameSound = NULL; + } + u32 gameSoundDataLen; + const u8 *gameSoundData = LoadBannerSound( header->id, &gameSoundDataLen ); + if ( gameSoundData ) + { + gameSound = new GuiSound( gameSoundData, gameSoundDataLen, Settings.gamesoundvolume, false, true ); + bgMusic->SetVolume( 0 ); + if ( Settings.gamesound == 2 ) + 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("\n\t%s",IDFull); - if (diskCover) + gprintf( "\n\t%s", 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()) { - snprintf (ID,sizeof(ID),"%c%c%c%c", header->id[0], header->id[1], header->id[2], header->id[3]); + if ( !diskCover->GetImage() ) + { + 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", CFG.theme_path); //changed to nodisc.png - diskCover = new GuiImageData(imgPath,nodisc_png); + snprintf( imgPath, sizeof( imgPath ), "%snodisc.png", CFG.theme_path ); //changed to nodisc.png + diskCover = new GuiImageData( imgPath, nodisc_png ); } } } - 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); + 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 ); 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); - } 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( 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 ) + { + 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); - } else - diskImg.SetImage(diskCover); + 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 ); - if (!mountMethod) - { - WBFS_GameSize(header->id, &size); - sizeTxt.SetTextf("%.2fGB", size); //set size text; - } + if ( !mountMethod ) + { + WBFS_GameSize( header->id, &size ); + sizeTxt.SetTextf( "%.2fGB", size ); //set size text; + } - nameTxt.SetText(get_title(header)); + nameTxt.SetText( get_title( header ) ); - struct Game_NUM* game_num = CFG_get_game_num(header->id); - if (game_num) { + struct Game_NUM* game_num = CFG_get_game_num( header->id ); + if ( game_num ) + { playcount = game_num->count; favoritevar = game_num->favorite; - } else { + } + else + { 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 (); - 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); - HaltGui(); - mainWindow->Remove(&promptWindow); - ResumeGui(); - wiilight(0); + 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 ); + HaltGui(); + mainWindow->Remove( &promptWindow ); + ResumeGui(); + wiilight( 0 ); Sys_Shutdown(); } - if (reset == 1) //for reset button + 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; - } else { + } + else + { favoritevar = 0; playcount = 0; } playcount += 1; - if (isInserted(bootDevice)) { - CFG_save_game_num(header->id); + if ( isInserted( bootDevice ) ) + { + 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 - if (isInserted(bootDevice)) { - SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 1); - SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); + else if ( btnFavorite1.GetState() == STATE_CLICKED ) //switch favorite + { + if ( isInserted( bootDevice ) ) + { + SetFavorite( &btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 1 ); + SetFavoriteImages( &btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite ); } btnFavorite1.ResetState(); } - else if (btnFavorite2.GetState() == STATE_CLICKED) {//switch favorite - if (isInserted(bootDevice)) { - SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 2); - SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); + else if ( btnFavorite2.GetState() == STATE_CLICKED ) //switch favorite + { + if ( isInserted( bootDevice ) ) + { + SetFavorite( &btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 2 ); + SetFavoriteImages( &btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite ); } btnFavorite2.ResetState(); } - else if (btnFavorite3.GetState() == STATE_CLICKED) {//switch favorite - if (isInserted(bootDevice)) { - SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 3); - SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); + else if ( btnFavorite3.GetState() == STATE_CLICKED ) //switch favorite + { + if ( isInserted( bootDevice ) ) + { + SetFavorite( &btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 3 ); + SetFavoriteImages( &btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite ); } btnFavorite3.ResetState(); } - else if (btnFavorite4.GetState() == STATE_CLICKED) {//switch favorite - if (isInserted(bootDevice)) { - SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 4); - SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); + else if ( btnFavorite4.GetState() == STATE_CLICKED ) //switch favorite + { + if ( isInserted( bootDevice ) ) + { + SetFavorite( &btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 4 ); + SetFavoriteImages( &btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite ); } btnFavorite4.ResetState(); } - else if (btnFavorite5.GetState() == STATE_CLICKED) {//switch favorite - if (isInserted(bootDevice)) { - SetFavorite(&btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 5); - SetFavoriteImages(&btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite); + else if ( btnFavorite5.GetState() == STATE_CLICKED ) //switch favorite + { + if ( isInserted( bootDevice ) ) + { + SetFavorite( &btnFavorite1, &btnFavorite2, &btnFavorite3, &btnFavorite4, &btnFavorite5, header->id, 5 ); + SetFavoriteImages( &btnFavoriteImg1, &btnFavoriteImg2, &btnFavoriteImg3, &btnFavoriteImg4, &btnFavoriteImg5, &imgFavorite, &imgNotFavorite ); } btnFavorite5.ResetState(); } - else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tscreenShotBtn clicked"); - screenShotBtn.ResetState(); - ScreenShot(); - gprintf("...It's easy, mmmmmmKay"); - } + else if ( screenShotBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tscreenShotBtn clicked" ); + screenShotBtn.ResetState(); + ScreenShot(); + gprintf( "...It's easy, mmmmmmKay" ); + } // this next part is long because nobody could agree on what the left/right buttons should do - else if ((btnRight.GetState() == STATE_CLICKED) && (Settings.xflip == no)) {//next game - promptWindow.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50); + else if ( ( btnRight.GetState() == STATE_CLICKED ) && ( Settings.xflip == no ) ) //next game + { + 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 - promptWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50); + else if ( ( btnLeft.GetState() == STATE_CLICKED ) && ( Settings.xflip == no ) ) //previous game + { + 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 - promptWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50); + else if ( ( btnRight.GetState() == STATE_CLICKED ) && ( Settings.xflip == yes ) ) //previous game + { + 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 - promptWindow.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50); + else if ( ( btnLeft.GetState() == STATE_CLICKED ) && ( Settings.xflip == yes ) ) //next game + { + 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 - promptWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50); + else if ( ( btnRight.GetState() == STATE_CLICKED ) && ( Settings.xflip == sysmenu ) ) //previous game + { + 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 - promptWindow.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50); + else if ( ( btnLeft.GetState() == STATE_CLICKED ) && ( Settings.xflip == sysmenu ) ) //next game + { + 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 - promptWindow.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 50); + else if ( ( btnRight.GetState() == STATE_CLICKED ) && ( Settings.xflip == wtf ) ) //previous game + { + 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 - promptWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 50); + else if ( ( btnLeft.GetState() == STATE_CLICKED ) && ( Settings.xflip == wtf ) ) //next game + { + 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 -// diskImg.SetBetaRotateEffect(45, 90); + else if ( ( btnRight.GetState() == STATE_CLICKED ) && ( Settings.xflip == disk3d ) ) //next game + { +// 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 -// diskImg.SetBetaRotateEffect(-45, 90); -// promptWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 1/*50*/); + 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*/); 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 - mainWindow->Remove(&promptWindow); + if ( changed != 3 && changed != 4 ) // changed==3 or changed==4 --> only Halt the GUI + { + mainWindow->Remove( &promptWindow ); ResumeGui(); } } delete diskCover; delete diskCover2; - if(gameSound) + if ( gameSound ) { gameSound->Stop(); - delete gameSound; + delete gameSound; gameSound = NULL; } - bgMusic->SetVolume(Settings.volume); + bgMusic->SetVolume( Settings.volume ); - gprintf("\n\treturn %i",choice); + gprintf( "\n\treturn %i", choice ); return choice; } @@ -1668,144 +1811,161 @@ int GameWindowPrompt() { * DiscWait ***************************************************************************/ int -DiscWait(const char *title, const char *msg, const char *btn1Label, const char *btn2Label, int IsDeviceWait) { +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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiWindow promptWindow( 472, 320 ); + promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); + promptWindow.SetPosition( 0, -10 ); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", CFG.theme_path ); + GuiImageData dialogBox( imgPath, dialogue_box_png ); GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + 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) { - dialogBoxImg.SetWidescreen(CFG.widescreen); + GuiImage dialogBoxImg( &dialogBox ); + if ( Settings.wsprompt == yes ) + { + dialogBoxImg.SetWidescreen( CFG.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) { - btn1Txt.SetWidescreen(CFG.widescreen); - btn1Img.SetWidescreen(CFG.widescreen); + GuiText btn1Txt( btn1Label, 22, THEME.prompttext ); + GuiImage btn1Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn1Txt.SetWidescreen( CFG.widescreen ); + btn1Img.SetWidescreen( CFG.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) { - btn1.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM); - btn1.SetPosition(40, -45); - } else { - btn1.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - btn1.SetPosition(0, -45); + if ( btn2Label ) + { + btn1.SetAlignment( ALIGN_LEFT, ALIGN_BOTTOM ); + btn1.SetPosition( 40, -45 ); + } + else + { + 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) { - btn2Txt.SetWidescreen(CFG.widescreen); - btn2Img.SetWidescreen(CFG.widescreen); + GuiText btn2Txt( btn2Label, 22, THEME.prompttext ); + GuiImage btn2Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn2Txt.SetWidescreen( CFG.widescreen ); + btn2Img.SetWidescreen( CFG.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) && (CFG.widescreen)) {/////////////adjust buttons for widescreen - msgTxt.SetMaxWidth(380); - if (btn2Label) { - 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); + if ( ( Settings.wsprompt == yes ) && ( CFG.widescreen ) ) /////////////adjust buttons for widescreen + { + msgTxt.SetMaxWidth( 380 ); + if ( btn2Label ) + { + 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 ); } } - 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) { - while (i >= 0) { + if ( IsDeviceWait ) + { + while ( i >= 0 ) + { VIDEO_WaitVSync(); - timerTxt.SetTextf("%u %s", i,tr("seconds left")); - /* HaltGui(); - if (Settings.cios == ios222) { - ret = IOS_ReloadIOS(222); - load_ehc_module(); - } else { - ret = IOS_ReloadIOS(249); - } - ResumeGui();*/ - sleep(1); + timerTxt.SetTextf( "%u %s", i, tr( "seconds left" ) ); + /* HaltGui(); + if (Settings.cios == ios222) { + ret = IOS_ReloadIOS(222); + load_ehc_module(); + } else { + ret = IOS_ReloadIOS(249); + } + ResumeGui();*/ + sleep( 1 ); USBDevice_deInit(); USBDevice_Init(); - ret = WBFS_Init(WBFS_DEVICE_USB); - if (ret>=0) + ret = WBFS_Init( WBFS_DEVICE_USB ); + if ( ret >= 0 ) break; i--; } - } else { - while (!(cover & 0x2)) { + } + else + { + 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) + 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; } @@ -1814,51 +1974,53 @@ DiscWait(const char *title, const char *msg, const char *btn1Label, const char * * FormatingPartition ***************************************************************************/ int -FormatingPartition(const char *title, partitionEntry *entry) { +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", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", CFG.theme_path ); + GuiImageData dialogBox( imgPath, dialogue_box_png ); GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); - GuiImage dialogBoxImg(&dialogBox); - if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen(CFG.widescreen); + GuiImage dialogBoxImg( &dialogBox ); + if ( Settings.wsprompt == yes ) + { + dialogBoxImg.SetWidescreen( CFG.widescreen ); } - GuiText 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; } @@ -1867,215 +2029,235 @@ FormatingPartition(const char *title, partitionEntry *entry) { /**************************************************************************** * 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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", CFG.theme_path ); + GuiImageData dialogBox( imgPath, dialogue_box_png ); GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); - GuiImage dialogBoxImg(&dialogBox); + GuiImage dialogBoxImg( &dialogBox ); - if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen(CFG.widescreen); + if ( Settings.wsprompt == yes ) + { + dialogBoxImg.SetWidescreen( CFG.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 gameList.LoadUnfiltered(); - cntMissFiles = 0; - int i = 0; - char filename[11]; + cntMissFiles = 0; + int i = 0; + char filename[11]; - //add IDs of games that are missing covers to cntMissFiles - bool found1 = false; - bool found2 = false; - bool found3 = false; - for (i = 0; i < gameList.size() && cntMissFiles < 500; i++) { - struct discHdr* header = gameList[i]; - if (choice2 != 3) { + //add IDs of games that are missing covers to cntMissFiles + bool found1 = false; + bool found2 = false; + bool found3 = false; + for ( i = 0; i < gameList.size() && cntMissFiles < 500; i++ ) + { + struct discHdr* header = gameList[i]; + if ( choice2 != 3 ) + { - char *covers_path = choice2==1 ? Settings.covers2d_path : Settings.covers_path; + char *covers_path = choice2 == 1 ? Settings.covers2d_path : Settings.covers_path; - snprintf (filename,sizeof(filename),"%c%c%c.png", header->id[0], header->id[1], header->id[2]); - found2 = findfile(filename, covers_path); + snprintf ( filename, sizeof( filename ), "%c%c%c.png", header->id[0], header->id[1], header->id[2] ); + found2 = findfile( filename, covers_path ); - snprintf (filename,sizeof(filename),"%c%c%c%c.png", header->id[0], header->id[1], header->id[2], header->id[3]); - found3 = findfile(filename, covers_path); + snprintf ( filename, sizeof( filename ), "%c%c%c%c.png", header->id[0], header->id[1], header->id[2], header->id[3] ); + found3 = findfile( filename, covers_path ); - snprintf(filename,sizeof(filename),"%c%c%c%c%c%c.png",header->id[0], header->id[1], header->id[2], - header->id[3], header->id[4], header->id[5]); //full id - found1 = findfile(filename, covers_path); - if (!found1 && !found2 && !found3) { //if could not find any image - snprintf(missingFiles[cntMissFiles],11,"%s",filename); - cntMissFiles++; - } - } else if (choice2 == 3) { - snprintf (filename,sizeof(filename),"%c%c%c.png", header->id[0], header->id[1], header->id[2]); - found2 = findfile(filename, Settings.disc_path); - snprintf(filename,sizeof(filename),"%c%c%c%c%c%c.png",header->id[0], header->id[1], header->id[2], - header->id[3], header->id[4], header->id[5]); //full id - found1 = findfile(filename,Settings.disc_path); - if (!found1 && !found2) { - snprintf(missingFiles[cntMissFiles],11,"%s",filename); - cntMissFiles++; - } - } - } - if (cntMissFiles == 0) { - msgTxt.SetText(tr("No file missing!")); - sleep(1); - } + snprintf( filename, sizeof( filename ), "%c%c%c%c%c%c.png", header->id[0], header->id[1], header->id[2], + header->id[3], header->id[4], header->id[5] ); //full id + found1 = findfile( filename, covers_path ); + if ( !found1 && !found2 && !found3 ) //if could not find any image + { + snprintf( missingFiles[cntMissFiles], 11, "%s", filename ); + cntMissFiles++; + } + } + else if ( choice2 == 3 ) + { + snprintf ( filename, sizeof( filename ), "%c%c%c.png", header->id[0], header->id[1], header->id[2] ); + found2 = findfile( filename, Settings.disc_path ); + snprintf( filename, sizeof( filename ), "%c%c%c%c%c%c.png", header->id[0], header->id[1], header->id[2], + header->id[3], header->id[4], header->id[5] ); //full id + found1 = findfile( filename, Settings.disc_path ); + if ( !found1 && !found2 ) + { + snprintf( missingFiles[cntMissFiles], 11, "%s", filename ); + cntMissFiles++; + } + } + } + if ( cntMissFiles == 0 ) + { + msgTxt.SetText( tr( "No file missing!" ) ); + sleep( 1 ); + } - promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); - 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); - gameList.FilterList(); + mainWindow->Remove( &promptWindow ); + mainWindow->SetState( STATE_DEFAULT ); + gameList.FilterList(); ResumeGui(); - gprintf(" = %i",cntMissFiles); - if (cntMissFiles > 0) { //&& !IsNetworkInit()) { - NetworkInitPrompt(); - } + gprintf( " = %i", cntMissFiles ); + if ( cntMissFiles > 0 ) //&& !IsNetworkInit()) { + { + NetworkInitPrompt(); + } - if (cntMissFiles == 0) { - return false; - } else { - return true; - } + if ( cntMissFiles == 0 ) + { + return false; + } + else + { + return true; + } } /**************************************************************************** * NetworkInitPrompt ***************************************************************************/ -bool NetworkInitPrompt() { +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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", CFG.theme_path ); + GuiImageData dialogBox( imgPath, dialogue_box_png ); GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); - GuiImage dialogBoxImg(&dialogBox); + GuiImage dialogBoxImg( &dialogBox ); - if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen(CFG.widescreen); + if ( Settings.wsprompt == yes ) + { + dialogBoxImg.SetWidescreen( CFG.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) { - btn1Txt.SetWidescreen(CFG.widescreen); - btn1Img.SetWidescreen(CFG.widescreen); + GuiText btn1Txt( tr( "Cancel" ), 22, THEME.prompttext ); + GuiImage btn1Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn1Txt.SetWidescreen( CFG.widescreen ); + btn1Img.SetWidescreen( CFG.widescreen ); } - GuiButton btn1(&btn1Img,&btn1Img, 2, 4, 0, -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) && (CFG.widescreen)) {/////////////adjust buttons for widescreen - btn1.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - btn1.SetPosition(0, -80); + if ( ( Settings.wsprompt == yes ) && ( CFG.widescreen ) ) /////////////adjust buttons for widescreen + { + 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()) { - msgTxt.SetText(tr("Could not initialize network!")); - sleep(3); + if ( !IsNetworkInit() ) + { + 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; 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 success; @@ -2089,202 +2271,224 @@ bool NetworkInitPrompt() { * action is in progress. ***************************************************************************/ int -ProgressDownloadWindow(int choice2) { +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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", CFG.theme_path ); + GuiImageData dialogBox( imgPath, dialogue_box_png ); GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); - GuiImage dialogBoxImg(&dialogBox); - if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen(CFG.widescreen); + GuiImage dialogBoxImg( &dialogBox ); + if ( Settings.wsprompt == yes ) + { + dialogBoxImg.SetWidescreen( CFG.widescreen ); } - snprintf(imgPath, sizeof(imgPath), "%sprogressbar_outline.png", CFG.theme_path); - GuiImageData progressbarOutline(imgPath, progressbar_outline_png); - GuiImage progressbarOutlineImg(&progressbarOutline); - if (Settings.wsprompt == yes) { - progressbarOutlineImg.SetWidescreen(CFG.widescreen); + snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_outline.png", CFG.theme_path ); + GuiImageData progressbarOutline( imgPath, progressbar_outline_png ); + GuiImage progressbarOutlineImg( &progressbarOutline ); + if ( Settings.wsprompt == yes ) + { + progressbarOutlineImg.SetWidescreen( CFG.widescreen ); } - progressbarOutlineImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarOutlineImg.SetPosition(25, 40); + progressbarOutlineImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + progressbarOutlineImg.SetPosition( 25, 40 ); - snprintf(imgPath, sizeof(imgPath), "%sprogressbar_empty.png", CFG.theme_path); - GuiImageData progressbarEmpty(imgPath, progressbar_empty_png); - GuiImage progressbarEmptyImg(&progressbarEmpty); - progressbarEmptyImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarEmptyImg.SetPosition(25, 40); - progressbarEmptyImg.SetTile(100); + snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_empty.png", CFG.theme_path ); + GuiImageData progressbarEmpty( imgPath, progressbar_empty_png ); + GuiImage progressbarEmptyImg( &progressbarEmpty ); + progressbarEmptyImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + progressbarEmptyImg.SetPosition( 25, 40 ); + progressbarEmptyImg.SetTile( 100 ); - snprintf(imgPath, sizeof(imgPath), "%sprogressbar.png", CFG.theme_path); - GuiImageData progressbar(imgPath, progressbar_png); - GuiImage progressbarImg(&progressbar); - progressbarImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarImg.SetPosition(25, 40); + snprintf( imgPath, sizeof( imgPath ), "%sprogressbar.png", CFG.theme_path ); + GuiImageData progressbar( imgPath, progressbar_png ); + GuiImage progressbarImg( &progressbar ); + progressbarImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + progressbarImg.SetPosition( 25, 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) { - btn1Txt.SetWidescreen(CFG.widescreen); - btn1Img.SetWidescreen(CFG.widescreen); + GuiText btn1Txt( tr( "Cancel" ), 22, THEME.prompttext ); + GuiImage btn1Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn1Txt.SetWidescreen( CFG.widescreen ); + btn1Img.SetWidescreen( CFG.widescreen ); } - GuiButton btn1(&btn1Img,&btn1Img, 2, 4, 0, -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) && (CFG.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); + if ( ( Settings.wsprompt == yes ) && ( CFG.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 ); } - 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; - int serverCnt3d = 1,serverCnt2d = 1,serverCntDisc = 2; + int offset = 0, tries = 0; + int serverCnt3d = 1, serverCnt2d = 1, serverCntDisc = 2; char server3d[100]; char serverDisc[100]; 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 (subfoldercreate(Settings.covers_path) != 1) { - WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK")); + if ( stat( Settings.covers_path, &st ) != 0 ) + { + if ( subfoldercreate( Settings.covers_path ) != 1 ) + { + WindowPrompt( tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" ) ); cntMissFiles = 0; } } - if (stat(Settings.covers2d_path, &st) != 0) { - if (subfoldercreate(Settings.covers2d_path) != 1) { - WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK")); + if ( stat( Settings.covers2d_path, &st ) != 0 ) + { + if ( subfoldercreate( Settings.covers2d_path ) != 1 ) + { + WindowPrompt( tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" ) ); cntMissFiles = 0; } } - if (stat(Settings.disc_path,&st) != 0) { - if (subfoldercreate(Settings.disc_path) != 1) { - WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK")); + if ( stat( Settings.disc_path, &st ) != 0 ) + { + if ( subfoldercreate( Settings.disc_path ) != 1 ) + { + WindowPrompt( tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" ) ); cntMissFiles = 0; } } //int server = 1; - while (i < cntMissFiles) { - tries=0; - prTxt.SetTextf("%i%%", 100*i/cntMissFiles); + while ( i < cntMissFiles ) + { + tries = 0; + prTxt.SetTextf( "%i%%", 100*i / cntMissFiles ); - if ((Settings.wsprompt == yes) && (CFG.widescreen)) { + if ( ( Settings.wsprompt == yes ) && ( CFG.widescreen ) ) + { //adjust for widescreen - progressbarImg.SetPosition(80,40); - progressbarImg.SetTile(80*i/cntMissFiles); - } else { - progressbarImg.SetTile(100*i/cntMissFiles); + progressbarImg.SetPosition( 80, 40 ); + progressbarImg.SetTile( 80*i / cntMissFiles ); + } + else + { + 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) { - while (triesRemove(&promptWindow); - mainWindow->SetState(STATE_DEFAULT); + mainWindow->Remove( &promptWindow ); + mainWindow->SetState( STATE_DEFAULT ); ResumeGui(); - if (cntNotFound != 0) { + if ( cntNotFound != 0 ) + { return cntNotFound; - } else { + } + else + { return 0; } } @@ -2557,12 +2860,12 @@ ProgressDownloadWindow(int choice2) { //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; - } + 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); @@ -2571,144 +2874,158 @@ ProgressDownloadWindow(int choice2) { */ #ifdef FULLCHANNEL ///////////////////this is only used if the dol is being compiled for a full channel -int ProgressUpdateWindow() { +int ProgressUpdateWindow() +{ int ret = 0, failed = 0; - gprintf("\nProgressUpdateWindow(full channel)"); - GuiWindow promptWindow(472,320); - promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - promptWindow.SetPosition(0, -10); + gprintf( "\nProgressUpdateWindow(full channel)" ); + GuiWindow promptWindow( 472, 320 ); + promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); + promptWindow.SetPosition( 0, -10 ); - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, SOUND_PCM, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, SOUND_PCM, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", CFG.theme_path ); + GuiImageData dialogBox( imgPath, dialogue_box_png ); GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); - GuiImage dialogBoxImg(&dialogBox); - if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen(CFG.widescreen); + GuiImage dialogBoxImg( &dialogBox ); + if ( Settings.wsprompt == yes ) + { + dialogBoxImg.SetWidescreen( CFG.widescreen ); } - snprintf(imgPath, sizeof(imgPath), "%sprogressbar_outline.png", CFG.theme_path); - GuiImageData progressbarOutline(imgPath, progressbar_outline_png); - GuiImage progressbarOutlineImg(&progressbarOutline); - if (Settings.wsprompt == yes) { - progressbarOutlineImg.SetWidescreen(CFG.widescreen); + snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_outline.png", CFG.theme_path ); + GuiImageData progressbarOutline( imgPath, progressbar_outline_png ); + GuiImage progressbarOutlineImg( &progressbarOutline ); + if ( Settings.wsprompt == yes ) + { + progressbarOutlineImg.SetWidescreen( CFG.widescreen ); } - progressbarOutlineImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarOutlineImg.SetPosition(25, 7); + progressbarOutlineImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + progressbarOutlineImg.SetPosition( 25, 7 ); - snprintf(imgPath, sizeof(imgPath), "%sprogressbar_empty.png", CFG.theme_path); - GuiImageData progressbarEmpty(imgPath, progressbar_empty_png); - GuiImage progressbarEmptyImg(&progressbarEmpty); - progressbarEmptyImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarEmptyImg.SetPosition(25, 7); - progressbarEmptyImg.SetTile(100); + snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_empty.png", CFG.theme_path ); + GuiImageData progressbarEmpty( imgPath, progressbar_empty_png ); + GuiImage progressbarEmptyImg( &progressbarEmpty ); + progressbarEmptyImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + progressbarEmptyImg.SetPosition( 25, 7 ); + progressbarEmptyImg.SetTile( 100 ); - snprintf(imgPath, sizeof(imgPath), "%sprogressbar.png", CFG.theme_path); - GuiImageData progressbar(imgPath, progressbar_png); - GuiImage progressbarImg(&progressbar); - progressbarImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarImg.SetPosition(25, 7); + snprintf( imgPath, sizeof( imgPath ), "%sprogressbar.png", CFG.theme_path ); + GuiImageData progressbar( imgPath, progressbar_png ); + GuiImage progressbarImg( &progressbar ); + progressbarImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + progressbarImg.SetPosition( 25, 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(NULL, 26, THEME.prompttext); - prTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - prTxt.SetPosition(0, 7); + GuiText prTxt( 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) { - btn1Txt.SetWidescreen(CFG.widescreen); - btn1Img.SetWidescreen(CFG.widescreen); + GuiText btn1Txt( tr( "Cancel" ), 22, THEME.prompttext ); + GuiImage btn1Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn1Txt.SetWidescreen( CFG.widescreen ); + btn1Img.SetWidescreen( CFG.widescreen ); } - GuiButton btn1(&btn1Img,&btn1Img, 2, 4, 0, -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) && (CFG.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); + if ( ( Settings.wsprompt == yes ) && ( CFG.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 ); } - 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 (subfoldercreate(Settings.covers_path) != 1) { - WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK")); + if ( stat( Settings.update_path, &st ) != 0 ) + { + if ( subfoldercreate( Settings.covers_path ) != 1 ) + { + WindowPrompt( tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" ) ); ret = -1; failed = -1; } } - if (stat(Settings.titlestxt_path, &st) != 0) { - if (subfoldercreate(Settings.titlestxt_path) != 1) { - WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK")); + if ( stat( Settings.titlestxt_path, &st ) != 0 ) + { + if ( subfoldercreate( Settings.titlestxt_path ) != 1 ) + { + WindowPrompt( tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" ) ); ret = -1; failed = -1; } } //make the URL to get XML based on our games - char XMLurl[3540]; - build_XML_URL(XMLurl,sizeof(XMLurl)); + char XMLurl[3540]; + build_XML_URL( XMLurl, sizeof( XMLurl ) ); char dolpath[150]; // char dolpathsuccess[150];//use coverspath as a folder for the update wad so we dont make a new folder and have to delete it - snprintf(dolpath, sizeof(dolpath), "%sULNR.wad", Settings.covers_path); + snprintf( dolpath, sizeof( dolpath ), "%sULNR.wad", Settings.covers_path ); //snprintf(dolpathsuccess, sizeof(dolpathsuccess), "%sUNEO.wad", Settings.covers_path); Initialize_Network(); - while (!IsNetworkInit()) { + while ( !IsNetworkInit() ) + { VIDEO_WaitVSync(); Initialize_Network(); - if (IsNetworkInit()) { - msgTxt.SetText(GetNetworkIP()); - } else { - msgTxt.SetText(tr("Could not initialize network!")); + if ( IsNetworkInit() ) + { + msgTxt.SetText( GetNetworkIP() ); + } + else + { + msgTxt.SetText( tr( "Could not initialize network!" ) ); } - if (btn1.GetState() == STATE_CLICKED) { + if ( btn1.GetState() == STATE_CLICKED ) + { ret = -1; failed = -1; btn1.ResetState(); @@ -2716,162 +3033,193 @@ int ProgressUpdateWindow() { } } - if (IsNetworkInit() && ret >= 0) { + if ( IsNetworkInit() && ret >= 0 ) + { int newrev = CheckUpdate(); - if (newrev > 0) { + if ( newrev > 0 ) + { FILE * pfile; - sprintf(msg, "Rev%i %s.", newrev, tr("available")); - int choice = WindowPrompt(msg, 0, tr("Update"),tr("Cancel")); - if (choice == 1) { - titleTxt.SetTextf("%s USB Loader GX", tr("Updating")); - msgTxt.SetPosition(0,100); - msgTxt.SetTextf("%s", tr("Updating WiiTDB.zip")); + sprintf( msg, "Rev%i %s.", newrev, tr( "available" ) ); + int choice = WindowPrompt( msg, 0, tr( "Update" ), tr( "Cancel" ) ); + if ( choice == 1 ) + { + titleTxt.SetTextf( "%s USB Loader GX", tr( "Updating" ) ); + msgTxt.SetPosition( 0, 100 ); + msgTxt.SetTextf( "%s", tr( "Updating WiiTDB.zip" ) ); - char wiitdbpath[200]; - char wiitdbpathtmp[200]; - struct block file = downloadfile(XMLurl); - if (file.data != NULL) { - snprintf(wiitdbpath, sizeof(wiitdbpath), "%swiitdb_%s.zip", Settings.titlestxt_path,game_partition); - snprintf(wiitdbpathtmp, sizeof(wiitdbpathtmp), "%swiitmp_%s.zip", Settings.titlestxt_path,game_partition); - rename(wiitdbpath,wiitdbpathtmp); - pfile = fopen(wiitdbpath, "wb"); - fwrite(file.data,1,file.size,pfile); - fclose(pfile); - free(file.data); - CloseXMLDatabase(); - if (OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true)) { // open file, reload titles, keep in memory - remove(wiitdbpathtmp); - } else { - remove(wiitdbpath); - rename(wiitdbpathtmp,wiitdbpath); - OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true); // open file, reload titles, keep in memory - } - } + char wiitdbpath[200]; + char wiitdbpathtmp[200]; + struct block file = downloadfile( XMLurl ); + if ( file.data != NULL ) + { + snprintf( wiitdbpath, sizeof( wiitdbpath ), "%swiitdb_%s.zip", Settings.titlestxt_path, game_partition ); + snprintf( wiitdbpathtmp, sizeof( wiitdbpathtmp ), "%swiitmp_%s.zip", Settings.titlestxt_path, game_partition ); + rename( wiitdbpath, wiitdbpathtmp ); + pfile = fopen( wiitdbpath, "wb" ); + fwrite( file.data, 1, file.size, pfile ); + fclose( pfile ); + free( file.data ); + CloseXMLDatabase(); + if ( OpenXMLDatabase( Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride == 1 ? true : false, true ) ) // open file, reload titles, keep in memory + { + remove( wiitdbpathtmp ); + } + else + { + remove( wiitdbpath ); + rename( wiitdbpathtmp, wiitdbpath ); + OpenXMLDatabase( Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride == 1 ? true : false, true ); // open file, reload titles, keep in memory + } + } - msgTxt.SetTextf("%s", tr("Updating Language Files:")); + msgTxt.SetTextf( "%s", tr( "Updating Language Files:" ) ); updateLanguageFiles(); - promptWindow.Append(&progressbarEmptyImg); - promptWindow.Append(&progressbarImg); - promptWindow.Append(&progressbarOutlineImg); - promptWindow.Append(&prTxt); - msgTxt.SetTextf("%s Rev%i wad.", tr("Downloading"), newrev); + promptWindow.Append( &progressbarEmptyImg ); + promptWindow.Append( &progressbarImg ); + promptWindow.Append( &progressbarOutlineImg ); + promptWindow.Append( &prTxt ); + msgTxt.SetTextf( "%s Rev%i wad.", tr( "Downloading" ), newrev ); s32 filesize; - if (Settings.beta_upgrades) { - char url[255]; - memset(&url, 0, 255); - sprintf((char *) &url, "http://usbloader-gui.googlecode.com/files/r%d.wad", newrev); - filesize = download_request((char *) &url); - } else { - filesize = download_request("http://www.techjawa.com/usbloadergx/ULNR.file");//for some reason it didn't download completely when saved as a wad. - } + if ( Settings.beta_upgrades ) + { + char url[255]; + memset( &url, 0, 255 ); + sprintf( ( char * ) &url, "http://usbloader-gui.googlecode.com/files/r%d.wad", newrev ); + filesize = download_request( ( char * ) & url ); + } + else + { + filesize = download_request( "http://www.techjawa.com/usbloadergx/ULNR.file" );//for some reason it didn't download completely when saved as a wad. + } - if (filesize > 0) { + if ( filesize > 0 ) + { - pfile = fopen(dolpath, "wb");//here we save the txt as a wad + pfile = fopen( dolpath, "wb" );//here we save the txt as a wad u8 * blockbuffer = new unsigned char[BLOCKSIZE]; - for (s32 i = 0; i < filesize; i += BLOCKSIZE) { - usleep(100); - prTxt.SetTextf("%i%%", (100*i/filesize)+1); - if ((Settings.wsprompt == yes) && (CFG.widescreen)) { - progressbarImg.SetTile(80*i/filesize); - } else { - progressbarImg.SetTile(100*i/filesize); + for ( s32 i = 0; i < filesize; i += BLOCKSIZE ) + { + usleep( 100 ); + prTxt.SetTextf( "%i%%", ( 100*i / filesize ) + 1 ); + if ( ( Settings.wsprompt == yes ) && ( CFG.widescreen ) ) + { + progressbarImg.SetTile( 80*i / filesize ); } - msg2Txt.SetTextf("%iKB/%iKB", i/1024, filesize/1024); + else + { + progressbarImg.SetTile( 100*i / filesize ); + } + msg2Txt.SetTextf( "%iKB/%iKB", i / 1024, filesize / 1024 ); - if (btn1.GetState() == STATE_CLICKED) { - fclose(pfile); - remove(dolpath); + if ( btn1.GetState() == STATE_CLICKED ) + { + fclose( pfile ); + remove( dolpath ); failed = -1; btn1.ResetState(); break; } u32 blksize; - blksize = (u32)(filesize - i); - if (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 ) + { } - } else { + } + else + { failed = -1; } - } else { + } + else + { ret = -1; } - } else { - WindowPrompt(tr("No new updates."), 0, tr("OK")); + } + else + { + WindowPrompt( tr( "No new updates." ), 0, tr( "OK" ) ); ret = -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->Remove( &promptWindow ); //mainWindow->SetState(STATE_DEFAULT); ResumeGui(); CloseConnection(); - sleep(1);//sleep 1 because it froze without this for some reason + sleep( 1 );//sleep 1 because it froze without this for some reason - if (!failed && ret >= 0) { + if ( !failed && ret >= 0 ) + { FILE *wadFile = NULL; s32 error = 1; int diarhea = 0; char nipple[100]; - wadFile = fopen (dolpath ,"rb"); - 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")); + wadFile = fopen ( dolpath , "rb" ); + 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" ) ); failed = -1; - } else { + } + else + { //sprintf(nipple, tr("The update wad has been saved as %s. Now let's try to install it."),dolpath); //WindowPrompt(0,nipple, tr("OK")); - gprintf("\n\tinstall wad"); - error = Wad_Install(wadFile); - fclose(wadFile); - if (error==0) { - 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")); - } else { - gprintf(" -> failed"); - sprintf(nipple, tr("The wad installation failed with error %ld"),error); - WindowPrompt(tr("Error"),nipple,tr("OK")); + gprintf( "\n\tinstall wad" ); + error = Wad_Install( wadFile ); + fclose( wadFile ); + if ( error == 0 ) + { + 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" ) ); + } + else + { + gprintf( " -> failed" ); + sprintf( nipple, tr( "The wad installation failed with error %ld" ), error ); + WindowPrompt( tr( "Error" ), nipple, tr( "OK" ) ); } } - if (error) - WindowPrompt(tr("ERROR") , tr("An Error occured"), tr("OK")); + if ( error ) + 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(); ShutdownAudio(); StopGX(); - gprintf("\nRebooting"); - WII_Initialize(); - WII_LaunchTitle(TITLE_ID(0x00010001,0x554c4e52)); + gprintf( "\nRebooting" ); + WII_Initialize(); + WII_LaunchTitle( TITLE_ID( 0x00010001, 0x554c4e52 ) ); } // promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50); @@ -2879,119 +3227,126 @@ int ProgressUpdateWindow() { HaltGui(); //mainWindow->Remove(&promptWindow); - mainWindow->SetState(STATE_DEFAULT); + mainWindow->SetState( STATE_DEFAULT ); ResumeGui(); - if (failed != 0) + if ( failed != 0 ) return failed; return 1; } #else -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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", CFG.theme_path ); + GuiImageData dialogBox( imgPath, dialogue_box_png ); GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); - GuiImage dialogBoxImg(&dialogBox); - if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen(CFG.widescreen); + GuiImage dialogBoxImg( &dialogBox ); + if ( Settings.wsprompt == yes ) + { + dialogBoxImg.SetWidescreen( CFG.widescreen ); } - snprintf(imgPath, sizeof(imgPath), "%sprogressbar_outline.png", CFG.theme_path); - GuiImageData progressbarOutline(imgPath, progressbar_outline_png); - GuiImage progressbarOutlineImg(&progressbarOutline); - if (Settings.wsprompt == yes) { - progressbarOutlineImg.SetWidescreen(CFG.widescreen); + snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_outline.png", CFG.theme_path ); + GuiImageData progressbarOutline( imgPath, progressbar_outline_png ); + GuiImage progressbarOutlineImg( &progressbarOutline ); + if ( Settings.wsprompt == yes ) + { + progressbarOutlineImg.SetWidescreen( CFG.widescreen ); } - progressbarOutlineImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarOutlineImg.SetPosition(25, 7); + progressbarOutlineImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + progressbarOutlineImg.SetPosition( 25, 7 ); - snprintf(imgPath, sizeof(imgPath), "%sprogressbar_empty.png", CFG.theme_path); - GuiImageData progressbarEmpty(imgPath, progressbar_empty_png); - GuiImage progressbarEmptyImg(&progressbarEmpty); - progressbarEmptyImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarEmptyImg.SetPosition(25, 7); - progressbarEmptyImg.SetTile(100); + snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_empty.png", CFG.theme_path ); + GuiImageData progressbarEmpty( imgPath, progressbar_empty_png ); + GuiImage progressbarEmptyImg( &progressbarEmpty ); + progressbarEmptyImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + progressbarEmptyImg.SetPosition( 25, 7 ); + progressbarEmptyImg.SetTile( 100 ); - snprintf(imgPath, sizeof(imgPath), "%sprogressbar.png", CFG.theme_path); - GuiImageData progressbar(imgPath, progressbar_png); - GuiImage progressbarImg(&progressbar); - progressbarImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarImg.SetPosition(25, 7); + snprintf( imgPath, sizeof( imgPath ), "%sprogressbar.png", CFG.theme_path ); + GuiImageData progressbar( imgPath, progressbar_png ); + GuiImage progressbarImg( &progressbar ); + progressbarImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + progressbarImg.SetPosition( 25, 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) { - btn1Txt.SetWidescreen(CFG.widescreen); - btn1Img.SetWidescreen(CFG.widescreen); + GuiText btn1Txt( tr( "Cancel" ), 22, THEME.prompttext ); + GuiImage btn1Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn1Txt.SetWidescreen( CFG.widescreen ); + btn1Img.SetWidescreen( CFG.widescreen ); } - GuiButton btn1(&btn1Img,&btn1Img, 2, 4, 0, -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) && (CFG.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); + if ( ( Settings.wsprompt == yes ) && ( CFG.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 ); } - 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 (subfoldercreate(Settings.update_path) != 1) { - WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK")); + if ( stat( Settings.update_path, &st ) != 0 ) + { + if ( subfoldercreate( Settings.update_path ) != 1 ) + { + WindowPrompt( tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" ) ); ret = -1; failed = -1; } @@ -2999,22 +3354,27 @@ 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()) { - msgTxt.SetText(GetNetworkIP()); - } else { - msgTxt.SetText(tr("Could not initialize network!")); + if ( IsNetworkInit() ) + { + msgTxt.SetText( GetNetworkIP() ); + } + else + { + msgTxt.SetText( tr( "Could not initialize network!" ) ); } - if (btn1.GetState() == STATE_CLICKED) { + if ( btn1.GetState() == STATE_CLICKED ) + { ret = -1; failed = -1; btn1.ResetState(); @@ -3022,203 +3382,245 @@ int ProgressUpdateWindow() { } } - //make the URL to get XML based on our games - char XMLurl[3540]; - build_XML_URL(XMLurl,sizeof(XMLurl)); + //make the URL to get XML based on our games + char XMLurl[3540]; + build_XML_URL( XMLurl, sizeof( XMLurl ) ); - if (IsNetworkInit() && ret >= 0) { + if ( IsNetworkInit() && ret >= 0 ) + { - updatemode = WindowPrompt(tr("What do you want to update?"), 0, "USB Loader GX", tr("WiiTDB Files"), tr("Language File"), tr("Cancel")); - mainWindow->SetState(STATE_DISABLED); - promptWindow.SetState(STATE_DEFAULT); - mainWindow->ChangeFocus(&promptWindow); + updatemode = WindowPrompt( tr( "What do you want to update?" ), 0, "USB Loader GX", tr( "WiiTDB Files" ), tr( "Language File" ), tr( "Cancel" ) ); + mainWindow->SetState( STATE_DISABLED ); + promptWindow.SetState( STATE_DEFAULT ); + mainWindow->ChangeFocus( &promptWindow ); - if(updatemode == 1) { + if ( updatemode == 1 ) + { - int newrev = CheckUpdate(); - if (newrev > 0) { + int newrev = CheckUpdate(); + if ( newrev > 0 ) + { - sprintf(msg, "Rev%i %s.", newrev, tr("available")); - int choice = WindowPrompt(msg, tr("How do you want to update?"), tr("Update DOL"), tr("Update All"), tr("Cancel")); - mainWindow->SetState(STATE_DISABLED); - promptWindow.SetState(STATE_DEFAULT); - mainWindow->ChangeFocus(&promptWindow); - if (choice == 1 || choice == 2) { - titleTxt.SetTextf("%s USB Loader GX", tr("Updating")); - msgTxt.SetPosition(0,100); - promptWindow.Append(&progressbarEmptyImg); - promptWindow.Append(&progressbarImg); - promptWindow.Append(&progressbarOutlineImg); - promptWindow.Append(&prTxt); - msgTxt.SetTextf("%s Rev%i", tr("Update to"), newrev); + sprintf( msg, "Rev%i %s.", newrev, tr( "available" ) ); + int choice = WindowPrompt( msg, tr( "How do you want to update?" ), tr( "Update DOL" ), tr( "Update All" ), tr( "Cancel" ) ); + mainWindow->SetState( STATE_DISABLED ); + promptWindow.SetState( STATE_DEFAULT ); + mainWindow->ChangeFocus( &promptWindow ); + if ( choice == 1 || choice == 2 ) + { + titleTxt.SetTextf( "%s USB Loader GX", tr( "Updating" ) ); + msgTxt.SetPosition( 0, 100 ); + promptWindow.Append( &progressbarEmptyImg ); + promptWindow.Append( &progressbarImg ); + promptWindow.Append( &progressbarOutlineImg ); + promptWindow.Append( &prTxt ); + msgTxt.SetTextf( "%s Rev%i", tr( "Update to" ), newrev ); - s32 filesize; - if (Settings.beta_upgrades) { - char url[255]; - memset(&url, 0, 255); - sprintf((char *) &url, "http://usbloader-gui.googlecode.com/files/r%d.dol", newrev); - filesize = download_request((char *) &url); - } else { - filesize = download_request("http://www.techjawa.com/usbloadergx/boot.dol"); - } - if (filesize > 0) { - FILE * pfile; - pfile = fopen(dolpath, "wb"); - u8 * blockbuffer = new unsigned char[BLOCKSIZE]; - for (s32 i = 0; i < filesize; i += BLOCKSIZE) { - usleep(100); - prTxt.SetTextf("%i%%", (100*i/filesize)+1); - if ((Settings.wsprompt == yes) && (CFG.widescreen)) { - progressbarImg.SetTile(80*i/filesize); - } else { - progressbarImg.SetTile(100*i/filesize); - } - msg2Txt.SetTextf("%iKB/%iKB", i/1024, filesize/1024); - - if (btn1.GetState() == STATE_CLICKED) { - fclose(pfile); - remove(dolpath); - failed = -1; - btn1.ResetState(); - break; - } - - u32 blksize; - blksize = (u32)(filesize - i); - if (blksize > BLOCKSIZE) - blksize = BLOCKSIZE; - - ret = network_read(blockbuffer, blksize); - if (ret != (s32) blksize) { - failed = -1; - ret = -1; - fclose(pfile); - remove(dolpath); - break; - } - fwrite(blockbuffer,1,blksize, pfile); + s32 filesize; + if ( Settings.beta_upgrades ) + { + char url[255]; + memset( &url, 0, 255 ); + sprintf( ( char * ) &url, "http://usbloader-gui.googlecode.com/files/r%d.dol", newrev ); + filesize = download_request( ( char * ) & url ); } - fclose(pfile); - delete blockbuffer; - if (!failed) { - //remove old - if (checkfile(dolpathsuccess)) { - remove(dolpathsuccess); - } - //rename new to old - rename(dolpath, dolpathsuccess); + else + { + filesize = download_request( "http://www.techjawa.com/usbloadergx/boot.dol" ); + } + if ( filesize > 0 ) + { + FILE * pfile; + pfile = fopen( dolpath, "wb" ); + u8 * blockbuffer = new unsigned char[BLOCKSIZE]; + for ( s32 i = 0; i < filesize; i += BLOCKSIZE ) + { + usleep( 100 ); + prTxt.SetTextf( "%i%%", ( 100*i / filesize ) + 1 ); + if ( ( Settings.wsprompt == yes ) && ( CFG.widescreen ) ) + { + progressbarImg.SetTile( 80*i / filesize ); + } + else + { + progressbarImg.SetTile( 100*i / filesize ); + } + msg2Txt.SetTextf( "%iKB/%iKB", i / 1024, filesize / 1024 ); - if (choice == 2) { - //get the icon.png and the meta.xml - char xmliconpath[150]; - struct block file = downloadfile("http://www.techjawa.com/usbloadergx/meta.file"); - if (file.data != NULL) { - sprintf(xmliconpath, "%smeta.xml", Settings.update_path); - pfile = fopen(xmliconpath, "wb"); - fwrite(file.data,1,file.size,pfile); - fclose(pfile); - free(file.data); + if ( btn1.GetState() == STATE_CLICKED ) + { + fclose( pfile ); + remove( dolpath ); + failed = -1; + btn1.ResetState(); + break; } - 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); + + u32 blksize; + blksize = ( u32 )( filesize - i ); + if ( blksize > BLOCKSIZE ) + blksize = BLOCKSIZE; + + ret = network_read( blockbuffer, blksize ); + if ( ret != ( s32 ) blksize ) + { + failed = -1; + ret = -1; + fclose( pfile ); + remove( dolpath ); + break; } - msgTxt.SetTextf("%s", tr("Updating WiiTDB.zip")); - char wiitdbpath[200]; - char wiitdbpathtmp[200]; - file = downloadfile(XMLurl); - if (file.data != NULL) { - subfoldercreate(Settings.titlestxt_path); - snprintf(wiitdbpath, sizeof(wiitdbpath), "%swiitdb_%s.zip", Settings.titlestxt_path,game_partition); - snprintf(wiitdbpathtmp, sizeof(wiitdbpathtmp), "%swiitmp_%s.zip", Settings.titlestxt_path,game_partition); - rename(wiitdbpath,wiitdbpathtmp); - pfile = fopen(wiitdbpath, "wb"); - fwrite(file.data,1,file.size,pfile); - fclose(pfile); - free(file.data); - CloseXMLDatabase(); - if (OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true)) { // open file, reload titles, keep in memory - remove(wiitdbpathtmp); - } else { - remove(wiitdbpath); - rename(wiitdbpathtmp,wiitdbpath); - OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true); // open file, reload titles, keep in memory - } + fwrite( blockbuffer, 1, blksize, pfile ); + } + fclose( pfile ); + delete blockbuffer; + if ( !failed ) + { + //remove old + if ( checkfile( dolpathsuccess ) ) + { + remove( dolpathsuccess ); + } + //rename new to old + rename( dolpath, dolpathsuccess ); + + if ( choice == 2 ) + { + //get the icon.png and the meta.xml + char xmliconpath[150]; + struct block file = downloadfile( "http://www.techjawa.com/usbloadergx/meta.file" ); + if ( file.data != NULL ) + { + sprintf( xmliconpath, "%smeta.xml", Settings.update_path ); + pfile = fopen( xmliconpath, "wb" ); + fwrite( file.data, 1, file.size, pfile ); + fclose( pfile ); + free( file.data ); + } + file = downloadfile( "http://www.techjawa.com/usbloadergx/icon.png" ); + if ( file.data != NULL ) + { + sprintf( xmliconpath, "%sicon.png", Settings.update_path ); + pfile = fopen( xmliconpath, "wb" ); + fwrite( file.data, 1, file.size, pfile ); + fclose( pfile ); + free( file.data ); + } + msgTxt.SetTextf( "%s", tr( "Updating WiiTDB.zip" ) ); + char wiitdbpath[200]; + char wiitdbpathtmp[200]; + file = downloadfile( XMLurl ); + if ( file.data != NULL ) + { + subfoldercreate( Settings.titlestxt_path ); + snprintf( wiitdbpath, sizeof( wiitdbpath ), "%swiitdb_%s.zip", Settings.titlestxt_path, game_partition ); + snprintf( wiitdbpathtmp, sizeof( wiitdbpathtmp ), "%swiitmp_%s.zip", Settings.titlestxt_path, game_partition ); + rename( wiitdbpath, wiitdbpathtmp ); + pfile = fopen( wiitdbpath, "wb" ); + fwrite( file.data, 1, file.size, pfile ); + fclose( pfile ); + free( file.data ); + CloseXMLDatabase(); + if ( OpenXMLDatabase( Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride == 1 ? true : false, true ) ) // open file, reload titles, keep in memory + { + remove( wiitdbpathtmp ); + } + else + { + remove( wiitdbpath ); + rename( wiitdbpathtmp, wiitdbpath ); + OpenXMLDatabase( Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride == 1 ? true : false, true ); // open file, reload titles, keep in memory + } + } + msgTxt.SetTextf( "%s", tr( "Updating Language Files:" ) ); + updateLanguageFiles(); } - msgTxt.SetTextf("%s", tr("Updating Language Files:")); - updateLanguageFiles(); } } - } else { - failed = -1; + else + { + failed = -1; + } } - } else { + else + { + ret = -1; + } + } + else + { + WindowPrompt( tr( "No new updates." ), 0, tr( "OK" ) ); ret = -1; } - } else { - WindowPrompt(tr("No new updates."), 0, tr("OK")); - ret = -1; - } - } else if(updatemode == 2) { - msgTxt.SetTextf("%s", tr("Updating WiiTDB.zip")); + } + else if ( updatemode == 2 ) + { + msgTxt.SetTextf( "%s", tr( "Updating WiiTDB.zip" ) ); char wiitdbpath[200]; char wiitdbpathtmp[200]; - struct block file = downloadfile(XMLurl); - if (file.data != NULL) { - subfoldercreate(Settings.titlestxt_path); - snprintf(wiitdbpath, sizeof(wiitdbpath), "%swiitdb_%s.zip", Settings.titlestxt_path,game_partition); - snprintf(wiitdbpathtmp, sizeof(wiitdbpathtmp), "%swiitmp_%s.zip", Settings.titlestxt_path,game_partition); - rename(wiitdbpath,wiitdbpathtmp); - FILE *pfile = fopen(wiitdbpath, "wb"); - fwrite(file.data,1,file.size,pfile); - fclose(pfile); - free(file.data); - CloseXMLDatabase(); - if (OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true)) { // open file, reload titles, keep in memory - remove(wiitdbpathtmp); - } else { - remove(wiitdbpath); - rename(wiitdbpathtmp,wiitdbpath); - OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride==1?true:false, true); // open file, reload titles, keep in memory - } + struct block file = downloadfile( XMLurl ); + if ( file.data != NULL ) + { + subfoldercreate( Settings.titlestxt_path ); + snprintf( wiitdbpath, sizeof( wiitdbpath ), "%swiitdb_%s.zip", Settings.titlestxt_path, game_partition ); + snprintf( wiitdbpathtmp, sizeof( wiitdbpathtmp ), "%swiitmp_%s.zip", Settings.titlestxt_path, game_partition ); + rename( wiitdbpath, wiitdbpathtmp ); + FILE *pfile = fopen( wiitdbpath, "wb" ); + fwrite( file.data, 1, file.size, pfile ); + fclose( pfile ); + free( file.data ); + CloseXMLDatabase(); + if ( OpenXMLDatabase( Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride == 1 ? true : false, true ) ) // open file, reload titles, keep in memory + { + remove( wiitdbpathtmp ); + } + else + { + remove( wiitdbpath ); + rename( wiitdbpathtmp, wiitdbpath ); + OpenXMLDatabase( Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, Settings.titlesOverride == 1 ? true : false, true ); // open file, reload titles, keep in memory + } } 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; - } else { + } + else + { ret = -1; } } CloseConnection(); - if (!failed && ret >= 0 && updatemode == 1) { - WindowPrompt(tr("Restarting..."), tr("Successfully Updated thanks to www.techjawa.com") , 0,0,0,0,150); + if ( !failed && ret >= 0 && updatemode == 1 ) + { + WindowPrompt( tr( "Restarting..." ), tr( "Successfully Updated thanks to www.techjawa.com" ) , 0, 0, 0, 0, 150 ); - loadStub(); - Set_Stub_Split(0x00010001,"UNEO"); + loadStub(); + Set_Stub_Split( 0x00010001, "UNEO" ); Sys_BackToLoader(); - } else if(updatemode > 0 && ret > 0) { - WindowPrompt(tr("Successfully Updated") , 0, tr("OK")); + } + else if ( updatemode > 0 && ret > 0 ) + { + 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) + if ( failed != 0 ) return failed; return 1; @@ -3226,151 +3628,167 @@ int ProgressUpdateWindow() { #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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", CFG.theme_path ); + GuiImageData dialogBox( imgPath, dialogue_box_png ); GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); - GuiImage dialogBoxImg(&dialogBox); - if (Settings.wsprompt == yes) { - dialogBoxImg.SetWidescreen(CFG.widescreen); + GuiImage dialogBoxImg( &dialogBox ); + if ( Settings.wsprompt == yes ) + { + dialogBoxImg.SetWidescreen( CFG.widescreen ); } 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) { - btn1Txt.SetWidescreen(CFG.widescreen); - btn1Img.SetWidescreen(CFG.widescreen); + GuiText btn1Txt( tr( "Cancel" ), 22, THEME.prompttext ); + GuiImage btn1Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn1Txt.SetWidescreen( CFG.widescreen ); + btn1Img.SetWidescreen( CFG.widescreen ); } - GuiButton btn1(&btn1Img,&btn1Img, 2, 4, 0, -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 (subfoldercreate(Settings.TxtCheatcodespath) != 1) { - WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK")); + if ( stat( Settings.TxtCheatcodespath, &st ) != 0 ) + { + if ( subfoldercreate( Settings.TxtCheatcodespath ) != 1 ) + { + WindowPrompt( tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" ) ); ret = -1; goto exit; } } - while (!IsNetworkInit()) { + while ( !IsNetworkInit() ) + { VIDEO_WaitVSync(); Initialize_Network(); - if (IsNetworkInit()) { - msgTxt.SetText(GetNetworkIP()); - } else { - msgTxt.SetText(tr("Could not initialize network!")); + if ( IsNetworkInit() ) + { + msgTxt.SetText( GetNetworkIP() ); } - if (btn1.GetState() == STATE_CLICKED) { + else + { + msgTxt.SetText( tr( "Could not initialize network!" ) ); + } + if ( btn1.GetState() == STATE_CLICKED ) + { ret = -1; btn1.ResetState(); goto exit; } } - 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) { - strcat(codeurl, tr(" is not on the server.")); + if ( file.size == 333 || file.size == 216 || file.size == 284 ) + { + strcat( codeurl, tr( " is not on the server." ) ); - WindowPrompt(tr("Error"),codeurl,tr("OK")); - ret =-1; + 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")); - } else { - strcat(codeurl, tr(" could not be downloaded.")); + WindowPrompt( 0, txtpath, tr( "OK" ) ); + } + else + { + strcat( codeurl, tr( " could not be downloaded." ) ); - WindowPrompt(tr("Error"),codeurl,tr("OK")); - ret =-1; + 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); + 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; } -char * GetMissingFiles() { - return (char *) missingFiles; +char * GetMissingFiles() +{ + return ( char * ) missingFiles; } @@ -3389,269 +3807,276 @@ 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) { +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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sbg_options.png", CFG.theme_path); - GuiImageData whiteBox(imgPath, bg_options_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", CFG.theme_path ); + GuiImageData dialogBox( imgPath, dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sbg_options.png", CFG.theme_path ); + GuiImageData whiteBox( imgPath, bg_options_png ); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar.png", CFG.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", CFG.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", CFG.theme_path); - GuiImageData arrowDown(imgPath, scrollbar_arrowdown_png); - GuiImage arrowDownImg(&arrowDown); - arrowDownImg.SetScale(.8); + snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_arrowdown.png", CFG.theme_path ); + GuiImageData arrowDown( imgPath, scrollbar_arrowdown_png ); + GuiImage arrowDownImg( &arrowDown ); + arrowDownImg.SetScale( .8 ); - snprintf(imgPath, sizeof(imgPath), "%sscrollbar_arrowup.png", CFG.theme_path); - GuiImageData arrowUp(imgPath, scrollbar_arrowup_png); - GuiImage arrowUpImg (&arrowUp); - arrowUpImg.SetScale(.8); + snprintf( imgPath, sizeof( imgPath ), "%sscrollbar_arrowup.png", CFG.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); + GuiImageData *iconData = NULL; + GuiImage *iconImg = NULL; + snprintf( imgPath, sizeof( imgPath ), "%s", iconPath ); - 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); + 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 ); } - 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(CFG.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) { - sizeAdjusted = filesize/1024.0; - snprintf(temp2, sizeof(temp2), "%.2f",sizeAdjusted); - snprintf(filesizeCH, sizeof(filesizeCH), "%s KB",temp2); + if ( filesize > 1024.0 ) + { + sizeAdjusted = filesize / 1024.0; + snprintf( temp2, sizeof( temp2 ), "%.2f", sizeAdjusted ); + snprintf( filesizeCH, sizeof( filesizeCH ), "%s KB", temp2 ); } - if (filesize>1048576.0) { - sizeAdjusted = filesize/1048576.0; - snprintf(temp2, sizeof(temp2), "%.2f",sizeAdjusted); - snprintf(filesizeCH, sizeof(filesizeCH), "%s MB",temp2); + if ( filesize > 1048576.0 ) + { + sizeAdjusted = filesize / 1048576.0; + 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) { - btn1Txt.SetWidescreen(CFG.widescreen); - btn1Img.SetWidescreen(CFG.widescreen); + GuiText btn1Txt( tr( "Load" ), 22, THEME.prompttext ); + GuiImage btn1Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn1Txt.SetWidescreen( CFG.widescreen ); + btn1Img.SetWidescreen( CFG.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) { - btn2Txt.SetWidescreen(CFG.widescreen); - btn2Img.SetWidescreen(CFG.widescreen); + GuiText btn2Txt( tr( "Back" ), 22, THEME.prompttext ); + GuiImage btn2Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn2Txt.SetWidescreen( CFG.widescreen ); + btn2Img.SetWidescreen( CFG.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))) + 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))) + 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 fea4acfb..0a381147 100644 --- a/source/prompts/PromptWindows.h +++ b/source/prompts/PromptWindows.h @@ -10,27 +10,27 @@ #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 8e948829..2b60d15a 100644 --- a/source/prompts/TitleBrowser.cpp +++ b/source/prompts/TitleBrowser.cpp @@ -56,470 +56,489 @@ extern wchar_t *gameFilter; int TitleBrowser() { - u32 num_titles; - u32 num_sys_titles; - s32 ret = -1; - u64 *titleList = NULL; + u32 num_titles; + u32 num_sys_titles; + s32 ret = -1; + u64 *titleList = NULL; - ISFS_Initialize();//initialize for "titles.Exists()" + ISFS_Initialize();//initialize for "titles.Exists()" - // Get count of titles of the good titles - num_titles = titles.SetType( 0x10001 ); - u32 n = num_titles; - for( u32 i = 0; i < n; i++ ) - { - u64 tid = titles.Next(); - if( !tid ) - { - break; - } - - //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 ); - n = num_sys_titles; - 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; - } - - //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 ) - { - gprintf("TitleBrowser(): out of memory!\n"); - return -1; - } - customOptionList options3( num_titles + num_sys_titles + 1 ); - //write the titles on the option browser - - u32 i = 0; - titles.SetType( 0x10001 ); - //first add the good stuff - 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 ) ); - - if( !titles.Exists( tid ) ) - { - continue; - } - - char id[ 5 ]; - titles.AsciiTID( tid, (char*)&id ); - - char* name = titles.NameOf( tid ); - - options3.SetName( i, "%s", id ); - options3.SetValue( i, "%s", name ? titles.NameOf( tid ): "Unknown" ); - titleList[ i ] = tid; - i++; - } - - 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; - - if( !titles.Exists( tid ) ) - { - continue; - } - - char id[ 5 ]; - titles.AsciiTID( tid, (char*)&id ); - char* name = titles.NameOf( tid ); - - options3.SetName( i, "%s", id ); - options3.SetValue( i, "%s", name ? titles.NameOf( tid ): "Unknown" ); - titleList[ i ] = tid; - i++; - } - - ISFS_Deinitialize(); - - - if( i == num_titles+num_sys_titles ) + // Get count of titles of the good titles + num_titles = titles.SetType( 0x10001 ); + u32 n = num_titles; + for ( u32 i = 0; i < n; i++ ) { - options3.SetName( i, " " ); - options3.SetValue( i, "%s",tr("Wii Settings") ); + u64 tid = titles.Next(); + if ( !tid ) + { + break; + } + + //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 ); + n = num_sys_titles; + 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; + } + + //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 ) + { + gprintf( "TitleBrowser(): out of memory!\n" ); + return -1; + } + customOptionList options3( num_titles + num_sys_titles + 1 ); + //write the titles on the option browser + + u32 i = 0; + titles.SetType( 0x10001 ); + //first add the good stuff + 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 ) ); + + if ( !titles.Exists( tid ) ) + { + continue; + } + + char id[ 5 ]; + titles.AsciiTID( tid, ( char* )&id ); + + char* name = titles.NameOf( tid ); + + options3.SetName( i, "%s", id ); + options3.SetValue( i, "%s", name ? titles.NameOf( tid ) : "Unknown" ); + titleList[ i ] = tid; + i++; + } + + 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; + + if ( !titles.Exists( tid ) ) + { + continue; + } + + char id[ 5 ]; + titles.AsciiTID( tid, ( char* )&id ); + char* name = titles.NameOf( tid ); + + options3.SetName( i, "%s", id ); + options3.SetValue( i, "%s", name ? titles.NameOf( tid ) : "Unknown" ); + titleList[ i ] = tid; + i++; + } + + ISFS_Deinitialize(); + + + if ( i == num_titles + num_sys_titles ) + { + options3.SetName( i, " " ); + options3.SetValue( i, "%s", tr( "Wii Settings" ) ); } bool exit = false; int total = num_titles + num_sys_titles; - if( IsNetworkInit() ) + if ( IsNetworkInit() ) ResumeNetworkWait(); - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sgamesettings_background.png", CFG.theme_path); - GuiImageData settingsbg(imgPath, settings_background_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sgamesettings_background.png", CFG.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) { - cancelBtnTxt.SetWidescreen(CFG.widescreen); - cancelBtnImg.SetWidescreen(CFG.widescreen); + GuiText cancelBtnTxt( tr( "Back" ), 22, THEME.prompttext ); + cancelBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); + GuiImage cancelBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + cancelBtnTxt.SetWidescreen( CFG.widescreen ); + cancelBtnImg.SetWidescreen( CFG.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, CFG.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, CFG.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", CFG.theme_path); - GuiImageData wifiImgData(imgPath, Wifi_btn_png); - GuiImage wifiImg(&wifiImgData); - if (Settings.wsprompt == yes) { - wifiImg.SetWidescreen(CFG.widescreen); + snprintf( imgPath, sizeof( imgPath ), "%sWifi_btn.png", CFG.theme_path ); + GuiImageData wifiImgData( imgPath, Wifi_btn_png ); + GuiImage wifiImg( &wifiImgData ); + if ( Settings.wsprompt == yes ) + { + wifiImg.SetWidescreen( CFG.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); + 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 ); 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(); - 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(); - if( ret > -1 ) - { //if a click happened + if ( ret > -1 ) + { //if a click happened - if ( ret < total ) - { + if ( ret < total ) + { //set the title's name, number, ID to text - char text[ 0x100 ]; - char id[ 5 ]; - titles.AsciiTID( titleList[ ret ], (char*)&id ); + 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(); - } - - } - else if( ret == total ) - { //if they clicked to go to the wii settings + //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_ReturnToSettings(); + 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(); } } #if 0 - if(infilesize > 0) { + if ( infilesize > 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); - + char filesizetxt[50]; + char temp[50]; + char filepath[100]; +// u32 read = 0; - 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); + //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 ); - snprintf(temp, sizeof(temp), tr("Load file from: %s ?"), GetIncommingIP()); - int choice = WindowPrompt(filesizetxt, temp, tr("OK"), tr("Cancel")); - gprintf("\nchoice:%d",choice); + 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 (choice == 1) { + snprintf( temp, sizeof( temp ), tr( "Load file from: %s ?" ), GetIncommingIP() ); - u32 read = 0; - u8 *temp = NULL; - int len = NETWORKBLOCKSIZE; - temp = (u8 *) malloc(infilesize); + int choice = WindowPrompt( filesizetxt, temp, tr( "OK" ), tr( "Cancel" ) ); + gprintf( "\nchoice:%d", choice ); - bool error = false; - u8 *ptr = temp; - gprintf("\nrecieving shit"); - while (read < infilesize) { + if ( choice == 1 ) + { - ShowProgress(tr("Receiving file from:"), GetIncommingIP(), NULL, read, infilesize, true); + u32 read = 0; + u8 *temp = NULL; + int len = NETWORKBLOCKSIZE; + temp = ( u8 * ) malloc( infilesize ); - if (infilesize - read < (u32) len) - len = infilesize-read; - else - len = NETWORKBLOCKSIZE; + bool error = false; + u8 *ptr = temp; + gprintf( "\nrecieving shit" ); + while ( read < infilesize ) + { - int result = network_read(ptr, len); + ShowProgress( tr( "Receiving file from:" ), GetIncommingIP(), NULL, read, infilesize, true ); - 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 ( infilesize - read < ( u32 ) len ) + len = infilesize - read; + else + len = NETWORKBLOCKSIZE; - char filename[101]; - char tmptxt[200]; + int result = network_read( ptr, len ); + + if ( result < 0 ) + { + WindowPrompt( tr( "Error while transfering data." ), 0, tr( "OK" ) ); + error = true; + break; + } + if ( !result ) + { + gprintf( "\n!RESULT" ); + break; + } + ptr += result; + read += result; + } + ProgressStop(); + + char filename[101]; + char tmptxt[200]; - //bool installWad=0; - if (!error) { - gprintf("\nno error yet"); + //bool installWad=0; + if ( !error ) + { + gprintf( "\nno error yet" ); - network_read((u8*) &filename, 100); - gprintf("\nfilename: %s",filename); + network_read( ( u8* ) &filename, 100 ); + gprintf( "\nfilename: %s", filename ); - // Do we need to unzip this thing? - if (wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4) { - gprintf("\nusing newer wiiload version"); + // Do we need to unzip this thing? + if ( wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4 ) + { + gprintf( "\nusing newer wiiload version" ); - if (uncfilesize != 0) { // if uncfilesize == 0, it's not compressed - gprintf("\ntrying to uncompress"); - // It's compressed, uncompress - u8 *unc = (u8 *) malloc(uncfilesize); - uLongf f = uncfilesize; - error = uncompress(unc, &f, temp, infilesize) != Z_OK; - uncfilesize = f; + if ( uncfilesize != 0 ) // if uncfilesize == 0, it's not compressed + { + gprintf( "\ntrying to uncompress" ); + // It's compressed, uncompress + u8 *unc = ( u8 * ) malloc( uncfilesize ); + uLongf f = uncfilesize; + error = uncompress( unc, &f, temp, infilesize ) != Z_OK; + uncfilesize = f; - free(temp); - temp = unc; - } - } + free( temp ); + temp = unc; + } + } - if (!error) { - sprintf(tmptxt,"%s",filename); - //if we got a wad - if (strcasestr(tmptxt,".wad")) { - FILE *file = fopen(filepath, "wb"); - fwrite(temp, 1, (uncfilesize>0?uncfilesize:infilesize), file); - fclose(file); + if ( !error ) + { + sprintf( tmptxt, "%s", filename ); + //if we got a wad + if ( strcasestr( tmptxt, ".wad" ) ) + { + FILE *file = fopen( filepath, "wb" ); + fwrite( temp, 1, ( uncfilesize > 0 ? uncfilesize : infilesize ), file ); + fclose( file ); - sprintf(tmptxt,"%s/wad/%s",bootDevice,filename); - if (checkfile(tmptxt))remove(tmptxt); - rename(filepath, tmptxt); + sprintf( tmptxt, "%s/wad/%s", bootDevice, filename ); + if ( checkfile( tmptxt ) )remove( tmptxt ); + rename( filepath, tmptxt ); - //check and make sure the wad we just saved is the correct size - u32 lSize; - file = fopen(tmptxt, "rb"); + //check and make sure the wad we just saved is the correct size + u32 lSize; + file = fopen( tmptxt, "rb" ); - // obtain file size: - fseek (file , 0 , SEEK_END); - lSize = ftell (file); + // obtain file size: + fseek ( file , 0 , SEEK_END ); + lSize = ftell ( file ); - rewind (file); - if (lSize==(uncfilesize>0?uncfilesize:infilesize)) { - gprintf("\nsize is ok"); - int pick = WindowPrompt(tr(" Wad Saved as:"), tmptxt, tr("Install"),tr("Uninstall"),tr("Cancel")); - //install or uninstall it - if (pick==1) - { - HaltGui(); - w.Remove(&titleTxt); - w.Remove(&cancelBtn); - w.Remove(&wifiBtn); - w.Remove(&optionBrowser3); - ResumeGui(); + rewind ( file ); + if ( lSize == ( uncfilesize > 0 ? uncfilesize : infilesize ) ) + { + gprintf( "\nsize is ok" ); + int pick = WindowPrompt( tr( " Wad Saved as:" ), tmptxt, tr( "Install" ), tr( "Uninstall" ), tr( "Cancel" ) ); + //install or uninstall it + if ( pick == 1 ) + { + HaltGui(); + w.Remove( &titleTxt ); + w.Remove( &cancelBtn ); + w.Remove( &wifiBtn ); + w.Remove( &optionBrowser3 ); + ResumeGui(); - Wad_Install(file); + Wad_Install( file ); - HaltGui(); - w.Append(&titleTxt); - w.Append(&cancelBtn); - w.Append(&wifiBtn); - w.Append(&optionBrowser3); - ResumeGui(); + HaltGui(); + w.Append( &titleTxt ); + w.Append( &cancelBtn ); + w.Append( &wifiBtn ); + w.Append( &optionBrowser3 ); + ResumeGui(); - } - if (pick==2)Wad_Uninstall(file); - } - else gprintf("\nBad size"); - //close that beast, we're done with it - fclose (file); + } + if ( pick == 2 )Wad_Uninstall( file ); + } + else gprintf( "\nBad size" ); + //close that beast, we're done with it + fclose ( file ); - //do we want to keep the file in the wad folder - if (WindowPrompt(tr("Delete ?"), tmptxt, tr("Delete"),tr("Keep"))!=0) - remove(tmptxt); - } - else { - WindowPrompt(tr("ERROR:"), tr("Not a WAD file."), tr("OK")); - } - } - } + //do we want to keep the file in the wad folder + if ( WindowPrompt( tr( "Delete ?" ), tmptxt, tr( "Delete" ), tr( "Keep" ) ) != 0 ) + remove( tmptxt ); + } + else + { + WindowPrompt( tr( "ERROR:" ), tr( "Not a WAD file." ), tr( "OK" ) ); + } + } + } - if (error || read != infilesize) { - WindowPrompt(tr("Error:"), tr("No data could be read."), tr("OK")); + if ( error || read != infilesize ) + { + WindowPrompt( tr( "Error:" ), tr( "No data could be read." ), tr( "OK" ) ); - } - if(temp)free(temp); - } + } + if ( temp )free( temp ); + } - CloseConnection(); - ResumeNetworkWait(); + CloseConnection(); + ResumeNetworkWait(); } #endif - if (cancelBtn.GetState() == STATE_CLICKED) { + if ( cancelBtn.GetState() == STATE_CLICKED ) + { //break the loop and end the function exit = true; ret = -10; } - else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tscreenShotBtn clicked"); - screenShotBtn.ResetState(); - ScreenShot(); - gprintf("...It's easy, mmmmmmKay"); - } + else if ( screenShotBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tscreenShotBtn clicked" ); + screenShotBtn.ResetState(); + ScreenShot(); + gprintf( "...It's easy, mmmmmmKay" ); + } } CloseConnection(); - if (IsNetworkInit()) + if ( IsNetworkInit() ) HaltNetworkThread(); HaltGui(); - mainWindow->Remove(&w); + mainWindow->Remove( &w ); free( titleList ); ResumeGui(); diff --git a/source/prompts/filebrowser.cpp b/source/prompts/filebrowser.cpp index ea4f07a3..91a9ccd2 100644 --- a/source/prompts/filebrowser.cpp +++ b/source/prompts/filebrowser.cpp @@ -47,73 +47,75 @@ BROWSERINFO *browser = NULL; * FileFilterCallbacks * return: 1-visible 0-hidden ***************************************************************************/ -int noDIRS(BROWSERENTRY *Entry, void* Args) +int noDIRS( BROWSERENTRY *Entry, void* Args ) { - return !Entry->isdir; + return !Entry->isdir; } -int noFILES(BROWSERENTRY *Entry, void* Args) +int noFILES( BROWSERENTRY *Entry, void* Args ) { - return Entry->isdir; + return Entry->isdir; } -int noEXT(BROWSERENTRY *Entry, void* Args) +int noEXT( BROWSERENTRY *Entry, void* Args ) { - if(!Entry->isdir) - { - char *cptr = strrchr(Entry->displayname, '.'); - if(cptr && cptr!= Entry->displayname) *cptr = 0; - } - return 1; + if ( !Entry->isdir ) + { + 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 ***************************************************************************/ -int InitBrowsers() { - curDevice = -1; - browsers.clear(); - browser = NULL; - char rootdir[ROOTDIRLEN]; - for(int i=3; iname, "stdnull") && devoptab_list[i]->write_r != NULL) - { - snprintf(rootdir, sizeof(rootdir) , "%s:/", devoptab_list[i]->name); - if(DIR_ITER *dir = diropen(rootdir)) - { - dirclose(dir); - BROWSERINFO browser; - browser.dir[0] = '\0'; - strcpy(browser.rootdir, rootdir); - ResetBrowser(&browser); - browsers.push_back(browser); - } - } - } - if(!browsers.size()) return -1; - curDevice = 0; - browser = &browsers[curDevice]; - return 0; +int InitBrowsers() +{ + curDevice = -1; + browsers.clear(); + browser = NULL; + char rootdir[ROOTDIRLEN]; + for ( int i = 3; i < STD_MAX; i++ ) + { + if ( strcmp( devoptab_list[i]->name, "stdnull" ) && devoptab_list[i]->write_r != NULL ) + { + snprintf( rootdir, sizeof( rootdir ) , "%s:/", devoptab_list[i]->name ); + if ( DIR_ITER *dir = diropen( rootdir ) ) + { + dirclose( dir ); + BROWSERINFO browser; + browser.dir[0] = '\0'; + strcpy( browser.rootdir, rootdir ); + ResetBrowser( &browser ); + browsers.push_back( browser ); + } + } + } + if ( !browsers.size() ) return -1; + curDevice = 0; + browser = &browsers[curDevice]; + return 0; } /**************************************************************************** * ResetBrowser() * Clears the file browser memory, and allocates one initial entry ***************************************************************************/ -void ResetBrowser(BROWSERINFO *browser) { - browser->pageIndex = 0; - browser->browserList.clear(); -/* - // Clear any existing values - if (browser->browserList != NULL) { - free(browser->browserList); - browser->browserList = NULL; - } - // set aside space for 1 entry - browser->browserList = (BROWSERENTRY *)malloc(sizeof(BROWSERENTRY)); - if(browser->browserList) - memset(browser->browserList, 0, sizeof(BROWSERENTRY)); -*/ +void ResetBrowser( BROWSERINFO *browser ) +{ + browser->pageIndex = 0; + browser->browserList.clear(); + /* + // Clear any existing values + if (browser->browserList != NULL) { + free(browser->browserList); + browser->browserList = NULL; + } + // set aside space for 1 entry + browser->browserList = (BROWSERENTRY *)malloc(sizeof(BROWSERENTRY)); + if(browser->browserList) + memset(browser->browserList, 0, sizeof(BROWSERENTRY)); + */ } /**************************************************************************** @@ -126,155 +128,162 @@ void ResetBrowser(BROWSERINFO *browser) { * ***************************************************************************/ //int FileSortCallback(const void *f1, const void *f2) { -bool operator< (const BROWSERENTRY &f1, const BROWSERENTRY &f2) { - /* Special case for implicit directories */ - if (f1.filename[0] == '.' || f2.filename[0] == '.') { - if (strcmp(f1.filename, ".") == 0) { - return true; - } - if (strcmp(f2.filename, ".") == 0) { - return false; - } - if (strcmp(f1.filename, "..") == 0) { - return true; - } - if (strcmp(f2.filename, "..") == 0) { - return false; - } - } +bool operator< ( const BROWSERENTRY &f1, const BROWSERENTRY &f2 ) +{ + /* Special case for implicit directories */ + if ( f1.filename[0] == '.' || f2.filename[0] == '.' ) + { + if ( strcmp( f1.filename, "." ) == 0 ) + { + return true; + } + if ( strcmp( f2.filename, "." ) == 0 ) + { + return false; + } + if ( strcmp( f1.filename, ".." ) == 0 ) + { + return true; + } + if ( strcmp( f2.filename, ".." ) == 0 ) + { + return false; + } + } - /* If one is a file and one is a directory the directory is first. */ - if (f1.isdir && !(f2.isdir)) return true; - if (!(f1.isdir) && f2.isdir) return false; + /* If one is a file and one is a directory the directory is first. */ + if ( f1.isdir && !( f2.isdir ) ) return true; + if ( !( f1.isdir ) && f2.isdir ) return false; - return stricmp(f1.filename, f2.filename)<0; + return stricmp( f1.filename, f2.filename ) < 0; } -int ParseFilter(FILTERCASCADE *Filter, BROWSERENTRY* Entry) +int ParseFilter( FILTERCASCADE *Filter, BROWSERENTRY* Entry ) { - while(Filter) - { - if(Filter->filter && Filter->filter(Entry, Filter->filter_args) == 0) - return 0; - Filter = Filter->next; - } - return 1; + while ( Filter ) + { + if ( Filter->filter && Filter->filter( Entry, Filter->filter_args ) == 0 ) + return 0; + Filter = Filter->next; + } + return 1; } /*************************************************************************** * Browse subdirectories **************************************************************************/ -int ParseDirectory(const char* Path, int Flags, FILTERCASCADE *Filter) { - DIR_ITER *dir = NULL; - char fulldir[MAXPATHLEN]; - char filename[MAXPATHLEN]; - struct stat filestat; - unsigned int i; - - if(curDevice == -1) - if(InitBrowsers()) return -1; // InitBrowser fails - - if(Path) // note in this codeblock use filename temporary - { - strlcpy(fulldir, Path, sizeof(fulldir)); - if(*fulldir && fulldir[strlen(fulldir)-1] != '/') // a file - { - char * chrp = strrchr(fulldir, '/'); - if(chrp) chrp[1] = 0; - } - if(strchr(fulldir, ':') == NULL) // Path has no device device - { - getcwd(filename, sizeof(filename)); // save the current working dir - if(*fulldir==0) // if path is empty - strlcpy(fulldir, filename, sizeof(fulldir)); // we use the current working dir - else - { // path is not empty - if(chdir(fulldir)); // sets the path to concatenate and validate - { - if(Flags & (FB_TRYROOTDIR | FB_TRYSTDDEV)) - if(chdir("/") && !(Flags & FB_TRYSTDDEV))// try to set root if is needed - return -1; - } - if(getcwd(fulldir, sizeof(fulldir))) return -1; // gets the concatenated current working dir - chdir(filename); // restore the saved cwd - } - } - for(i=0; idir, &fulldir[strlen(browser->rootdir)]); - } - else if(Flags & FB_TRYSTDDEV) - { - curDevice = 0; - browser = &browsers[curDevice]; // when no browser was found and - browser->dir[0] = 0; // we alowed try StdDevice and try RootDir - strlcpy(fulldir, browser->rootdir, sizeof(fulldir)); // set the first browser with root-dir - } - else - return -1; - } - else - snprintf(fulldir, sizeof(fulldir), "%s%s", browser->rootdir, browser->dir); - - // reset browser - ResetBrowser(browser); - - // open the directory - if((dir = diropen(fulldir)) == NULL) - { - if(Flags & FB_TRYROOTDIR) - { - browser->dir[0] = 0; - if((dir = diropen(browser->rootdir)) == NULL) - return -1; - } - else - return -1; - } - - while (dirnext(dir,filename,&filestat) == 0) - { - if (strcmp(filename,".") != 0) - { - BROWSERENTRY newEntry; - memset(&newEntry, 0, sizeof(BROWSERENTRY)); // clear the new entry - strlcpy(newEntry.filename, filename, sizeof(newEntry.filename)); - strlcpy(newEntry.displayname, filename, sizeof(newEntry.displayname)); - newEntry.length = filestat.st_size; - newEntry.isdir = (filestat.st_mode & S_IFDIR) == 0 ? 0 : 1; // flag this as a dir - if(ParseFilter(Filter, &newEntry)) - browser->browserList.push_back(newEntry); - } - } - - // close directory - dirclose(dir); - - // Sort the file list - std::sort(browser->browserList.begin(), browser->browserList.end()); - return 0; -} -int ParseDirectory(int Device, int Flags, FILTERCASCADE *Filter) +int ParseDirectory( const char* Path, int Flags, FILTERCASCADE *Filter ) { - if(Device >=0 && Device < (int)browsers.size()) - { - int old_curDevice = curDevice; - curDevice = Device; - browser = &browsers[curDevice]; - if(ParseDirectory((char*)NULL, Flags, Filter) == 0) return 0; - curDevice = old_curDevice; - browser = &browsers[old_curDevice]; - } - return -1; + DIR_ITER *dir = NULL; + char fulldir[MAXPATHLEN]; + char filename[MAXPATHLEN]; + struct stat filestat; + unsigned int i; + + if ( curDevice == -1 ) + if ( InitBrowsers() ) return -1; // InitBrowser fails + + if ( Path ) // note in this codeblock use filename temporary + { + strlcpy( fulldir, Path, sizeof( fulldir ) ); + if ( *fulldir && fulldir[strlen( fulldir )-1] != '/' ) // a file + { + char * chrp = strrchr( fulldir, '/' ); + if ( chrp ) chrp[1] = 0; + } + if ( strchr( fulldir, ':' ) == NULL ) // Path has no device device + { + getcwd( filename, sizeof( filename ) ); // save the current working dir + if ( *fulldir == 0 ) // if path is empty + strlcpy( fulldir, filename, sizeof( fulldir ) ); // we use the current working dir + else + { // path is not empty + if ( chdir( fulldir ) ); // sets the path to concatenate and validate + { + if ( Flags & ( FB_TRYROOTDIR | FB_TRYSTDDEV ) ) + if ( chdir( "/" ) && !( Flags & FB_TRYSTDDEV ) )// try to set root if is needed + return -1; + } + if ( getcwd( fulldir, sizeof( fulldir ) ) ) return -1; // gets the concatenated current working dir + chdir( filename ); // restore the saved cwd + } + } + for ( i = 0; 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 ) + { + browser = &browsers[curDevice]; + break; + } + } + if ( i != browsers.size() ) // found browser + { + curDevice = i; + browser = &browsers[curDevice]; + strcpy( browser->dir, &fulldir[strlen( browser->rootdir )] ); + } + else if ( Flags & FB_TRYSTDDEV ) + { + curDevice = 0; + browser = &browsers[curDevice]; // when no browser was found and + browser->dir[0] = 0; // we alowed try StdDevice and try RootDir + strlcpy( fulldir, browser->rootdir, sizeof( fulldir ) ); // set the first browser with root-dir + } + else + return -1; + } + else + snprintf( fulldir, sizeof( fulldir ), "%s%s", browser->rootdir, browser->dir ); + + // reset browser + ResetBrowser( browser ); + + // open the directory + if ( ( dir = diropen( fulldir ) ) == NULL ) + { + if ( Flags & FB_TRYROOTDIR ) + { + browser->dir[0] = 0; + if ( ( dir = diropen( browser->rootdir ) ) == NULL ) + return -1; + } + else + return -1; + } + + while ( dirnext( dir, filename, &filestat ) == 0 ) + { + if ( strcmp( filename, "." ) != 0 ) + { + BROWSERENTRY newEntry; + memset( &newEntry, 0, sizeof( BROWSERENTRY ) ); // clear the new entry + strlcpy( newEntry.filename, filename, sizeof( newEntry.filename ) ); + strlcpy( newEntry.displayname, filename, sizeof( newEntry.displayname ) ); + newEntry.length = filestat.st_size; + newEntry.isdir = ( filestat.st_mode & S_IFDIR ) == 0 ? 0 : 1; // flag this as a dir + if ( ParseFilter( Filter, &newEntry ) ) + browser->browserList.push_back( newEntry ); + } + } + + // close directory + dirclose( dir ); + + // Sort the file list + std::sort( browser->browserList.begin(), browser->browserList.end() ); + return 0; +} +int ParseDirectory( int Device, int Flags, FILTERCASCADE *Filter ) +{ + if ( Device >= 0 && Device < ( int )browsers.size() ) + { + int old_curDevice = curDevice; + curDevice = Device; + browser = &browsers[curDevice]; + if ( ParseDirectory( ( char* )NULL, Flags, Filter ) == 0 ) return 0; + curDevice = old_curDevice; + browser = &browsers[old_curDevice]; + } + return -1; } /**************************************************************************** @@ -282,256 +291,268 @@ 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; + int result = -1; + int i; - if(InitBrowsers() || ParseDirectory(Path, Flags, Filter)) - { - WindowPrompt(tr("Error"),0,tr("OK")); - return -1; - } - int menu = MENU_NONE; + if ( InitBrowsers() || ParseDirectory( Path, Flags, Filter ) ) + { + WindowPrompt( tr( "Error" ), 0, tr( "OK" ) ); + return -1; + } + int menu = MENU_NONE; - /* - GuiText titleTxt("Browse Files", 28, (GXColor){0, 0, 0, 230}); - titleTxt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - titleTxt.SetPosition(70,20); - */ - GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiTrigger trigB; - trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); + /* + GuiText titleTxt("Browse Files", 28, (GXColor){0, 0, 0, 230}); + titleTxt.SetAlignment(ALIGN_LEFT, ALIGN_TOP); + titleTxt.SetPosition(70,20); + */ + GuiTrigger trigA; + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + GuiTrigger trigB; + trigB.SetButtonOnlyTrigger( -1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B ); - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - GuiImageData folderImgData(icon_folder_png); - GuiImage folderImg(&folderImgData); - GuiButton folderBtn(folderImg.GetWidth(), folderImg.GetHeight()); - folderBtn.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - folderBtn.SetPosition(-210, -145); - folderBtn.SetImage(&folderImg); - folderBtn.SetTrigger(&trigA); - folderBtn.SetEffectGrow(); - - char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - GuiText ExitBtnTxt(tr("Cancel"), 24, (GXColor) {0, 0, 0, 255}); - GuiImage ExitBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { - ExitBtnTxt.SetWidescreen(CFG.widescreen); - ExitBtnImg.SetWidescreen(CFG.widescreen); - } - GuiButton ExitBtn(btnOutline.GetWidth(), btnOutline.GetHeight()); - ExitBtn.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM); - ExitBtn.SetPosition(-40, -35); - ExitBtn.SetLabel(&ExitBtnTxt); - ExitBtn.SetImage(&ExitBtnImg); - ExitBtn.SetTrigger(&trigA); - ExitBtn.SetTrigger(&trigB); - ExitBtn.SetEffectGrow(); + 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(); - GuiText usbBtnTxt(browsers[(curDevice+1)%browsers.size()].rootdir, 24, (GXColor) {0, 0, 0, 255}); - GuiImage usbBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { - usbBtnTxt.SetWidescreen(CFG.widescreen); - usbBtnImg.SetWidescreen(CFG.widescreen); - } - GuiButton usbBtn(btnOutline.GetWidth(), btnOutline.GetHeight()); - usbBtn.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); - usbBtn.SetPosition(0, -35); - usbBtn.SetLabel(&usbBtnTxt); - usbBtn.SetImage(&usbBtnImg); - usbBtn.SetTrigger(&trigA); - usbBtn.SetEffectGrow(); + char imgPath[100]; + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + GuiText ExitBtnTxt( tr( "Cancel" ), 24, ( GXColor ) {0, 0, 0, 255} ); + GuiImage ExitBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + ExitBtnTxt.SetWidescreen( CFG.widescreen ); + ExitBtnImg.SetWidescreen( CFG.widescreen ); + } + GuiButton ExitBtn( btnOutline.GetWidth(), btnOutline.GetHeight() ); + ExitBtn.SetAlignment( ALIGN_RIGHT, ALIGN_BOTTOM ); + ExitBtn.SetPosition( -40, -35 ); + ExitBtn.SetLabel( &ExitBtnTxt ); + ExitBtn.SetImage( &ExitBtnImg ); + ExitBtn.SetTrigger( &trigA ); + ExitBtn.SetTrigger( &trigB ); + ExitBtn.SetEffectGrow(); - GuiText okBtnTxt(tr("OK"), 22, THEME.prompttext); - GuiImage okBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { - okBtnTxt.SetWidescreen(CFG.widescreen); - okBtnImg.SetWidescreen(CFG.widescreen); - } - GuiButton okBtn(&okBtnImg,&okBtnImg, 0, 4, 40, -35, &trigA, &btnSoundOver, btnClick2,1); - okBtn.SetLabel(&okBtnTxt); + GuiText usbBtnTxt( browsers[( curDevice+1 )%browsers.size()].rootdir, 24, ( GXColor ) {0, 0, 0, 255} ); + GuiImage usbBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + usbBtnTxt.SetWidescreen( CFG.widescreen ); + usbBtnImg.SetWidescreen( CFG.widescreen ); + } + GuiButton usbBtn( btnOutline.GetWidth(), btnOutline.GetHeight() ); + usbBtn.SetAlignment( ALIGN_CENTRE, ALIGN_BOTTOM ); + usbBtn.SetPosition( 0, -35 ); + usbBtn.SetLabel( &usbBtnTxt ); + usbBtn.SetImage( &usbBtnImg ); + usbBtn.SetTrigger( &trigA ); + usbBtn.SetEffectGrow(); - GuiFileBrowser fileBrowser(396, 248); - fileBrowser.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - fileBrowser.SetPosition(0, 120); + GuiText okBtnTxt( tr( "OK" ), 22, THEME.prompttext ); + GuiImage okBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + okBtnTxt.SetWidescreen( CFG.widescreen ); + okBtnImg.SetWidescreen( CFG.widescreen ); + } + GuiButton okBtn( &okBtnImg, &okBtnImg, 0, 4, 40, -35, &trigA, &btnSoundOver, btnClick2, 1 ); + okBtn.SetLabel( &okBtnTxt ); - 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); + GuiFileBrowser fileBrowser( 396, 248 ); + fileBrowser.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + fileBrowser.SetPosition( 0, 120 ); - HaltGui(); - GuiWindow w(screenwidth, screenheight); - w.Append(&ExitBtn); -// w.Append(&titleTxt); - w.Append(&fileBrowser); - w.Append(&Adressbar); - w.Append(&okBtn); - if(!(Flags & FB_NOFOLDER_BTN)) - w.Append(&folderBtn); - if(browsers.size()>1 && !(Flags & FB_NODEVICE_BTN)) - w.Append(&usbBtn); - mainWindow->Append(&w); - ResumeGui(); - int clickedIndex = -1; - while (menu == MENU_NONE) { - VIDEO_WaitVSync(); + 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 ); - if (shutdown == 1) - Sys_Shutdown(); + HaltGui(); + GuiWindow w( screenwidth, screenheight ); + w.Append( &ExitBtn ); +// w.Append(&titleTxt); + w.Append( &fileBrowser ); + w.Append( &Adressbar ); + w.Append( &okBtn ); + if ( !( Flags & FB_NOFOLDER_BTN ) ) + w.Append( &folderBtn ); + if ( browsers.size() > 1 && !( Flags & FB_NODEVICE_BTN ) ) + w.Append( &usbBtn ); + mainWindow->Append( &w ); + ResumeGui(); + int clickedIndex = -1; + while ( menu == MENU_NONE ) + { + VIDEO_WaitVSync(); - if (reset == 1) - Sys_Reboot(); + if ( shutdown == 1 ) + Sys_Shutdown(); - for (i=0; iGetState() == STATE_CLICKED) { - fileBrowser.fileList[i]->ResetState(); + if ( reset == 1 ) + Sys_Reboot(); - clickedIndex = browser->pageIndex + i; - bool pathCanged = false; - // check corresponding browser entry - if (browser->browserList[clickedIndex].isdir) - { - /* go up to parent directory */ - if (strcmp(browser->browserList[clickedIndex].filename,"..") == 0) - { - /* remove last subdirectory name */ - int len = strlen(browser->dir); - while(browser->dir[0] && browser->dir[len-1] == '/') - browser->dir[--len] = '\0'; // remove all trailing '/' - char *cptr = strrchr(browser->dir, '/'); - if(cptr) *++cptr = 0; else browser->dir[0] = '\0'; // remove trailing dir - pathCanged = true; - } - /* Open a directory */ - /* current directory doesn't change */ - else if (strcmp(browser->browserList[clickedIndex].filename,".")) - { - /* test new directory namelength */ - if ((strlen(browser->dir) + strlen(browser->browserList[clickedIndex].filename) - + 1/*'/'*/) < MAXPATHLEN) - { - /* update current directory name */ - sprintf(browser->dir, "%s%s/",browser->dir, - browser->browserList[clickedIndex].filename); - pathCanged = true; - } - } - if (pathCanged) - { - LOCK(&fileBrowser); - ParseDirectory((char*)NULL, Flags, Filter); - fileBrowser.ResetState(); - fileBrowser.TriggerUpdate(); - AdressText.SetTextf("%s%s", browser->rootdir, browser->dir); - } - clickedIndex = -1; - } - else /* isFile */ - { - AdressText.SetTextf("%s%s%s", browser->rootdir, browser->dir, browser->browserList[clickedIndex].filename); - } - } - } + for ( i = 0; i < FILEBROWSERSIZE; i++ ) + { + if ( fileBrowser.fileList[i]->GetState() == STATE_CLICKED ) + { + fileBrowser.fileList[i]->ResetState(); - if (ExitBtn.GetState() == STATE_CLICKED) { - result = 0; - break; - } - else if (okBtn.GetState() == STATE_CLICKED) { - if(clickedIndex>=0) - snprintf(Path, Path_size, "%s%s%s", browser->rootdir, browser->dir,browser->browserList[clickedIndex].filename); - else - snprintf(Path, Path_size, "%s%s", browser->rootdir, browser->dir); - result = 1; - break; - } - else if (usbBtn.GetState() == STATE_CLICKED) { - usbBtn.ResetState(); - for(u32 i=1; irootdir, browser->dir); - usbBtnTxt.SetText(browsers[(curDevice+1)%browsers.size()].rootdir); - break; - } - } - } - else if (folderBtn.GetState() == STATE_CLICKED) { - folderBtn.ResetState(); + clickedIndex = browser->pageIndex + i; + bool pathCanged = false; + // check corresponding browser entry + if ( browser->browserList[clickedIndex].isdir ) + { + /* go up to parent directory */ + if ( strcmp( browser->browserList[clickedIndex].filename, ".." ) == 0 ) + { + /* remove last subdirectory name */ + int len = strlen( browser->dir ); + while ( browser->dir[0] && browser->dir[len-1] == '/' ) + browser->dir[--len] = '\0'; // remove all trailing '/' + char *cptr = strrchr( browser->dir, '/' ); + if ( cptr ) *++cptr = 0; else browser->dir[0] = '\0'; // remove trailing dir + pathCanged = true; + } + /* Open a directory */ + /* current directory doesn't change */ + else if ( strcmp( browser->browserList[clickedIndex].filename, "." ) ) + { + /* test new directory namelength */ + if ( ( strlen( browser->dir ) + strlen( browser->browserList[clickedIndex].filename ) + + 1/*'/'*/ ) < MAXPATHLEN ) + { + /* update current directory name */ + sprintf( browser->dir, "%s%s/", browser->dir, + browser->browserList[clickedIndex].filename ); + pathCanged = true; + } + } + if ( pathCanged ) + { + LOCK( &fileBrowser ); + ParseDirectory( ( char* )NULL, Flags, Filter ); + fileBrowser.ResetState(); + fileBrowser.TriggerUpdate(); + AdressText.SetTextf( "%s%s", browser->rootdir, browser->dir ); + } + clickedIndex = -1; + } + else /* isFile */ + { + AdressText.SetTextf( "%s%s%s", browser->rootdir, browser->dir, browser->browserList[clickedIndex].filename ); + } + } + } - HaltGui(); - mainWindow->Remove(&w); - ResumeGui(); - char newfolder[100]; - char oldfolder[100]; - snprintf(newfolder, sizeof(newfolder), "%s%s", browser->rootdir, browser->dir); - strcpy(oldfolder,newfolder); - - int result = OnScreenKeyboard(newfolder, sizeof(newfolder), strlen(browser->rootdir)); - if ( result == 1 ) { - unsigned int len = strlen(newfolder); - if (len>0 && len+1 < sizeof(newfolder) && newfolder[len-1] !='/') - { - newfolder[len] = '/'; - newfolder[len+1] = '\0'; - } + if ( ExitBtn.GetState() == STATE_CLICKED ) + { + result = 0; + break; + } + else if ( okBtn.GetState() == STATE_CLICKED ) + { + if ( clickedIndex >= 0 ) + snprintf( Path, Path_size, "%s%s%s", browser->rootdir, browser->dir, browser->browserList[clickedIndex].filename ); + else + snprintf( Path, Path_size, "%s%s", browser->rootdir, browser->dir ); + result = 1; + break; + } + else if ( usbBtn.GetState() == STATE_CLICKED ) + { + usbBtn.ResetState(); + for ( u32 i = 1; i < browsers.size(); i++ ) + { + LOCK( &fileBrowser ); + 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 ); + break; + } + } + } + else if ( folderBtn.GetState() == STATE_CLICKED ) + { + folderBtn.ResetState(); - struct stat st; - if (stat(newfolder, &st) != 0) { - if(WindowPrompt(tr("Directory does not exist!"),tr("The entered directory does not exist. Would you like to create it?") ,tr("OK"), tr("Cancel")) == 1) - if (subfoldercreate(newfolder) == false) - WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK")); - } - if(ParseDirectory(newfolder, Flags, Filter)==0) - { - fileBrowser.ResetState(); - fileBrowser.TriggerUpdate(); - AdressText.SetTextf("%s%s", browser->rootdir, browser->dir); - usbBtnTxt.SetText(browsers[(curDevice+1)%browsers.size()].rootdir); - } - } - HaltGui(); - mainWindow->Append(&w); - ResumeGui(); - } + HaltGui(); + mainWindow->Remove( &w ); + ResumeGui(); + char newfolder[100]; + char oldfolder[100]; + snprintf( newfolder, sizeof( newfolder ), "%s%s", browser->rootdir, browser->dir ); + strcpy( oldfolder, newfolder ); - } - HaltGui(); - mainWindow->Remove(&w); - ResumeGui(); + int result = OnScreenKeyboard( newfolder, sizeof( newfolder ), strlen( browser->rootdir ) ); + if ( result == 1 ) + { + unsigned int len = strlen( newfolder ); + if ( len > 0 && len + 1 < sizeof( newfolder ) && newfolder[len-1] != '/' ) + { + newfolder[len] = '/'; + newfolder[len+1] = '\0'; + } - //} + struct stat st; + if ( stat( newfolder, &st ) != 0 ) + { + if ( WindowPrompt( tr( "Directory does not exist!" ), tr( "The entered directory does not exist. Would you like to create it?" ) , tr( "OK" ), tr( "Cancel" ) ) == 1 ) + if ( subfoldercreate( newfolder ) == false ) + WindowPrompt( tr( "Error !" ), tr( "Can't create directory" ), tr( "OK" ) ); + } + if ( ParseDirectory( newfolder, Flags, Filter ) == 0 ) + { + fileBrowser.ResetState(); + fileBrowser.TriggerUpdate(); + AdressText.SetTextf( "%s%s", browser->rootdir, browser->dir ); + usbBtnTxt.SetText( browsers[( curDevice+1 )%browsers.size()].rootdir ); + } + } + HaltGui(); + mainWindow->Append( &w ); + ResumeGui(); + } - return result; + } + HaltGui(); + mainWindow->Remove( &w ); + ResumeGui(); + + //} + + 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) - { - FILTERCASCADE filter = {Filter, FilterArgs, NULL}; - return BrowseDevice(Path, Path_size, Flags, &filter); - } - return BrowseDevice(Path, Path_size, Flags); + if ( Filter ) + { + FILTERCASCADE filter = {Filter, FilterArgs, NULL}; + return BrowseDevice( Path, Path_size, Flags, &filter ); + } + return BrowseDevice( Path, Path_size, Flags ); } diff --git a/source/prompts/filebrowser.h b/source/prompts/filebrowser.h index 5d05b079..06122650 100644 --- a/source/prompts/filebrowser.h +++ b/source/prompts/filebrowser.h @@ -20,7 +20,8 @@ #define ROOTDIRLEN 10 -typedef struct { +typedef struct +{ u64 offset; // DVD offset u64 length; // file length in 64 bytes for sizes higher than 4GB char isdir; // 0 - file, 1 - directory @@ -28,30 +29,32 @@ typedef struct { 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; +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; } 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) +#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; +typedef struct _FILTERCASCADE +{ + FILEFILTERCALLBACK filter; + void *filter_args; + _FILTERCASCADE *next; } FILTERCASCADE; @@ -72,8 +75,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 3da99b36..374e3118 100644 --- a/source/prompts/gameinfo.cpp +++ b/source/prompts/gameinfo.cpp @@ -37,40 +37,42 @@ extern void HaltGui(); /**************************************************************************** * gameinfo ***************************************************************************/ -int showGameInfo(char *ID) { +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; - int choice=-1; - int titley=10; - int marginY=titley+40; + int choice = -1; + int titley = 10; + int marginY = titley + 40; 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; - int newline=1; - u8 page=1; + 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; + int newline = 1; + u8 page = 1; GuiImageData * playersImgData = NULL; GuiImage * playersImg = NULL; @@ -133,330 +135,347 @@ 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", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sgameinfo1_png.png", CFG.theme_path); - GuiImageData dialogBox1(imgPath, gameinfo1_png); - snprintf(imgPath, sizeof(imgPath), "%sgameinfo1a_png.png", CFG.theme_path); - GuiImageData dialogBox2(imgPath, gameinfo1a_png); - snprintf(imgPath, sizeof(imgPath), "%sgameinfo2_png.png", CFG.theme_path); - GuiImageData dialogBox3(imgPath, gameinfo2_png); - snprintf(imgPath, sizeof(imgPath), "%sgameinfo2a_png.png", CFG.theme_path); - GuiImageData dialogBox4(imgPath, gameinfo2a_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sgameinfo1_png.png", CFG.theme_path ); + GuiImageData dialogBox1( imgPath, gameinfo1_png ); + snprintf( imgPath, sizeof( imgPath ), "%sgameinfo1a_png.png", CFG.theme_path ); + GuiImageData dialogBox2( imgPath, gameinfo1a_png ); + snprintf( imgPath, sizeof( imgPath ), "%sgameinfo2_png.png", CFG.theme_path ); + GuiImageData dialogBox3( imgPath, gameinfo2_png ); + snprintf( imgPath, sizeof( imgPath ), "%sgameinfo2a_png.png", CFG.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++) { - 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) + 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],"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); + //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++) { - 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) + 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],"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(CFG.widescreen); - coverImg->SetPosition(15,30); - gameinfoWindow.Append(coverImg); + coverImg = new GuiImage( cover ); + coverImg->SetWidescreen( CFG.widescreen ); + coverImg->SetPosition( 15, 30 ); + gameinfoWindow.Append( coverImg ); // # of players - if (strcmp(gameinfo.players,"") != 0) { - playersImgData = new GuiImageData(Wiimote1_png); - if (atoi(gameinfo.players)>1) { - playersImgData= new GuiImageData(Wiimote2_png); + if ( strcmp( gameinfo.players, "" ) != 0 ) + { + playersImgData = new GuiImageData( Wiimote1_png ); + if ( atoi( gameinfo.players ) > 1 ) + { + playersImgData = new GuiImageData( Wiimote2_png ); } - if (atoi(gameinfo.players)>2) { - playersImgData= new GuiImageData(Wiimote4_png); + if ( atoi( gameinfo.players ) > 2 ) + { + playersImgData = new GuiImageData( Wiimote4_png ); } - playersImg = new GuiImage(playersImgData); - playersImg->SetWidescreen(CFG.widescreen); - playersImg->SetPosition(intputX , inputY); - playersImg->SetAlignment(0,4); - gameinfoWindow.Append(playersImg); - intputX += (CFG.widescreen ? playersImg->GetWidth() * .8 : playersImg->GetWidth())+5; + playersImg = new GuiImage( playersImgData ); + playersImg->SetWidescreen( CFG.widescreen ); + playersImg->SetPosition( intputX , inputY ); + playersImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( playersImg ); + intputX += ( CFG.widescreen ? playersImg->GetWidth() * .8 : playersImg->GetWidth() ) + 5; } //draw the input types for this game - if (motionplus==1) { - motionplusImg = new GuiImage(motionplusImgData); - motionplusImg->SetWidescreen(CFG.widescreen); - motionplusImg->SetPosition(intputX , inputY); - motionplusImg->SetAlignment(0,4); - gameinfoWindow.Append(motionplusImg); - intputX += (CFG.widescreen ? motionplusImg->GetWidth() * .8 : motionplusImg->GetWidth())+5; + if ( motionplus == 1 ) + { + motionplusImg = new GuiImage( motionplusImgData ); + motionplusImg->SetWidescreen( CFG.widescreen ); + motionplusImg->SetPosition( intputX , inputY ); + motionplusImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( motionplusImg ); + intputX += ( CFG.widescreen ? motionplusImg->GetWidth() * .8 : motionplusImg->GetWidth() ) + 5; } - if (nunchuk==1) { - nunchukImg = new GuiImage(nunchukImgData); - nunchukImg->SetWidescreen(CFG.widescreen); - nunchukImg->SetPosition(intputX , inputY); - nunchukImg->SetAlignment(0,4); - gameinfoWindow.Append(nunchukImg); - intputX += (CFG.widescreen ? nunchukImg->GetWidth() * .8 : nunchukImg->GetWidth())+5; + if ( nunchuk == 1 ) + { + nunchukImg = new GuiImage( nunchukImgData ); + nunchukImg->SetWidescreen( CFG.widescreen ); + nunchukImg->SetPosition( intputX , inputY ); + nunchukImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( nunchukImg ); + intputX += ( CFG.widescreen ? nunchukImg->GetWidth() * .8 : nunchukImg->GetWidth() ) + 5; } - if (classiccontroller==1) { - classiccontrollerImg = new GuiImage(classiccontrollerImgData); - classiccontrollerImg->SetWidescreen(CFG.widescreen); - classiccontrollerImg->SetPosition(intputX , inputY); - classiccontrollerImg->SetAlignment(0,4); - gameinfoWindow.Append(classiccontrollerImg); - intputX += (CFG.widescreen ? classiccontrollerImg->GetWidth() * .8 : classiccontrollerImg->GetWidth())+5; + if ( classiccontroller == 1 ) + { + classiccontrollerImg = new GuiImage( classiccontrollerImgData ); + classiccontrollerImg->SetWidescreen( CFG.widescreen ); + classiccontrollerImg->SetPosition( intputX , inputY ); + classiccontrollerImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( classiccontrollerImg ); + intputX += ( CFG.widescreen ? classiccontrollerImg->GetWidth() * .8 : classiccontrollerImg->GetWidth() ) + 5; } - if (gamecube==1) { - gcImg = new GuiImage(gamecubeImgData); - gcImg->SetWidescreen(CFG.widescreen); - gcImg->SetPosition(intputX , inputY); - gcImg->SetAlignment(0,4); - gameinfoWindow.Append(gcImg); - intputX += (CFG.widescreen ? gcImg->GetWidth() * .8 : gcImg->GetWidth())+5; + if ( gamecube == 1 ) + { + gcImg = new GuiImage( gamecubeImgData ); + gcImg->SetWidescreen( CFG.widescreen ); + gcImg->SetPosition( intputX , inputY ); + gcImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( gcImg ); + intputX += ( CFG.widescreen ? gcImg->GetWidth() * .8 : gcImg->GetWidth() ) + 5; } - if (wheel==1) { - wheelImg = new GuiImage(wheelImgData); - wheelImg->SetWidescreen(CFG.widescreen); - wheelImg->SetPosition(intputX , inputY); - wheelImg->SetAlignment(0,4); - gameinfoWindow.Append(wheelImg); - intputX += (CFG.widescreen ? wheelImg->GetWidth() * .8 : wheelImg->GetWidth())+5; + if ( wheel == 1 ) + { + wheelImg = new GuiImage( wheelImgData ); + wheelImg->SetWidescreen( CFG.widescreen ); + wheelImg->SetPosition( intputX , inputY ); + wheelImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( wheelImg ); + intputX += ( CFG.widescreen ? wheelImg->GetWidth() * .8 : wheelImg->GetWidth() ) + 5; } - if (guitar==1) { - guitarImg = new GuiImage(guitarImgData); - guitarImg->SetWidescreen(CFG.widescreen); - guitarImg->SetPosition(intputX , inputY); - guitarImg->SetAlignment(0,4); - gameinfoWindow.Append(guitarImg); - intputX += (CFG.widescreen ? guitarImg->GetWidth() * .8 : guitarImg->GetWidth())+5; + if ( guitar == 1 ) + { + guitarImg = new GuiImage( guitarImgData ); + guitarImg->SetWidescreen( CFG.widescreen ); + guitarImg->SetPosition( intputX , inputY ); + guitarImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( guitarImg ); + intputX += ( CFG.widescreen ? guitarImg->GetWidth() * .8 : guitarImg->GetWidth() ) + 5; } - if (drums==1) { - drumsImg = new GuiImage(drumsImgData); - drumsImg->SetWidescreen(CFG.widescreen); - drumsImg->SetPosition(intputX , inputY); - drumsImg->SetAlignment(0,4); - gameinfoWindow.Append(drumsImg); - intputX += (CFG.widescreen ? drumsImg->GetWidth() * .8 : drumsImg->GetWidth())+5; + if ( drums == 1 ) + { + drumsImg = new GuiImage( drumsImgData ); + drumsImg->SetWidescreen( CFG.widescreen ); + drumsImg->SetPosition( intputX , inputY ); + drumsImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( drumsImg ); + intputX += ( CFG.widescreen ? drumsImg->GetWidth() * .8 : drumsImg->GetWidth() ) + 5; } - if (microphone==1) { - microphoneImg = new GuiImage(microphoneImgData); - microphoneImg->SetWidescreen(CFG.widescreen); - microphoneImg->SetPosition(intputX , inputY); - microphoneImg->SetAlignment(0,4); - gameinfoWindow.Append(microphoneImg); - intputX += (CFG.widescreen ? microphoneImg->GetWidth() * .8 : microphoneImg->GetWidth())+5; + if ( microphone == 1 ) + { + microphoneImg = new GuiImage( microphoneImgData ); + microphoneImg->SetWidescreen( CFG.widescreen ); + microphoneImg->SetPosition( intputX , inputY ); + microphoneImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( microphoneImg ); + intputX += ( CFG.widescreen ? microphoneImg->GetWidth() * .8 : microphoneImg->GetWidth() ) + 5; } - if (zapper==1) { - zapperImg = new GuiImage( zapperImgData); - zapperImg->SetWidescreen(CFG.widescreen); - zapperImg->SetPosition(intputX , inputY); - zapperImg->SetAlignment(0,4); - gameinfoWindow.Append(zapperImg); - intputX += (CFG.widescreen ? zapperImg->GetWidth() * .8 : zapperImg->GetWidth())+5; + if ( zapper == 1 ) + { + zapperImg = new GuiImage( zapperImgData ); + zapperImg->SetWidescreen( CFG.widescreen ); + zapperImg->SetPosition( intputX , inputY ); + zapperImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( zapperImg ); + intputX += ( CFG.widescreen ? zapperImg->GetWidth() * .8 : zapperImg->GetWidth() ) + 5; } - if (wiispeak==1) { - wiispeakImg = new GuiImage(wiispeakImgData); - wiispeakImg->SetWidescreen(CFG.widescreen); - wiispeakImg->SetPosition(intputX , inputY); - wiispeakImg->SetAlignment(0,4); - gameinfoWindow.Append(wiispeakImg); - intputX += (CFG.widescreen ? wiispeakImg->GetWidth() * .8 : wiispeakImg->GetWidth())+5; + if ( wiispeak == 1 ) + { + wiispeakImg = new GuiImage( wiispeakImgData ); + wiispeakImg->SetWidescreen( CFG.widescreen ); + wiispeakImg->SetPosition( intputX , inputY ); + wiispeakImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( wiispeakImg ); + intputX += ( CFG.widescreen ? wiispeakImg->GetWidth() * .8 : wiispeakImg->GetWidth() ) + 5; } - if (nintendods==1) { - nintendodsImg = new GuiImage(nintendodsImgData); - nintendodsImg->SetWidescreen(CFG.widescreen); - nintendodsImg->SetPosition(intputX , inputY); - nintendodsImg->SetAlignment(0,4); - gameinfoWindow.Append(nintendodsImg); - intputX += (CFG.widescreen ? nintendodsImg->GetWidth() * .8 : nintendodsImg->GetWidth())+5; + if ( nintendods == 1 ) + { + nintendodsImg = new GuiImage( nintendodsImgData ); + nintendodsImg->SetWidescreen( CFG.widescreen ); + nintendodsImg->SetPosition( intputX , inputY ); + nintendodsImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( nintendodsImg ); + intputX += ( CFG.widescreen ? nintendodsImg->GetWidth() * .8 : nintendodsImg->GetWidth() ) + 5; } - /* - if (vitalitysensor==1) { + /* + if (vitalitysensor==1) { vitalitysensorImg = new GuiImage(vitalitysensorImgData); vitalitysensorImg->SetWidescreen(CFG.widescreen); vitalitysensorImg->SetPosition(intputX , inputY); @@ -464,477 +483,529 @@ int showGameInfo(char *ID) { gameinfoWindow.Append(vitalitysensorImg); intputX += (CFG.widescreen ? vitalitysensorImg->GetWidth() * .8 : vitalitysensorImg->GetWidth())+5; } - */ - if (dancepad==1) { - dancepadImg = new GuiImage(dancepadImgData); - dancepadImg->SetWidescreen(CFG.widescreen); - dancepadImg->SetPosition(intputX , inputY); - dancepadImg->SetAlignment(0,4); - gameinfoWindow.Append(dancepadImg); - intputX += (CFG.widescreen ? dancepadImg->GetWidth() * .8 : dancepadImg->GetWidth())+5; + */ + if ( dancepad == 1 ) + { + dancepadImg = new GuiImage( dancepadImgData ); + dancepadImg->SetWidescreen( CFG.widescreen ); + dancepadImg->SetPosition( intputX , inputY ); + dancepadImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( dancepadImg ); + intputX += ( CFG.widescreen ? dancepadImg->GetWidth() * .8 : dancepadImg->GetWidth() ) + 5; } - if (balanceboard==1) { - balanceboardImg = new GuiImage(balanceboardImgData); - balanceboardImg->SetWidescreen(CFG.widescreen); - balanceboardImg->SetPosition(intputX , inputY); - balanceboardImg->SetAlignment(0,4); - gameinfoWindow.Append(balanceboardImg); - intputX += (CFG.widescreen ? balanceboardImg->GetWidth() * .8 : balanceboardImg->GetWidth())+5; + if ( balanceboard == 1 ) + { + balanceboardImg = new GuiImage( balanceboardImgData ); + balanceboardImg->SetWidescreen( CFG.widescreen ); + balanceboardImg->SetPosition( intputX , inputY ); + balanceboardImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( balanceboardImg ); + intputX += ( CFG.widescreen ? balanceboardImg->GetWidth() * .8 : balanceboardImg->GetWidth() ) + 5; } // # online players - if ((strcmp(gameinfo.wifiplayers,"") != 0) && (strcmp(gameinfo.wifiplayers,"0") != 0)) { - wifiplayersImgData = new GuiImageData(wifi1_png); - if (atoi(gameinfo.wifiplayers)>1) { - wifiplayersImgData= new GuiImageData(wifi2_png); + if ( ( strcmp( gameinfo.wifiplayers, "" ) != 0 ) && ( strcmp( gameinfo.wifiplayers, "0" ) != 0 ) ) + { + wifiplayersImgData = new GuiImageData( wifi1_png ); + if ( atoi( gameinfo.wifiplayers ) > 1 ) + { + wifiplayersImgData = new GuiImageData( wifi2_png ); } - if (atoi(gameinfo.wifiplayers)>2) { - wifiplayersImgData= new GuiImageData(wifi4_png); + if ( atoi( gameinfo.wifiplayers ) > 2 ) + { + 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 ); + } + /* + if (atoi(gameinfo.wifiplayers)>6) { wifiplayersImgData= new GuiImageData(wifi8_png); } - /* - if (atoi(gameinfo.wifiplayers)>6) { - wifiplayersImgData= new GuiImageData(wifi8_png); + */ + if ( atoi( gameinfo.wifiplayers ) > 8 ) + { + wifiplayersImgData = new GuiImageData( wifi12_png ); } - */ - if (atoi(gameinfo.wifiplayers)>8) { - wifiplayersImgData= new GuiImageData(wifi12_png); - } - if (atoi(gameinfo.wifiplayers)>12) { - wifiplayersImgData= new GuiImageData(wifi16_png); - } - if (atoi(gameinfo.wifiplayers)>16) { - wifiplayersImgData= new GuiImageData(wifi32_png); - } - wifiplayersImg = new GuiImage(wifiplayersImgData); - wifiplayersImg->SetWidescreen(CFG.widescreen); - wifiplayersImg->SetPosition(intputX , inputY); - wifiplayersImg->SetAlignment(0,4); - gameinfoWindow.Append(wifiplayersImg); - intputX += (CFG.widescreen ? wifiplayersImg->GetWidth() * .8 : wifiplayersImg->GetWidth())+5; + if ( atoi( gameinfo.wifiplayers ) > 12 ) + { + wifiplayersImgData = new GuiImageData( wifi16_png ); + } + if ( atoi( gameinfo.wifiplayers ) > 16 ) + { + wifiplayersImgData = new GuiImageData( wifi32_png ); + } + wifiplayersImg = new GuiImage( wifiplayersImgData ); + wifiplayersImg->SetWidescreen( CFG.widescreen ); + wifiplayersImg->SetPosition( intputX , inputY ); + wifiplayersImg->SetAlignment( 0, 4 ); + gameinfoWindow.Append( wifiplayersImg ); + intputX += ( CFG.widescreen ? wifiplayersImg->GetWidth() * .8 : wifiplayersImg->GetWidth() ) + 5; } // ratings - if (strcmp(gameinfo.ratingtype,"") !=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); - else { - ratingImgData = new GuiImageData(norating_png); + if ( strcmp( gameinfo.ratingtype, "" ) != 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 ); + else + { + 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 - 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); + } //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 ); + else + { + ratingImgData = new GuiImageData( norating_png ); } - } 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); - else { - ratingImgData = new GuiImageData(norating_png); + } + 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 ); + else + { + ratingImgData = new GuiImageData( norating_png ); } } - else { - ratingImgData = new GuiImageData(norating_png); + else + { + ratingImgData = new GuiImageData( norating_png ); } - ratingImg = new GuiImage(ratingImgData); - ratingImg->SetWidescreen(CFG.widescreen); - ratingImg->SetPosition(-25 , inputY); - ratingImg->SetAlignment(1,4); - gameinfoWindow.Append(ratingImg); - intputX += (CFG.widescreen ? ratingImg->GetWidth() * .8 : ratingImg->GetWidth())+5; + ratingImg = new GuiImage( ratingImgData ); + ratingImg->SetWidescreen( CFG.widescreen ); + ratingImg->SetPosition( -25 , inputY ); + ratingImg->SetAlignment( 1, 4 ); + gameinfoWindow.Append( ratingImg ); + intputX += ( CFG.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) { - snprintf(linebuf, sizeof(linebuf), "%s",gameinfo.title); - titleTxt = new GuiText(linebuf, titlefontsize, (GXColor) {0,0,0, 255}); - titleTxt->SetMaxWidth(350, SCROLL_HORIZONTAL); + int titlefontsize = 25; + if ( strcmp( gameinfo.title, "" ) != 0 ) + { + snprintf( linebuf, sizeof( linebuf ), "%s", gameinfo.title ); + titleTxt = new GuiText( linebuf, titlefontsize, ( GXColor ) {0, 0, 0, 255} ); + titleTxt->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), "%s ", gameinfo.day); + snprintf( linebuf2, sizeof( linebuf2 ), " " ); + if ( strcmp( gameinfo.day, "" ) != 0 ) + { + snprintf( linebuf2, sizeof( linebuf2 ), "%s ", gameinfo.day ); } - if (strcmp(gameinfo.month,"") != 0) { - switch (atoi(gameinfo.month)) { - case 1: - snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr("Jan")); - break; - case 2: - snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr("Feb")); - break; - case 3: - snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr("Mar")); - break; - case 4: - snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr("Apr")); - break; - case 5: - snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr("May")); - break; - case 6: - snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr("June")); - break; - case 7: - snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr("July")); - break; - case 8: - snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr("Aug")); - break; - case 9: - snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr("Sept")); - break; - case 10: - snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr("Oct")); - break; - case 11: - snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr("Nov")); - break; - case 12: - snprintf(linebuf2, sizeof(linebuf2), "%s%s ", linebuf2, tr("Dec")); - break; + if ( strcmp( gameinfo.month, "" ) != 0 ) + { + switch ( atoi( gameinfo.month ) ) + { + case 1: + snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Jan" ) ); + break; + case 2: + snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Feb" ) ); + break; + case 3: + snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Mar" ) ); + break; + case 4: + snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Apr" ) ); + break; + case 5: + snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "May" ) ); + break; + case 6: + snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "June" ) ); + break; + case 7: + snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "July" ) ); + break; + case 8: + snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Aug" ) ); + break; + case 9: + snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Sept" ) ); + break; + case 10: + snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Oct" ) ); + break; + case 11: + snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Nov" ) ); + break; + case 12: + snprintf( linebuf2, sizeof( linebuf2 ), "%s%s ", linebuf2, tr( "Dec" ) ); + break; } } - 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); - newline=1; - gameinfoWindow.Append(releasedTxt); + 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 ); + newline = 1; + gameinfoWindow.Append( releasedTxt ); } //publisher - if (strcmp(gameinfo.publisher,"") != 0) { - snprintf(linebuf, sizeof(linebuf), "%s %s", tr("Published by"), gameinfo.publisher); - publisherTxt = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); - 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); + 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 ); + newline = 1; + gameinfoWindow.Append( publisherTxt ); } //developer - if (strcmp(gameinfo.developer,"") != 0 && strcasecmp(gameinfo.developer,gameinfo.publisher) != 0) { - snprintf(linebuf, sizeof(linebuf), "%s %s", tr("Developed by"), gameinfo.developer); - developerTxt = new GuiText(linebuf, 16, (GXColor) {0,0,0, 255}); - 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); + 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 ); + newline = 1; + gameinfoWindow.Append( developerTxt ); } //genre int genreY = marginY; 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); - genreY+=20; - gameinfoWindow.Append(genreTxt[i]); + 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 ); + genreY += 20; + gameinfoWindow.Append( genreTxt[i] ); } //online wifiTxt = new GuiText * [gameinfo.wifiCnt + 1]; - for (int i=gameinfo.wifiCnt;i>=1;i--) { - if (strcmp(gameinfo.wififeatures[i],"Nintendods") == 0) { - snprintf(linebuf, sizeof(linebuf), "Nintendo DS"); - } else { - snprintf(linebuf, sizeof(linebuf), "%s",gameinfo.wififeatures[i]); + for ( int i = gameinfo.wifiCnt; i >= 1; i-- ) + { + if ( strcmp( gameinfo.wififeatures[i], "Nintendods" ) == 0 ) + { + snprintf( linebuf, sizeof( linebuf ), "Nintendo DS" ); } - 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]); + else + { + 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 ); + wifiY -= 20; + gameinfoWindow.Append( wifiTxt[i] ); } - if (strcmp(gameinfo.wififeatures[1],"") !=0) { - snprintf(linebuf, sizeof(linebuf), "%s:",tr("WiFi Features")); - } else { - strcpy(linebuf,""); + if ( strcmp( gameinfo.wififeatures[1], "" ) != 0 ) + { + snprintf( linebuf, sizeof( linebuf ), "%s:", tr( "WiFi Features" ) ); } - 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]); + else + { + 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] ); //synopsis - int pagesize=12; - 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); + int pagesize = 12; + 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 ); 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(CFG.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( CFG.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); + GuiTrigger trigZ; + trigZ.SetButtonOnlyTrigger( -1, WPAD_NUNCHUK_BUTTON_Z | WPAD_CLASSIC_BUTTON_ZL, PAD_TRIGGER_Z ); - GuiButton screenShotBtn(0,0); - screenShotBtn.SetPosition(0,0); - screenShotBtn.SetTrigger(&trigZ); - gameinfoWindow.Append(&screenShotBtn); + GuiButton screenShotBtn( 0, 0 ); + screenShotBtn.SetPosition( 0, 0 ); + screenShotBtn.SetTrigger( &trigZ ); + gameinfoWindow.Append( &screenShotBtn ); HaltGui(); //mainWindow->SetState(STATE_DISABLED); - mainWindow->Append(&gameinfoWindow); - mainWindow->ChangeFocus(&gameinfoWindow); + mainWindow->Append( &gameinfoWindow ); + mainWindow->ChangeFocus( &gameinfoWindow ); ResumeGui(); - bool savedURL = false; + bool savedURL = false; - while (choice == -1) { + while ( choice == -1 ) + { VIDEO_WaitVSync(); - if (shutdown == 1) { - wiilight(0); + if ( shutdown == 1 ) + { + wiilight( 0 ); Sys_Shutdown(); - } else if (reset == 1) + } + else if ( reset == 1 ) Sys_Reboot(); - else if ((backBtn.GetState()==STATE_CLICKED)||(backBtn.GetState()==STATE_HELD)) { - backBtn.ResetState(); - if (page==1) { - choice=1; - if(synopsisTxt) + else if ( ( backBtn.GetState() == STATE_CLICKED ) || ( backBtn.GetState() == STATE_HELD ) ) + { + backBtn.ResetState(); + if ( page == 1 ) + { + choice = 1; + 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; + 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; + 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; + 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))) + 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))) + 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) { - choice=2; - if(synopsisTxt) + if ( page == 1 ) + { + choice = 2; + if ( synopsisTxt ) delete synopsisTxt; synopsisTxt = NULL; break; - } else if (page==2) { - HaltGui(); - gameinfoWindow2.SetVisible(false); - gameinfoWindow.SetVisible(true); - mainWindow->Remove(&gameinfoWindow2); - ResumeGui(); - page=1; } - } 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("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); - } - urlBtn.ResetState(); + else if ( page == 2 ) + { + HaltGui(); + gameinfoWindow2.SetVisible( false ); + gameinfoWindow.SetVisible( true ); + mainWindow->Remove( &gameinfoWindow2 ); + ResumeGui(); + page = 1; + } + } + 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( "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 ); + } + urlBtn.ResetState(); + } + else if ( screenShotBtn.GetState() == STATE_CLICKED ) + { + gprintf( "\n\tscreenShotBtn clicked" ); + screenShotBtn.ResetState(); + ScreenShot(); + gprintf( "...It's easy, mmmmmmKay" ); } - else if (screenShotBtn.GetState() == STATE_CLICKED) { - gprintf("\n\tscreenShotBtn clicked"); - screenShotBtn.ResetState(); - ScreenShot(); - gprintf("...It's easy, mmmmmmKay"); - } } - if (page==1) { - gameinfoWindow.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 100); - while (gameinfoWindow.GetEffect() > 0) usleep(50); + if ( page == 1 ) + { + 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; @@ -993,137 +1064,158 @@ int showGameInfo(char *ID) { delete wiitdb2Txt; delete wiitdb3Txt; delete memTxt; - if (gameinfo.genreCnt>0) { - for (int i=1;i<=gameinfo.genreCnt;i++) { + if ( gameinfo.genreCnt > 0 ) + { + for ( int i = 1; i <= gameinfo.genreCnt; i++ ) + { delete genreTxt[i]; } } - if (gameinfo.wifiCnt>0) { - for (int i=0;i<=gameinfo.wifiCnt;i++) { + if ( gameinfo.wifiCnt > 0 ) + { + for ( int i = 0; i <= gameinfo.wifiCnt; i++ ) + { delete wifiTxt[i]; } } ResumeGui(); - } else { - gameinfoWindow2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 100); - while (gameinfoWindow2.GetEffect() > 0) usleep(50); + } + else + { + 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 */ - } else { + /* File not found */ + } + else + { return -1; } } -bool save_gamelist(int txt) { // save gamelist - mainWindow->SetState(STATE_DISABLED); +bool save_gamelist( int txt ) // save gamelist +{ + 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) { - mkdir(tmp, 0777); + if ( stat( tmp, &st ) != 0 ) + { + 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) { - sleep(1); - mainWindow->SetState(STATE_DEFAULT); + 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 ); return false; } //make sure that all games are added to the gamelist gameList.LoadUnfiltered(); f32 size = 0.0; - f32 freespace, used; - int i; + 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) { - fprintf(f, "# USB Loader Has Saved this file\n"); - fprintf(f, "# This file was created based on your list of games and language settings.\n\n"); + if ( txt == 0 ) + { + fprintf( f, "# USB Loader Has Saved this file\n" ); + fprintf( f, "# This file was created based on your list of games and language settings.\n\n" ); - fprintf(f, "%.2fGB %s %.2fGB %s\n\n",freespace,tr("of"),(freespace+used),tr("free")); - fprintf(f, "ID Size(GB) Name\n"); + fprintf( f, "%.2fGB %s %.2fGB %s\n\n", freespace, tr( "of" ), ( freespace + used ), tr( "free" ) ); + fprintf( f, "ID Size(GB) Name\n" ); - for (i = 0; i < gameList.size() ; i++) { - struct discHdr* header = gameList[i]; - WBFS_GameSize(header->id, &size); - if (i<500) { - fprintf(f, "%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5]); - fprintf(f, " [%.2f] ", size); - fprintf(f, " %s",get_title(header)); - } - fprintf(f, "\n"); - } - } else { + for ( i = 0; i < gameList.size() ; i++ ) + { + struct discHdr* header = gameList[i]; + WBFS_GameSize( header->id, &size ); + if ( i < 500 ) + { + fprintf( f, "%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5] ); + fprintf( f, " [%.2f] ", size ); + fprintf( f, " %s", get_title( header ) ); + } + fprintf( f, "\n" ); + } + } + else + { - fprintf(f, "\"ID\",\"Size(GB)\",\"Name\"\n"); + fprintf( f, "\"ID\",\"Size(GB)\",\"Name\"\n" ); - for (i = 0; i < gameList.size() ; i++) { - struct discHdr* header = gameList[i]; - WBFS_GameSize(header->id, &size); - if (i<500) { - fprintf(f, "\"%c%c%c%c%c%c\",\"%.2f\",\"%s\"\n", header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5], size,get_title(header)); - //fprintf(f, "\"%.2f\",", size); - //fprintf(f, "\"%s\"",get_title(header)); - } - //fprintf(f, "\n"); - } - } - fclose(f); + for ( i = 0; i < gameList.size() ; i++ ) + { + struct discHdr* header = gameList[i]; + WBFS_GameSize( header->id, &size ); + if ( i < 500 ) + { + fprintf( f, "\"%c%c%c%c%c%c\",\"%.2f\",\"%s\"\n", header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5], size, get_title( header ) ); + //fprintf(f, "\"%.2f\",", size); + //fprintf(f, "\"%s\"",get_title(header)); + } + //fprintf(f, "\n"); + } + } + fclose( f ); 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) { - mkdir(tmp, 0777); + if ( stat( tmp, &st ) != 0 ) + { + mkdir( tmp, 0777 ); } FILE *f; - sprintf(tmp, "%sWiiTDB_URL.txt", Settings.update_path); - f = fopen(tmp, "w"); - if (!f) { - sleep(1); + sprintf( tmp, "%sWiiTDB_URL.txt", Settings.update_path ); + f = fopen( tmp, "w" ); + if ( !f ) + { + sleep( 1 ); return false; } - char XMLurl[3540]; - build_XML_URL(XMLurl,sizeof(XMLurl)); + char XMLurl[3540]; + build_XML_URL( XMLurl, sizeof( XMLurl ) ); - fprintf(f, "# USB Loader Has Saved this file\n"); - fprintf(f, "# This URL was created based on your list of games and language settings.\n"); - fclose(f); + 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; } @@ -1131,29 +1223,31 @@ bool save_XML_URL() { // save xml url as as txt file for people without wifi void MemInfoPrompt() { - char meminfotxt[200]; - strlcpy(meminfotxt,MemInfo(),sizeof(meminfotxt)); - WindowPrompt(0,meminfotxt, tr("OK")); + char meminfotxt[200]; + 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 + // 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) { - 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); + 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 ); } } - strlcpy(XMLurl,url,XMLurlsize); - gameList.FilterList(); + strlcpy( XMLurl, url, XMLurlsize ); + gameList.FilterList(); } diff --git a/source/prompts/gameinfo.h b/source/prompts/gameinfo.h index 4f46670b..03bc347a 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 77478636..feebf83b 100644 --- a/source/ramdisk/ramdisk.cpp +++ b/source/ramdisk/ramdisk.cpp @@ -8,8 +8,8 @@ #include #include "ramdisk.h" -#define NAMELENMAX 0x80 -#define MAXPATHLEN 0x100 +#define NAMELENMAX 0x80 +#define MAXPATHLEN 0x100 @@ -20,976 +20,1006 @@ class RAMDISK_DIR_ENTRY; class RAMDISK_FILE_ENTRY; class RAMDISK_BASE_ENTRY { -public: - RAMDISK_BASE_ENTRY(const char *Name, RAMDISK_DIR_ENTRY *Parent); - virtual ~RAMDISK_BASE_ENTRY(); - void Rename(const char *Name); - RAMDISK_LINK_ENTRY *IsLink(); - RAMDISK_DIR_ENTRY *IsDir(); - RAMDISK_FILE_ENTRY *IsFile(); - RAMDISK_PARTITION *GetPartition(); - char *name; - RAMDISK_DIR_ENTRY *parent; - RAMDISK_BASE_ENTRY *next; + public: + RAMDISK_BASE_ENTRY( const char *Name, RAMDISK_DIR_ENTRY *Parent ); + virtual ~RAMDISK_BASE_ENTRY(); + void Rename( const char *Name ); + RAMDISK_LINK_ENTRY *IsLink(); + RAMDISK_DIR_ENTRY *IsDir(); + RAMDISK_FILE_ENTRY *IsFile(); + RAMDISK_PARTITION *GetPartition(); + char *name; + RAMDISK_DIR_ENTRY *parent; + RAMDISK_BASE_ENTRY *next; }; class RAMDISK_LINK_ENTRY : public RAMDISK_BASE_ENTRY { -public: - RAMDISK_LINK_ENTRY(const char* Name, RAMDISK_DIR_ENTRY *Parent, RAMDISK_BASE_ENTRY *Link); - RAMDISK_BASE_ENTRY *link; + public: + 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 { -public: - RAMDISK_DIR_ENTRY(const char* Name, RAMDISK_DIR_ENTRY *Parent); - ~RAMDISK_DIR_ENTRY(); - RAMDISK_BASE_ENTRY *FindEntry(const char* Path); - RAMDISK_FILE_ENTRY *CreateFile(const char *Filename); - RAMDISK_DIR_ENTRY *CreateDir(const char *Filename); - void RemoveEntry(RAMDISK_BASE_ENTRY *Entry); - RAMDISK_BASE_ENTRY *first; - RAMDISK_BASE_ENTRY *last; + public: + RAMDISK_DIR_ENTRY( const char* Name, RAMDISK_DIR_ENTRY *Parent ); + ~RAMDISK_DIR_ENTRY(); + RAMDISK_BASE_ENTRY *FindEntry( const char* Path ); + RAMDISK_FILE_ENTRY *CreateFile( const char *Filename ); + RAMDISK_DIR_ENTRY *CreateDir( const char *Filename ); + void RemoveEntry( RAMDISK_BASE_ENTRY *Entry ); + RAMDISK_BASE_ENTRY *first; + RAMDISK_BASE_ENTRY *last; }; 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 { -public: - RAMDISK_PARTITION(const char *Mountpoint, bool AutoMount); - RAMDISK_BASE_ENTRY *FindEntry(const char* Path); - RAMDISK_DIR_ENTRY *FindPath(const char* Path, const char **Basename=NULL); - RAMDISK_DIR_ENTRY *cwd; - bool automount; + public: + RAMDISK_PARTITION( const char *Mountpoint, bool AutoMount ); + RAMDISK_BASE_ENTRY *FindEntry( const char* Path ); + RAMDISK_DIR_ENTRY *FindPath( const char* Path, const char **Basename = NULL ); + RAMDISK_DIR_ENTRY *cwd; + bool automount; }; class FILE_DATA { -public: - FILE_DATA(size_t Len); - ~FILE_DATA(); - u8 *data; - size_t len; - FILE_DATA *next; + public: + FILE_DATA( size_t Len ); + ~FILE_DATA(); + u8 *data; + size_t len; + FILE_DATA *next; }; typedef struct { - RAMDISK_FILE_ENTRY *file; - bool isLink; - u32 current_pos; - bool read; - bool write; + RAMDISK_FILE_ENTRY *file; + bool isLink; + u32 current_pos; + bool read; + bool write; } FILE_STRUCT; class RAMDISK_FILE_ENTRY : public RAMDISK_BASE_ENTRY { -public: - RAMDISK_FILE_ENTRY(const char* Name, RAMDISK_DIR_ENTRY *Parent); - ~RAMDISK_FILE_ENTRY(); - bool Truncate(size_t newLen); - bool AddCluster(size_t size); - size_t Read(struct _reent *r, FILE_STRUCT *fileStruct, char *ptr, size_t len); - size_t Write(struct _reent *r, FILE_STRUCT *fileStruct, const char *ptr, size_t len); - size_t file_len; - size_t cluster_len; - FILE_DATA *first_cluster; - FILE_DATA *last_cluster; + public: + RAMDISK_FILE_ENTRY( const char* Name, RAMDISK_DIR_ENTRY *Parent ); + ~RAMDISK_FILE_ENTRY(); + bool Truncate( size_t newLen ); + bool AddCluster( size_t size ); + size_t Read( struct _reent *r, FILE_STRUCT *fileStruct, char *ptr, size_t len ); + size_t Write( struct _reent *r, FILE_STRUCT *fileStruct, const char *ptr, size_t len ); + size_t file_len; + size_t cluster_len; + FILE_DATA *first_cluster; + FILE_DATA *last_cluster; }; -RAMDISK_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() +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() +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); - return NULL; + 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); - first = entry; - last = entry; - if(parent) - { - entry = new RAMDISK_LINK_ENTRY("..", this, parent); - first->next = entry; - last = entry; - } + RAMDISK_BASE_ENTRY* entry = new RAMDISK_LINK_ENTRY( ".", this, this ); + first = entry; + last = entry; + if ( parent ) + { + entry = new RAMDISK_LINK_ENTRY( "..", this, parent ); + first->next = entry; + last = entry; + } } RAMDISK_DIR_ENTRY::~RAMDISK_DIR_ENTRY() { - while(first) - { - first->parent = NULL; // ~RAMDISK_BASE_ENTRY() no calls RemoveEntry() - RAMDISK_BASE_ENTRY* next = first->next; - delete first; - first = next; - } + while ( first ) + { + first->parent = NULL; // ~RAMDISK_BASE_ENTRY() no calls RemoveEntry() + RAMDISK_BASE_ENTRY* next = first->next; + delete first; + first = next; + } } -RAMDISK_BASE_ENTRY *RAMDISK_DIR_ENTRY::FindEntry(const char* Path) +RAMDISK_BASE_ENTRY *RAMDISK_DIR_ENTRY::FindEntry( const char* Path ) { - const char* dirpath = Path; - const char* cptr; - while( dirpath[0] == '/') dirpath++; // move past leading '/' + const char* dirpath = Path; + const char* cptr; + while ( dirpath[0] == '/' ) dirpath++; // move past leading '/' - if(dirpath[0] == '\0') // this path is found - return this; + if ( dirpath[0] == '\0' ) // this path is found + return this; - cptr = strchr(dirpath,'/'); // find next '/' - if(cptr == NULL) - cptr = strchr(dirpath,'\0'); // cptr at end - for(RAMDISK_BASE_ENTRY *curr = first; curr; curr=curr->next) - { - if( strncmp(curr->name, dirpath, cptr-dirpath) == 0) - { - if(RAMDISK_DIR_ENTRY *dir = curr->IsDir()) - return dir->FindEntry(cptr); - else - return curr; - } - } - - return NULL; + cptr = strchr( dirpath, '/' ); // find next '/' + if ( cptr == NULL ) + cptr = strchr( dirpath, '\0' ); // cptr at end + for ( RAMDISK_BASE_ENTRY *curr = first; curr; curr = curr->next ) + { + if ( strncmp( curr->name, dirpath, cptr - dirpath ) == 0 ) + { + if ( RAMDISK_DIR_ENTRY *dir = curr->IsDir() ) + return dir->FindEntry( cptr ); + else + return curr; + } + } + + return NULL; } -RAMDISK_FILE_ENTRY *RAMDISK_DIR_ENTRY::CreateFile(const char *Filename) +RAMDISK_FILE_ENTRY *RAMDISK_DIR_ENTRY::CreateFile( const char *Filename ) { - try - { - RAMDISK_FILE_ENTRY* file = new RAMDISK_FILE_ENTRY(Filename, this); - if(!first) first = file; - last->next = file; - last = file; - return file; + try + { + RAMDISK_FILE_ENTRY* file = new RAMDISK_FILE_ENTRY( Filename, this ); + if ( !first ) first = file; + last->next = file; + last = file; + return file; + } + catch ( ... ) { return NULL; } } -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; - last->next = dir; - last = dir; - return dir; + try + { + RAMDISK_DIR_ENTRY* dir = new RAMDISK_DIR_ENTRY( Filename, this ); + if ( !first ) first = dir; + last->next = dir; + last = dir; + return dir; + } + catch ( ... ) { return NULL; } } -catch(...) { return NULL; } -} -void RAMDISK_DIR_ENTRY::RemoveEntry(RAMDISK_BASE_ENTRY *Entry) +void RAMDISK_DIR_ENTRY::RemoveEntry( RAMDISK_BASE_ENTRY *Entry ) { - RAMDISK_BASE_ENTRY **p_last = NULL; - for(RAMDISK_BASE_ENTRY **curr = &first; *curr; curr=&((*curr)->next) ) - { - if( *curr == Entry ) - { - *curr = Entry->next; - if(Entry->next == NULL) // entry is last - last = *p_last; - break; - } - p_last = curr; - } + RAMDISK_BASE_ENTRY **p_last = NULL; + for ( RAMDISK_BASE_ENTRY **curr = &first; *curr; curr = &( ( *curr )->next ) ) + { + if ( *curr == Entry ) + { + *curr = Entry->next; + if ( Entry->next == NULL ) // entry is last + last = *p_last; + break; + } + p_last = curr; + } } -RAMDISK_PARTITION::RAMDISK_PARTITION(const char *Mountpoint, bool AutoMount) : -RAMDISK_DIR_ENTRY(Mountpoint, NULL), -cwd(this), -automount(AutoMount) +RAMDISK_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 ) - { -// 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); + char *cptr; + if ( ( cptr = strchr( path, ':' ) ) ) + path = cptr + 1; //move path past any device names + if ( strchr( path, ':' ) != NULL ) + { +// r->_errno = EINVAL; + return NULL; + } + if ( *path == '/' ) // if first character is '/' use absolute root path + return RAMDISK_DIR_ENTRY::FindEntry( path ); + else // else use current working dir + return cwd->FindEntry( path ); } -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 - { - if((*cptr=='/') || (*cptr==':')) // split at either / or : (whichever comes first form the end!) - { - cptr++; - strlcpy(dirfilename, path, 1+cptr-path); //copy string up till and including / or : - filename = cptr; //filename = now remainder of string - break; - } - } - - if(!filename) - { - filename = path; //filename = complete path - dirfilename[0] = 0; //make directory path "" - } - RAMDISK_BASE_ENTRY *entry = FindEntry(dirfilename); - if(entry) - { - if(basename) *basename = filename; - return entry->IsDir(); - } - return NULL; + int pathLen = strlen( path ); + char dirfilename[pathLen+1]; // to hold a full path + const char *cptr = path + pathLen; // find the end... + const char *filename = NULL; // to hold filename + while ( cptr-- > path ) //search till start + { + if ( ( *cptr == '/' ) || ( *cptr == ':' ) ) // split at either / or : (whichever comes first form the end!) + { + cptr++; + strlcpy( dirfilename, path, 1 + cptr - path ); //copy string up till and including / or : + filename = cptr; //filename = now remainder of string + break; + } + } + + if ( !filename ) + { + filename = path; //filename = complete path + dirfilename[0] = 0; //make directory path "" + } + RAMDISK_BASE_ENTRY *entry = FindEntry( dirfilename ); + if ( entry ) + { + if ( basename ) *basename = filename; + return entry->IsDir(); + } + return NULL; } -FILE_DATA::FILE_DATA(size_t Len) : -next(NULL) +FILE_DATA::FILE_DATA( size_t Len ) : + next( NULL ) { - data = new u8[Len]; - len = Len; - memset(data, 0, len); -} + data = new u8[Len]; + len = Len; + memset( data, 0, len ); +} FILE_DATA::~FILE_DATA() { - delete [] data; - delete next; + 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) - { - // Expanding the file over cluster_len - return AddCluster(newSize - cluster_len); - } - else if (newSize < file_len) - { - // Shrinking the file - FILE_DATA *prev_cluster = NULL; - size_t len = 0; - for(FILE_DATA **p_cluster = &first_cluster; *p_cluster; p_cluster = &(*p_cluster)->next) - { - if(len >= newSize) - { - last_cluster = prev_cluster; - delete *p_cluster; - (*p_cluster) = NULL; - break; - } - len += (*p_cluster)->len; - prev_cluster = *p_cluster; - } - } - file_len = newSize; - return true; + if ( newSize > cluster_len ) + { + // Expanding the file over cluster_len + return AddCluster( newSize - cluster_len ); + } + else if ( newSize < file_len ) + { + // Shrinking the file + FILE_DATA *prev_cluster = NULL; + size_t len = 0; + for ( FILE_DATA **p_cluster = &first_cluster; *p_cluster; p_cluster = &( *p_cluster )->next ) + { + if ( len >= newSize ) + { + last_cluster = prev_cluster; + delete *p_cluster; + ( *p_cluster ) = NULL; + break; + } + len += ( *p_cluster )->len; + prev_cluster = *p_cluster; + } + } + file_len = newSize; + return true; } -bool RAMDISK_FILE_ENTRY::AddCluster(size_t len) +bool RAMDISK_FILE_ENTRY::AddCluster( size_t len ) { - if(len < CLUSTER_SIZE) - len = CLUSTER_SIZE; - try - { - *(last_cluster ? &last_cluster->next : &first_cluster) = last_cluster = new FILE_DATA(len); - cluster_len += len; - return true; - } - catch(...) { return false; } + if ( len < CLUSTER_SIZE ) + len = CLUSTER_SIZE; + try + { + *( last_cluster ? &last_cluster->next : &first_cluster ) = last_cluster = new FILE_DATA( len ); + cluster_len += len; + return true; + } + catch ( ... ) { return false; } } -size_t RAMDISK_FILE_ENTRY::Read(struct _reent *r, FILE_STRUCT *fileStruct, char *ptr, size_t len) +size_t RAMDISK_FILE_ENTRY::Read( struct _reent *r, FILE_STRUCT *fileStruct, char *ptr, size_t len ) { - if (!fileStruct->read) - { - r->_errno = EBADF; - return 0; - } - // Short circuit cases where len is 0 (or less) - if (len <= 0) - return 0; - // Don't try to read if the read pointer is past the end of file - if (fileStruct->current_pos >= file_len) - { - r->_errno = EOVERFLOW; - return 0; - } + if ( !fileStruct->read ) + { + r->_errno = EBADF; + return 0; + } + // Short circuit cases where len is 0 (or less) + if ( len <= 0 ) + return 0; + // Don't try to read if the read pointer is past the end of file + if ( fileStruct->current_pos >= file_len ) + { + r->_errno = EOVERFLOW; + return 0; + } - // Don't read past end of file - if (len + fileStruct->current_pos > file_len) - { - r->_errno = EOVERFLOW; - len = fileStruct->current_pos - file_len; - } + // Don't read past end of file + if ( len + fileStruct->current_pos > file_len ) + { + r->_errno = EOVERFLOW; + len = fileStruct->current_pos - file_len; + } - off_t pos = fileStruct->current_pos; - size_t readed = 0; - size_t max_len = file_len; - for(FILE_DATA *cluster = first_cluster; cluster; cluster = cluster->next) - { - if(pos > cluster->len) - { - pos -= cluster->len; - max_len -= cluster->len; - } - else - { - size_t read = max_len; - if(read > cluster->len) - read = cluster->len; - read -= pos; - if(read > len) - read = len; - memcpy(ptr, &(cluster->data[pos]), read); - readed += read; - ptr += read; - len -= read; - if(len == 0) - break; - pos -= cluster->len; - max_len -= cluster->len; - - } - } - fileStruct->current_pos += readed; - return readed; + off_t pos = fileStruct->current_pos; + size_t readed = 0; + size_t max_len = file_len; + for ( FILE_DATA *cluster = first_cluster; cluster; cluster = cluster->next ) + { + if ( pos > cluster->len ) + { + pos -= cluster->len; + max_len -= cluster->len; + } + else + { + size_t read = max_len; + if ( read > cluster->len ) + read = cluster->len; + read -= pos; + if ( read > len ) + read = len; + memcpy( ptr, &( cluster->data[pos] ), read ); + readed += read; + ptr += read; + len -= read; + if ( len == 0 ) + break; + pos -= cluster->len; + max_len -= cluster->len; + + } + } + fileStruct->current_pos += readed; + return readed; } -size_t RAMDISK_FILE_ENTRY::Write(struct _reent *r, FILE_STRUCT *fileStruct, const char *ptr, size_t len) +size_t RAMDISK_FILE_ENTRY::Write( struct _reent *r, FILE_STRUCT *fileStruct, const char *ptr, size_t len ) { - if (!fileStruct->write) - { - r->_errno = EBADF; - return 0; - } - // Short circuit cases where len is 0 (or less) - if (len <= 0) - return 0; + if ( !fileStruct->write ) + { + r->_errno = EBADF; + return 0; + } + // Short circuit cases where len is 0 (or less) + if ( len <= 0 ) + return 0; - off_t pos = fileStruct->current_pos; - if(cluster_len < (pos+len) && !AddCluster((pos+len) - cluster_len)) - { - // Couldn't get a cluster, so abort - r->_errno = ENOSPC; - return 0; - } - if(file_len < (pos+len)) - file_len = (pos+len); - - size_t written = 0; - size_t max_len = cluster_len; - for(FILE_DATA *cluster = first_cluster; cluster; cluster = cluster->next) - { - if(pos > cluster->len) - { - pos -= cluster->len; - max_len -= cluster->len; - } - else - { - size_t write = cluster->len - pos; - if(write > len) write = len; - memcpy(&(cluster->data[pos]), ptr, write); - written += write; - ptr += write; - len -= write; - if(len == 0) - break; - pos -= cluster->len; - max_len -= cluster->len; - } - } - fileStruct->current_pos += written; - return written; + off_t pos = fileStruct->current_pos; + if ( cluster_len < ( pos + len ) && !AddCluster( ( pos + len ) - cluster_len ) ) + { + // Couldn't get a cluster, so abort + r->_errno = ENOSPC; + return 0; + } + if ( file_len < ( pos + len ) ) + file_len = ( pos + len ); + + size_t written = 0; + size_t max_len = cluster_len; + for ( FILE_DATA *cluster = first_cluster; cluster; cluster = cluster->next ) + { + if ( pos > cluster->len ) + { + pos -= cluster->len; + max_len -= cluster->len; + } + else + { + size_t write = cluster->len - pos; + if ( write > len ) write = len; + memcpy( &( cluster->data[pos] ), ptr, write ); + written += write; + ptr += write; + len -= write; + if ( len == 0 ) + break; + pos -= cluster->len; + max_len -= cluster->len; + } + } + fileStruct->current_pos += written; + return written; } -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 ) - { - r->_errno = ENODEV; - return -1; - } + RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath( path ); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } - if ((flags & 0x03) == O_RDONLY) { - // Open the file for read-only access - fileStruct->read = true; - fileStruct->write = false; - } else if ((flags & 0x03) == O_WRONLY) { - // Open file for write only access - fileStruct->read = false; - fileStruct->write = true; - } else if ((flags & 0x03) == O_RDWR) { - // Open file for read/write access - fileStruct->read = true; - fileStruct->write = true; - } else { - r->_errno = EACCES; - return -1; - } - RAMDISK_BASE_ENTRY *entry = partition->FindEntry(path); - - // The file shouldn't exist if we are trying to create it - if (entry && (flags & O_CREAT) && (flags & O_EXCL)) - { - r->_errno = EEXIST; - return -1; - } - // It should not be a directory if we're openning a file, - if (entry && entry->IsDir()) - { - r->_errno = EISDIR; - return -1; - } + if ( ( flags & 0x03 ) == O_RDONLY ) + { + // Open the file for read-only access + fileStruct->read = true; + fileStruct->write = false; + } + else if ( ( flags & 0x03 ) == O_WRONLY ) + { + // Open file for write only access + fileStruct->read = false; + fileStruct->write = true; + } + else if ( ( flags & 0x03 ) == O_RDWR ) + { + // Open file for read/write access + fileStruct->read = true; + fileStruct->write = true; + } + else + { + r->_errno = EACCES; + return -1; + } + RAMDISK_BASE_ENTRY *entry = partition->FindEntry( path ); - fileStruct->isLink = entry ? entry->IsLink() : false; - fileStruct->file = entry ? entry->IsFile() : NULL; - if(!fileStruct->file) // entry not exists - { - if (flags & O_CREAT) - { - const char *filename; - RAMDISK_DIR_ENTRY *dir = partition->FindPath(path, &filename); - if(!dir) - { - r->_errno = ENOTDIR; - return -1; - } - fileStruct->file = dir->CreateFile(filename); - } - else - { - // file doesn't exist, and we aren't creating it - r->_errno = ENOENT; - return -1; - } - } - if(fileStruct->file) - { - fileStruct->current_pos = 0; - // Truncate the file if requested - if ((flags & O_TRUNC) && fileStruct->write) - fileStruct->file->Truncate(0); - if (flags & O_APPEND) - fileStruct->current_pos = fileStruct->file->file_len; - return 0; - } - r->_errno = ENOENT; - return(-1); + // The file shouldn't exist if we are trying to create it + if ( entry && ( flags & O_CREAT ) && ( flags & O_EXCL ) ) + { + r->_errno = EEXIST; + return -1; + } + // It should not be a directory if we're openning a file, + if ( entry && entry->IsDir() ) + { + r->_errno = EISDIR; + return -1; + } + + fileStruct->isLink = entry ? entry->IsLink() : false; + fileStruct->file = entry ? entry->IsFile() : NULL; + if ( !fileStruct->file ) // entry not exists + { + if ( flags & O_CREAT ) + { + const char *filename; + RAMDISK_DIR_ENTRY *dir = partition->FindPath( path, &filename ); + if ( !dir ) + { + r->_errno = ENOTDIR; + return -1; + } + fileStruct->file = dir->CreateFile( filename ); + } + else + { + // file doesn't exist, and we aren't creating it + r->_errno = ENOENT; + return -1; + } + } + if ( fileStruct->file ) + { + fileStruct->current_pos = 0; + // Truncate the file if requested + if ( ( flags & O_TRUNC ) && fileStruct->write ) + fileStruct->file->Truncate( 0 ); + if ( flags & O_APPEND ) + fileStruct->current_pos = fileStruct->file->file_len; + return 0; + } + r->_errno = ENOENT; + return( -1 ); } //--------------------------------------------------------------------------------- -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; - - switch(dir) - { - case SEEK_SET: - break; - case SEEK_CUR: - pos += fileStruct->current_pos; - break; - case SEEK_END: - pos += fileStruct->file->file_len; // set start to end of file - break; - default: - r->_errno = EINVAL; - return -1; - } - return fileStruct->current_pos = pos; + //need check for eof here... + FILE_STRUCT *fileStruct = ( FILE_STRUCT* )fd; + + switch ( dir ) + { + case SEEK_SET: + break; + case SEEK_CUR: + pos += fileStruct->current_pos; + break; + case SEEK_END: + pos += fileStruct->file->file_len; // set start to end of file + break; + default: + r->_errno = EINVAL; + return -1; + } + return fileStruct->current_pos = pos; } //--------------------------------------------------------------------------------- -static int ramdiskFS_fstat_r(struct _reent *r, int fd, struct stat *st) { +static int ramdiskFS_fstat_r( struct _reent *r, int fd, struct stat *st ) +{ //--------------------------------------------------------------------------------- - FILE_STRUCT *fileStruct = (FILE_STRUCT*)fd; + FILE_STRUCT *fileStruct = ( FILE_STRUCT* )fd; - st->st_mode = fileStruct->isLink ? S_IFLNK : S_IFREG; - st->st_size = fileStruct->file->file_len; - return(0); + st->st_mode = fileStruct->isLink ? S_IFLNK : S_IFREG; + st->st_size = fileStruct->file->file_len; + return( 0 ); } //--------------------------------------------------------------------------------- -static int ramdiskFS_stat_r(struct _reent *r, const char *file, struct stat *st) { +static int ramdiskFS_stat_r( struct _reent *r, const char *file, struct stat *st ) +{ //--------------------------------------------------------------------------------- - FILE_STRUCT fileStruct; - DIR_STRUCT dirStruct; - DIR_ITER dirState; - dirState.dirStruct=&dirStruct; //create a temp dirstruct - int ret; + FILE_STRUCT fileStruct; + DIR_STRUCT dirStruct; + DIR_ITER dirState; + dirState.dirStruct = &dirStruct; //create a temp dirstruct + int ret; - if( ramdiskFS_open_r(r, &fileStruct, file, 0, 0) ==0 ) - { - ret = ramdiskFS_fstat_r(r, (int)&fileStruct, st); - ramdiskFS_close_r(r, (int)&fileStruct); - return(ret); - } - else if( (ramdiskFS_diropen_r(r, &dirState, file)!=NULL) ) - { - st->st_mode = S_IFDIR; - ramdiskFS_dirclose_r(r, &dirState); - return(0); - } - r->_errno = ENOENT; - return(-1); + if ( ramdiskFS_open_r( r, &fileStruct, file, 0, 0 ) == 0 ) + { + ret = ramdiskFS_fstat_r( r, ( int ) & fileStruct, st ); + ramdiskFS_close_r( r, ( int )&fileStruct ); + return( ret ); + } + else if ( ( ramdiskFS_diropen_r( r, &dirState, file ) != NULL ) ) + { + st->st_mode = S_IFDIR; + ramdiskFS_dirclose_r( r, &dirState ); + return( 0 ); + } + r->_errno = ENOENT; + return( -1 ); } //--------------------------------------------------------------------------------- -static int ramdiskFS_unlink_r(struct _reent *r, const char *name) { +static int ramdiskFS_unlink_r( struct _reent *r, const char *name ) +{ //--------------------------------------------------------------------------------- - RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath(name); - if ( partition == NULL ) - { - r->_errno = ENODEV; - return -1; - } - RAMDISK_BASE_ENTRY *entry = partition->FindEntry(name); - if(!entry) - { - r->_errno = ENOENT; - return -1; - } - - if (entry->IsLink()) - { - if(entry->name[0] == '.' && (entry->name[1] == '\0' || (entry->name[1] == '.' && entry->name[2] == '\0'))) - { - r->_errno = EPERM; - return -1; - } - delete entry; - return 0; - } + RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath( name ); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } + RAMDISK_BASE_ENTRY *entry = partition->FindEntry( name ); + if ( !entry ) + { + r->_errno = ENOENT; + return -1; + } - if (RAMDISK_DIR_ENTRY *dir = entry->IsDir()) - { - for(RAMDISK_BASE_ENTRY *entry = dir->first; entry; entry = entry->next) - { - if(!(entry->name[0] == '.' && (entry->name[1] == '\0' - || (entry->name[1] == '.' && entry->name[2] == '\0')))) - { - r->_errno = EPERM; - return -1; - } - } - } - delete entry; - return 0; + if ( entry->IsLink() ) + { + if ( entry->name[0] == '.' && ( entry->name[1] == '\0' || ( entry->name[1] == '.' && entry->name[2] == '\0' ) ) ) + { + r->_errno = EPERM; + return -1; + } + delete entry; + return 0; + } + + if ( RAMDISK_DIR_ENTRY *dir = entry->IsDir() ) + { + for ( RAMDISK_BASE_ENTRY *entry = dir->first; entry; entry = entry->next ) + { + if ( !( entry->name[0] == '.' && ( entry->name[1] == '\0' + || ( entry->name[1] == '.' && entry->name[2] == '\0' ) ) ) ) + { + r->_errno = EPERM; + return -1; + } + } + } + delete entry; + return 0; } //--------------------------------------------------------------------------------- -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) ) - { - r->_errno = ENODEV; - return -1; - } - - if( (ramdiskFS_diropen_r(r, &dirState, name) == NULL) ) - return -1; + DIR_STRUCT dirStruct; + DIR_ITER dirState; + dirState.dirStruct = &dirStruct; + if ( ( name == NULL ) ) + { + r->_errno = ENODEV; + return -1; + } - RAMDISK_PARTITION *partition = dirStruct.dir->GetPartition(); - if ( partition == NULL ) - { - r->_errno = ENODEV; - return -1; - } - partition->cwd = dirStruct.dir; - ramdiskFS_dirclose_r(r, &dirState); - return 0; + if ( ( ramdiskFS_diropen_r( r, &dirState, name ) == NULL ) ) + return -1; + + RAMDISK_PARTITION *partition = dirStruct.dir->GetPartition(); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } + partition->cwd = dirStruct.dir; + ramdiskFS_dirclose_r( r, &dirState ); + return 0; } //--------------------------------------------------------------------------------- -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 ) - { - r->_errno = ENODEV; - return -1; - } - RAMDISK_BASE_ENTRY *entry = partition->FindEntry(path); - if (entry) - { - r->_errno = EEXIST; - return -1; - } - const char *filename; - RAMDISK_DIR_ENTRY *dir = partition->FindPath(path, &filename); - if(!dir) - { - r->_errno = ENOTDIR; - return -1; - } - dir->CreateDir(filename); - return 0; + RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath( path ); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return -1; + } + RAMDISK_BASE_ENTRY *entry = partition->FindEntry( path ); + if ( entry ) + { + r->_errno = EEXIST; + return -1; + } + const char *filename; + RAMDISK_DIR_ENTRY *dir = partition->FindPath( path, &filename ); + if ( !dir ) + { + r->_errno = ENOTDIR; + return -1; + } + dir->CreateDir( filename ); + return 0; } //--------------------------------------------------------------------------------- // 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; - char *cptr; + DIR_STRUCT *dirStruct = ( DIR_STRUCT* )dirState->dirStruct; + char *cptr; - RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath(path); - if ( partition == NULL ) - { - r->_errno = ENODEV; - return NULL; - } + RAMDISK_PARTITION *partition = ramdiskFS_getPartitionFromPath( path ); + if ( partition == NULL ) + { + r->_errno = ENODEV; + return NULL; + } - if ( (cptr=strchr(path,':')) ) - path=cptr+1; //move path past any device names - if ( strchr(path, ':') != NULL ) - { - r->_errno = EINVAL; - return NULL; - } + if ( ( cptr = strchr( path, ':' ) ) ) + path = cptr + 1; //move path past any device names + if ( strchr( path, ':' ) != NULL ) + { + r->_errno = EINVAL; + return NULL; + } - if(*path=='/') //if first character is '/' use absolute root path - dirStruct->dir = partition; //first root dir - else - dirStruct->dir = partition->cwd; //else use current working dir + if ( *path == '/' ) //if first character is '/' use absolute root path + dirStruct->dir = partition; //first root dir + else + dirStruct->dir = partition->cwd; //else use current working dir - RAMDISK_BASE_ENTRY *entry = dirStruct->dir->FindEntry(path); - if(entry==NULL) - { - r->_errno = ENOENT; - return NULL; - } - dirStruct->dir = entry->IsDir(); - if(dirStruct->dir==NULL) - { - r->_errno = ENOTDIR; - return NULL; - } - dirStruct->current_entry = dirStruct->dir->first; - return dirState; + RAMDISK_BASE_ENTRY *entry = dirStruct->dir->FindEntry( path ); + if ( entry == NULL ) + { + r->_errno = ENOENT; + return NULL; + } + dirStruct->dir = entry->IsDir(); + if ( dirStruct->dir == NULL ) + { + r->_errno = ENOTDIR; + return NULL; + } + dirStruct->current_entry = dirStruct->dir->first; + return dirState; } /*Consts containing relative system path strings*/ //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; - dirStruct->current_entry = dirStruct->dir->first; - return(0); + DIR_STRUCT *dirStruct = ( DIR_STRUCT* )dirState->dirStruct; + dirStruct->current_entry = dirStruct->dir->first; + return( 0 ); } //--------------------------------------------------------------------------------- -static int ramdiskFS_dirnext_r(struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *st) { +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) - { - strcpy(filename, dirStruct->current_entry->name); - if(dirStruct->current_entry->IsDir()) - { - if(st) st->st_mode=S_IFDIR; - } - else - { - if(st) st->st_mode=0; - } - dirStruct->current_entry = dirStruct->current_entry->next; - return(0); - } - r->_errno = ENOENT; - return(-1); + if ( dirStruct->current_entry ) + { + strcpy( filename, dirStruct->current_entry->name ); + if ( dirStruct->current_entry->IsDir() ) + { + if ( st ) st->st_mode = S_IFDIR; + } + else + { + if ( st ) st->st_mode = 0; + } + dirStruct->current_entry = dirStruct->current_entry->next; + return( 0 ); + } + r->_errno = ENOENT; + return( -1 ); } //--------------------------------------------------------------------------------- -static int ramdiskFS_dirclose_r(struct _reent *r, DIR_ITER *dirState) { +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) - { - // Trying to truncate to a negative size - r->_errno = EINVAL; - return -1; - } -/* - if ((sizeof(len) > 4) && len > (off_t)FILE_MAX_SIZE) - { - // Trying to extend the file beyond what supports - r->_errno = EFBIG; - return -1; - } -*/ - if (!fileStruct->write) - { - // Read-only file - r->_errno = EINVAL; - return -1; - } - if(fileStruct->file->Truncate(len)) - return 0; - r->_errno = ENOSPC; - return -1; + if ( len < 0 ) + { + // Trying to truncate to a negative size + r->_errno = EINVAL; + return -1; + } + /* + if ((sizeof(len) > 4) && len > (off_t)FILE_MAX_SIZE) + { + // Trying to extend the file beyond what supports + r->_errno = EFBIG; + return -1; + } + */ + if ( !fileStruct->write ) + { + // Read-only file + r->_errno = EINVAL; + return -1; + } + if ( fileStruct->file->Truncate( len ) ) + return 0; + r->_errno = ENOSPC; + return -1; } //--------------------------------------------------------------------------------- -void ramdiskFS_Unmount(const char* mountpoint) { +void ramdiskFS_Unmount( const char* mountpoint ) +{ //--------------------------------------------------------------------------------- - RAMDISK_PARTITION *partition; - devoptab_t *devops = (devoptab_t*)GetDeviceOpTab(mountpoint); - - if (!devops) - return; + RAMDISK_PARTITION *partition; + devoptab_t *devops = ( devoptab_t* )GetDeviceOpTab( mountpoint ); - // Perform a quick check to make sure we're dealing with a ramdiskFS_ controlled device - if (devops->open_r != ramdiskFS_devoptab.open_r) - return; - - if (RemoveDevice (mountpoint) == -1) - return; + if ( !devops ) + return; - partition = *((RAMDISK_PARTITION **)devops->deviceData); - if(partition->automount) - delete partition; - free (devops); + // Perform a quick check to make sure we're dealing with a ramdiskFS_ controlled device + if ( devops->open_r != ramdiskFS_devoptab.open_r ) + return; + + if ( RemoveDevice ( mountpoint ) == -1 ) + return; + + partition = *( ( RAMDISK_PARTITION ** )devops->deviceData ); + if ( partition->automount ) + delete partition; + free ( devops ); } -extern "C" void ramdiskUnmount(const char *mountpoint) { - ramdiskFS_Unmount(mountpoint); +extern "C" void ramdiskUnmount( const char *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; + devoptab_t* devops; + char* nameCopy; + RAMDISK_PARTITION** partition; + char Mountpoint[100]; + char *cptr; - strlcpy(Mountpoint, mountpoint, sizeof(Mountpoint)); - int len = strlen(Mountpoint); - cptr = strchr(Mountpoint, ':'); - if(cptr) - { - len = cptr-Mountpoint; - *++cptr = 0; - } - else - strlcat(Mountpoint, ":", sizeof(Mountpoint)); - ramdiskFS_Unmount(Mountpoint); - if(handle) ramdiskFS_Unmount(((RAMDISK_PARTITION*)handle)->name); - - devops = (devoptab_t*)malloc(sizeof(devoptab_t) + sizeof(RAMDISK_PARTITION*) + len + 1); - if (!devops) - return false; + 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 ); - partition = (RAMDISK_PARTITION**)(devops+1); // Use the space allocated at the end of the devoptab struct - // for storing the partition - nameCopy = (char*)( partition+1); // Use the space allocated at the end of the partition struct - // for storing the name - - memcpy (devops, &ramdiskFS_devoptab, sizeof(ramdiskFS_devoptab)); // Add an entry for this device to the devoptab table + devops = ( devoptab_t* )malloc( sizeof( devoptab_t ) + sizeof( RAMDISK_PARTITION* ) + len + 1 ); + if ( !devops ) + return false; - strlcpy (nameCopy, Mountpoint, len + 1); - devops->name = nameCopy; - - if(handle) - { - *partition = (RAMDISK_PARTITION*)handle; - (*partition)->Rename(Mountpoint); - } - else - *partition = new RAMDISK_PARTITION(Mountpoint, true); - devops->deviceData = partition; + partition = ( RAMDISK_PARTITION** )( devops + 1 ); // Use the space allocated at the end of the devoptab struct + // for storing the partition + nameCopy = ( char* )( partition + 1 ); // Use the space allocated at the end of the partition struct + // for storing the name - if(AddDevice(devops)<0) - { - free(devops); - return false; - } + memcpy ( devops, &ramdiskFS_devoptab, sizeof( ramdiskFS_devoptab ) ); // Add an entry for this device to the devoptab table - return true; + strlcpy ( nameCopy, Mountpoint, len + 1 ); + devops->name = nameCopy; + + if ( handle ) + { + *partition = ( RAMDISK_PARTITION* )handle; + ( *partition )->Rename( Mountpoint ); + } + else + *partition = new RAMDISK_PARTITION( Mountpoint, true ); + devops->deviceData = partition; + + if ( AddDevice( devops ) < 0 ) + { + free( devops ); + return false; + } + + return true; } -extern "C" int ramdiskMount(const char *mountpoint, void *handle) { - return ramdiskFS_Mount(mountpoint, handle); +extern "C" int ramdiskMount( const char *mountpoint, void *handle ) +{ + return ramdiskFS_Mount( mountpoint, handle ); } //--------------------------------------------------------------------------------- -extern "C" void* ramdiskCreate() { +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); - delete partition; + RAMDISK_PARTITION *partition = ( RAMDISK_PARTITION* )Handle; + if ( partition->automount == false ) + ramdiskFS_Unmount( partition->name ); + delete partition; } diff --git a/source/ramdisk/ramdisk.h b/source/ramdisk/ramdisk.h index 60e64fcd..2d7efdc8 100644 --- a/source/ramdisk/ramdisk.h +++ b/source/ramdisk/ramdisk.h @@ -6,78 +6,78 @@ extern "C" { #endif -/* -ramdiskCreate initialize a dynamic RAM-disk. -return: Handle for ramdiskMount -*/ -void* ramdiskCreate(); + /* + ramdiskCreate initialize a dynamic RAM-disk. + return: Handle for ramdiskMount + */ + void* ramdiskCreate(); -/************************************************** - * ramdiskDelete - * - * destroy all datas - * if the ramdisk is allready mounted forces ramdiskUnmount - * IN: a Handle was created witch ramdiskCreate(); - **************************************************/ -void ramdiskDelete(void* Handle); + /************************************************** + * ramdiskDelete + * + * destroy all datas + * if the ramdisk is allready mounted forces ramdiskUnmount + * IN: a Handle was created witch ramdiskCreate(); + **************************************************/ + void ramdiskDelete( void* Handle ); -/************************************************** - * ramdiskMount - * - * mounts a ramdisk - * IN: mountpoint e.g. "RAM" or "MEM:" - * handle is a Handle was created ramdiskCreate() - * or NULL for auto-create - * OUT: 0 = Error / !0 = OK - **************************************************/ -int ramdiskMount(const char *mountpoint, void *handle); + /************************************************** + * ramdiskMount + * + * mounts a ramdisk + * IN: mountpoint e.g. "RAM" or "MEM:" + * handle is a Handle was created ramdiskCreate() + * or NULL for auto-create + * OUT: 0 = Error / !0 = OK + **************************************************/ + int ramdiskMount( const char *mountpoint, void *handle ); -/************************************************** - * ramdiskUnmount - * - * unmounts a ramdisk - * IN: mountpoint e.g "RAM" or "MEM:" - **************************************************/ -void ramdiskUnmount(const char *mountpoint); + /************************************************** + * ramdiskUnmount + * + * unmounts a ramdisk + * IN: mountpoint e.g "RAM" or "MEM:" + **************************************************/ + void ramdiskUnmount( const char *mountpoint ); -/* -NOTE: -if the ramdisk not explizit created with ramdiskCreate (e.g ramdiskMount("RAMDISK:", NULL)) -the ramdisk is implizit created. When unmount this "auto-created" ramdisk the ramdisk automitic deleted + /* + NOTE: + if the ramdisk not explizit created with ramdiskCreate (e.g ramdiskMount("RAMDISK:", NULL)) + the ramdisk is implizit created. When unmount this "auto-created" ramdisk the ramdisk automitic deleted -but if the ramdisk explizit created (with ramdiskCreate), -then we can remount the filesystem without lost all datas. + but if the ramdisk explizit created (with ramdiskCreate), + then we can remount the filesystem without lost all datas. -Example1: -========= -void *ram = ramdiskCreate(); // create ramdisk -ramdiskMount("RAM", ram); // mount the ramdisk -... -fopen("RAM:/file", ...); -... -ramdiskMount("MEM", ram); // remount as MEM: (without lost of data) -... -fopen("RAM:/file", ...); -... -ramdiskUnmount("MEM"); // unmount -... -ramdiskMount("RAM", ram); // remount as RAM: (without lost of data) -... -ramdiskDelete(ram); // unmount and delete + Example1: + ========= + void *ram = ramdiskCreate(); // create ramdisk + ramdiskMount("RAM", ram); // mount the ramdisk + ... + fopen("RAM:/file", ...); + ... + ramdiskMount("MEM", ram); // remount as MEM: (without lost of data) + ... + fopen("RAM:/file", ...); + ... + ramdiskUnmount("MEM"); // unmount + ... + ramdiskMount("RAM", ram); // remount as RAM: (without lost of data) + ... + ramdiskDelete(ram); // unmount and delete -Example2: -========= -ramdiskMount("RAM", NULL); // create and mount the ramdisk -... -fopen("RAM:/file", ...); -... -ramdiskUnmount("RAM"); // unmount and delete -*/ + Example2: + ========= + ramdiskMount("RAM", NULL); // create and mount the ramdisk + ... + fopen("RAM:/file", ...); + ... + ramdiskUnmount("RAM"); // unmount and delete + */ #ifdef __cplusplus } diff --git a/source/settings/Settings.cpp b/source/settings/Settings.cpp index 073f82fc..e541f30c 100644 --- a/source/settings/Settings.cpp +++ b/source/settings/Settings.cpp @@ -43,22 +43,26 @@ 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_cios[settings_ios_max] = {"IOS 249","IOS 222", "IOS 223", "IOS 250"}; -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[settings_error002_max] = {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_cios[settings_ios_max] = {"IOS 249", "IOS 222", "IOS 223", "IOS 250"}; +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[settings_error002_max] = {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) { - if (cios == 249 || cios == 250) { - return fs_type == FS_TYPE_WBFS; - } else { - return fs_type == FS_TYPE_WBFS || fs_type == FS_TYPE_FAT32 || fs_type == FS_TYPE_NTFS; - } +bool IsValidPartition( int fs_type, int cios ) +{ + if ( cios == 249 || cios == 250 ) + { + return fs_type == FS_TYPE_WBFS; + } + else + { + return fs_type == FS_TYPE_WBFS || fs_type == FS_TYPE_FAT32 || fs_type == FS_TYPE_NTFS; + } } /**************************************************************************** @@ -66,2981 +70,2993 @@ bool IsValidPartition(int fs_type, int cios) { ***************************************************************************/ int MenuSettings() { - int menu = MENU_NONE; - int ret; - int choice = 0; - bool exit = false; - - // backup game language setting - char opt_lang[100]; - strcpy(opt_lang,Settings.language_path); - // backup title override setting - int opt_override = Settings.titlesOverride; - // backup partition index - u8 settingspartitionold = Settings.partition; - - - enum - { - FADE, - LEFT, - RIGHT - }; - - int slidedirection = FADE; - - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - GuiSound btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); - - char imgPath[100]; - - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path); - GuiImageData settingsbg(imgPath, settings_background_png); - - snprintf(imgPath, sizeof(imgPath), "%ssettings_title.png", CFG.theme_path); - GuiImageData MainButtonImgData(imgPath, settings_title_png); - - snprintf(imgPath, sizeof(imgPath), "%ssettings_title_over.png", CFG.theme_path); - GuiImageData MainButtonImgOverData(imgPath, settings_title_over_png); - - snprintf(imgPath, sizeof(imgPath), "%spageindicator.png", CFG.theme_path); - GuiImageData PageindicatorImgData(imgPath, pageindicator_png); - - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", CFG.theme_path); - GuiImageData arrow_left(imgPath, startgame_arrow_left_png); - - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", CFG.theme_path); - GuiImageData arrow_right(imgPath, startgame_arrow_right_png); - - snprintf(imgPath, sizeof(imgPath), "%scredits_button.png", CFG.theme_path); - GuiImageData creditsImgData(imgPath, credits_button_png); - - snprintf(imgPath, sizeof(imgPath), "%scredits_button_over.png", CFG.theme_path); - GuiImageData creditsOver(imgPath, credits_button_over_png); - - GuiImage creditsImg(&creditsImgData); - GuiImage creditsImgOver(&creditsOver); - - GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiTrigger trigHome; - trigHome.SetButtonOnlyTrigger(-1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0); - GuiTrigger trigB; - trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - GuiTrigger trigL; - trigL.SetButtonOnlyTrigger(-1, WPAD_BUTTON_LEFT | WPAD_CLASSIC_BUTTON_LEFT, PAD_BUTTON_LEFT); - GuiTrigger trigR; - trigR.SetButtonOnlyTrigger(-1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT); - GuiTrigger trigMinus; - trigMinus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0); - GuiTrigger trigPlus; - trigPlus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0); - - GuiText titleTxt(tr("Settings"), 28, (GXColor) {0, 0, 0, 255}); - titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - titleTxt.SetPosition(0,40); - - GuiImage settingsbackground(&settingsbg); - - GuiText backBtnTxt(tr("Back") , 22, THEME.prompttext); - backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); - GuiImage backBtnImg(&btnOutline); - if (Settings.wsprompt == yes) - { - backBtnTxt.SetWidescreen(CFG.widescreen); - backBtnImg.SetWidescreen(CFG.widescreen); - } - GuiButton backBtn(&backBtnImg,&backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2,1); - backBtn.SetLabel(&backBtnTxt); - backBtn.SetTrigger(&trigB); - - GuiButton homo(1,1); - homo.SetTrigger(&trigHome); - - GuiImage PageindicatorImg1(&PageindicatorImgData); - GuiText PageindicatorTxt1("1", 22, (GXColor) { 0, 0, 0, 255}); - GuiButton PageIndicatorBtn1(PageindicatorImg1.GetWidth(), PageindicatorImg1.GetHeight()); - PageIndicatorBtn1.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - PageIndicatorBtn1.SetPosition(165, 400); - PageIndicatorBtn1.SetImage(&PageindicatorImg1); - PageIndicatorBtn1.SetLabel(&PageindicatorTxt1); - PageIndicatorBtn1.SetSoundOver(&btnSoundOver); - PageIndicatorBtn1.SetSoundClick(&btnClick1); - PageIndicatorBtn1.SetTrigger(&trigA); - PageIndicatorBtn1.SetEffectGrow(); - - GuiImage PageindicatorImg2(&PageindicatorImgData); - GuiText PageindicatorTxt2("2", 22, (GXColor) {0, 0, 0, 255}); - GuiButton PageIndicatorBtn2(PageindicatorImg2.GetWidth(), PageindicatorImg2.GetHeight()); - PageIndicatorBtn2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - PageIndicatorBtn2.SetPosition(200, 400); - PageIndicatorBtn2.SetImage(&PageindicatorImg2); - PageIndicatorBtn2.SetLabel(&PageindicatorTxt2); - PageIndicatorBtn2.SetSoundOver(&btnSoundOver); - PageIndicatorBtn2.SetSoundClick(&btnClick1); - PageIndicatorBtn2.SetTrigger(&trigA); - PageIndicatorBtn2.SetEffectGrow(); - - GuiImage PageindicatorImg3(&PageindicatorImgData); - GuiText PageindicatorTxt3("3", 22, (GXColor) {0, 0, 0, 255}); - GuiButton PageIndicatorBtn3(PageindicatorImg3.GetWidth(), PageindicatorImg3.GetHeight()); - PageIndicatorBtn3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - PageIndicatorBtn3.SetPosition(235, 400); - PageIndicatorBtn3.SetImage(&PageindicatorImg3); - PageIndicatorBtn3.SetLabel(&PageindicatorTxt3); - PageIndicatorBtn3.SetSoundOver(&btnSoundOver); - PageIndicatorBtn3.SetSoundClick(&btnClick1); - PageIndicatorBtn3.SetTrigger(&trigA); - PageIndicatorBtn3.SetEffectGrow(); - - GuiImage GoLeftImg(&arrow_left); - GuiButton GoLeftBtn(GoLeftImg.GetWidth(), GoLeftImg.GetHeight()); - GoLeftBtn.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - GoLeftBtn.SetPosition(25, -25); - GoLeftBtn.SetImage(&GoLeftImg); - GoLeftBtn.SetSoundOver(&btnSoundOver); - GoLeftBtn.SetSoundClick(btnClick2); - GoLeftBtn.SetEffectGrow(); - GoLeftBtn.SetTrigger(&trigA); - GoLeftBtn.SetTrigger(&trigL); - GoLeftBtn.SetTrigger(&trigMinus); - - GuiImage GoRightImg(&arrow_right); - GuiButton GoRightBtn(GoRightImg.GetWidth(), GoRightImg.GetHeight()); - GoRightBtn.SetAlignment(ALIGN_RIGHT, ALIGN_MIDDLE); - GoRightBtn.SetPosition(-25, -25); - GoRightBtn.SetImage(&GoRightImg); - GoRightBtn.SetSoundOver(&btnSoundOver); - GoRightBtn.SetSoundClick(btnClick2); - GoRightBtn.SetEffectGrow(); - GoRightBtn.SetTrigger(&trigA); - GoRightBtn.SetTrigger(&trigR); - GoRightBtn.SetTrigger(&trigPlus); - - char MainButtonText[50]; - snprintf(MainButtonText, sizeof(MainButtonText), "%s", " "); - - GuiImage MainButton1Img(&MainButtonImgData); - GuiImage MainButton1ImgOver(&MainButtonImgOverData); - GuiText MainButton1Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton1Txt.SetMaxWidth(MainButton1Img.GetWidth()); - GuiButton MainButton1(MainButton1Img.GetWidth(), MainButton1Img.GetHeight()); - MainButton1.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton1.SetPosition(0, 90); - MainButton1.SetImage(&MainButton1Img); - MainButton1.SetImageOver(&MainButton1ImgOver); - MainButton1.SetLabel(&MainButton1Txt); - MainButton1.SetSoundOver(&btnSoundOver); - MainButton1.SetSoundClick(&btnClick1); - MainButton1.SetEffectGrow(); - MainButton1.SetTrigger(&trigA); - - GuiImage MainButton2Img(&MainButtonImgData); - GuiImage MainButton2ImgOver(&MainButtonImgOverData); - GuiText MainButton2Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255 }); - MainButton2Txt.SetMaxWidth(MainButton2Img.GetWidth()); - GuiButton MainButton2(MainButton2Img.GetWidth(), MainButton2Img.GetHeight()); - MainButton2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton2.SetPosition(0, 160); - MainButton2.SetImage(&MainButton2Img); - MainButton2.SetImageOver(&MainButton2ImgOver); - MainButton2.SetLabel(&MainButton2Txt); - MainButton2.SetSoundOver(&btnSoundOver); - MainButton2.SetSoundClick(&btnClick1); - MainButton2.SetEffectGrow(); - MainButton2.SetTrigger(&trigA); - - GuiImage MainButton3Img(&MainButtonImgData); - GuiImage MainButton3ImgOver(&MainButtonImgOverData); - GuiText MainButton3Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton3Txt.SetMaxWidth(MainButton3Img.GetWidth()); - GuiButton MainButton3(MainButton3Img.GetWidth(), MainButton3Img.GetHeight()); - MainButton3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton3.SetPosition(0, 230); - MainButton3.SetImage(&MainButton3Img); - MainButton3.SetImageOver(&MainButton3ImgOver); - MainButton3.SetLabel(&MainButton3Txt); - MainButton3.SetSoundOver(&btnSoundOver); - MainButton3.SetSoundClick(&btnClick1); - MainButton3.SetEffectGrow(); - MainButton3.SetTrigger(&trigA); - - GuiImage MainButton4Img(&MainButtonImgData); - GuiImage MainButton4ImgOver(&MainButtonImgOverData); - GuiText MainButton4Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton4Txt.SetMaxWidth(MainButton4Img.GetWidth()); - GuiButton MainButton4(MainButton4Img.GetWidth(), MainButton4Img.GetHeight()); - MainButton4.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton4.SetPosition(0, 300); - MainButton4.SetImage(&MainButton4Img); - MainButton4.SetImageOver(&MainButton4ImgOver); - MainButton4.SetLabel(&MainButton4Txt); - MainButton4.SetSoundOver(&btnSoundOver); - MainButton4.SetSoundClick(&btnClick1); - MainButton4.SetEffectGrow(); - MainButton4.SetTrigger(&trigA); - - customOptionList options2(MAXOPTIONS); - GuiCustomOptionBrowser optionBrowser2(396, 280, &options2, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, 0, 150); - optionBrowser2.SetPosition(0, 90); - optionBrowser2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - - GuiWindow w(screenwidth, screenheight); - - int pageToDisplay = 1; - while ( pageToDisplay > 0) - { - usleep(100); - - menu = MENU_NONE; - - if ( pageToDisplay == 1) - { - /** Standard procedure made in all pages **/ - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); - - if (slidedirection == RIGHT) - { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - while (MainButton1.GetEffect()>0) usleep(50); - } - else if (slidedirection == LEFT) - { - MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - while (MainButton1.GetEffect()>0) usleep(50); - } - - 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); - - mainWindow->RemoveAll(); - mainWindow->Append(&w); - w.RemoveAll(); - w.Append(&settingsbackground); - w.Append(&PageIndicatorBtn1); - w.Append(&PageIndicatorBtn2); - w.Append(&PageIndicatorBtn3); - w.Append(&titleTxt); - w.Append(&backBtn); - w.Append(&homo); - w.Append(&GoRightBtn); - w.Append(&GoLeftBtn); - w.Append(&MainButton1); - w.Append(&MainButton2); - w.Append(&MainButton3); - w.Append(&MainButton4); - - PageIndicatorBtn1.SetAlpha(255); - PageIndicatorBtn2.SetAlpha(50); - PageIndicatorBtn3.SetAlpha(50); - - /** Creditsbutton change **/ - MainButton4.SetImage(&MainButton4Img); - MainButton4.SetImageOver(&MainButton4ImgOver); - - /** Disable ability to click through MainButtons */ - optionBrowser2.SetClickable(false); - /** Default no scrollbar and reset position **/ -// optionBrowser2.SetScrollbar(0); - optionBrowser2.SetOffset(0); - - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); - - MainButton1.SetEffectGrow(); - MainButton2.SetEffectGrow(); - MainButton3.SetEffectGrow(); - MainButton4.SetEffectGrow(); - - if (slidedirection == FADE) - { - MainButton1.SetEffect(EFFECT_FADE, 20); - MainButton2.SetEffect(EFFECT_FADE, 20); - MainButton3.SetEffect(EFFECT_FADE, 20); - MainButton4.SetEffect(EFFECT_FADE, 20); - } - else if (slidedirection == LEFT) - { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - } - else if (slidedirection == RIGHT) - { - MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - } - - mainWindow->Append(&w); - - ResumeGui(); - - while (MainButton1.GetEffect() > 0) usleep(50); - - } - else if ( pageToDisplay == 2 ) - { - /** Standard procedure made in all pages **/ - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); - - if (slidedirection == RIGHT) - { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - while (MainButton1.GetEffect()>0) usleep(50); - } - else if (slidedirection == LEFT) - { - MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - while (MainButton1.GetEffect()>0) usleep(50); - } - - 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); - - mainWindow->RemoveAll(); - mainWindow->Append(&w); - w.RemoveAll(); - w.Append(&settingsbackground); - w.Append(&PageIndicatorBtn1); - w.Append(&PageIndicatorBtn2); - w.Append(&PageIndicatorBtn3); - w.Append(&titleTxt); - w.Append(&backBtn); - w.Append(&homo); - w.Append(&GoRightBtn); - w.Append(&GoLeftBtn); - w.Append(&MainButton1); - w.Append(&MainButton2); - w.Append(&MainButton3); - w.Append(&MainButton4); - - PageIndicatorBtn1.SetAlpha(50); - PageIndicatorBtn2.SetAlpha(255); - PageIndicatorBtn3.SetAlpha(50); - - /** Creditsbutton change **/ - MainButton4.SetImage(&creditsImg); - MainButton4.SetImageOver(&creditsImgOver); - - /** Disable ability to click through MainButtons */ - optionBrowser2.SetClickable(false); - /** Default no scrollbar and reset position **/ -// optionBrowser2.SetScrollbar(0); - optionBrowser2.SetOffset(0); - - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); - - MainButton1.SetEffectGrow(); - MainButton2.SetEffectGrow(); - MainButton3.SetEffectGrow(); - MainButton4.SetEffectGrow(); - - if (slidedirection == FADE) - { - MainButton1.SetEffect(EFFECT_FADE, 20); - MainButton2.SetEffect(EFFECT_FADE, 20); - MainButton3.SetEffect(EFFECT_FADE, 20); - MainButton4.SetEffect(EFFECT_FADE, 20); - } - else if (slidedirection == LEFT) - { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - } - else if (slidedirection == RIGHT) - { - MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - } - - mainWindow->Append(&w); - - ResumeGui(); - - while (MainButton1.GetEffect() > 0) usleep(50); - - } - else if ( pageToDisplay == 3 ) - { - /** Standard procedure made in all pages **/ - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); - - if (slidedirection == RIGHT) - { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35); - while (MainButton1.GetEffect()>0) usleep(50); - } - else if (slidedirection == LEFT) - { - MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35); - while (MainButton1.GetEffect()>0) usleep(50); - } - - 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); - - mainWindow->RemoveAll(); - mainWindow->Append(&w); - w.RemoveAll(); - w.Append(&settingsbackground); - w.Append(&PageIndicatorBtn1); - w.Append(&PageIndicatorBtn2); - w.Append(&PageIndicatorBtn3); - w.Append(&titleTxt); - w.Append(&backBtn); - w.Append(&homo); - w.Append(&GoRightBtn); - w.Append(&GoLeftBtn); - w.Append(&MainButton1); - - PageIndicatorBtn1.SetAlpha(50); - PageIndicatorBtn2.SetAlpha(50); - PageIndicatorBtn3.SetAlpha(255); - - /** Disable ability to click through MainButtons */ - optionBrowser2.SetClickable(false); - /** Default no scrollbar and reset position **/ -// optionBrowser2.SetScrollbar(0); - optionBrowser2.SetOffset(0); - - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); - - MainButton1.SetEffectGrow(); - MainButton2.SetEffectGrow(); - MainButton3.SetEffectGrow(); - MainButton4.SetEffectGrow(); - - if (slidedirection == FADE) - { - MainButton1.SetEffect(EFFECT_FADE, 20); - MainButton2.SetEffect(EFFECT_FADE, 20); - MainButton3.SetEffect(EFFECT_FADE, 20); - MainButton4.SetEffect(EFFECT_FADE, 20); - } - else if (slidedirection == LEFT) - { - MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35); - } - else if (slidedirection == RIGHT) - { - MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35); - } - - mainWindow->Append(&w); - - ResumeGui(); - - while (MainButton1.GetEffect() > 0) usleep(50); - } - - while (menu == MENU_NONE) - { - usleep(100); - - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - - if ( pageToDisplay == 1 ) - { - if (MainButton1.GetState() == STATE_CLICKED) - { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton1.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - titleTxt.SetText(tr("GUI Settings")); - exit = false; - options2.SetLength(0); -// optionBrowser2.SetScrollbar(1); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); - - optionBrowser2.SetEffect(EFFECT_FADE, 20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - - int returnhere = 1; - char * languagefile; - languagefile = strrchr(Settings.language_path, '/')+1; - - bool firstRun = true; - while (!exit) - { - usleep(100); - - returnhere = 1; - - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - - else if (backBtn.GetState() == STATE_CLICKED) - { - backBtn.ResetState(); - exit = true; - break; - } - - else if (menu == MENU_DISCLIST) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - WindowCredits(); - w.Append(&optionBrowser2); - w.Append(&backBtn); - } - - else if (homo.GetState() == STATE_CLICKED) - { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - - ret = optionBrowser2.GetClickedOption(); - - if(firstRun || ret >= 0) - { - int Idx = -1; - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("App Language")); - if(ret == Idx) - { - if (isInserted(bootDevice)) - { - if ( Settings.godmode == 1) - { - w.SetEffect(EFFECT_FADE, -20); - while (w.GetEffect()>0) usleep(50); - mainWindow->Remove(&w); - while (returnhere == 1) - returnhere = MenuLanguageSelect(); - if (returnhere == 2) - { - menu = MENU_SETTINGS; - pageToDisplay = 0; - exit = true; - mainWindow->Append(&w); - break; - } - else - { - HaltGui(); - mainWindow->Append(&w); - w.SetEffect(EFFECT_FADE, 20); - ResumeGui(); - while (w.GetEffect()>0) usleep(50); - } - } - else - { - WindowPrompt(tr("Language change:"),tr("Console should be unlocked to modify it."),tr("OK")); - } - } - else - { - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to use this option."),tr("OK")); - } - } - - if (!strcmp("notset", Settings.language_path)) - options2.SetValue(Idx, "%s", tr("Default")); - else - options2.SetValue(Idx, "%s", languagefile); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Display")); - if(ret == Idx && ++Settings.sinfo >= settings_sinfo_max) - Settings.sinfo = 0; - static const char *opts[settings_sinfo_max] = {trNOOP("Game ID"),trNOOP("Game Region"),trNOOP("Both"),trNOOP("Neither")}; - options2.SetValue(Idx,"%s",tr(opts[Settings.sinfo])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Clock")); - if(ret == Idx && ++Settings.hddinfo >= settings_clock_max) - Settings.hddinfo = 0; //CLOCK - if (Settings.hddinfo == hr12) options2.SetValue(Idx,"12 %s",tr("Hour")); - else if (Settings.hddinfo == hr24) options2.SetValue(Idx,"24 %s",tr("Hour")); - else if (Settings.hddinfo == Off) options2.SetValue(Idx,"%s",tr("OFF")); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Tooltips")); - if(ret == Idx && ++Settings.tooltips >= settings_tooltips_max) - Settings.tooltips = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.tooltips])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Flip-X")); - if(ret == Idx && ++Settings.xflip >= settings_xflip_max) - Settings.xflip = 0; - static const char *opts[settings_xflip_max][3] = { {trNOOP("Right"),"/",trNOOP("Next")}, - {trNOOP("Left"),"/",trNOOP("Prev")}, - {trNOOP("Like SysMenu"),"",""}, - {trNOOP("Right"),"/",trNOOP("Prev")}, - {trNOOP("DiskFlip"),"",""}}; - options2.SetValue(Idx,"%s%s%s",tr(opts[Settings.xflip][0]),opts[Settings.xflip][1],tr(opts[Settings.xflip][2])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Prompts Buttons")); - if(ret == Idx && ++Settings.wsprompt >= settings_off_on_max ) - Settings.wsprompt = 0; - static const char *opts[settings_off_on_max] = {trNOOP("Normal"),trNOOP("Widescreen Fix")}; - options2.SetValue(Idx,"%s",tr(opts[Settings.wsprompt])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Keyboard")); - if(ret == Idx && ++Settings.keyset >= settings_keyset_max) - Settings.keyset = 0; - static const char *opts[settings_keyset_max] = {"QWERTY","QWERTY 2","DVORAK","QWERTZ","AZERTY"}; - options2.SetValue(Idx,"%s", opts[Settings.keyset]); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Disc Artwork Download")); - if(ret == Idx && ++Settings.discart >= 4) - Settings.discart = 0; - static const char *opts[4] = {trNOOP("Only Original"),trNOOP("Only Customs"),trNOOP("Original/Customs"),trNOOP("Customs/Original")}; - options2.SetValue(Idx,"%s",tr(opts[Settings.discart])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Wiilight")); - if(ret == Idx && ++Settings.wiilight >= settings_wiilight_max ) - Settings.wiilight = 0; - static const char *opts[settings_wiilight_max] = {trNOOP("OFF"),trNOOP("ON"),trNOOP("Only for Install")}; - options2.SetValue(Idx,"%s",tr(opts[Settings.wiilight])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Rumble")); - if(ret == Idx && ++Settings.rumble >= settings_rumble_max) - Settings.rumble = 0; //RUMBLE - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.rumble])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("AutoInit Network")); - if(ret == Idx && ++Settings.autonetwork >= settings_off_on_max) - Settings.autonetwork = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.autonetwork])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("BETA revisions")); - if(ret == Idx && ++Settings.beta_upgrades >= settings_off_on_max) - Settings.beta_upgrades = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.beta_upgrades])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Titles from WiiTDB")); - if(ret == Idx && ++Settings.titlesOverride >= settings_off_on_max) - Settings.titlesOverride = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.titlesOverride])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Screensaver")); - if(ret == Idx && ++Settings.screensaver >= settings_screensaver_max) - Settings.screensaver = 0; //RUMBLE - static const char *opts[settings_screensaver_max] = {trNOOP("OFF"),trNOOP("3 min"),trNOOP("5 min"),trNOOP("10 min"),trNOOP("20 min"),trNOOP("30 min"),trNOOP("1 hour")}; - options2.SetValue(Idx,"%s",tr(opts[Settings.screensaver])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Mark new games")); - if(ret == Idx && ++Settings.marknewtitles >= settings_off_on_max) - Settings.marknewtitles = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.marknewtitles])); - } - - firstRun = false; - } - } - optionBrowser2.SetEffect(EFFECT_FADE, -20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - titleTxt.SetText(tr("Settings")); - slidedirection = FADE; - if (returnhere != 2) - pageToDisplay = 1; - MainButton1.ResetState(); - break; - } - - else if (MainButton2.GetState() == STATE_CLICKED) - { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton2.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - titleTxt.SetText(tr("Game Load")); - exit = false; - options2.SetLength(0); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); - - optionBrowser2.SetEffect(EFFECT_FADE, 20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - - bool firstRun = true; - while (!exit) - { - usleep(100); - - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - - else if (backBtn.GetState() == STATE_CLICKED) - { - backBtn.ResetState(); - exit = true; - break; - } - - else if (homo.GetState() == STATE_CLICKED) - { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - - ret = optionBrowser2.GetClickedOption(); - - if(firstRun || ret >= 0) - { - int Idx = -1; - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Video Mode")); - if(ret == Idx && ++Settings.video >= settings_video_max) - Settings.video = 0; - options2.SetValue(Idx,"%s%s",opts_videomode[Settings.video][0], tr(opts_videomode[Settings.video][1])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("VIDTV Patch")); - if(ret == Idx && ++Settings.vpatch >= settings_off_on_max) - Settings.vpatch = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.vpatch])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Game Language")); - if(ret == Idx && ++Settings.language >= settings_language_max) - Settings.language = 0; - options2.SetValue(Idx,"%s",tr(opts_language[Settings.language])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Patch Country Strings")); - if(ret == Idx && ++Settings.patchcountrystrings >= settings_off_on_max) - Settings.patchcountrystrings = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.patchcountrystrings])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "Ocarina"); - if(ret == Idx && ++Settings.ocarina >= settings_off_on_max) - Settings.ocarina = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[Settings.ocarina])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx,"%s", tr("Boot/Standard")); - if(ret == Idx && Settings.godmode == 1) { - if (++Settings.cios >= settings_cios_max) { - Settings.cios = 0; - } - if ((Settings.cios == 1 && 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")); - } - } - if (Settings.godmode == 1) - options2.SetValue(Idx, "%s", opts_cios[Settings.cios]); - else - options2.SetValue(Idx, "********"); - } - - if (ret == ++Idx || firstRun) - { - if (firstRun) options2.SetName(Idx, "%s", tr("Partition")); - if (ret == Idx) { - // Select the next valid partition, even if that's the same one - do - { - Settings.partition = Settings.partition + 1 == partitions.num ? 0 : Settings.partition + 1; - } - while (!IsValidPartition(partitions.pinfo[Settings.partition].fs_type, Settings.cios)); - } - - PartInfo pInfo = partitions.pinfo[Settings.partition]; - f32 partition_size = partitions.pentry[Settings.partition].size * (partitions.sector_size / GB_SIZE); - - // Get the partition name and it's size in GB's - options2.SetValue(Idx,"%s%d (%.2fGB)", pInfo.fs_type == FS_TYPE_FAT32 ? "FAT" : pInfo.fs_type == FS_TYPE_NTFS ? "NTFS" : "WBFS", - pInfo.index, - partition_size); - } - - if (ret == ++Idx || firstRun) - { - if (firstRun) options2.SetName(Idx, "%s", tr("FAT: Use directories")); - if (ret == Idx && ++Settings.FatInstallToDir >= settings_installdir_max) - Settings.FatInstallToDir = 0; - options2.SetValue(Idx, "%s", tr(opts_installdir[Settings.FatInstallToDir])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Quick Boot")); - if(ret == Idx && ++Settings.qboot >= settings_off_on_max) - Settings.qboot = 0; - options2.SetValue(Idx,"%s",tr(opts_no_yes[Settings.qboot])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Error 002 fix")); - if(ret == Idx && ++Settings.error002 >= settings_error002_max) - Settings.error002 = 0; - options2.SetValue(Idx,"%s",tr(opts_error002[Settings.error002])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Install partitions")); - if(ret == Idx && ++Settings.partitions_to_install >= settings_partitions_max) - Settings.partitions_to_install = 0; - options2.SetValue(Idx,"%s",tr(opts_partitions[Settings.partitions_to_install])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Install 1:1 Copy")); - if(ret == Idx) { - Settings.fullcopy = Settings.fullcopy == 0 ? 1 : 0; - } - options2.SetValue(Idx,"%s",tr(opts_no_yes[Settings.fullcopy])); - } - - firstRun = false; - } - } - optionBrowser2.SetEffect(EFFECT_FADE, -20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - titleTxt.SetText(tr("Settings")); - slidedirection = FADE; - pageToDisplay = 1; - MainButton2.ResetState(); - break; - } - - else if (MainButton3.GetState() == STATE_CLICKED) - { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton3.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - titleTxt.SetText(tr("Parental Control")); - exit = false; - options2.SetLength(0); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); - - optionBrowser2.SetEffect(EFFECT_FADE, 20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - - bool firstRun = true; - while (!exit) - { - usleep(100); - - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - - else if (backBtn.GetState() == STATE_CLICKED) - { - backBtn.ResetState(); - exit = true; - break; - } - - else if (homo.GetState() == STATE_CLICKED) - { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - - ret = optionBrowser2.GetClickedOption(); - - if(firstRun || ret >= 0) - { - - int Idx = -1; - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Console")); - if(ret == Idx) - { - if (!strcmp("", Settings.unlockCode) && Settings.parental.enabled == 0) - { - Settings.godmode = !Settings.godmode; - } - else if ( Settings.godmode == 0 ) - { - char entered[20]; - memset(entered, 0, 20); - - //password check to unlock Install,Delete and Format - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - int result = Settings.parental.enabled == 0 ? OnScreenKeyboard(entered, 20,0) : OnScreenNumpad(entered, 5); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) - { - if (!strcmp(entered, Settings.unlockCode) || !memcmp(entered, Settings.parental.pin, 4)) { //if password correct - if (Settings.godmode == 0) - { - WindowPrompt(tr("Correct Password"),tr("All the features of USB Loader GX are unlocked."),tr("OK")); - Settings.godmode = 1; - menu = MENU_DISCLIST; - } - } - else - WindowPrompt(tr("Wrong Password"),tr("USB Loader GX is protected"),tr("OK")); - } - } - else - { - int choice = WindowPrompt (tr("Lock Console"),tr("Are you sure?"),tr("Yes"),tr("No")); - if (choice == 1) - { - WindowPrompt(tr("Console Locked"),tr("USB Loader GX is protected"),tr("OK")); - Settings.godmode = 0; - menu = MENU_DISCLIST; - } - } - } - static const char *opts[] = {trNOOP("Locked"),trNOOP("Unlocked")}; - options2.SetValue(Idx,"%s",tr(opts[Settings.godmode])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Password")); - if(ret == Idx) - { - if ( Settings.godmode == 1) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[20] = ""; - strlcpy(entered, Settings.unlockCode, sizeof(entered)); - int result = OnScreenKeyboard(entered, 20,0); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) - { - strlcpy(Settings.unlockCode, entered, sizeof(Settings.unlockCode)); - WindowPrompt(tr("Password Changed"),tr("Password has been changed"),tr("OK")); - } - } - else - { - WindowPrompt(tr("Password Changed"),tr("Console should be unlocked to modify it."),tr("OK")); - } - } - if ( Settings.godmode != 1) options2.SetValue(Idx, "********"); - else if (!strcmp("", Settings.unlockCode)) options2.SetValue(Idx, "%s",tr("not set")); - else options2.SetValue(Idx, Settings.unlockCode); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Controllevel")); - if(ret == Idx && Settings.godmode == 1 && ++Settings.parentalcontrol >= 5 ) - Settings.parentalcontrol = 0; - if (Settings.godmode == 1) - options2.SetValue(Idx,"%s",tr(opts_parentalcontrol[Settings.parentalcontrol])); - else - options2.SetValue(Idx, "********"); - } - - firstRun = false; - } - } - optionBrowser2.SetEffect(EFFECT_FADE, -20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - titleTxt.SetText(tr("Settings")); - slidedirection = FADE; - pageToDisplay = 1; - MainButton3.ResetState(); - break; - } - - else if (MainButton4.GetState() == STATE_CLICKED) - { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton4.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - titleTxt.SetText(tr("Sound")); - exit = false; - options2.SetLength(0); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); - - optionBrowser2.SetEffect(EFFECT_FADE, 20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - - - bool firstRun = true; - while (!exit) - { - usleep(100); - - bool returnhere = true; - - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - else if (backBtn.GetState() == STATE_CLICKED) - { - backBtn.ResetState(); - exit = true; - break; - } - - else if (homo.GetState() == STATE_CLICKED) - { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - - ret = optionBrowser2.GetClickedOption(); - - if(firstRun || ret >= 0) - { - int Idx = -1; - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Backgroundmusic")); - if(ret == Idx) - { - if (isInserted(bootDevice)) - { - w.SetEffect(EFFECT_FADE, -20); - while (w.GetEffect()>0) usleep(50); - mainWindow->Remove(&w); - - returnhere = MenuBackgroundMusic(); - - HaltGui(); - mainWindow->Append(&w); - w.SetEffect(EFFECT_FADE, 20); - ResumeGui(); - while (w.GetEffect()>0) usleep(50); - } else - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to use this option."),tr("OK")); - } - - char * filename = strrchr(Settings.ogg_path, '/'); - if(filename) - { - filename += 1; - options2.SetValue(Idx, "%s", filename); - } - else - options2.SetValue(Idx, "%s", tr("Standard")); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Music Volume")); - if(ret == Idx) - { - Settings.volume += 10; - if (Settings.volume > 100) - Settings.volume = 0; - bgMusic->SetVolume(Settings.volume); - } - if (Settings.volume > 0) - options2.SetValue(Idx,"%i", Settings.volume); - else - options2.SetValue(Idx,"%s", tr("OFF")); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("SFX Volume")); - if(ret == Idx) - { - Settings.sfxvolume += 10; - if (Settings.sfxvolume > 100) - Settings.sfxvolume = 0; - btnSoundOver.SetVolume(Settings.sfxvolume); - btnClick2->SetVolume(Settings.sfxvolume); - btnClick1.SetVolume(Settings.sfxvolume); - } - if (Settings.sfxvolume > 0) - options2.SetValue(Idx,"%i", Settings.sfxvolume); - else - options2.SetValue(Idx,"%s", tr("OFF")); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Game Sound Mode")); - if(ret == Idx) - { - Settings.gamesound++; - if (Settings.gamesound > 2) - Settings.gamesound = 0; - } - - if(Settings.gamesound == 1) - options2.SetValue(Idx,"%s", tr("Sound+BGM")); - else if(Settings.gamesound == 2) - options2.SetValue(Idx,"%s", tr("Loop Sound")); + int menu = MENU_NONE; + int ret; + int choice = 0; + bool exit = false; + + // backup game language setting + char opt_lang[100]; + strcpy( opt_lang, Settings.language_path ); + // backup title override setting + int opt_override = Settings.titlesOverride; + // backup partition index + u8 settingspartitionold = Settings.partition; + + + enum + { + FADE, + LEFT, + RIGHT + }; + + int slidedirection = FADE; + + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnClick1( button_click_pcm, button_click_pcm_size, Settings.sfxvolume ); + + char imgPath[100]; + + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%ssettings_background.png", CFG.theme_path ); + GuiImageData settingsbg( imgPath, settings_background_png ); + + snprintf( imgPath, sizeof( imgPath ), "%ssettings_title.png", CFG.theme_path ); + GuiImageData MainButtonImgData( imgPath, settings_title_png ); + + snprintf( imgPath, sizeof( imgPath ), "%ssettings_title_over.png", CFG.theme_path ); + GuiImageData MainButtonImgOverData( imgPath, settings_title_over_png ); + + snprintf( imgPath, sizeof( imgPath ), "%spageindicator.png", CFG.theme_path ); + GuiImageData PageindicatorImgData( imgPath, pageindicator_png ); + + snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_left.png", CFG.theme_path ); + GuiImageData arrow_left( imgPath, startgame_arrow_left_png ); + + snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_right.png", CFG.theme_path ); + GuiImageData arrow_right( imgPath, startgame_arrow_right_png ); + + snprintf( imgPath, sizeof( imgPath ), "%scredits_button.png", CFG.theme_path ); + GuiImageData creditsImgData( imgPath, credits_button_png ); + + snprintf( imgPath, sizeof( imgPath ), "%scredits_button_over.png", CFG.theme_path ); + GuiImageData creditsOver( imgPath, credits_button_over_png ); + + GuiImage creditsImg( &creditsImgData ); + GuiImage creditsImgOver( &creditsOver ); + + GuiTrigger trigA; + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + GuiTrigger trigHome; + trigHome.SetButtonOnlyTrigger( -1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0 ); + GuiTrigger trigB; + trigB.SetButtonOnlyTrigger( -1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B ); + GuiTrigger trigL; + trigL.SetButtonOnlyTrigger( -1, WPAD_BUTTON_LEFT | WPAD_CLASSIC_BUTTON_LEFT, PAD_BUTTON_LEFT ); + GuiTrigger trigR; + trigR.SetButtonOnlyTrigger( -1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT ); + GuiTrigger trigMinus; + trigMinus.SetButtonOnlyTrigger( -1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0 ); + GuiTrigger trigPlus; + trigPlus.SetButtonOnlyTrigger( -1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0 ); + + GuiText titleTxt( tr( "Settings" ), 28, ( GXColor ) {0, 0, 0, 255} ); + titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + titleTxt.SetPosition( 0, 40 ); + + GuiImage settingsbackground( &settingsbg ); + + GuiText backBtnTxt( tr( "Back" ) , 22, THEME.prompttext ); + backBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); + GuiImage backBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + backBtnTxt.SetWidescreen( CFG.widescreen ); + backBtnImg.SetWidescreen( CFG.widescreen ); + } + GuiButton backBtn( &backBtnImg, &backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2, 1 ); + backBtn.SetLabel( &backBtnTxt ); + backBtn.SetTrigger( &trigB ); + + GuiButton homo( 1, 1 ); + homo.SetTrigger( &trigHome ); + + GuiImage PageindicatorImg1( &PageindicatorImgData ); + GuiText PageindicatorTxt1( "1", 22, ( GXColor ) { 0, 0, 0, 255} ); + GuiButton PageIndicatorBtn1( PageindicatorImg1.GetWidth(), PageindicatorImg1.GetHeight() ); + PageIndicatorBtn1.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + PageIndicatorBtn1.SetPosition( 165, 400 ); + PageIndicatorBtn1.SetImage( &PageindicatorImg1 ); + PageIndicatorBtn1.SetLabel( &PageindicatorTxt1 ); + PageIndicatorBtn1.SetSoundOver( &btnSoundOver ); + PageIndicatorBtn1.SetSoundClick( &btnClick1 ); + PageIndicatorBtn1.SetTrigger( &trigA ); + PageIndicatorBtn1.SetEffectGrow(); + + GuiImage PageindicatorImg2( &PageindicatorImgData ); + GuiText PageindicatorTxt2( "2", 22, ( GXColor ) {0, 0, 0, 255} ); + GuiButton PageIndicatorBtn2( PageindicatorImg2.GetWidth(), PageindicatorImg2.GetHeight() ); + PageIndicatorBtn2.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + PageIndicatorBtn2.SetPosition( 200, 400 ); + PageIndicatorBtn2.SetImage( &PageindicatorImg2 ); + PageIndicatorBtn2.SetLabel( &PageindicatorTxt2 ); + PageIndicatorBtn2.SetSoundOver( &btnSoundOver ); + PageIndicatorBtn2.SetSoundClick( &btnClick1 ); + PageIndicatorBtn2.SetTrigger( &trigA ); + PageIndicatorBtn2.SetEffectGrow(); + + GuiImage PageindicatorImg3( &PageindicatorImgData ); + GuiText PageindicatorTxt3( "3", 22, ( GXColor ) {0, 0, 0, 255} ); + GuiButton PageIndicatorBtn3( PageindicatorImg3.GetWidth(), PageindicatorImg3.GetHeight() ); + PageIndicatorBtn3.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + PageIndicatorBtn3.SetPosition( 235, 400 ); + PageIndicatorBtn3.SetImage( &PageindicatorImg3 ); + PageIndicatorBtn3.SetLabel( &PageindicatorTxt3 ); + PageIndicatorBtn3.SetSoundOver( &btnSoundOver ); + PageIndicatorBtn3.SetSoundClick( &btnClick1 ); + PageIndicatorBtn3.SetTrigger( &trigA ); + PageIndicatorBtn3.SetEffectGrow(); + + GuiImage GoLeftImg( &arrow_left ); + GuiButton GoLeftBtn( GoLeftImg.GetWidth(), GoLeftImg.GetHeight() ); + GoLeftBtn.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + GoLeftBtn.SetPosition( 25, -25 ); + GoLeftBtn.SetImage( &GoLeftImg ); + GoLeftBtn.SetSoundOver( &btnSoundOver ); + GoLeftBtn.SetSoundClick( btnClick2 ); + GoLeftBtn.SetEffectGrow(); + GoLeftBtn.SetTrigger( &trigA ); + GoLeftBtn.SetTrigger( &trigL ); + GoLeftBtn.SetTrigger( &trigMinus ); + + GuiImage GoRightImg( &arrow_right ); + GuiButton GoRightBtn( GoRightImg.GetWidth(), GoRightImg.GetHeight() ); + GoRightBtn.SetAlignment( ALIGN_RIGHT, ALIGN_MIDDLE ); + GoRightBtn.SetPosition( -25, -25 ); + GoRightBtn.SetImage( &GoRightImg ); + GoRightBtn.SetSoundOver( &btnSoundOver ); + GoRightBtn.SetSoundClick( btnClick2 ); + GoRightBtn.SetEffectGrow(); + GoRightBtn.SetTrigger( &trigA ); + GoRightBtn.SetTrigger( &trigR ); + GoRightBtn.SetTrigger( &trigPlus ); + + char MainButtonText[50]; + snprintf( MainButtonText, sizeof( MainButtonText ), "%s", " " ); + + GuiImage MainButton1Img( &MainButtonImgData ); + GuiImage MainButton1ImgOver( &MainButtonImgOverData ); + GuiText MainButton1Txt( MainButtonText, 22, ( GXColor ) {0, 0, 0, 255} ); + MainButton1Txt.SetMaxWidth( MainButton1Img.GetWidth() ); + GuiButton MainButton1( MainButton1Img.GetWidth(), MainButton1Img.GetHeight() ); + MainButton1.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + MainButton1.SetPosition( 0, 90 ); + MainButton1.SetImage( &MainButton1Img ); + MainButton1.SetImageOver( &MainButton1ImgOver ); + MainButton1.SetLabel( &MainButton1Txt ); + MainButton1.SetSoundOver( &btnSoundOver ); + MainButton1.SetSoundClick( &btnClick1 ); + MainButton1.SetEffectGrow(); + MainButton1.SetTrigger( &trigA ); + + GuiImage MainButton2Img( &MainButtonImgData ); + GuiImage MainButton2ImgOver( &MainButtonImgOverData ); + GuiText MainButton2Txt( MainButtonText, 22, ( GXColor ) {0, 0, 0, 255 } ); + MainButton2Txt.SetMaxWidth( MainButton2Img.GetWidth() ); + GuiButton MainButton2( MainButton2Img.GetWidth(), MainButton2Img.GetHeight() ); + MainButton2.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + MainButton2.SetPosition( 0, 160 ); + MainButton2.SetImage( &MainButton2Img ); + MainButton2.SetImageOver( &MainButton2ImgOver ); + MainButton2.SetLabel( &MainButton2Txt ); + MainButton2.SetSoundOver( &btnSoundOver ); + MainButton2.SetSoundClick( &btnClick1 ); + MainButton2.SetEffectGrow(); + MainButton2.SetTrigger( &trigA ); + + GuiImage MainButton3Img( &MainButtonImgData ); + GuiImage MainButton3ImgOver( &MainButtonImgOverData ); + GuiText MainButton3Txt( MainButtonText, 22, ( GXColor ) {0, 0, 0, 255} ); + MainButton3Txt.SetMaxWidth( MainButton3Img.GetWidth() ); + GuiButton MainButton3( MainButton3Img.GetWidth(), MainButton3Img.GetHeight() ); + MainButton3.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + MainButton3.SetPosition( 0, 230 ); + MainButton3.SetImage( &MainButton3Img ); + MainButton3.SetImageOver( &MainButton3ImgOver ); + MainButton3.SetLabel( &MainButton3Txt ); + MainButton3.SetSoundOver( &btnSoundOver ); + MainButton3.SetSoundClick( &btnClick1 ); + MainButton3.SetEffectGrow(); + MainButton3.SetTrigger( &trigA ); + + GuiImage MainButton4Img( &MainButtonImgData ); + GuiImage MainButton4ImgOver( &MainButtonImgOverData ); + GuiText MainButton4Txt( MainButtonText, 22, ( GXColor ) {0, 0, 0, 255} ); + MainButton4Txt.SetMaxWidth( MainButton4Img.GetWidth() ); + GuiButton MainButton4( MainButton4Img.GetWidth(), MainButton4Img.GetHeight() ); + MainButton4.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + MainButton4.SetPosition( 0, 300 ); + MainButton4.SetImage( &MainButton4Img ); + MainButton4.SetImageOver( &MainButton4ImgOver ); + MainButton4.SetLabel( &MainButton4Txt ); + MainButton4.SetSoundOver( &btnSoundOver ); + MainButton4.SetSoundClick( &btnClick1 ); + MainButton4.SetEffectGrow(); + MainButton4.SetTrigger( &trigA ); + + customOptionList options2( MAXOPTIONS ); + GuiCustomOptionBrowser optionBrowser2( 396, 280, &options2, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, 0, 150 ); + optionBrowser2.SetPosition( 0, 90 ); + optionBrowser2.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + + GuiWindow w( screenwidth, screenheight ); + + int pageToDisplay = 1; + while ( pageToDisplay > 0 ) + { + usleep( 100 ); + + menu = MENU_NONE; + + if ( pageToDisplay == 1 ) + { + /** Standard procedure made in all pages **/ + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); + + if ( slidedirection == RIGHT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35 ); + MainButton2.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35 ); + MainButton3.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35 ); + MainButton4.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35 ); + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + } + else if ( slidedirection == LEFT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35 ); + MainButton2.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35 ); + MainButton3.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35 ); + MainButton4.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35 ); + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + } + + 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 ); + + mainWindow->RemoveAll(); + mainWindow->Append( &w ); + w.RemoveAll(); + w.Append( &settingsbackground ); + w.Append( &PageIndicatorBtn1 ); + w.Append( &PageIndicatorBtn2 ); + w.Append( &PageIndicatorBtn3 ); + w.Append( &titleTxt ); + w.Append( &backBtn ); + w.Append( &homo ); + w.Append( &GoRightBtn ); + w.Append( &GoLeftBtn ); + w.Append( &MainButton1 ); + w.Append( &MainButton2 ); + w.Append( &MainButton3 ); + w.Append( &MainButton4 ); + + PageIndicatorBtn1.SetAlpha( 255 ); + PageIndicatorBtn2.SetAlpha( 50 ); + PageIndicatorBtn3.SetAlpha( 50 ); + + /** Creditsbutton change **/ + MainButton4.SetImage( &MainButton4Img ); + MainButton4.SetImageOver( &MainButton4ImgOver ); + + /** Disable ability to click through MainButtons */ + optionBrowser2.SetClickable( false ); + /** Default no scrollbar and reset position **/ +// optionBrowser2.SetScrollbar(0); + optionBrowser2.SetOffset( 0 ); + + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); + + MainButton1.SetEffectGrow(); + MainButton2.SetEffectGrow(); + MainButton3.SetEffectGrow(); + MainButton4.SetEffectGrow(); + + if ( slidedirection == FADE ) + { + MainButton1.SetEffect( EFFECT_FADE, 20 ); + MainButton2.SetEffect( EFFECT_FADE, 20 ); + MainButton3.SetEffect( EFFECT_FADE, 20 ); + MainButton4.SetEffect( EFFECT_FADE, 20 ); + } + else if ( slidedirection == LEFT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35 ); + MainButton2.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35 ); + MainButton3.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35 ); + MainButton4.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35 ); + } + else if ( slidedirection == RIGHT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35 ); + MainButton2.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35 ); + MainButton3.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35 ); + MainButton4.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35 ); + } + + mainWindow->Append( &w ); + + ResumeGui(); + + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + + } + else if ( pageToDisplay == 2 ) + { + /** Standard procedure made in all pages **/ + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); + + if ( slidedirection == RIGHT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35 ); + MainButton2.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35 ); + MainButton3.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35 ); + MainButton4.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35 ); + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + } + else if ( slidedirection == LEFT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35 ); + MainButton2.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35 ); + MainButton3.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35 ); + MainButton4.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35 ); + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + } + + 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 ); + + mainWindow->RemoveAll(); + mainWindow->Append( &w ); + w.RemoveAll(); + w.Append( &settingsbackground ); + w.Append( &PageIndicatorBtn1 ); + w.Append( &PageIndicatorBtn2 ); + w.Append( &PageIndicatorBtn3 ); + w.Append( &titleTxt ); + w.Append( &backBtn ); + w.Append( &homo ); + w.Append( &GoRightBtn ); + w.Append( &GoLeftBtn ); + w.Append( &MainButton1 ); + w.Append( &MainButton2 ); + w.Append( &MainButton3 ); + w.Append( &MainButton4 ); + + PageIndicatorBtn1.SetAlpha( 50 ); + PageIndicatorBtn2.SetAlpha( 255 ); + PageIndicatorBtn3.SetAlpha( 50 ); + + /** Creditsbutton change **/ + MainButton4.SetImage( &creditsImg ); + MainButton4.SetImageOver( &creditsImgOver ); + + /** Disable ability to click through MainButtons */ + optionBrowser2.SetClickable( false ); + /** Default no scrollbar and reset position **/ +// optionBrowser2.SetScrollbar(0); + optionBrowser2.SetOffset( 0 ); + + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); + + MainButton1.SetEffectGrow(); + MainButton2.SetEffectGrow(); + MainButton3.SetEffectGrow(); + MainButton4.SetEffectGrow(); + + if ( slidedirection == FADE ) + { + MainButton1.SetEffect( EFFECT_FADE, 20 ); + MainButton2.SetEffect( EFFECT_FADE, 20 ); + MainButton3.SetEffect( EFFECT_FADE, 20 ); + MainButton4.SetEffect( EFFECT_FADE, 20 ); + } + else if ( slidedirection == LEFT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35 ); + MainButton2.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35 ); + MainButton3.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35 ); + MainButton4.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35 ); + } + else if ( slidedirection == RIGHT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35 ); + MainButton2.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35 ); + MainButton3.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35 ); + MainButton4.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35 ); + } + + mainWindow->Append( &w ); + + ResumeGui(); + + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + + } + else if ( pageToDisplay == 3 ) + { + /** Standard procedure made in all pages **/ + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); + + if ( slidedirection == RIGHT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35 ); + MainButton2.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35 ); + MainButton3.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35 ); + MainButton4.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 35 ); + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + } + else if ( slidedirection == LEFT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35 ); + MainButton2.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35 ); + MainButton3.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35 ); + MainButton4.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 35 ); + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + } + + 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 ); + + mainWindow->RemoveAll(); + mainWindow->Append( &w ); + w.RemoveAll(); + w.Append( &settingsbackground ); + w.Append( &PageIndicatorBtn1 ); + w.Append( &PageIndicatorBtn2 ); + w.Append( &PageIndicatorBtn3 ); + w.Append( &titleTxt ); + w.Append( &backBtn ); + w.Append( &homo ); + w.Append( &GoRightBtn ); + w.Append( &GoLeftBtn ); + w.Append( &MainButton1 ); + + PageIndicatorBtn1.SetAlpha( 50 ); + PageIndicatorBtn2.SetAlpha( 50 ); + PageIndicatorBtn3.SetAlpha( 255 ); + + /** Disable ability to click through MainButtons */ + optionBrowser2.SetClickable( false ); + /** Default no scrollbar and reset position **/ +// optionBrowser2.SetScrollbar(0); + optionBrowser2.SetOffset( 0 ); + + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); + + MainButton1.SetEffectGrow(); + MainButton2.SetEffectGrow(); + MainButton3.SetEffectGrow(); + MainButton4.SetEffectGrow(); + + if ( slidedirection == FADE ) + { + MainButton1.SetEffect( EFFECT_FADE, 20 ); + MainButton2.SetEffect( EFFECT_FADE, 20 ); + MainButton3.SetEffect( EFFECT_FADE, 20 ); + MainButton4.SetEffect( EFFECT_FADE, 20 ); + } + else if ( slidedirection == LEFT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35 ); + MainButton2.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35 ); + MainButton3.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35 ); + MainButton4.SetEffect( EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 35 ); + } + else if ( slidedirection == RIGHT ) + { + MainButton1.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35 ); + MainButton2.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35 ); + MainButton3.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35 ); + MainButton4.SetEffect( EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 35 ); + } + + mainWindow->Append( &w ); + + ResumeGui(); + + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + } + + while ( menu == MENU_NONE ) + { + usleep( 100 ); + + if ( shutdown == 1 ) + Sys_Shutdown(); + if ( reset == 1 ) + Sys_Reboot(); + + if ( pageToDisplay == 1 ) + { + if ( MainButton1.GetState() == STATE_CLICKED ) + { + MainButton1.SetEffect( EFFECT_FADE, -20 ); + MainButton2.SetEffect( EFFECT_FADE, -20 ); + MainButton3.SetEffect( EFFECT_FADE, -20 ); + MainButton4.SetEffect( EFFECT_FADE, -20 ); + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + HaltGui(); + w.Remove( &PageIndicatorBtn1 ); + w.Remove( &PageIndicatorBtn2 ); + w.Remove( &PageIndicatorBtn3 ); + w.Remove( &GoRightBtn ); + w.Remove( &GoLeftBtn ); + w.Remove( &MainButton1 ); + w.Remove( &MainButton2 ); + w.Remove( &MainButton3 ); + w.Remove( &MainButton4 ); + titleTxt.SetText( tr( "GUI Settings" ) ); + exit = false; + options2.SetLength( 0 ); +// optionBrowser2.SetScrollbar(1); + w.Append( &optionBrowser2 ); + optionBrowser2.SetClickable( true ); + ResumeGui(); + + optionBrowser2.SetEffect( EFFECT_FADE, 20 ); + while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + + int returnhere = 1; + char * languagefile; + languagefile = strrchr( Settings.language_path, '/' ) + 1; + + bool firstRun = true; + while ( !exit ) + { + usleep( 100 ); + + returnhere = 1; + + if ( shutdown == 1 ) + Sys_Shutdown(); + if ( reset == 1 ) + Sys_Reboot(); + + else if ( backBtn.GetState() == STATE_CLICKED ) + { + backBtn.ResetState(); + exit = true; + break; + } + + else if ( menu == MENU_DISCLIST ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + WindowCredits(); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + } + + else if ( homo.GetState() == STATE_CLICKED ) + { + cfg_save_global(); + optionBrowser2.SetState( STATE_DISABLED ); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if ( choice == 3 ) + Sys_LoadMenu(); // Back to System Menu + else if ( choice == 2 ) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState( STATE_DEFAULT ); + } + + ret = optionBrowser2.GetClickedOption(); + + if ( firstRun || ret >= 0 ) + { + int Idx = -1; + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "App Language" ) ); + if ( ret == Idx ) + { + if ( isInserted( bootDevice ) ) + { + if ( Settings.godmode == 1 ) + { + w.SetEffect( EFFECT_FADE, -20 ); + while ( w.GetEffect() > 0 ) usleep( 50 ); + mainWindow->Remove( &w ); + while ( returnhere == 1 ) + returnhere = MenuLanguageSelect(); + if ( returnhere == 2 ) + { + menu = MENU_SETTINGS; + pageToDisplay = 0; + exit = true; + mainWindow->Append( &w ); + break; + } + else + { + HaltGui(); + mainWindow->Append( &w ); + w.SetEffect( EFFECT_FADE, 20 ); + ResumeGui(); + while ( w.GetEffect() > 0 ) usleep( 50 ); + } + } + else + { + WindowPrompt( tr( "Language change:" ), tr( "Console should be unlocked to modify it." ), tr( "OK" ) ); + } + } + else + { + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to use this option." ), tr( "OK" ) ); + } + } + + if ( !strcmp( "notset", Settings.language_path ) ) + options2.SetValue( Idx, "%s", tr( "Default" ) ); else - options2.SetValue(Idx,"%s", tr("Sound+Quiet")); - } + options2.SetValue( Idx, "%s", languagefile ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Game Sound Volume")); - if(ret == Idx) - { - Settings.gamesoundvolume += 10; - if (Settings.gamesoundvolume > 100) - Settings.gamesoundvolume = 0; - } + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "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 (Settings.gamesoundvolume > 0) - options2.SetValue(Idx,"%i", Settings.gamesoundvolume); - else - options2.SetValue(Idx,"%s", tr("OFF")); - } + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Clock" ) ); + if ( ret == Idx && ++Settings.hddinfo >= settings_clock_max ) + Settings.hddinfo = 0; //CLOCK + if ( Settings.hddinfo == hr12 ) options2.SetValue( Idx, "12 %s", tr( "Hour" ) ); + else if ( Settings.hddinfo == hr24 ) options2.SetValue( Idx, "24 %s", tr( "Hour" ) ); + else if ( Settings.hddinfo == Off ) options2.SetValue( Idx, "%s", tr( "OFF" ) ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Music Loop Mode")); - if(ret == Idx) - { - Settings.musicloopmode++; - if (Settings.musicloopmode > 3) - Settings.musicloopmode = 0; - bgMusic->SetLoop(Settings.musicloopmode); - } + 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 (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(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) + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Flip-X" ) ); + if ( ret == Idx && ++Settings.xflip >= settings_xflip_max ) + Settings.xflip = 0; + static const char *opts[settings_xflip_max][3] = { {trNOOP( "Right" ), "/", trNOOP( "Next" )}, + {trNOOP( "Left" ), "/", trNOOP( "Prev" )}, + {trNOOP( "Like SysMenu" ), "", ""}, + {trNOOP( "Right" ), "/", trNOOP( "Prev" )}, + {trNOOP( "DiskFlip" ), "", ""} + }; + options2.SetValue( Idx, "%s%s%s", tr( opts[Settings.xflip][0] ), opts[Settings.xflip][1], tr( opts[Settings.xflip][2] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Prompts Buttons" ) ); + if ( ret == Idx && ++Settings.wsprompt >= settings_off_on_max ) + Settings.wsprompt = 0; + static const char *opts[settings_off_on_max] = {trNOOP( "Normal" ), trNOOP( "Widescreen Fix" )}; + options2.SetValue( Idx, "%s", tr( opts[Settings.wsprompt] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Keyboard" ) ); + if ( ret == Idx && ++Settings.keyset >= settings_keyset_max ) + Settings.keyset = 0; + static const char *opts[settings_keyset_max] = {"QWERTY", "QWERTY 2", "DVORAK", "QWERTZ", "AZERTY"}; + options2.SetValue( Idx, "%s", opts[Settings.keyset] ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Disc Artwork Download" ) ); + if ( ret == Idx && ++Settings.discart >= 4 ) + Settings.discart = 0; + static const char *opts[4] = {trNOOP( "Only Original" ), trNOOP( "Only Customs" ), trNOOP( "Original/Customs" ), trNOOP( "Customs/Original" )}; + options2.SetValue( Idx, "%s", tr( opts[Settings.discart] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Wiilight" ) ); + if ( ret == Idx && ++Settings.wiilight >= settings_wiilight_max ) + Settings.wiilight = 0; + static const char *opts[settings_wiilight_max] = {trNOOP( "OFF" ), trNOOP( "ON" ), trNOOP( "Only for Install" )}; + options2.SetValue( Idx, "%s", tr( opts[Settings.wiilight] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Rumble" ) ); + if ( ret == Idx && ++Settings.rumble >= settings_rumble_max ) + Settings.rumble = 0; //RUMBLE + options2.SetValue( Idx, "%s", tr( opts_off_on[Settings.rumble] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "AutoInit Network" ) ); + if ( ret == Idx && ++Settings.autonetwork >= settings_off_on_max ) + Settings.autonetwork = 0; + options2.SetValue( Idx, "%s", tr( opts_off_on[Settings.autonetwork] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "BETA revisions" ) ); + if ( ret == Idx && ++Settings.beta_upgrades >= settings_off_on_max ) + Settings.beta_upgrades = 0; + options2.SetValue( Idx, "%s", tr( opts_off_on[Settings.beta_upgrades] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Titles from WiiTDB" ) ); + if ( ret == Idx && ++Settings.titlesOverride >= settings_off_on_max ) + Settings.titlesOverride = 0; + options2.SetValue( Idx, "%s", tr( opts_off_on[Settings.titlesOverride] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Screensaver" ) ); + if ( ret == Idx && ++Settings.screensaver >= settings_screensaver_max ) + Settings.screensaver = 0; //RUMBLE + static const char *opts[settings_screensaver_max] = {trNOOP( "OFF" ), trNOOP( "3 min" ), trNOOP( "5 min" ), trNOOP( "10 min" ), trNOOP( "20 min" ), trNOOP( "30 min" ), trNOOP( "1 hour" )}; + options2.SetValue( Idx, "%s", tr( opts[Settings.screensaver] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Mark new games" ) ); + if ( ret == Idx && ++Settings.marknewtitles >= settings_off_on_max ) + Settings.marknewtitles = 0; + options2.SetValue( Idx, "%s", tr( opts_off_on[Settings.marknewtitles] ) ); + } + + firstRun = false; + } + } + optionBrowser2.SetEffect( EFFECT_FADE, -20 ); + while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + titleTxt.SetText( tr( "Settings" ) ); + slidedirection = FADE; + if ( returnhere != 2 ) + pageToDisplay = 1; + MainButton1.ResetState(); + break; + } + + else if ( MainButton2.GetState() == STATE_CLICKED ) + { + MainButton1.SetEffect( EFFECT_FADE, -20 ); + MainButton2.SetEffect( EFFECT_FADE, -20 ); + MainButton3.SetEffect( EFFECT_FADE, -20 ); + MainButton4.SetEffect( EFFECT_FADE, -20 ); + while ( MainButton2.GetEffect() > 0 ) usleep( 50 ); + HaltGui(); + w.Remove( &PageIndicatorBtn1 ); + w.Remove( &PageIndicatorBtn2 ); + w.Remove( &PageIndicatorBtn3 ); + w.Remove( &GoRightBtn ); + w.Remove( &GoLeftBtn ); + w.Remove( &MainButton1 ); + w.Remove( &MainButton2 ); + w.Remove( &MainButton3 ); + w.Remove( &MainButton4 ); + titleTxt.SetText( tr( "Game Load" ) ); + exit = false; + options2.SetLength( 0 ); + w.Append( &optionBrowser2 ); + optionBrowser2.SetClickable( true ); + ResumeGui(); + + optionBrowser2.SetEffect( EFFECT_FADE, 20 ); + while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + + bool firstRun = true; + while ( !exit ) + { + usleep( 100 ); + + if ( shutdown == 1 ) + Sys_Shutdown(); + if ( reset == 1 ) + Sys_Reboot(); + + else if ( backBtn.GetState() == STATE_CLICKED ) + { + backBtn.ResetState(); + exit = true; + break; + } + + else if ( homo.GetState() == STATE_CLICKED ) + { + cfg_save_global(); + optionBrowser2.SetState( STATE_DISABLED ); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if ( choice == 3 ) + Sys_LoadMenu(); // Back to System Menu + if ( choice == 2 ) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState( STATE_DEFAULT ); + } + + ret = optionBrowser2.GetClickedOption(); + + if ( firstRun || ret >= 0 ) + { + int Idx = -1; + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Video Mode" ) ); + if ( ret == Idx && ++Settings.video >= settings_video_max ) + Settings.video = 0; + options2.SetValue( Idx, "%s%s", opts_videomode[Settings.video][0], tr( opts_videomode[Settings.video][1] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "VIDTV Patch" ) ); + if ( ret == Idx && ++Settings.vpatch >= settings_off_on_max ) + Settings.vpatch = 0; + options2.SetValue( Idx, "%s", tr( opts_off_on[Settings.vpatch] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Game Language" ) ); + if ( ret == Idx && ++Settings.language >= settings_language_max ) + Settings.language = 0; + options2.SetValue( Idx, "%s", tr( opts_language[Settings.language] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Patch Country Strings" ) ); + if ( ret == Idx && ++Settings.patchcountrystrings >= settings_off_on_max ) + Settings.patchcountrystrings = 0; + options2.SetValue( Idx, "%s", tr( opts_off_on[Settings.patchcountrystrings] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "Ocarina" ); + if ( ret == Idx && ++Settings.ocarina >= settings_off_on_max ) + Settings.ocarina = 0; + options2.SetValue( Idx, "%s", tr( opts_off_on[Settings.ocarina] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Boot/Standard" ) ); + if ( ret == Idx && Settings.godmode == 1 ) + { + if ( ++Settings.cios >= settings_cios_max ) + { + Settings.cios = 0; + } + if ( ( Settings.cios == 1 && 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" ) ); + } + } + if ( Settings.godmode == 1 ) + options2.SetValue( Idx, "%s", opts_cios[Settings.cios] ); + else + options2.SetValue( Idx, "********" ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Partition" ) ); + if ( ret == Idx ) + { + // Select the next valid partition, even if that's the same one + do + { + Settings.partition = Settings.partition + 1 == partitions.num ? 0 : Settings.partition + 1; + } + while ( !IsValidPartition( partitions.pinfo[Settings.partition].fs_type, Settings.cios ) ); + } + + PartInfo pInfo = partitions.pinfo[Settings.partition]; + f32 partition_size = partitions.pentry[Settings.partition].size * ( partitions.sector_size / GB_SIZE ); + + // Get the partition name and it's size in GB's + options2.SetValue( Idx, "%s%d (%.2fGB)", pInfo.fs_type == FS_TYPE_FAT32 ? "FAT" : pInfo.fs_type == FS_TYPE_NTFS ? "NTFS" : "WBFS", + pInfo.index, + partition_size ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "FAT: Use directories" ) ); + if ( ret == Idx && ++Settings.FatInstallToDir >= settings_installdir_max ) + Settings.FatInstallToDir = 0; + options2.SetValue( Idx, "%s", tr( opts_installdir[Settings.FatInstallToDir] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Quick Boot" ) ); + if ( ret == Idx && ++Settings.qboot >= settings_off_on_max ) + Settings.qboot = 0; + options2.SetValue( Idx, "%s", tr( opts_no_yes[Settings.qboot] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Error 002 fix" ) ); + if ( ret == Idx && ++Settings.error002 >= settings_error002_max ) + Settings.error002 = 0; + options2.SetValue( Idx, "%s", tr( opts_error002[Settings.error002] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Install partitions" ) ); + if ( ret == Idx && ++Settings.partitions_to_install >= settings_partitions_max ) + Settings.partitions_to_install = 0; + options2.SetValue( Idx, "%s", tr( opts_partitions[Settings.partitions_to_install] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Install 1:1 Copy" ) ); + if ( ret == Idx ) + { + Settings.fullcopy = Settings.fullcopy == 0 ? 1 : 0; + } + options2.SetValue( Idx, "%s", tr( opts_no_yes[Settings.fullcopy] ) ); + } + + firstRun = false; + } + } + optionBrowser2.SetEffect( EFFECT_FADE, -20 ); + while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + titleTxt.SetText( tr( "Settings" ) ); + slidedirection = FADE; + pageToDisplay = 1; + MainButton2.ResetState(); + break; + } + + else if ( MainButton3.GetState() == STATE_CLICKED ) + { + MainButton1.SetEffect( EFFECT_FADE, -20 ); + MainButton2.SetEffect( EFFECT_FADE, -20 ); + MainButton3.SetEffect( EFFECT_FADE, -20 ); + MainButton4.SetEffect( EFFECT_FADE, -20 ); + while ( MainButton3.GetEffect() > 0 ) usleep( 50 ); + HaltGui(); + w.Remove( &PageIndicatorBtn1 ); + w.Remove( &PageIndicatorBtn2 ); + w.Remove( &PageIndicatorBtn3 ); + w.Remove( &GoRightBtn ); + w.Remove( &GoLeftBtn ); + w.Remove( &MainButton1 ); + w.Remove( &MainButton2 ); + w.Remove( &MainButton3 ); + w.Remove( &MainButton4 ); + titleTxt.SetText( tr( "Parental Control" ) ); + exit = false; + options2.SetLength( 0 ); + w.Append( &optionBrowser2 ); + optionBrowser2.SetClickable( true ); + ResumeGui(); + + optionBrowser2.SetEffect( EFFECT_FADE, 20 ); + while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + + bool firstRun = true; + while ( !exit ) + { + usleep( 100 ); + + if ( shutdown == 1 ) + Sys_Shutdown(); + if ( reset == 1 ) + Sys_Reboot(); + + else if ( backBtn.GetState() == STATE_CLICKED ) + { + backBtn.ResetState(); + exit = true; + break; + } + + else if ( homo.GetState() == STATE_CLICKED ) + { + cfg_save_global(); + optionBrowser2.SetState( STATE_DISABLED ); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if ( choice == 3 ) + Sys_LoadMenu(); // Back to System Menu + else if ( choice == 2 ) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState( STATE_DEFAULT ); + } + + ret = optionBrowser2.GetClickedOption(); + + if ( firstRun || ret >= 0 ) + { + + int Idx = -1; + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Console" ) ); + if ( ret == Idx ) + { + if ( !strcmp( "", Settings.unlockCode ) && Settings.parental.enabled == 0 ) + { + Settings.godmode = !Settings.godmode; + } + else if ( Settings.godmode == 0 ) + { + char entered[20]; + memset( entered, 0, 20 ); + + //password check to unlock Install,Delete and Format + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + int result = Settings.parental.enabled == 0 ? OnScreenKeyboard( entered, 20, 0 ) : OnScreenNumpad( entered, 5 ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + if ( result == 1 ) + { + if ( !strcmp( entered, Settings.unlockCode ) || !memcmp( entered, Settings.parental.pin, 4 ) ) //if password correct + { + if ( Settings.godmode == 0 ) + { + WindowPrompt( tr( "Correct Password" ), tr( "All the features of USB Loader GX are unlocked." ), tr( "OK" ) ); + Settings.godmode = 1; + menu = MENU_DISCLIST; + } + } + else + WindowPrompt( tr( "Wrong Password" ), tr( "USB Loader GX is protected" ), tr( "OK" ) ); + } + } + else + { + int choice = WindowPrompt ( tr( "Lock Console" ), tr( "Are you sure?" ), tr( "Yes" ), tr( "No" ) ); + if ( choice == 1 ) + { + WindowPrompt( tr( "Console Locked" ), tr( "USB Loader GX is protected" ), tr( "OK" ) ); + Settings.godmode = 0; + menu = MENU_DISCLIST; + } + } + } + static const char *opts[] = {trNOOP( "Locked" ), trNOOP( "Unlocked" )}; + options2.SetValue( Idx, "%s", tr( opts[Settings.godmode] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Password" ) ); + if ( ret == Idx ) + { + if ( Settings.godmode == 1 ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[20] = ""; + strlcpy( entered, Settings.unlockCode, sizeof( entered ) ); + int result = OnScreenKeyboard( entered, 20, 0 ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + if ( result == 1 ) + { + strlcpy( Settings.unlockCode, entered, sizeof( Settings.unlockCode ) ); + WindowPrompt( tr( "Password Changed" ), tr( "Password has been changed" ), tr( "OK" ) ); + } + } + else + { + WindowPrompt( tr( "Password Changed" ), tr( "Console should be unlocked to modify it." ), tr( "OK" ) ); + } + } + if ( Settings.godmode != 1 ) options2.SetValue( Idx, "********" ); + else if ( !strcmp( "", Settings.unlockCode ) ) options2.SetValue( Idx, "%s", tr( "not set" ) ); + else options2.SetValue( Idx, Settings.unlockCode ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Controllevel" ) ); + if ( ret == Idx && Settings.godmode == 1 && ++Settings.parentalcontrol >= 5 ) + Settings.parentalcontrol = 0; + if ( Settings.godmode == 1 ) + options2.SetValue( Idx, "%s", tr( opts_parentalcontrol[Settings.parentalcontrol] ) ); + else + options2.SetValue( Idx, "********" ); + } + + firstRun = false; + } + } + optionBrowser2.SetEffect( EFFECT_FADE, -20 ); + while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + titleTxt.SetText( tr( "Settings" ) ); + slidedirection = FADE; + pageToDisplay = 1; + MainButton3.ResetState(); + break; + } + + else if ( MainButton4.GetState() == STATE_CLICKED ) + { + MainButton1.SetEffect( EFFECT_FADE, -20 ); + MainButton2.SetEffect( EFFECT_FADE, -20 ); + MainButton3.SetEffect( EFFECT_FADE, -20 ); + MainButton4.SetEffect( EFFECT_FADE, -20 ); + while ( MainButton4.GetEffect() > 0 ) usleep( 50 ); + HaltGui(); + w.Remove( &PageIndicatorBtn1 ); + w.Remove( &PageIndicatorBtn2 ); + w.Remove( &PageIndicatorBtn3 ); + w.Remove( &GoRightBtn ); + w.Remove( &GoLeftBtn ); + w.Remove( &MainButton1 ); + w.Remove( &MainButton2 ); + w.Remove( &MainButton3 ); + w.Remove( &MainButton4 ); + titleTxt.SetText( tr( "Sound" ) ); + exit = false; + options2.SetLength( 0 ); + w.Append( &optionBrowser2 ); + optionBrowser2.SetClickable( true ); + ResumeGui(); + + optionBrowser2.SetEffect( EFFECT_FADE, 20 ); + while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + + + bool firstRun = true; + while ( !exit ) + { + usleep( 100 ); + + bool returnhere = true; + + if ( shutdown == 1 ) + Sys_Shutdown(); + if ( reset == 1 ) + Sys_Reboot(); + else if ( backBtn.GetState() == STATE_CLICKED ) + { + backBtn.ResetState(); + exit = true; + break; + } + + else if ( homo.GetState() == STATE_CLICKED ) + { + cfg_save_global(); + optionBrowser2.SetState( STATE_DISABLED ); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if ( choice == 3 ) + Sys_LoadMenu(); // Back to System Menu + else if ( choice == 2 ) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState( STATE_DEFAULT ); + } + + ret = optionBrowser2.GetClickedOption(); + + if ( firstRun || ret >= 0 ) + { + int Idx = -1; + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Backgroundmusic" ) ); + if ( ret == Idx ) + { + if ( isInserted( bootDevice ) ) + { + w.SetEffect( EFFECT_FADE, -20 ); + while ( w.GetEffect() > 0 ) usleep( 50 ); + mainWindow->Remove( &w ); + + returnhere = MenuBackgroundMusic(); + + HaltGui(); + mainWindow->Append( &w ); + w.SetEffect( EFFECT_FADE, 20 ); + ResumeGui(); + while ( w.GetEffect() > 0 ) usleep( 50 ); + } + else + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to use this option." ), tr( "OK" ) ); + } + + char * filename = strrchr( Settings.ogg_path, '/' ); + if ( filename ) + { + filename += 1; + options2.SetValue( Idx, "%s", filename ); + } + else + options2.SetValue( Idx, "%s", tr( "Standard" ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Music Volume" ) ); + if ( ret == Idx ) + { + Settings.volume += 10; + if ( Settings.volume > 100 ) + Settings.volume = 0; + bgMusic->SetVolume( Settings.volume ); + } + if ( Settings.volume > 0 ) + options2.SetValue( Idx, "%i", Settings.volume ); + else + options2.SetValue( Idx, "%s", tr( "OFF" ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "SFX Volume" ) ); + if ( ret == Idx ) + { + Settings.sfxvolume += 10; + if ( Settings.sfxvolume > 100 ) + Settings.sfxvolume = 0; + btnSoundOver.SetVolume( Settings.sfxvolume ); + btnClick2->SetVolume( Settings.sfxvolume ); + btnClick1.SetVolume( Settings.sfxvolume ); + } + if ( Settings.sfxvolume > 0 ) + options2.SetValue( Idx, "%i", Settings.sfxvolume ); + else + options2.SetValue( Idx, "%s", tr( "OFF" ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Game Sound Mode" ) ); + if ( ret == Idx ) + { + Settings.gamesound++; + if ( Settings.gamesound > 2 ) + Settings.gamesound = 0; + } + + if ( Settings.gamesound == 1 ) + options2.SetValue( Idx, "%s", tr( "Sound+BGM" ) ); + else if ( Settings.gamesound == 2 ) + options2.SetValue( Idx, "%s", tr( "Loop Sound" ) ); + else + options2.SetValue( Idx, "%s", tr( "Sound+Quiet" ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Game Sound Volume" ) ); + if ( ret == Idx ) + { + Settings.gamesoundvolume += 10; + if ( Settings.gamesoundvolume > 100 ) + Settings.gamesoundvolume = 0; + } + + if ( Settings.gamesoundvolume > 0 ) + options2.SetValue( Idx, "%i", Settings.gamesoundvolume ); + else + options2.SetValue( Idx, "%s", tr( "OFF" ) ); + } + + if ( ret == ++Idx || firstRun ) + { + 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 == 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 ( 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 ) { 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")); - slidedirection = FADE; - pageToDisplay = 1; - MainButton4.ResetState(); - break; - } - } + firstRun = false; + } + } + optionBrowser2.SetEffect( EFFECT_FADE, -20 ); + while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + titleTxt.SetText( tr( "Settings" ) ); + slidedirection = FADE; + pageToDisplay = 1; + MainButton4.ResetState(); + break; + } + } - else if ( pageToDisplay == 2) - { - if (MainButton1.GetState() == STATE_CLICKED) - { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton1.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - titleTxt.SetText(tr("Custom Paths")); - exit = false; - options2.SetLength(0); -// optionBrowser2.SetScrollbar(1); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); + else if ( pageToDisplay == 2 ) + { + if ( MainButton1.GetState() == STATE_CLICKED ) + { + MainButton1.SetEffect( EFFECT_FADE, -20 ); + MainButton2.SetEffect( EFFECT_FADE, -20 ); + MainButton3.SetEffect( EFFECT_FADE, -20 ); + MainButton4.SetEffect( EFFECT_FADE, -20 ); + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + HaltGui(); + w.Remove( &PageIndicatorBtn1 ); + w.Remove( &PageIndicatorBtn2 ); + w.Remove( &PageIndicatorBtn3 ); + w.Remove( &GoRightBtn ); + w.Remove( &GoLeftBtn ); + w.Remove( &MainButton1 ); + w.Remove( &MainButton2 ); + w.Remove( &MainButton3 ); + w.Remove( &MainButton4 ); + titleTxt.SetText( tr( "Custom Paths" ) ); + exit = false; + options2.SetLength( 0 ); +// optionBrowser2.SetScrollbar(1); + w.Append( &optionBrowser2 ); + optionBrowser2.SetClickable( true ); + ResumeGui(); - 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) - { - bool firstRun = true; - while (!exit) - { - usleep(100); + if ( Settings.godmode ) + { + bool firstRun = true; + while ( !exit ) + { + usleep( 100 ); - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); + if ( shutdown == 1 ) + Sys_Shutdown(); + if ( reset == 1 ) + Sys_Reboot(); - else if (backBtn.GetState() == STATE_CLICKED) - { - backBtn.ResetState(); - exit = true; - break; - } + else if ( backBtn.GetState() == STATE_CLICKED ) + { + backBtn.ResetState(); + exit = true; + break; + } - else if (homo.GetState() == STATE_CLICKED) - { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } + else if ( homo.GetState() == STATE_CLICKED ) + { + cfg_save_global(); + optionBrowser2.SetState( STATE_DISABLED ); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if ( choice == 3 ) + Sys_LoadMenu(); // Back to System Menu + else if ( choice == 2 ) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState( STATE_DEFAULT ); + } - ret = optionBrowser2.GetClickedOption(); + ret = optionBrowser2.GetClickedOption(); - if(firstRun || ret >= 0) - { + if ( firstRun || ret >= 0 ) + { - int Idx = -1; - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("3D Cover Path")); - if(ret == Idx) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.covers_path, sizeof(entered)); - titleTxt.SetText(tr("3D Cover Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) - { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.covers_path, entered, sizeof(Settings.covers_path)); - WindowPrompt(tr("Cover Path Changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.covers_path); - } + int Idx = -1; + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "3D Cover Path" ) ); + if ( ret == Idx ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[100] = ""; + strlcpy( entered, Settings.covers_path, sizeof( entered ) ); + titleTxt.SetText( tr( "3D Cover Path" ) ); + int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + titleTxt.SetText( tr( "Custom Paths" ) ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( Settings.covers_path, entered, sizeof( Settings.covers_path ) ); + WindowPrompt( tr( "Cover Path Changed" ), 0, tr( "OK" ) ); + if ( !isInserted( bootDevice ) ) + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ) ); + } + } + options2.SetValue( Idx, "%s", Settings.covers_path ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("2D Cover Path")); - if(ret == Idx) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.covers2d_path, sizeof(entered)); - titleTxt.SetText(tr("2D Cover Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) - { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.covers2d_path, entered, sizeof(Settings.covers2d_path)); - WindowPrompt(tr("Cover Path Changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.covers2d_path); - } + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "2D Cover Path" ) ); + if ( ret == Idx ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[100] = ""; + strlcpy( entered, Settings.covers2d_path, sizeof( entered ) ); + titleTxt.SetText( tr( "2D Cover Path" ) ); + int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + titleTxt.SetText( tr( "Custom Paths" ) ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( Settings.covers2d_path, entered, sizeof( Settings.covers2d_path ) ); + WindowPrompt( tr( "Cover Path Changed" ), 0, tr( "OK" ) ); + if ( !isInserted( bootDevice ) ) + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ) ); + } + } + options2.SetValue( Idx, "%s", Settings.covers2d_path ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("Disc Artwork Path")); - if(ret == Idx) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.disc_path, sizeof(entered)); - titleTxt.SetText(tr("Disc Artwork Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) - { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.disc_path, entered, sizeof(Settings.disc_path)); - WindowPrompt(tr("Disc Path Changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.disc_path); - } + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Disc Artwork Path" ) ); + if ( ret == Idx ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[100] = ""; + strlcpy( entered, Settings.disc_path, sizeof( entered ) ); + titleTxt.SetText( tr( "Disc Artwork Path" ) ); + int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + titleTxt.SetText( tr( "Custom Paths" ) ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( Settings.disc_path, entered, sizeof( Settings.disc_path ) ); + WindowPrompt( tr( "Disc Path Changed" ), 0, tr( "OK" ) ); + if ( !isInserted( bootDevice ) ) + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ) ); + } + } + options2.SetValue( Idx, "%s", Settings.disc_path ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("Theme Path")); - if(ret == Idx) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - titleTxt.SetText(tr("Theme Path")); - strlcpy(entered, CFG.theme_path, sizeof(entered)); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - HaltGui(); - w.RemoveAll(); - if ( result == 1 ) - { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(CFG.theme_path, entered, sizeof(CFG.theme_path)); - WindowPrompt(tr("Theme Path Changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - else - cfg_save_global(); - mainWindow->Remove(bgImg); - HaltGui(); - CFG_Load(); - CFG_LoadGlobal(); - ResumeGui(); - menu = MENU_SETTINGS; - snprintf(imgPath, sizeof(imgPath), "%splayer1_point.png", CFG.theme_path); - pointer[0] = new GuiImageData(imgPath, player1_point_png); - snprintf(imgPath, sizeof(imgPath), "%splayer2_point.png", CFG.theme_path); - pointer[1] = new GuiImageData(imgPath, player2_point_png); - snprintf(imgPath, sizeof(imgPath), "%splayer3_point.png", CFG.theme_path); - pointer[2] = new GuiImageData(imgPath, player3_point_png); - snprintf(imgPath, sizeof(imgPath), "%splayer4_point.png", CFG.theme_path); - pointer[3] = new GuiImageData(imgPath, player4_point_png); - if (CFG.widescreen) - snprintf(imgPath, sizeof(imgPath), "%swbackground.png", CFG.theme_path); - else - snprintf(imgPath, sizeof(imgPath), "%sbackground.png", CFG.theme_path); + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Theme Path" ) ); + if ( ret == Idx ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[100] = ""; + titleTxt.SetText( tr( "Theme Path" ) ); + strlcpy( entered, CFG.theme_path, sizeof( entered ) ); + int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + HaltGui(); + w.RemoveAll(); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( CFG.theme_path, entered, sizeof( CFG.theme_path ) ); + WindowPrompt( tr( "Theme Path Changed" ), 0, tr( "OK" ) ); + if ( !isInserted( bootDevice ) ) + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ) ); + else + cfg_save_global(); + mainWindow->Remove( bgImg ); + HaltGui(); + CFG_Load(); + CFG_LoadGlobal(); + ResumeGui(); + menu = MENU_SETTINGS; + snprintf( imgPath, sizeof( imgPath ), "%splayer1_point.png", CFG.theme_path ); + pointer[0] = new GuiImageData( imgPath, player1_point_png ); + snprintf( imgPath, sizeof( imgPath ), "%splayer2_point.png", CFG.theme_path ); + pointer[1] = new GuiImageData( imgPath, player2_point_png ); + snprintf( imgPath, sizeof( imgPath ), "%splayer3_point.png", CFG.theme_path ); + pointer[2] = new GuiImageData( imgPath, player3_point_png ); + snprintf( imgPath, sizeof( imgPath ), "%splayer4_point.png", CFG.theme_path ); + pointer[3] = new GuiImageData( imgPath, player4_point_png ); + if ( CFG.widescreen ) + snprintf( imgPath, sizeof( imgPath ), "%swbackground.png", CFG.theme_path ); + else + snprintf( imgPath, sizeof( imgPath ), "%sbackground.png", CFG.theme_path ); - background = new GuiImageData(imgPath, CFG.widescreen? wbackground_png : background_png); + background = new GuiImageData( imgPath, CFG.widescreen ? wbackground_png : background_png ); - bgImg = new GuiImage(background); - mainWindow->Append(bgImg); - mainWindow->Append(&w); - } - w.Append(&settingsbackground); - w.Append(&titleTxt); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&backBtn); - w.Append(&optionBrowser2); - ResumeGui(); - } - options2.SetValue(Idx, "%s", CFG.theme_path); - } + bgImg = new GuiImage( background ); + mainWindow->Append( bgImg ); + mainWindow->Append( &w ); + } + w.Append( &settingsbackground ); + w.Append( &titleTxt ); + titleTxt.SetText( tr( "Custom Paths" ) ); + w.Append( &backBtn ); + w.Append( &optionBrowser2 ); + ResumeGui(); + } + options2.SetValue( Idx, "%s", CFG.theme_path ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("WiiTDB Path")); - if(ret == Idx) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - titleTxt.SetText(tr("WiiTDB Path")); - strlcpy(entered, Settings.titlestxt_path, sizeof(entered)); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - w.Append(&optionBrowser2); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&backBtn); - if ( result == 1 ) - { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.titlestxt_path, entered, sizeof(Settings.titlestxt_path)); - WindowPrompt(tr("WiiTDB Path changed."),0,tr("OK")); - if (isInserted(bootDevice)) - { - cfg_save_global(); - HaltGui(); - CFG_Load(); - ResumeGui(); - } - else - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.titlestxt_path); - } + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "WiiTDB Path" ) ); + if ( ret == Idx ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[100] = ""; + titleTxt.SetText( tr( "WiiTDB Path" ) ); + strlcpy( entered, Settings.titlestxt_path, sizeof( entered ) ); + int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + w.Append( &optionBrowser2 ); + titleTxt.SetText( tr( "Custom Paths" ) ); + w.Append( &backBtn ); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( Settings.titlestxt_path, entered, sizeof( Settings.titlestxt_path ) ); + WindowPrompt( tr( "WiiTDB Path changed." ), 0, tr( "OK" ) ); + if ( isInserted( bootDevice ) ) + { + cfg_save_global(); + HaltGui(); + CFG_Load(); + ResumeGui(); + } + else + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ) ); + } + } + options2.SetValue( Idx, "%s", Settings.titlestxt_path ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("Update Path")); - if(ret == Idx) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.update_path, sizeof(entered)); - titleTxt.SetText(tr("Update Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) - { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.update_path, entered, sizeof(Settings.update_path)); - WindowPrompt(tr("Update Path changed."),0,tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.update_path); - } + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Update Path" ) ); + if ( ret == Idx ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[100] = ""; + strlcpy( entered, Settings.update_path, sizeof( entered ) ); + titleTxt.SetText( tr( "Update Path" ) ); + int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + titleTxt.SetText( tr( "Custom Paths" ) ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( Settings.update_path, entered, sizeof( Settings.update_path ) ); + WindowPrompt( tr( "Update Path changed." ), 0, tr( "OK" ) ); + } + } + options2.SetValue( Idx, "%s", Settings.update_path ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("GCT Cheatcodes Path")); - if(ret == Idx) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.Cheatcodespath, sizeof(entered)); - titleTxt.SetText(tr("GCT Cheatcodes Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) - { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.Cheatcodespath, entered, sizeof(Settings.Cheatcodespath)); - WindowPrompt(tr("GCT Cheatcodes Path changed"),0,tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.Cheatcodespath); - } + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "GCT Cheatcodes Path" ) ); + if ( ret == Idx ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[100] = ""; + strlcpy( entered, Settings.Cheatcodespath, sizeof( entered ) ); + titleTxt.SetText( tr( "GCT Cheatcodes Path" ) ); + int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + titleTxt.SetText( tr( "Custom Paths" ) ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( Settings.Cheatcodespath, entered, sizeof( Settings.Cheatcodespath ) ); + WindowPrompt( tr( "GCT Cheatcodes Path changed" ), 0, tr( "OK" ) ); + } + } + options2.SetValue( Idx, "%s", Settings.Cheatcodespath ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("TXT Cheatcodes Path")); - if(ret == Idx) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.TxtCheatcodespath, sizeof(entered)); - titleTxt.SetText(tr("TXT Cheatcodes Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) - { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.TxtCheatcodespath, entered, sizeof(Settings.TxtCheatcodespath)); - WindowPrompt(tr("TXT Cheatcodes Path changed"),0,tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.TxtCheatcodespath); - } + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "TXT Cheatcodes Path" ) ); + if ( ret == Idx ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[100] = ""; + strlcpy( entered, Settings.TxtCheatcodespath, sizeof( entered ) ); + titleTxt.SetText( tr( "TXT Cheatcodes Path" ) ); + int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + titleTxt.SetText( tr( "Custom Paths" ) ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( Settings.TxtCheatcodespath, entered, sizeof( Settings.TxtCheatcodespath ) ); + WindowPrompt( tr( "TXT Cheatcodes Path changed" ), 0, tr( "OK" ) ); + } + } + options2.SetValue( Idx, "%s", Settings.TxtCheatcodespath ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("DOL Path")); - if(ret == Idx) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.dolpath, sizeof(entered)); - titleTxt.SetText(tr("DOL Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) - { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.dolpath, entered, sizeof(Settings.dolpath)); - WindowPrompt(tr("DOL path changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - { - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - } - options2.SetValue(Idx, "%s", Settings.dolpath); - } + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "DOL Path" ) ); + if ( ret == Idx ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[100] = ""; + strlcpy( entered, Settings.dolpath, sizeof( entered ) ); + titleTxt.SetText( tr( "DOL Path" ) ); + int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + titleTxt.SetText( tr( "Custom Paths" ) ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( Settings.dolpath, entered, sizeof( Settings.dolpath ) ); + WindowPrompt( tr( "DOL path changed" ), 0, tr( "OK" ) ); + if ( !isInserted( bootDevice ) ) + { + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ) ); + } + } + } + options2.SetValue( Idx, "%s", Settings.dolpath ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("Homebrew Apps Path")); - if(ret == Idx) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.homebrewapps_path, sizeof(entered)); - titleTxt.SetText(tr("Homebrew Apps Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) - { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.homebrewapps_path, entered, sizeof(Settings.homebrewapps_path)); - WindowPrompt(tr("Homebrew Appspath changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - { - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - } - options2.SetValue(Idx, "%s", Settings.homebrewapps_path); - } + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Homebrew Apps Path" ) ); + if ( ret == Idx ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[100] = ""; + strlcpy( entered, Settings.homebrewapps_path, sizeof( entered ) ); + titleTxt.SetText( tr( "Homebrew Apps Path" ) ); + int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + titleTxt.SetText( tr( "Custom Paths" ) ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( Settings.homebrewapps_path, entered, sizeof( Settings.homebrewapps_path ) ); + WindowPrompt( tr( "Homebrew Appspath changed" ), 0, tr( "OK" ) ); + if ( !isInserted( bootDevice ) ) + { + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ) ); + } + } + } + options2.SetValue( Idx, "%s", Settings.homebrewapps_path ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("Theme Download Path")); - if(ret == Idx) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.theme_downloadpath, sizeof(entered)); - titleTxt.SetText(tr("Theme Download Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) - { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.theme_downloadpath, entered, sizeof(Settings.theme_downloadpath)); - WindowPrompt(tr("Theme Download Path changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.theme_downloadpath); - } + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Theme Download Path" ) ); + if ( ret == Idx ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[100] = ""; + strlcpy( entered, Settings.theme_downloadpath, sizeof( entered ) ); + titleTxt.SetText( tr( "Theme Download Path" ) ); + int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + titleTxt.SetText( tr( "Custom Paths" ) ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( Settings.theme_downloadpath, entered, sizeof( Settings.theme_downloadpath ) ); + WindowPrompt( tr( "Theme Download Path changed" ), 0, tr( "OK" ) ); + if ( !isInserted( bootDevice ) ) + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ) ); + } + } + options2.SetValue( Idx, "%s", Settings.theme_downloadpath ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("BCA Codes Path")); - if(ret == Idx) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.BcaCodepath, sizeof(entered)); - titleTxt.SetText(tr("BCA Codes Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) - { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.BcaCodepath, entered, sizeof(Settings.BcaCodepath)); - WindowPrompt(tr("BCA Codes Path changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.BcaCodepath); - } + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "BCA Codes Path" ) ); + if ( ret == Idx ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[100] = ""; + strlcpy( entered, Settings.BcaCodepath, sizeof( entered ) ); + titleTxt.SetText( tr( "BCA Codes Path" ) ); + int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + titleTxt.SetText( tr( "Custom Paths" ) ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( Settings.BcaCodepath, entered, sizeof( Settings.BcaCodepath ) ); + WindowPrompt( tr( "BCA Codes Path changed" ), 0, tr( "OK" ) ); + if ( !isInserted( bootDevice ) ) + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ) ); + } + } + options2.SetValue( Idx, "%s", Settings.BcaCodepath ); + } - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("WIP Patches Path")); - if(ret == Idx) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - char entered[100] = ""; - strlcpy(entered, Settings.WipCodepath, sizeof(entered)); - titleTxt.SetText(tr("WIP Patches Path")); - int result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT, noFILES); - titleTxt.SetText(tr("Custom Paths")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - if ( result == 1 ) - { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.WipCodepath, entered, sizeof(Settings.WipCodepath)); - WindowPrompt(tr("WIP Patches Path changed"),0,tr("OK")); - if (!isInserted(bootDevice)) - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - } - } - options2.SetValue(Idx, "%s", Settings.WipCodepath); - } + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "WIP Patches Path" ) ); + if ( ret == Idx ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + char entered[100] = ""; + strlcpy( entered, Settings.WipCodepath, sizeof( entered ) ); + titleTxt.SetText( tr( "WIP Patches Path" ) ); + int result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT, noFILES ); + titleTxt.SetText( tr( "Custom Paths" ) ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( Settings.WipCodepath, entered, sizeof( Settings.WipCodepath ) ); + WindowPrompt( tr( "WIP Patches Path changed" ), 0, tr( "OK" ) ); + if ( !isInserted( bootDevice ) ) + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ) ); + } + } + options2.SetValue( Idx, "%s", Settings.WipCodepath ); + } - firstRun = false; - } - } - /** If not godmode don't let him inside **/ - } - else - WindowPrompt(tr("Console Locked"),tr("Unlock console to use this option."),tr("OK")); - optionBrowser2.SetEffect(EFFECT_FADE, -20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - titleTxt.SetText(tr("Settings")); - slidedirection = FADE; - pageToDisplay = 2; - MainButton1.ResetState(); - break; - } + firstRun = false; + } + } + /** If not godmode don't let him inside **/ + } + else + WindowPrompt( tr( "Console Locked" ), tr( "Unlock console to use this option." ), tr( "OK" ) ); + optionBrowser2.SetEffect( EFFECT_FADE, -20 ); + while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + titleTxt.SetText( tr( "Settings" ) ); + slidedirection = FADE; + pageToDisplay = 2; + MainButton1.ResetState(); + break; + } - else if (MainButton2.GetState() == STATE_CLICKED) - { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton2.GetEffect() > 0) usleep(50); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - if (isInserted(bootDevice) && Settings.godmode) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - int ret = ProgressUpdateWindow(); - if (ret < 0) - WindowPrompt(tr("Update failed"),0,tr("OK")); - w.Append(&optionBrowser2); - w.Append(&backBtn); - } - else - WindowPrompt(tr("Console Locked"),tr("Unlock console to use this option."),tr("OK")); - slidedirection = FADE; - pageToDisplay = 2; - MainButton2.ResetState(); - break; - } + else if ( MainButton2.GetState() == STATE_CLICKED ) + { + MainButton1.SetEffect( EFFECT_FADE, -20 ); + MainButton2.SetEffect( EFFECT_FADE, -20 ); + MainButton3.SetEffect( EFFECT_FADE, -20 ); + MainButton4.SetEffect( EFFECT_FADE, -20 ); + while ( MainButton2.GetEffect() > 0 ) usleep( 50 ); + w.Remove( &PageIndicatorBtn1 ); + w.Remove( &PageIndicatorBtn2 ); + w.Remove( &PageIndicatorBtn3 ); + w.Remove( &GoRightBtn ); + w.Remove( &GoLeftBtn ); + w.Remove( &MainButton1 ); + w.Remove( &MainButton2 ); + w.Remove( &MainButton3 ); + w.Remove( &MainButton4 ); + if ( isInserted( bootDevice ) && Settings.godmode ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + int ret = ProgressUpdateWindow(); + if ( ret < 0 ) + WindowPrompt( tr( "Update failed" ), 0, tr( "OK" ) ); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + } + else + WindowPrompt( tr( "Console Locked" ), tr( "Unlock console to use this option." ), tr( "OK" ) ); + slidedirection = FADE; + pageToDisplay = 2; + MainButton2.ResetState(); + break; + } - else if (MainButton3.GetState() == STATE_CLICKED) - { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton3.GetEffect() > 0) usleep(50); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - w.Remove(&backBtn); - w.Remove(&optionBrowser2); - if (Settings.godmode) - { - int choice = WindowPrompt(tr("Are you sure?"), 0, tr("Yes"), tr("Cancel")); - if (choice == 1) - { - if (isInserted(bootDevice)) - { - char GXGlobal_cfg[26]; - sprintf(GXGlobal_cfg, "%s/config/GXGlobal.cfg", bootDevice); - remove(GXGlobal_cfg); - } - gettextCleanUp(); - HaltGui(); - CFG_Load(); - ResumeGui(); - menu = MENU_SETTINGS; - pageToDisplay = 0; - } - } - else - WindowPrompt(tr("Console Locked"),tr("Unlock console to use this option."),tr("OK")); - w.Append(&backBtn); - w.Append(&optionBrowser2); - slidedirection = FADE; - pageToDisplay = 2; - MainButton3.ResetState(); - break; - } + else if ( MainButton3.GetState() == STATE_CLICKED ) + { + MainButton1.SetEffect( EFFECT_FADE, -20 ); + MainButton2.SetEffect( EFFECT_FADE, -20 ); + MainButton3.SetEffect( EFFECT_FADE, -20 ); + MainButton4.SetEffect( EFFECT_FADE, -20 ); + while ( MainButton3.GetEffect() > 0 ) usleep( 50 ); + w.Remove( &PageIndicatorBtn1 ); + w.Remove( &PageIndicatorBtn2 ); + w.Remove( &PageIndicatorBtn3 ); + w.Remove( &GoRightBtn ); + w.Remove( &GoLeftBtn ); + w.Remove( &MainButton1 ); + w.Remove( &MainButton2 ); + w.Remove( &MainButton3 ); + w.Remove( &MainButton4 ); + w.Remove( &backBtn ); + w.Remove( &optionBrowser2 ); + if ( Settings.godmode ) + { + int choice = WindowPrompt( tr( "Are you sure?" ), 0, tr( "Yes" ), tr( "Cancel" ) ); + if ( choice == 1 ) + { + if ( isInserted( bootDevice ) ) + { + char GXGlobal_cfg[26]; + sprintf( GXGlobal_cfg, "%s/config/GXGlobal.cfg", bootDevice ); + remove( GXGlobal_cfg ); + } + gettextCleanUp(); + HaltGui(); + CFG_Load(); + ResumeGui(); + menu = MENU_SETTINGS; + pageToDisplay = 0; + } + } + else + WindowPrompt( tr( "Console Locked" ), tr( "Unlock console to use this option." ), tr( "OK" ) ); + w.Append( &backBtn ); + w.Append( &optionBrowser2 ); + slidedirection = FADE; + pageToDisplay = 2; + MainButton3.ResetState(); + break; + } - else if (MainButton4.GetState() == STATE_CLICKED) - { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton4.GetEffect() > 0) usleep(50); - w.Remove(&PageIndicatorBtn1); - w.Remove(&PageIndicatorBtn2); - w.Remove(&PageIndicatorBtn3); - w.Remove(&GoRightBtn); - w.Remove(&GoLeftBtn); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - WindowCredits(); - slidedirection = FADE; - pageToDisplay = 2; - MainButton4.ResetState(); - break; - } - } + else if ( MainButton4.GetState() == STATE_CLICKED ) + { + MainButton1.SetEffect( EFFECT_FADE, -20 ); + MainButton2.SetEffect( EFFECT_FADE, -20 ); + MainButton3.SetEffect( EFFECT_FADE, -20 ); + MainButton4.SetEffect( EFFECT_FADE, -20 ); + while ( MainButton4.GetEffect() > 0 ) usleep( 50 ); + w.Remove( &PageIndicatorBtn1 ); + w.Remove( &PageIndicatorBtn2 ); + w.Remove( &PageIndicatorBtn3 ); + w.Remove( &GoRightBtn ); + w.Remove( &GoLeftBtn ); + w.Remove( &MainButton1 ); + w.Remove( &MainButton2 ); + w.Remove( &MainButton3 ); + w.Remove( &MainButton4 ); + WindowCredits(); + slidedirection = FADE; + pageToDisplay = 2; + MainButton4.ResetState(); + break; + } + } - else if(pageToDisplay == 3) - { - if (MainButton1.GetState() == STATE_CLICKED) - { - if (isInserted(bootDevice)) - cfg_save_global(); - menu = MENU_THEMEDOWNLOADER; - pageToDisplay = 0; - break; - } - } + else if ( pageToDisplay == 3 ) + { + if ( MainButton1.GetState() == STATE_CLICKED ) + { + if ( isInserted( bootDevice ) ) + cfg_save_global(); + menu = MENU_THEMEDOWNLOADER; + pageToDisplay = 0; + break; + } + } - if (backBtn.GetState() == STATE_CLICKED) - { - //Add the procedure call to save the global configuration - if (isInserted(bootDevice)) - cfg_save_global(); - menu = MENU_DISCLIST; - pageToDisplay = 0; - backBtn.ResetState(); - break; - } + if ( backBtn.GetState() == STATE_CLICKED ) + { + //Add the procedure call to save the global configuration + if ( isInserted( bootDevice ) ) + cfg_save_global(); + menu = MENU_DISCLIST; + pageToDisplay = 0; + backBtn.ResetState(); + break; + } - else if (GoLeftBtn.GetState() == STATE_CLICKED) - { - pageToDisplay--; - /** Change direction of the flying buttons **/ - if (pageToDisplay < 1) - pageToDisplay = 3; - slidedirection = LEFT; - GoLeftBtn.ResetState(); - break; - } + else if ( GoLeftBtn.GetState() == STATE_CLICKED ) + { + pageToDisplay--; + /** Change direction of the flying buttons **/ + if ( pageToDisplay < 1 ) + pageToDisplay = 3; + slidedirection = LEFT; + GoLeftBtn.ResetState(); + break; + } - else if (GoRightBtn.GetState() == STATE_CLICKED) - { - pageToDisplay++; - /** Change direction of the flying buttons **/ - if (pageToDisplay > 3) - pageToDisplay = 1; - slidedirection = RIGHT; - GoRightBtn.ResetState(); - break; - } - else if (PageIndicatorBtn1.GetState() == STATE_CLICKED) - { - if (pageToDisplay > 1) - { - slidedirection = LEFT; - pageToDisplay = 1; - PageIndicatorBtn1.ResetState(); - break; - } - PageIndicatorBtn1.ResetState(); - } - else if (PageIndicatorBtn2.GetState() == STATE_CLICKED) - { - if (pageToDisplay < 2) - { - slidedirection = RIGHT; - pageToDisplay = 2; - PageIndicatorBtn2.ResetState(); - break; - } - else if (pageToDisplay > 2) - { - slidedirection = LEFT; - pageToDisplay = 2; - PageIndicatorBtn2.ResetState(); - break; - } - else - PageIndicatorBtn2.ResetState(); - } - else if (PageIndicatorBtn3.GetState() == STATE_CLICKED) - { - if (pageToDisplay < 3) - { - slidedirection = RIGHT; - pageToDisplay = 3; - PageIndicatorBtn3.ResetState(); - break; - } - else - PageIndicatorBtn3.ResetState(); - } - else if (homo.GetState() == STATE_CLICKED) - { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); + else if ( GoRightBtn.GetState() == STATE_CLICKED ) + { + pageToDisplay++; + /** Change direction of the flying buttons **/ + if ( pageToDisplay > 3 ) + pageToDisplay = 1; + slidedirection = RIGHT; + GoRightBtn.ResetState(); + break; + } + else if ( PageIndicatorBtn1.GetState() == STATE_CLICKED ) + { + if ( pageToDisplay > 1 ) + { + slidedirection = LEFT; + pageToDisplay = 1; + PageIndicatorBtn1.ResetState(); + break; + } + PageIndicatorBtn1.ResetState(); + } + else if ( PageIndicatorBtn2.GetState() == STATE_CLICKED ) + { + if ( pageToDisplay < 2 ) + { + slidedirection = RIGHT; + pageToDisplay = 2; + PageIndicatorBtn2.ResetState(); + break; + } + else if ( pageToDisplay > 2 ) + { + slidedirection = LEFT; + pageToDisplay = 2; + PageIndicatorBtn2.ResetState(); + break; + } + else + PageIndicatorBtn2.ResetState(); + } + else if ( PageIndicatorBtn3.GetState() == STATE_CLICKED ) + { + if ( pageToDisplay < 3 ) + { + slidedirection = RIGHT; + pageToDisplay = 3; + PageIndicatorBtn3.ResetState(); + break; + } + else + PageIndicatorBtn3.ResetState(); + } + else if ( homo.GetState() == STATE_CLICKED ) + { + cfg_save_global(); + optionBrowser2.SetState( STATE_DISABLED ); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - } - } + if ( choice == 3 ) + Sys_LoadMenu(); // Back to System Menu + else if ( choice == 2 ) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState( STATE_DEFAULT ); + } + } + } - w.SetEffect(EFFECT_FADE, -20); - while (w.GetEffect()>0) usleep(50); + w.SetEffect( EFFECT_FADE, -20 ); + while ( w.GetEffect() > 0 ) usleep( 50 ); - // if partition has changed, Reinitialize it - if (Settings.partition != settingspartitionold) { - 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); - load_from_fs = pinfo.part_fs; - } + // if partition has changed, Reinitialize it + 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 ); + load_from_fs = pinfo.part_fs; + } - // if language has changed, reload titles - char opt_langnew[100]; - strcpy(opt_langnew,Settings.language_path); - int opt_overridenew = Settings.titlesOverride; - bool reloaddatabasefile = false; - if (strcmp(opt_lang,opt_langnew) || (opt_override != opt_overridenew && Settings.titlesOverride==1) || (Settings.partition != settingspartitionold)) { - if (Settings.partition != settingspartitionold) { - reloaddatabasefile = true; - CloseXMLDatabase(); - 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 - } - // disable titles from database if setting has changed - if (opt_override != opt_overridenew && Settings.titlesOverride==0) - titles_default(); + // if language has changed, reload titles + char opt_langnew[100]; + strcpy( opt_langnew, Settings.language_path ); + int opt_overridenew = Settings.titlesOverride; + bool reloaddatabasefile = false; + if ( strcmp( opt_lang, opt_langnew ) || ( opt_override != opt_overridenew && Settings.titlesOverride == 1 ) || ( Settings.partition != settingspartitionold ) ) + { + if ( Settings.partition != settingspartitionold ) + { + reloaddatabasefile = true; + CloseXMLDatabase(); + 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 + } + // disable titles from database if setting has changed + if ( opt_override != opt_overridenew && Settings.titlesOverride == 0 ) + titles_default(); - HaltGui(); + HaltGui(); - mainWindow->RemoveAll(); - mainWindow->Append(bgImg); + mainWindow->RemoveAll(); + mainWindow->Append( bgImg ); - ResumeGui(); - return menu; - } + ResumeGui(); + return menu; +} /******************************************************************************** *Game specific settings *********************************************************************************/ -int GameSettings(struct discHdr * header) +int GameSettings( struct discHdr * header ) { - int menu = MENU_NONE; - int ret; - int choice = 0; - bool exit = false; - - int retVal = 0; - - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - GuiSound btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); - - char imgPath[100]; - - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path); - GuiImageData settingsbg(imgPath, settings_background_png); - - snprintf(imgPath, sizeof(imgPath), "%ssettings_title.png", CFG.theme_path); - GuiImageData MainButtonImgData(imgPath, settings_title_png); - - snprintf(imgPath, sizeof(imgPath), "%ssettings_title_over.png", CFG.theme_path); - GuiImageData MainButtonImgOverData(imgPath, settings_title_over_png); - - GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); - GuiTrigger trigHome; - trigHome.SetButtonOnlyTrigger(-1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0); - GuiTrigger trigB; - trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B); - - char gameName[31]; - if (!mountMethod) - { - if (strlen(get_title(header)) < (27 + 3)) - sprintf(gameName, "%s", get_title(header)); - else - { - strncpy(gameName, get_title(header), 27); - gameName[27] = '\0'; - strncat(gameName, "...", 3); - } - } - else - sprintf(gameName, "%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); - - 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); - - GuiText backBtnTxt(tr("Back"), 22, THEME.prompttext); - backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); - GuiImage backBtnImg(&btnOutline); - if (Settings.wsprompt == yes) - { - backBtnTxt.SetWidescreen(CFG.widescreen); - backBtnImg.SetWidescreen(CFG.widescreen); - } - GuiButton backBtn(&backBtnImg,&backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2,1); - backBtn.SetLabel(&backBtnTxt); - backBtn.SetTrigger(&trigB); - - GuiButton homo(1,1); - homo.SetTrigger(&trigHome); - - GuiText saveBtnTxt(tr("Save"), 22, THEME.prompttext); - saveBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); - GuiImage saveBtnImg(&btnOutline); - if (Settings.wsprompt == yes) - { - saveBtnTxt.SetWidescreen(CFG.widescreen); - saveBtnImg.SetWidescreen(CFG.widescreen); - } - GuiButton saveBtn(&saveBtnImg,&saveBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2,1); - saveBtn.SetLabel(&saveBtnTxt); - - - - char MainButtonText[50]; - snprintf(MainButtonText, sizeof(MainButtonText), "%s", " "); - - GuiImage MainButton1Img(&MainButtonImgData); - GuiImage MainButton1ImgOver(&MainButtonImgOverData); - GuiText MainButton1Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton1Txt.SetMaxWidth(MainButton1Img.GetWidth()); - GuiButton MainButton1(MainButton1Img.GetWidth(), MainButton1Img.GetHeight()); - MainButton1.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton1.SetPosition(0, 90); - MainButton1.SetImage(&MainButton1Img); - MainButton1.SetImageOver(&MainButton1ImgOver); - MainButton1.SetLabel(&MainButton1Txt); - MainButton1.SetSoundOver(&btnSoundOver); - MainButton1.SetSoundClick(&btnClick1); - MainButton1.SetEffectGrow(); - MainButton1.SetTrigger(&trigA); - - GuiImage MainButton2Img(&MainButtonImgData); - GuiImage MainButton2ImgOver(&MainButtonImgOverData); - GuiText MainButton2Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton2Txt.SetMaxWidth(MainButton2Img.GetWidth()); - GuiButton MainButton2(MainButton2Img.GetWidth(), MainButton2Img.GetHeight()); - MainButton2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton2.SetPosition(0, 160); - MainButton2.SetImage(&MainButton2Img); - MainButton2.SetImageOver(&MainButton2ImgOver); - MainButton2.SetLabel(&MainButton2Txt); - MainButton2.SetSoundOver(&btnSoundOver); - MainButton2.SetSoundClick(&btnClick1); - MainButton2.SetEffectGrow(); - MainButton2.SetTrigger(&trigA); - - GuiImage MainButton3Img(&MainButtonImgData); - GuiImage MainButton3ImgOver(&MainButtonImgOverData); - GuiText MainButton3Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton3Txt.SetMaxWidth(MainButton3Img.GetWidth()); - GuiButton MainButton3(MainButton3Img.GetWidth(), MainButton3Img.GetHeight()); - MainButton3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton3.SetPosition(0, 230); - MainButton3.SetImage(&MainButton3Img); - MainButton3.SetImageOver(&MainButton3ImgOver); - MainButton3.SetLabel(&MainButton3Txt); - MainButton3.SetSoundOver(&btnSoundOver); - MainButton3.SetSoundClick(&btnClick1); - MainButton3.SetEffectGrow(); - MainButton3.SetTrigger(&trigA); - - GuiImage MainButton4Img(&MainButtonImgData); - GuiImage MainButton4ImgOver(&MainButtonImgOverData); - GuiText MainButton4Txt(MainButtonText, 22, (GXColor) {0, 0, 0, 255}); - MainButton4Txt.SetMaxWidth(MainButton4Img.GetWidth()); - GuiButton MainButton4(MainButton4Img.GetWidth(), MainButton4Img.GetHeight()); - MainButton4.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - MainButton4.SetPosition(0, 300); - MainButton4.SetImage(&MainButton4Img); - MainButton4.SetImageOver(&MainButton4ImgOver); - MainButton4.SetLabel(&MainButton4Txt); - MainButton4.SetSoundOver(&btnSoundOver); - MainButton4.SetSoundClick(&btnClick1); - MainButton4.SetEffectGrow(); - MainButton4.SetTrigger(&trigA); - - customOptionList options2(MAXOPTIONS); - GuiCustomOptionBrowser optionBrowser2(396, 280, &options2, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, 0, 150); - optionBrowser2.SetPosition(0, 90); - optionBrowser2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - - GuiWindow w(screenwidth, screenheight); - //int opt_lang = languageChoice; // backup language setting - struct Game_CFG* game_cfg = CFG_get_game_opt(header->id); - - int pageToDisplay = 1; - while ( pageToDisplay > 0) - { - usleep(100); - - menu = MENU_NONE; - - /** Standard procedure made in all pages **/ - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); - - 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); - - mainWindow->RemoveAll(); - mainWindow->Append(&w); - w.RemoveAll(); - w.Append(&settingsbackground); - w.Append(&titleTxt); - w.Append(&backBtn); - w.Append(&homo); - w.Append(&MainButton1); - w.Append(&MainButton2); - w.Append(&MainButton3); - w.Append(&MainButton4); - - /** Disable ability to click through MainButtons */ - optionBrowser2.SetClickable(false); - /** Default no scrollbar and reset position **/ -// optionBrowser2.SetScrollbar(0); - optionBrowser2.SetOffset(0); - - MainButton1.StopEffect(); - MainButton2.StopEffect(); - MainButton3.StopEffect(); - MainButton4.StopEffect(); - - MainButton1.SetEffectGrow(); - MainButton2.SetEffectGrow(); - MainButton3.SetEffectGrow(); - MainButton4.SetEffectGrow(); - - - MainButton1.SetEffect(EFFECT_FADE, 20); - MainButton2.SetEffect(EFFECT_FADE, 20); - MainButton3.SetEffect(EFFECT_FADE, 20); - MainButton4.SetEffect(EFFECT_FADE, 20); - - mainWindow->Append(&w); - - - - if (game_cfg) { //if there are saved settings for this game use them - videoChoice = game_cfg->video; - languageChoice = game_cfg->language; - ocarinaChoice = game_cfg->ocarina; - viChoice = game_cfg->vipatch; - iosChoice = game_cfg->ios; - parentalcontrolChoice = game_cfg->parentalcontrol; - fix002 = game_cfg->errorfix002; - countrystrings = game_cfg->patchcountrystrings; - alternatedol = game_cfg->loadalternatedol; - alternatedoloffset = game_cfg->alternatedolstart; - reloadblock = game_cfg->iosreloadblock; - strlcpy(alternatedname, game_cfg->alternatedolname, sizeof(alternatedname)); - } - else - { - videoChoice = Settings.video; - languageChoice = Settings.language; - ocarinaChoice = Settings.ocarina; - viChoice = Settings.vpatch; - if (Settings.cios == ios222) - iosChoice = i222; - else if (Settings.cios == ios250) - iosChoice = i250; - else if (Settings.cios == ios223) - iosChoice = i223; - else - iosChoice = i249; - parentalcontrolChoice = 0; - fix002 = Settings.error002; - countrystrings = Settings.patchcountrystrings; - alternatedol = off; - alternatedoloffset = 0; - reloadblock = off; - strcpy(alternatedname, ""); - } - - ResumeGui(); - - while (MainButton1.GetEffect() > 0) usleep(50); - - - - while (menu == MENU_NONE) - { - usleep(100); - - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - - if (MainButton1.GetState() == STATE_CLICKED) - { - w.Append(&saveBtn); - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton1.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - exit = false; - options2.SetLength(0); -// optionBrowser2.SetScrollbar(1); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); - - optionBrowser2.SetEffect(EFFECT_FADE, 20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - - int returnhere = 1; - char * languagefile; - languagefile = strrchr(Settings.language_path, '/')+1; - - bool firstRun = true; - while (!exit) - { - usleep(100); - - returnhere = 1; - - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - if (backBtn.GetState() == STATE_CLICKED) - { - backBtn.ResetState(); - exit = true; - break; - } - - else if (menu == MENU_DISCLIST) - { - w.Remove(&optionBrowser2); - w.Remove(&backBtn); - WindowCredits(); - w.Append(&optionBrowser2); - w.Append(&backBtn); - } - - else if (homo.GetState() == STATE_CLICKED) - { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - - else if (saveBtn.GetState() == STATE_CLICKED) - { - if (isInserted(bootDevice)) - { - if (CFG_save_game_opt(header->id)) - { - /* commented because the database language now depends on the main language setting, this could be enabled again if there is a separate language setting for the database - // if game language has changed when saving game settings, reload titles - int opt_langnew = 0; - game_cfg = CFG_get_game_opt(header->id); - if (game_cfg) opt_langnew = game_cfg->language; - if (Settings.titlesOverride==1 && opt_lang != opt_langnew) - OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, true, false); // open file, reload titles, do not keep in memory - // titles are refreshed in menu.cpp as soon as this function returns - */ - game_cfg = CFG_get_game_opt(header->id); // needed here for "if (game_cfg)" earlier in case it's the first time settings are saved for a game - WindowPrompt(tr("Successfully Saved"),0,tr("OK")); - } - else - WindowPrompt(tr("Save Failed"),0,tr("OK")); - } - else - WindowPrompt(tr("No SD-Card inserted!"),tr("Insert an SD-Card to save."),tr("OK")); - - saveBtn.ResetState(); - optionBrowser2.SetFocus(1); - } - - ret = optionBrowser2.GetClickedOption(); - - if(ret >= 0 || firstRun == true) - { - int Idx = -1; - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("Video Mode")); - if(ret == Idx && ++videoChoice >= settings_video_max) - videoChoice = 0; - options2.SetValue(Idx,"%s%s",opts_videomode[videoChoice][0], tr(opts_videomode[videoChoice][1])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s",tr("VIDTV Patch")); - if(ret == Idx && ++viChoice >= settings_off_on_max) - viChoice = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[viChoice])); - - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("Game Language")); - if(ret == Idx && ++languageChoice >= settings_language_max) - languageChoice = 0; - options2.SetValue(Idx,"%s",tr(opts_language[languageChoice])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "Ocarina"); - if(ret == Idx && ++ocarinaChoice >= settings_off_on_max) - ocarinaChoice = 0; - options2.SetValue(Idx,"%s",tr(opts_off_on[ocarinaChoice])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "IOS"); - if(ret == Idx && ++iosChoice >= settings_ios_max) - iosChoice = 0; - options2.SetValue(Idx,"%s",opts_cios[iosChoice]); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("Parental Control")); - if(ret == Idx && ++parentalcontrolChoice >= 5) - parentalcontrolChoice = 0; - options2.SetValue(Idx,"%s", tr(opts_parentalcontrol[parentalcontrolChoice])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("Error 002 fix")); - if(ret == Idx && ++fix002 >= settings_error002_max) - fix002 = 0; - options2.SetValue(Idx,"%s", tr(opts_error002[fix002])); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("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(firstRun) options2.SetName(Idx, "%s", tr("Selected DOL")); - if(ret == Idx) - { - if (alternatedol == 2) - { - char filename[10]; - snprintf(filename,sizeof(filename),"%c%c%c%c%c%c",header->id[0], header->id[1], header->id[2], - header->id[3],header->id[4], header->id[5]); - int dolchoice = 0; - //alt dol menu for games that require more than a single alt dol - int autodol = autoSelectDolMenu(filename, false); - - if (autodol>0) - { - alternatedoloffset = autodol; - snprintf(alternatedname, sizeof(alternatedname), "%s <%i>", tr("AUTO"), autodol); - } - else if (autodol == 0) - alternatedol = 0; // default was chosen - else - { - //check to see if we already know the offset of the correct dol - int autodol = autoSelectDol(filename, false); - //if we do know that offset ask if they want to use it - if (autodol>0) - { - dolchoice = WindowPrompt(0,tr("Do you want to use the alternate DOL that is known to be correct?"),tr("Yes"),tr("Pick from a list"),tr("Cancel")); - if (dolchoice==0) - alternatedol = 0; - else if (dolchoice==1) - { - alternatedoloffset = autodol; - snprintf(alternatedname, sizeof(alternatedname), "%s <%i>", tr("AUTO"),autodol); - } - else if (dolchoice==2) //they want to search for the correct dol themselves - { - int res = DiscBrowse(header); - if ((res >= 0)&&(res !=696969)) //if res==696969 they pressed the back button - alternatedoloffset = res; - } - } - else - { - int res = DiscBrowse(header); - if ((res >= 0)&&(res !=696969)) - { - alternatedoloffset = res; - char tmp[170]; - snprintf(tmp,sizeof(tmp),"%s %s - %i",tr("It seems that you have some information that will be helpful to us. Please pass this information along to the DEV team.") ,filename,alternatedoloffset); - WindowPrompt(0,tmp,tr("OK")); - } - } - } - } - } - if(alternatedol == 0) - { - firstRun = true; // force re-init follow Entries - options2.SetLength(Idx--); // remove this Entry - options2.SetValue(Idx, "%s", tr("Default")); // re-set prev Entry - } - else - options2.SetValue(Idx, alternatedname); - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx, "%s", tr("Block IOS Reload")); - if(ret == Idx && ++reloadblock >= settings_off_on_max) - reloadblock = 0; - options2.SetValue(Idx,"%s", tr(opts_off_on[reloadblock])); - } - - firstRun = false; - } - } - - optionBrowser2.SetEffect(EFFECT_FADE, -20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - MainButton1.ResetState(); - break; - w.Remove(&saveBtn); - } - - else if (MainButton2.GetState() == STATE_CLICKED) - { - char ID[7]; - snprintf (ID,sizeof(ID),"%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); - CheatMenu(ID); - MainButton2.ResetState(); - break; - } - - else if (MainButton3.GetState() == STATE_CLICKED) - { - MainButton1.SetEffect(EFFECT_FADE, -20); - MainButton2.SetEffect(EFFECT_FADE, -20); - MainButton3.SetEffect(EFFECT_FADE, -20); - MainButton4.SetEffect(EFFECT_FADE, -20); - while (MainButton3.GetEffect() > 0) usleep(50); - HaltGui(); - w.Remove(&MainButton1); - w.Remove(&MainButton2); - w.Remove(&MainButton3); - w.Remove(&MainButton4); - exit = false; - options2.SetLength(0); - w.Append(&optionBrowser2); - optionBrowser2.SetClickable(true); - ResumeGui(); - - bool firstRun = true; - - optionBrowser2.SetEffect(EFFECT_FADE, 20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - - while (!exit) - { - usleep(100); - - if (shutdown == 1) - Sys_Shutdown(); - if (reset == 1) - Sys_Reboot(); - if (backBtn.GetState() == STATE_CLICKED) - { - backBtn.ResetState(); - exit = true; - break; - } - - else if (homo.GetState() == STATE_CLICKED) - { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - - ret = optionBrowser2.GetClickedOption(); - - if(firstRun || ret >= 0) - { - int Idx = -1; - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx,"%s", tr("Uninstall Game")); - if(ret == Idx) - { - int choice1 = WindowPrompt(tr("Do you really want to delete:"),gameName,tr("Yes"),tr("Cancel")); - if (choice1 == 1 && !mountMethod) - { - CFG_forget_game_opt(header->id); - CFG_forget_game_num(header->id); - ret = WBFS_RemoveGame(header->id); - if (ret < 0) - { - WindowPrompt( - tr("Can't delete:"), - gameName, - tr("OK")); - } - else - { - WindowPrompt(tr("Successfully deleted:"),gameName,tr("OK")); - retVal = 1; - } - } - else if (choice1 == 0) - optionBrowser2.SetFocus(1); - } - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx,"%s", tr("Reset Playcounter")); - if(ret == Idx) - { - int result = WindowPrompt(tr("Are you sure?"),0,tr("Yes"),tr("Cancel")); - if (result == 1) - { - if (isInserted(bootDevice)) - { - struct Game_NUM* game_num = CFG_get_game_num(header->id); - if (game_num) - { - favoritevar = game_num->favorite; - playcount = game_num->count; - } - else - { - favoritevar = 0; - playcount = 0; - } - playcount = 0; - CFG_save_game_num(header->id); - } - } - } - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx,"%s", tr("Delete Cover Artwork")); - if(ret == Idx) - { - char tmp[200]; - snprintf(tmp,sizeof(tmp),"%s%c%c%c%c%c%c.png", Settings.covers_path, header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); - - int choice1 = WindowPrompt(tr("Delete"),tmp,tr("Yes"),tr("No")); - if (choice1==1) - { - if (checkfile(tmp)) - remove(tmp); - } - } - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx,"%s", tr("Delete Disc Artwork")); - if(ret == Idx) - { - char tmp[200]; - snprintf(tmp,sizeof(tmp),"%s%c%c%c%c%c%c.png", Settings.disc_path, header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); - - int choice1 = WindowPrompt(tr("Delete"),tmp,tr("Yes"),tr("No")); - if (choice1==1) - { - if (checkfile(tmp)) - remove(tmp); - } - } - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx,"%s", tr("Delete Cheat TXT")); - if(ret == Idx) - { - char tmp[200]; - snprintf(tmp,sizeof(tmp),"%s%c%c%c%c%c%c.txt", Settings.TxtCheatcodespath, header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); - - int choice1 = WindowPrompt(tr("Delete"),tmp,tr("Yes"),tr("No")); - if (choice1==1) - { - if (checkfile(tmp)) - remove(tmp); - } - } - } - - if(ret == ++Idx || firstRun) - { - if(firstRun) options2.SetName(Idx,"%s", tr("Delete Cheat GCT")); - if(ret == Idx) - { - char tmp[200]; - snprintf(tmp,sizeof(tmp),"%s%c%c%c%c%c%c.gct", Settings.Cheatcodespath, header->id[0], header->id[1], header->id[2],header->id[3], header->id[4], header->id[5]); - - int choice1 = WindowPrompt(tr("Delete"),tmp,tr("Yes"),tr("No")); - if (choice1==1) - { - if (checkfile(tmp)) - remove(tmp); - } - } - } - - firstRun = false; - } - } - optionBrowser2.SetEffect(EFFECT_FADE, -20); - while (optionBrowser2.GetEffect() > 0) usleep(50); - pageToDisplay = 1; - MainButton3.ResetState(); - break; - } - - else if (MainButton4.GetState() == STATE_CLICKED) - { - int choice1 = WindowPrompt(tr("Are you sure?"),0,tr("Yes"),tr("Cancel")); - if (choice1 == 1) - { - videoChoice = Settings.video; - viChoice = Settings.vpatch; - languageChoice = Settings.language; - ocarinaChoice = Settings.ocarina; - fix002 = Settings.error002; - countrystrings = Settings.patchcountrystrings; - alternatedol = off; - alternatedoloffset = 0; - reloadblock = off; - if (Settings.cios == ios222) - iosChoice = i222; - else if (Settings.cios == ios250) - iosChoice = i250; - else if (Settings.cios == ios223) - iosChoice = i223; - else - iosChoice = i249; - parentalcontrolChoice = 0; - strcpy(alternatedname, ""); - CFG_forget_game_opt(header->id); - /* commented because the database language now depends on the main language setting, this could be enabled again if there is a separate language setting for the database - // if default language is different than language from main settings, reload titles - int opt_langnew = 0; - opt_langnew = Settings.language; - if (Settings.titlesOverride==1 && opt_lang != opt_langnew) - OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, true, false); // open file, reload titles, do not keep in memory - // titles are refreshed in menu.cpp as soon as this function returns - */ - } - - pageToDisplay = 1; - MainButton4.ResetState(); - break; - } - - - else if (backBtn.GetState() == STATE_CLICKED) - { - menu = MENU_DISCLIST; - pageToDisplay = 0; - backBtn.ResetState(); - break; - } - - else if (homo.GetState() == STATE_CLICKED) - { - cfg_save_global(); - optionBrowser2.SetState(STATE_DISABLED); - bgMusic->Pause(); - choice = WindowExitPrompt(); - bgMusic->Resume(); - - if (choice == 3) - Sys_LoadMenu(); // Back to System Menu - else if (choice == 2) - Sys_BackToLoader(); - else - homo.ResetState(); - optionBrowser2.SetState(STATE_DEFAULT); - } - } - } - w.SetEffect(EFFECT_FADE, -20); - while (w.GetEffect()>0) usleep(50); - - - - HaltGui(); - - mainWindow->RemoveAll(); - mainWindow->Append(bgImg); - - ResumeGui(); - return retVal; + int menu = MENU_NONE; + int ret; + int choice = 0; + bool exit = false; + + int retVal = 0; + + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnClick1( button_click_pcm, button_click_pcm_size, Settings.sfxvolume ); + + char imgPath[100]; + + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%ssettings_background.png", CFG.theme_path ); + GuiImageData settingsbg( imgPath, settings_background_png ); + + snprintf( imgPath, sizeof( imgPath ), "%ssettings_title.png", CFG.theme_path ); + GuiImageData MainButtonImgData( imgPath, settings_title_png ); + + snprintf( imgPath, sizeof( imgPath ), "%ssettings_title_over.png", CFG.theme_path ); + GuiImageData MainButtonImgOverData( imgPath, settings_title_over_png ); + + GuiTrigger trigA; + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); + GuiTrigger trigHome; + trigHome.SetButtonOnlyTrigger( -1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0 ); + GuiTrigger trigB; + trigB.SetButtonOnlyTrigger( -1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B ); + + char gameName[31]; + if ( !mountMethod ) + { + if ( strlen( get_title( header ) ) < ( 27 + 3 ) ) + sprintf( gameName, "%s", get_title( header ) ); + else + { + strncpy( gameName, get_title( header ), 27 ); + gameName[27] = '\0'; + strncat( gameName, "...", 3 ); + } + } + else + sprintf( gameName, "%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5] ); + + 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 ); + + GuiText backBtnTxt( tr( "Back" ), 22, THEME.prompttext ); + backBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); + GuiImage backBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + backBtnTxt.SetWidescreen( CFG.widescreen ); + backBtnImg.SetWidescreen( CFG.widescreen ); + } + GuiButton backBtn( &backBtnImg, &backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2, 1 ); + backBtn.SetLabel( &backBtnTxt ); + backBtn.SetTrigger( &trigB ); + + GuiButton homo( 1, 1 ); + homo.SetTrigger( &trigHome ); + + GuiText saveBtnTxt( tr( "Save" ), 22, THEME.prompttext ); + saveBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); + GuiImage saveBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + saveBtnTxt.SetWidescreen( CFG.widescreen ); + saveBtnImg.SetWidescreen( CFG.widescreen ); + } + GuiButton saveBtn( &saveBtnImg, &saveBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2, 1 ); + saveBtn.SetLabel( &saveBtnTxt ); + + + + char MainButtonText[50]; + snprintf( MainButtonText, sizeof( MainButtonText ), "%s", " " ); + + GuiImage MainButton1Img( &MainButtonImgData ); + GuiImage MainButton1ImgOver( &MainButtonImgOverData ); + GuiText MainButton1Txt( MainButtonText, 22, ( GXColor ) {0, 0, 0, 255} ); + MainButton1Txt.SetMaxWidth( MainButton1Img.GetWidth() ); + GuiButton MainButton1( MainButton1Img.GetWidth(), MainButton1Img.GetHeight() ); + MainButton1.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + MainButton1.SetPosition( 0, 90 ); + MainButton1.SetImage( &MainButton1Img ); + MainButton1.SetImageOver( &MainButton1ImgOver ); + MainButton1.SetLabel( &MainButton1Txt ); + MainButton1.SetSoundOver( &btnSoundOver ); + MainButton1.SetSoundClick( &btnClick1 ); + MainButton1.SetEffectGrow(); + MainButton1.SetTrigger( &trigA ); + + GuiImage MainButton2Img( &MainButtonImgData ); + GuiImage MainButton2ImgOver( &MainButtonImgOverData ); + GuiText MainButton2Txt( MainButtonText, 22, ( GXColor ) {0, 0, 0, 255} ); + MainButton2Txt.SetMaxWidth( MainButton2Img.GetWidth() ); + GuiButton MainButton2( MainButton2Img.GetWidth(), MainButton2Img.GetHeight() ); + MainButton2.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + MainButton2.SetPosition( 0, 160 ); + MainButton2.SetImage( &MainButton2Img ); + MainButton2.SetImageOver( &MainButton2ImgOver ); + MainButton2.SetLabel( &MainButton2Txt ); + MainButton2.SetSoundOver( &btnSoundOver ); + MainButton2.SetSoundClick( &btnClick1 ); + MainButton2.SetEffectGrow(); + MainButton2.SetTrigger( &trigA ); + + GuiImage MainButton3Img( &MainButtonImgData ); + GuiImage MainButton3ImgOver( &MainButtonImgOverData ); + GuiText MainButton3Txt( MainButtonText, 22, ( GXColor ) {0, 0, 0, 255} ); + MainButton3Txt.SetMaxWidth( MainButton3Img.GetWidth() ); + GuiButton MainButton3( MainButton3Img.GetWidth(), MainButton3Img.GetHeight() ); + MainButton3.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + MainButton3.SetPosition( 0, 230 ); + MainButton3.SetImage( &MainButton3Img ); + MainButton3.SetImageOver( &MainButton3ImgOver ); + MainButton3.SetLabel( &MainButton3Txt ); + MainButton3.SetSoundOver( &btnSoundOver ); + MainButton3.SetSoundClick( &btnClick1 ); + MainButton3.SetEffectGrow(); + MainButton3.SetTrigger( &trigA ); + + GuiImage MainButton4Img( &MainButtonImgData ); + GuiImage MainButton4ImgOver( &MainButtonImgOverData ); + GuiText MainButton4Txt( MainButtonText, 22, ( GXColor ) {0, 0, 0, 255} ); + MainButton4Txt.SetMaxWidth( MainButton4Img.GetWidth() ); + GuiButton MainButton4( MainButton4Img.GetWidth(), MainButton4Img.GetHeight() ); + MainButton4.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + MainButton4.SetPosition( 0, 300 ); + MainButton4.SetImage( &MainButton4Img ); + MainButton4.SetImageOver( &MainButton4ImgOver ); + MainButton4.SetLabel( &MainButton4Txt ); + MainButton4.SetSoundOver( &btnSoundOver ); + MainButton4.SetSoundClick( &btnClick1 ); + MainButton4.SetEffectGrow(); + MainButton4.SetTrigger( &trigA ); + + customOptionList options2( MAXOPTIONS ); + GuiCustomOptionBrowser optionBrowser2( 396, 280, &options2, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, 0, 150 ); + optionBrowser2.SetPosition( 0, 90 ); + optionBrowser2.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + + GuiWindow w( screenwidth, screenheight ); + //int opt_lang = languageChoice; // backup language setting + struct Game_CFG* game_cfg = CFG_get_game_opt( header->id ); + + int pageToDisplay = 1; + while ( pageToDisplay > 0 ) + { + usleep( 100 ); + + menu = MENU_NONE; + + /** Standard procedure made in all pages **/ + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); + + 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 ); + + mainWindow->RemoveAll(); + mainWindow->Append( &w ); + w.RemoveAll(); + w.Append( &settingsbackground ); + w.Append( &titleTxt ); + w.Append( &backBtn ); + w.Append( &homo ); + w.Append( &MainButton1 ); + w.Append( &MainButton2 ); + w.Append( &MainButton3 ); + w.Append( &MainButton4 ); + + /** Disable ability to click through MainButtons */ + optionBrowser2.SetClickable( false ); + /** Default no scrollbar and reset position **/ +// optionBrowser2.SetScrollbar(0); + optionBrowser2.SetOffset( 0 ); + + MainButton1.StopEffect(); + MainButton2.StopEffect(); + MainButton3.StopEffect(); + MainButton4.StopEffect(); + + MainButton1.SetEffectGrow(); + MainButton2.SetEffectGrow(); + MainButton3.SetEffectGrow(); + MainButton4.SetEffectGrow(); + + + MainButton1.SetEffect( EFFECT_FADE, 20 ); + MainButton2.SetEffect( EFFECT_FADE, 20 ); + MainButton3.SetEffect( EFFECT_FADE, 20 ); + MainButton4.SetEffect( EFFECT_FADE, 20 ); + + mainWindow->Append( &w ); + + + + if ( game_cfg ) //if there are saved settings for this game use them + { + videoChoice = game_cfg->video; + languageChoice = game_cfg->language; + ocarinaChoice = game_cfg->ocarina; + viChoice = game_cfg->vipatch; + iosChoice = game_cfg->ios; + parentalcontrolChoice = game_cfg->parentalcontrol; + fix002 = game_cfg->errorfix002; + countrystrings = game_cfg->patchcountrystrings; + alternatedol = game_cfg->loadalternatedol; + alternatedoloffset = game_cfg->alternatedolstart; + reloadblock = game_cfg->iosreloadblock; + strlcpy( alternatedname, game_cfg->alternatedolname, sizeof( alternatedname ) ); + } + else + { + videoChoice = Settings.video; + languageChoice = Settings.language; + ocarinaChoice = Settings.ocarina; + viChoice = Settings.vpatch; + if ( Settings.cios == ios222 ) + iosChoice = i222; + else if ( Settings.cios == ios250 ) + iosChoice = i250; + else if ( Settings.cios == ios223 ) + iosChoice = i223; + else + iosChoice = i249; + parentalcontrolChoice = 0; + fix002 = Settings.error002; + countrystrings = Settings.patchcountrystrings; + alternatedol = off; + alternatedoloffset = 0; + reloadblock = off; + strcpy( alternatedname, "" ); + } + + ResumeGui(); + + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + + + + while ( menu == MENU_NONE ) + { + usleep( 100 ); + + if ( shutdown == 1 ) + Sys_Shutdown(); + if ( reset == 1 ) + Sys_Reboot(); + + if ( MainButton1.GetState() == STATE_CLICKED ) + { + w.Append( &saveBtn ); + MainButton1.SetEffect( EFFECT_FADE, -20 ); + MainButton2.SetEffect( EFFECT_FADE, -20 ); + MainButton3.SetEffect( EFFECT_FADE, -20 ); + MainButton4.SetEffect( EFFECT_FADE, -20 ); + while ( MainButton1.GetEffect() > 0 ) usleep( 50 ); + HaltGui(); + w.Remove( &MainButton1 ); + w.Remove( &MainButton2 ); + w.Remove( &MainButton3 ); + w.Remove( &MainButton4 ); + exit = false; + options2.SetLength( 0 ); +// optionBrowser2.SetScrollbar(1); + w.Append( &optionBrowser2 ); + optionBrowser2.SetClickable( true ); + ResumeGui(); + + optionBrowser2.SetEffect( EFFECT_FADE, 20 ); + while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + + int returnhere = 1; + char * languagefile; + languagefile = strrchr( Settings.language_path, '/' ) + 1; + + bool firstRun = true; + while ( !exit ) + { + usleep( 100 ); + + returnhere = 1; + + if ( shutdown == 1 ) + Sys_Shutdown(); + if ( reset == 1 ) + Sys_Reboot(); + if ( backBtn.GetState() == STATE_CLICKED ) + { + backBtn.ResetState(); + exit = true; + break; + } + + else if ( menu == MENU_DISCLIST ) + { + w.Remove( &optionBrowser2 ); + w.Remove( &backBtn ); + WindowCredits(); + w.Append( &optionBrowser2 ); + w.Append( &backBtn ); + } + + else if ( homo.GetState() == STATE_CLICKED ) + { + cfg_save_global(); + optionBrowser2.SetState( STATE_DISABLED ); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if ( choice == 3 ) + Sys_LoadMenu(); // Back to System Menu + else if ( choice == 2 ) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState( STATE_DEFAULT ); + } + + else if ( saveBtn.GetState() == STATE_CLICKED ) + { + if ( isInserted( bootDevice ) ) + { + if ( CFG_save_game_opt( header->id ) ) + { + /* commented because the database language now depends on the main language setting, this could be enabled again if there is a separate language setting for the database + // if game language has changed when saving game settings, reload titles + int opt_langnew = 0; + game_cfg = CFG_get_game_opt(header->id); + if (game_cfg) opt_langnew = game_cfg->language; + if (Settings.titlesOverride==1 && opt_lang != opt_langnew) + OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, true, false); // open file, reload titles, do not keep in memory + // titles are refreshed in menu.cpp as soon as this function returns + */ + game_cfg = CFG_get_game_opt( header->id ); // needed here for "if (game_cfg)" earlier in case it's the first time settings are saved for a game + WindowPrompt( tr( "Successfully Saved" ), 0, tr( "OK" ) ); + } + else + WindowPrompt( tr( "Save Failed" ), 0, tr( "OK" ) ); + } + else + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ) ); + + saveBtn.ResetState(); + optionBrowser2.SetFocus( 1 ); + } + + ret = optionBrowser2.GetClickedOption(); + + if ( ret >= 0 || firstRun == true ) + { + int Idx = -1; + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Video Mode" ) ); + if ( ret == Idx && ++videoChoice >= settings_video_max ) + videoChoice = 0; + options2.SetValue( Idx, "%s%s", opts_videomode[videoChoice][0], tr( opts_videomode[videoChoice][1] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "VIDTV Patch" ) ); + if ( ret == Idx && ++viChoice >= settings_off_on_max ) + viChoice = 0; + options2.SetValue( Idx, "%s", tr( opts_off_on[viChoice] ) ); + + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Game Language" ) ); + if ( ret == Idx && ++languageChoice >= settings_language_max ) + languageChoice = 0; + options2.SetValue( Idx, "%s", tr( opts_language[languageChoice] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "Ocarina" ); + if ( ret == Idx && ++ocarinaChoice >= settings_off_on_max ) + ocarinaChoice = 0; + options2.SetValue( Idx, "%s", tr( opts_off_on[ocarinaChoice] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "IOS" ); + if ( ret == Idx && ++iosChoice >= settings_ios_max ) + iosChoice = 0; + options2.SetValue( Idx, "%s", opts_cios[iosChoice] ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Parental Control" ) ); + if ( ret == Idx && ++parentalcontrolChoice >= 5 ) + parentalcontrolChoice = 0; + options2.SetValue( Idx, "%s", tr( opts_parentalcontrol[parentalcontrolChoice] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Error 002 fix" ) ); + if ( ret == Idx && ++fix002 >= settings_error002_max ) + fix002 = 0; + options2.SetValue( Idx, "%s", tr( opts_error002[fix002] ) ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "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 ( firstRun ) options2.SetName( Idx, "%s", tr( "Selected DOL" ) ); + if ( ret == Idx ) + { + if ( alternatedol == 2 ) + { + char filename[10]; + snprintf( filename, sizeof( filename ), "%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2], + header->id[3], header->id[4], header->id[5] ); + int dolchoice = 0; + //alt dol menu for games that require more than a single alt dol + int autodol = autoSelectDolMenu( filename, false ); + + if ( autodol > 0 ) + { + alternatedoloffset = autodol; + snprintf( alternatedname, sizeof( alternatedname ), "%s <%i>", tr( "AUTO" ), autodol ); + } + else if ( autodol == 0 ) + alternatedol = 0; // default was chosen + else + { + //check to see if we already know the offset of the correct dol + int autodol = autoSelectDol( filename, false ); + //if we do know that offset ask if they want to use it + if ( autodol > 0 ) + { + dolchoice = WindowPrompt( 0, tr( "Do you want to use the alternate DOL that is known to be correct?" ), tr( "Yes" ), tr( "Pick from a list" ), tr( "Cancel" ) ); + if ( dolchoice == 0 ) + alternatedol = 0; + else if ( dolchoice == 1 ) + { + alternatedoloffset = autodol; + snprintf( alternatedname, sizeof( alternatedname ), "%s <%i>", tr( "AUTO" ), autodol ); + } + else if ( dolchoice == 2 ) //they want to search for the correct dol themselves + { + int res = DiscBrowse( header ); + if ( ( res >= 0 ) && ( res != 696969 ) ) //if res==696969 they pressed the back button + alternatedoloffset = res; + } + } + else + { + int res = DiscBrowse( header ); + if ( ( res >= 0 ) && ( res != 696969 ) ) + { + alternatedoloffset = res; + char tmp[170]; + snprintf( tmp, sizeof( tmp ), "%s %s - %i", tr( "It seems that you have some information that will be helpful to us. Please pass this information along to the DEV team." ) , filename, alternatedoloffset ); + WindowPrompt( 0, tmp, tr( "OK" ) ); + } + } + } + } + } + if ( alternatedol == 0 ) + { + firstRun = true; // force re-init follow Entries + options2.SetLength( Idx-- ); // remove this Entry + options2.SetValue( Idx, "%s", tr( "Default" ) ); // re-set prev Entry + } + else + options2.SetValue( Idx, alternatedname ); + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Block IOS Reload" ) ); + if ( ret == Idx && ++reloadblock >= settings_off_on_max ) + reloadblock = 0; + options2.SetValue( Idx, "%s", tr( opts_off_on[reloadblock] ) ); + } + + firstRun = false; + } + } + + optionBrowser2.SetEffect( EFFECT_FADE, -20 ); + while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + MainButton1.ResetState(); + break; + w.Remove( &saveBtn ); + } + + else if ( MainButton2.GetState() == STATE_CLICKED ) + { + char ID[7]; + snprintf ( ID, sizeof( ID ), "%c%c%c%c%c%c", header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5] ); + CheatMenu( ID ); + MainButton2.ResetState(); + break; + } + + else if ( MainButton3.GetState() == STATE_CLICKED ) + { + MainButton1.SetEffect( EFFECT_FADE, -20 ); + MainButton2.SetEffect( EFFECT_FADE, -20 ); + MainButton3.SetEffect( EFFECT_FADE, -20 ); + MainButton4.SetEffect( EFFECT_FADE, -20 ); + while ( MainButton3.GetEffect() > 0 ) usleep( 50 ); + HaltGui(); + w.Remove( &MainButton1 ); + w.Remove( &MainButton2 ); + w.Remove( &MainButton3 ); + w.Remove( &MainButton4 ); + exit = false; + options2.SetLength( 0 ); + w.Append( &optionBrowser2 ); + optionBrowser2.SetClickable( true ); + ResumeGui(); + + bool firstRun = true; + + optionBrowser2.SetEffect( EFFECT_FADE, 20 ); + while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + + while ( !exit ) + { + usleep( 100 ); + + if ( shutdown == 1 ) + Sys_Shutdown(); + if ( reset == 1 ) + Sys_Reboot(); + if ( backBtn.GetState() == STATE_CLICKED ) + { + backBtn.ResetState(); + exit = true; + break; + } + + else if ( homo.GetState() == STATE_CLICKED ) + { + cfg_save_global(); + optionBrowser2.SetState( STATE_DISABLED ); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + if ( choice == 3 ) + Sys_LoadMenu(); // Back to System Menu + else if ( choice == 2 ) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState( STATE_DEFAULT ); + } + + ret = optionBrowser2.GetClickedOption(); + + if ( firstRun || ret >= 0 ) + { + int Idx = -1; + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Uninstall Game" ) ); + if ( ret == Idx ) + { + int choice1 = WindowPrompt( tr( "Do you really want to delete:" ), gameName, tr( "Yes" ), tr( "Cancel" ) ); + if ( choice1 == 1 && !mountMethod ) + { + CFG_forget_game_opt( header->id ); + CFG_forget_game_num( header->id ); + ret = WBFS_RemoveGame( header->id ); + if ( ret < 0 ) + { + WindowPrompt( + tr( "Can't delete:" ), + gameName, + tr( "OK" ) ); + } + else + { + WindowPrompt( tr( "Successfully deleted:" ), gameName, tr( "OK" ) ); + retVal = 1; + } + } + else if ( choice1 == 0 ) + optionBrowser2.SetFocus( 1 ); + } + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Reset Playcounter" ) ); + if ( ret == Idx ) + { + int result = WindowPrompt( tr( "Are you sure?" ), 0, tr( "Yes" ), tr( "Cancel" ) ); + if ( result == 1 ) + { + if ( isInserted( bootDevice ) ) + { + struct Game_NUM* game_num = CFG_get_game_num( header->id ); + if ( game_num ) + { + favoritevar = game_num->favorite; + playcount = game_num->count; + } + else + { + favoritevar = 0; + playcount = 0; + } + playcount = 0; + CFG_save_game_num( header->id ); + } + } + } + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Delete Cover Artwork" ) ); + if ( ret == Idx ) + { + char tmp[200]; + snprintf( tmp, sizeof( tmp ), "%s%c%c%c%c%c%c.png", Settings.covers_path, header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5] ); + + int choice1 = WindowPrompt( tr( "Delete" ), tmp, tr( "Yes" ), tr( "No" ) ); + if ( choice1 == 1 ) + { + if ( checkfile( tmp ) ) + remove( tmp ); + } + } + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Delete Disc Artwork" ) ); + if ( ret == Idx ) + { + char tmp[200]; + snprintf( tmp, sizeof( tmp ), "%s%c%c%c%c%c%c.png", Settings.disc_path, header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5] ); + + int choice1 = WindowPrompt( tr( "Delete" ), tmp, tr( "Yes" ), tr( "No" ) ); + if ( choice1 == 1 ) + { + if ( checkfile( tmp ) ) + remove( tmp ); + } + } + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Delete Cheat TXT" ) ); + if ( ret == Idx ) + { + char tmp[200]; + snprintf( tmp, sizeof( tmp ), "%s%c%c%c%c%c%c.txt", Settings.TxtCheatcodespath, header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5] ); + + int choice1 = WindowPrompt( tr( "Delete" ), tmp, tr( "Yes" ), tr( "No" ) ); + if ( choice1 == 1 ) + { + if ( checkfile( tmp ) ) + remove( tmp ); + } + } + } + + if ( ret == ++Idx || firstRun ) + { + if ( firstRun ) options2.SetName( Idx, "%s", tr( "Delete Cheat GCT" ) ); + if ( ret == Idx ) + { + char tmp[200]; + snprintf( tmp, sizeof( tmp ), "%s%c%c%c%c%c%c.gct", Settings.Cheatcodespath, header->id[0], header->id[1], header->id[2], header->id[3], header->id[4], header->id[5] ); + + int choice1 = WindowPrompt( tr( "Delete" ), tmp, tr( "Yes" ), tr( "No" ) ); + if ( choice1 == 1 ) + { + if ( checkfile( tmp ) ) + remove( tmp ); + } + } + } + + firstRun = false; + } + } + optionBrowser2.SetEffect( EFFECT_FADE, -20 ); + while ( optionBrowser2.GetEffect() > 0 ) usleep( 50 ); + pageToDisplay = 1; + MainButton3.ResetState(); + break; + } + + else if ( MainButton4.GetState() == STATE_CLICKED ) + { + int choice1 = WindowPrompt( tr( "Are you sure?" ), 0, tr( "Yes" ), tr( "Cancel" ) ); + if ( choice1 == 1 ) + { + videoChoice = Settings.video; + viChoice = Settings.vpatch; + languageChoice = Settings.language; + ocarinaChoice = Settings.ocarina; + fix002 = Settings.error002; + countrystrings = Settings.patchcountrystrings; + alternatedol = off; + alternatedoloffset = 0; + reloadblock = off; + if ( Settings.cios == ios222 ) + iosChoice = i222; + else if ( Settings.cios == ios250 ) + iosChoice = i250; + else if ( Settings.cios == ios223 ) + iosChoice = i223; + else + iosChoice = i249; + parentalcontrolChoice = 0; + strcpy( alternatedname, "" ); + CFG_forget_game_opt( header->id ); + /* commented because the database language now depends on the main language setting, this could be enabled again if there is a separate language setting for the database + // if default language is different than language from main settings, reload titles + int opt_langnew = 0; + opt_langnew = Settings.language; + if (Settings.titlesOverride==1 && opt_lang != opt_langnew) + OpenXMLDatabase(Settings.titlestxt_path, Settings.db_language, Settings.db_JPtoEN, true, true, false); // open file, reload titles, do not keep in memory + // titles are refreshed in menu.cpp as soon as this function returns + */ + } + + pageToDisplay = 1; + MainButton4.ResetState(); + break; + } + + + else if ( backBtn.GetState() == STATE_CLICKED ) + { + menu = MENU_DISCLIST; + pageToDisplay = 0; + backBtn.ResetState(); + break; + } + + else if ( homo.GetState() == STATE_CLICKED ) + { + cfg_save_global(); + optionBrowser2.SetState( STATE_DISABLED ); + bgMusic->Pause(); + choice = WindowExitPrompt(); + bgMusic->Resume(); + + if ( choice == 3 ) + Sys_LoadMenu(); // Back to System Menu + else if ( choice == 2 ) + Sys_BackToLoader(); + else + homo.ResetState(); + optionBrowser2.SetState( STATE_DEFAULT ); + } + } + } + w.SetEffect( EFFECT_FADE, -20 ); + while ( w.GetEffect() > 0 ) usleep( 50 ); + + + + HaltGui(); + + mainWindow->RemoveAll(); + mainWindow->Append( bgImg ); + + ResumeGui(); + return retVal; } diff --git a/source/settings/Settings.h b/source/settings/Settings.h index 3cec126e..7dc36eaf 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/SettingsPrompts.cpp b/source/settings/SettingsPrompts.cpp index d7e8d10c..72800bad 100644 --- a/source/settings/SettingsPrompts.cpp +++ b/source/settings/SettingsPrompts.cpp @@ -34,28 +34,28 @@ bool MenuBackgroundMusic() bool ret = false; char entered[1024]; int result = -1; - snprintf(entered, sizeof(entered), "%s", Settings.ogg_path); + snprintf( entered, sizeof( entered ), "%s", Settings.ogg_path ); - if(strcmp(entered, "") == 0) + if ( strcmp( entered, "" ) == 0 ) { - sprintf(entered, "%s", bootDevice); + sprintf( entered, "%s", bootDevice ); } else { - char * pathptr = strrchr(entered, '/'); - if(pathptr) + char * pathptr = strrchr( entered, '/' ); + if ( pathptr ) { pathptr++; - int choice = WindowPrompt(tr("Playing Music:"), pathptr, tr("Play Previous"), tr("Play Next"), tr("Change Play Path"), tr("Cancel")); - if(choice == 1) + int choice = WindowPrompt( tr( "Playing Music:" ), pathptr, tr( "Play Previous" ), tr( "Play Next" ), tr( "Change Play Path" ), tr( "Cancel" ) ); + if ( choice == 1 ) { return bgMusic->PlayPrevious(); } - else if(choice == 2) + else if ( choice == 2 ) { return bgMusic->PlayNext(); } - else if(choice == 3) + else if ( choice == 3 ) { pathptr[0] = 0; } @@ -63,21 +63,21 @@ bool MenuBackgroundMusic() return true; } else - sprintf(entered, "%s", bootDevice); + sprintf( entered, "%s", bootDevice ); } - result = BrowseDevice(entered, sizeof(entered), FB_DEFAULT); + result = BrowseDevice( entered, sizeof( entered ), FB_DEFAULT ); - if(result) + if ( result ) { - if (!bgMusic->Load(entered)) + if ( !bgMusic->Load( entered ) ) { - WindowPrompt(tr("Not supported format!"), tr("Loading standard music."), tr("OK")); + WindowPrompt( tr( "Not supported format!" ), tr( "Loading standard music." ), tr( "OK" ) ); } else ret = true; bgMusic->Play(); - bgMusic->SetVolume(Settings.volume); + bgMusic->SetVolume( Settings.volume ); } return ret; @@ -86,211 +86,233 @@ bool MenuBackgroundMusic() /**************************************************************************** * MenuLanguageSelect ***************************************************************************/ -int MenuLanguageSelect() { +int MenuLanguageSelect() +{ int cnt = 0; int ret = 0, choice = 0; int scrollon; int returnhere = 0; - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path); - GuiImageData settingsbg(imgPath, settings_background_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%ssettings_background.png", CFG.theme_path ); + GuiImageData settingsbg( imgPath, settings_background_png ); 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 ); char fullpath[100]; - int countfiles = GetAllDirFiles(Settings.languagefiles_path); + int countfiles = GetAllDirFiles( Settings.languagefiles_path ); - if (!strcmp("", Settings.languagefiles_path)) { - sprintf(fullpath, "%s", tr("Standard")); - } else { - sprintf(fullpath, "%s", Settings.languagefiles_path); + if ( !strcmp( "", Settings.languagefiles_path ) ) + { + sprintf( fullpath, "%s", tr( "Standard" ) ); + } + else + { + sprintf( fullpath, "%s", Settings.languagefiles_path ); } - GuiText titleTxt(fullpath, 24, (GXColor) {0, 0, 0, 255}); - titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - titleTxt.SetPosition(0,0); - GuiButton pathBtn(300, 50); - pathBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - pathBtn.SetPosition(0,28); - pathBtn.SetLabel(&titleTxt); - pathBtn.SetSoundOver(&btnSoundOver); - pathBtn.SetSoundClick(btnClick2); - pathBtn.SetTrigger(&trigA); + GuiText titleTxt( fullpath, 24, ( GXColor ) {0, 0, 0, 255} ); + titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); + titleTxt.SetPosition( 0, 0 ); + GuiButton pathBtn( 300, 50 ); + pathBtn.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + pathBtn.SetPosition( 0, 28 ); + pathBtn.SetLabel( &titleTxt ); + pathBtn.SetSoundOver( &btnSoundOver ); + pathBtn.SetSoundClick( btnClick2 ); + pathBtn.SetTrigger( &trigA ); pathBtn.SetEffectGrow(); - GuiImage oggmenubackground(&settingsbg); - oggmenubackground.SetAlignment(ALIGN_LEFT, ALIGN_TOP); - oggmenubackground.SetPosition(0, 0); + GuiImage oggmenubackground( &settingsbg ); + oggmenubackground.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); + oggmenubackground.SetPosition( 0, 0 ); - GuiText backBtnTxt(tr("Back") , 22, THEME.prompttext); - backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); - GuiImage backBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { - backBtnTxt.SetWidescreen(CFG.widescreen); - backBtnImg.SetWidescreen(CFG.widescreen); + GuiText backBtnTxt( tr( "Back" ) , 22, THEME.prompttext ); + backBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); + GuiImage backBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + backBtnTxt.SetWidescreen( CFG.widescreen ); + backBtnImg.SetWidescreen( CFG.widescreen ); } - GuiButton backBtn(btnOutline.GetWidth(), btnOutline.GetHeight()); - backBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - backBtn.SetPosition(-190, 400); - backBtn.SetLabel(&backBtnTxt); - backBtn.SetImage(&backBtnImg); - backBtn.SetSoundOver(&btnSoundOver); - backBtn.SetSoundClick(btnClick2); - backBtn.SetTrigger(&trigA); - backBtn.SetTrigger(&trigB); + GuiButton backBtn( btnOutline.GetWidth(), btnOutline.GetHeight() ); + backBtn.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + backBtn.SetPosition( -190, 400 ); + backBtn.SetLabel( &backBtnTxt ); + backBtn.SetImage( &backBtnImg ); + backBtn.SetSoundOver( &btnSoundOver ); + backBtn.SetSoundClick( btnClick2 ); + backBtn.SetTrigger( &trigA ); + backBtn.SetTrigger( &trigB ); backBtn.SetEffectGrow(); - GuiText defaultBtnTxt(tr("Default") , 22, THEME.prompttext); - defaultBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); - GuiImage defaultBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { - defaultBtnTxt.SetWidescreen(CFG.widescreen); - defaultBtnImg.SetWidescreen(CFG.widescreen); + GuiText defaultBtnTxt( tr( "Default" ) , 22, THEME.prompttext ); + defaultBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); + GuiImage defaultBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + defaultBtnTxt.SetWidescreen( CFG.widescreen ); + defaultBtnImg.SetWidescreen( CFG.widescreen ); } - GuiButton defaultBtn(btnOutline.GetWidth(), btnOutline.GetHeight()); - defaultBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - defaultBtn.SetPosition(190, 400); - defaultBtn.SetLabel(&defaultBtnTxt); - defaultBtn.SetImage(&defaultBtnImg); - defaultBtn.SetSoundOver(&btnSoundOver); - defaultBtn.SetSoundClick(btnClick2); - defaultBtn.SetTrigger(&trigA); + GuiButton defaultBtn( btnOutline.GetWidth(), btnOutline.GetHeight() ); + defaultBtn.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + defaultBtn.SetPosition( 190, 400 ); + defaultBtn.SetLabel( &defaultBtnTxt ); + defaultBtn.SetImage( &defaultBtnImg ); + defaultBtn.SetSoundOver( &btnSoundOver ); + defaultBtn.SetSoundClick( btnClick2 ); + defaultBtn.SetTrigger( &trigA ); defaultBtn.SetEffectGrow(); - GuiText updateBtnTxt(tr("Update Files") , 22, THEME.prompttext); - updateBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30); - GuiImage updateBtnImg(&btnOutline); - if (Settings.wsprompt == yes) { - updateBtnTxt.SetWidescreen(CFG.widescreen); - updateBtnImg.SetWidescreen(CFG.widescreen); + GuiText updateBtnTxt( tr( "Update Files" ) , 22, THEME.prompttext ); + updateBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); + GuiImage updateBtnImg( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + updateBtnTxt.SetWidescreen( CFG.widescreen ); + updateBtnImg.SetWidescreen( CFG.widescreen ); } - GuiButton updateBtn(btnOutline.GetWidth(), btnOutline.GetHeight()); - updateBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - updateBtn.SetPosition(0, 400); - updateBtn.SetLabel(&updateBtnTxt); - updateBtn.SetImage(&updateBtnImg); - updateBtn.SetSoundOver(&btnSoundOver); - updateBtn.SetSoundClick(btnClick2); - updateBtn.SetTrigger(&trigA); + GuiButton updateBtn( btnOutline.GetWidth(), btnOutline.GetHeight() ); + updateBtn.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + updateBtn.SetPosition( 0, 400 ); + updateBtn.SetLabel( &updateBtnTxt ); + updateBtn.SetImage( &updateBtnImg ); + updateBtn.SetSoundOver( &btnSoundOver ); + updateBtn.SetSoundClick( btnClick2 ); + updateBtn.SetTrigger( &trigA ); updateBtn.SetEffectGrow(); - customOptionList options2(countfiles); + customOptionList options2( countfiles ); - for (cnt = 0; cnt < countfiles; cnt++) { + for ( cnt = 0; cnt < countfiles; cnt++ ) + { char filename[64]; - strlcpy(filename, GetFileName(cnt), sizeof(filename)); - char *dot = strchr(filename, '.'); - if (dot) *dot='\0'; - options2.SetName(cnt, "%s", filename); - options2.SetValue(cnt, NULL); + strlcpy( filename, GetFileName( cnt ), sizeof( filename ) ); + char *dot = strchr( filename, '.' ); + if ( dot ) *dot = '\0'; + options2.SetName( cnt, "%s", filename ); + options2.SetValue( cnt, NULL ); } - if (cnt < 9) { + if ( cnt < 9 ) + { scrollon = 0; - } else { + } + else + { scrollon = 1; } - GuiCustomOptionBrowser optionBrowser4(396, 280, &options2, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, scrollon, 10); - optionBrowser4.SetPosition(0, 90); - optionBrowser4.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); + GuiCustomOptionBrowser optionBrowser4( 396, 280, &options2, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, scrollon, 10 ); + optionBrowser4.SetPosition( 0, 90 ); + optionBrowser4.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); HaltGui(); - GuiWindow w(screenwidth, screenheight); - w.Append(&oggmenubackground); - w.Append(&pathBtn); - w.Append(&backBtn); - w.Append(&defaultBtn); - w.Append(&updateBtn); - w.Append(&optionBrowser4); - mainWindow->Append(&w); + GuiWindow w( screenwidth, screenheight ); + w.Append( &oggmenubackground ); + w.Append( &pathBtn ); + w.Append( &backBtn ); + w.Append( &defaultBtn ); + w.Append( &updateBtn ); + w.Append( &optionBrowser4 ); + mainWindow->Append( &w ); - w.SetEffect(EFFECT_FADE, 20); + w.SetEffect( EFFECT_FADE, 20 ); ResumeGui(); - while (w.GetEffect()>0) usleep(50); + while ( w.GetEffect() > 0 ) usleep( 50 ); - while (!returnhere) { + while ( !returnhere ) + { - if (shutdown == 1) + 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 ) + { backBtn.ResetState(); break; } - else if (defaultBtn.GetState() == STATE_CLICKED) { - choice = WindowPrompt(tr("Loading standard language."),0,tr("OK"), tr("Cancel")); - if (choice == 1) { - sprintf(Settings.language_path, "notset"); + else if ( defaultBtn.GetState() == STATE_CLICKED ) + { + choice = WindowPrompt( tr( "Loading standard language." ), 0, tr( "OK" ), tr( "Cancel" ) ); + if ( choice == 1 ) + { + sprintf( Settings.language_path, "notset" ); cfg_save_global(); gettextCleanUp(); - HaltGui(); + HaltGui(); CFG_Load(); - ResumeGui(); + ResumeGui(); returnhere = 2; } defaultBtn.ResetState(); - //optionBrowser4.SetFocus(1); // commented out to prevent crash + //optionBrowser4.SetFocus(1); // commented out to prevent crash } - else if (updateBtn.GetState() == STATE_CLICKED) { - choice = WindowPrompt(tr("Update all Language Files"),tr("Do you wish to update/download all language files?"),tr("OK"), tr("Cancel")); - if (choice == 1) { + else if ( updateBtn.GetState() == STATE_CLICKED ) + { + choice = WindowPrompt( tr( "Update all Language Files" ), tr( "Do you wish to update/download all language files?" ), tr( "OK" ), tr( "Cancel" ) ); + if ( choice == 1 ) + { bool network = true; - if (!IsNetworkInit()) { + if ( !IsNetworkInit() ) + { network = NetworkInitPrompt(); } - if (network) { + if ( network ) + { const char URL[60] = "http://usbloader-gui.googlecode.com/svn/trunk/Languages/"; char fullURL[300]; FILE *pfile; - URL_List LinkList(URL); + URL_List LinkList( URL ); int listsize = LinkList.GetURLCount(); - subfoldercreate(Settings.languagefiles_path); + subfoldercreate( Settings.languagefiles_path ); - for (int i = 0; i < listsize; i++) { + for ( int i = 0; i < listsize; i++ ) + { - ShowProgress(tr("Updating Language Files:"), 0, LinkList.GetURL(i), i, listsize-1); + ShowProgress( tr( "Updating Language Files:" ), 0, LinkList.GetURL( i ), i, listsize - 1 ); - if (strcasecmp(".lang", strrchr(LinkList.GetURL(i), '.')) == 0) { + if ( strcasecmp( ".lang", strrchr( LinkList.GetURL( i ), '.' ) ) == 0 ) + { - snprintf(fullURL, sizeof(fullURL), "%s%s", URL, LinkList.GetURL(i)); + snprintf( fullURL, sizeof( fullURL ), "%s%s", URL, LinkList.GetURL( i ) ); - struct block file = downloadfile(fullURL); + struct block file = downloadfile( fullURL ); - if (file.data && file.size) { + if ( file.data && file.size ) + { char filepath[300]; - snprintf(filepath, sizeof(filepath), "%s%s", Settings.languagefiles_path, LinkList.GetURL(i)); - pfile = fopen(filepath, "wb"); - fwrite(file.data, 1, file.size, pfile); - fclose(pfile); + snprintf( filepath, sizeof( filepath ), "%s%s", Settings.languagefiles_path, LinkList.GetURL( i ) ); + pfile = fopen( filepath, "wb" ); + fwrite( file.data, 1, file.size, pfile ); + fclose( pfile ); } - free(file.data); + free( file.data ); } } ProgressStop(); @@ -298,74 +320,86 @@ int MenuLanguageSelect() { break; } } - updateBtn.ResetState(); - //optionBrowser4.SetFocus(1); // commented out to prevent crash + updateBtn.ResetState(); + //optionBrowser4.SetFocus(1); // commented out to prevent crash } - else if (pathBtn.GetState() == STATE_CLICKED) { - w.Remove(&optionBrowser4); - w.Remove(&backBtn); - w.Remove(&pathBtn); - w.Remove(&defaultBtn); + else if ( pathBtn.GetState() == STATE_CLICKED ) + { + w.Remove( &optionBrowser4 ); + w.Remove( &backBtn ); + w.Remove( &pathBtn ); + w.Remove( &defaultBtn ); char entered[43] = ""; - strlcpy(entered, Settings.languagefiles_path, sizeof(entered)); - int result = OnScreenKeyboard(entered,43,0); - w.Append(&optionBrowser4); - w.Append(&pathBtn); - w.Append(&backBtn); - w.Append(&defaultBtn); - if ( result == 1 ) { - int len = (strlen(entered)-1); - if (entered[len] !='/') - strncat (entered, "/", 1); - strlcpy(Settings.languagefiles_path, entered, sizeof(Settings.languagefiles_path)); - WindowPrompt(tr("Languagepath changed."),0,tr("OK")); - if (isInserted(bootDevice)) { + strlcpy( entered, Settings.languagefiles_path, sizeof( entered ) ); + int result = OnScreenKeyboard( entered, 43, 0 ); + w.Append( &optionBrowser4 ); + w.Append( &pathBtn ); + w.Append( &backBtn ); + w.Append( &defaultBtn ); + if ( result == 1 ) + { + int len = ( strlen( entered ) - 1 ); + if ( entered[len] != '/' ) + strncat ( entered, "/", 1 ); + strlcpy( Settings.languagefiles_path, entered, sizeof( Settings.languagefiles_path ) ); + WindowPrompt( tr( "Languagepath changed." ), 0, tr( "OK" ) ); + if ( isInserted( bootDevice ) ) + { cfg_save_global(); returnhere = 1; break; - } 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" ) ); } } - if (countfiles > 0) { - optionBrowser4.SetFocus(1); + if ( countfiles > 0 ) + { + optionBrowser4.SetFocus( 1 ); } pathBtn.ResetState(); } ret = optionBrowser4.GetClickedOption(); - if (ret>=0) { - choice = WindowPrompt(tr("Do you want to change language?"), 0, tr("Yes"), tr("Cancel")); - if (choice == 1) { - if (isInserted(bootDevice)) { - snprintf(Settings.language_path, sizeof(Settings.language_path), "%s%s", Settings.languagefiles_path, GetFileName(ret)); + if ( ret >= 0 ) + { + choice = WindowPrompt( tr( "Do you want to change language?" ), 0, tr( "Yes" ), tr( "Cancel" ) ); + if ( choice == 1 ) + { + if ( isInserted( bootDevice ) ) + { + snprintf( Settings.language_path, sizeof( Settings.language_path ), "%s%s", Settings.languagefiles_path, GetFileName( ret ) ); cfg_save_global(); - if (!checkfile(Settings.language_path)) { - sprintf(Settings.language_path, tr("not set")); - WindowPrompt(tr("File not found."),tr("Loading standard language."),tr("OK")); + if ( !checkfile( Settings.language_path ) ) + { + sprintf( Settings.language_path, tr( "not set" ) ); + WindowPrompt( tr( "File not found." ), tr( "Loading standard language." ), tr( "OK" ) ); } gettextCleanUp(); - HaltGui(); - CFG_Load(); - ResumeGui(); + HaltGui(); + CFG_Load(); + ResumeGui(); returnhere = 2; break; - } else { - WindowPrompt(tr("No SD-Card inserted!"), tr("Insert an SD-Card to save."), tr("OK"), 0,0,0,-1); + } + else + { + WindowPrompt( tr( "No SD-Card inserted!" ), tr( "Insert an SD-Card to save." ), tr( "OK" ), 0, 0, 0, -1 ); } } - optionBrowser4.SetFocus(1); + optionBrowser4.SetFocus( 1 ); } } - w.SetEffect(EFFECT_FADE, -20); - while (w.GetEffect()>0) usleep(50); + w.SetEffect( EFFECT_FADE, -20 ); + while ( w.GetEffect() > 0 ) usleep( 50 ); HaltGui(); - mainWindow->Remove(&w); + mainWindow->Remove( &w ); ResumeGui(); return returnhere; diff --git a/source/settings/cfg.c b/source/settings/cfg.c index 04a8e786..1bd8da54 100644 --- a/source/settings/cfg.c +++ b/source/settings/cfg.c @@ -42,12 +42,14 @@ u8 listDisplay = 0; u8 partition = -1; char alternatedname[40]; -struct ID_Title { +struct ID_Title +{ char id[6]; char * title; }; -struct ID_Control { +struct ID_Control +{ char id[6]; u8 block; }; @@ -70,12 +72,14 @@ struct Game_NUM cfg_game_num[MAX_SAVED_GAME_NUM]; static char *cfg_name, *cfg_val; -struct TextMap { +struct TextMap +{ char *name; int id; }; -struct TextMap map_video[] = { +struct TextMap map_video[] = +{ { "system", CFG_VIDEO_SYS }, { "game", CFG_VIDEO_GAME }, { "patch", CFG_VIDEO_PATCH }, @@ -85,7 +89,8 @@ struct TextMap map_video[] = { { NULL, -1 } }; -struct TextMap map_language[] = { +struct TextMap map_language[] = +{ { "console", CFG_LANG_CONSOLE }, { "japanese", CFG_LANG_JAPANESE }, { "english", CFG_LANG_ENGLISH }, @@ -101,7 +106,8 @@ struct TextMap map_language[] = { }; -struct TextMap map_alignment[] = { +struct TextMap map_alignment[] = +{ { "left", CFG_ALIGN_LEFT }, { "right", CFG_ALIGN_RIGHT }, { "center", CFG_ALIGN_CENTRE }, @@ -111,26 +117,32 @@ struct TextMap map_alignment[] = { { 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++) { - if (strcmp(name, map[i].name) == 0) return map[i].id; + for ( i = 0; map[i].name != NULL; i++ ) + { + 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++) { - if (id == map[i].id) return map[i].name; + for ( i = 0; map[i].name != NULL; i++ ) + { + 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) { - if (strcmp(name, name2) != 0) return false; - int id = map_get_id(map, val); - if (id == -1) { +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 ) + { //printf("MAP FAIL: %s=%s : %d\n", name, val, id); sleep(1); return false; } @@ -139,32 +151,38 @@ bool map_auto(char *name, char *name2, char *val, struct TextMap *map, short *va return true; } -bool cfg_map_auto(char *name, struct TextMap *map, short *var) { - return map_auto(name, cfg_name, cfg_val, map, var); +bool cfg_map_auto( char *name, struct TextMap *map, short *var ) +{ + return map_auto( name, cfg_name, cfg_val, map, var ); } -bool cfg_map(char *name, char *val, short *var, short id) { - if (strcmp(name, cfg_name)==0 && strcmpi(val, cfg_val)==0) { +bool cfg_map( char *name, char *val, short *var, short id ) +{ + if ( strcmp( name, cfg_name ) == 0 && strcmpi( val, cfg_val ) == 0 ) + { *var = id; return true; } return false; } -bool cfg_bool(char *name, short *var) { - return (cfg_map(name, "0", var, 0) || cfg_map(name, "1", var, 1)); +bool cfg_bool( char *name, short *var ) +{ + 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 + if ( count > 10 ) //avoid overflow return; - for (i = 0; i < count; i++) { - sprintf(tmp, "%d", i); - cfg_map(name, tmp, var, i); + for ( i = 0; i < count; i++ ) + { + sprintf( tmp, "%d", i ); + cfg_map( name, tmp, var, i ); } } @@ -172,174 +190,181 @@ void cfg_int(char *name, short *var, int count) { //static char bg_path[100]; -void CFG_Default(int widescreen) { // -1 = non forced Mode - if (widescreen == -1) +void CFG_Default( int widescreen ) // -1 = non forced Mode +{ + if ( widescreen == -1 ) CFG.widescreen = CONF_GetAspectRatio(); else CFG.widescreen = widescreen; - if (CFG.widescreen) { - snprintf(CFG.theme_path, sizeof(CFG.theme_path), "%s/wtheme/", bootDevice); - } else { - snprintf(CFG.theme_path, sizeof(CFG.theme_path), "%s/theme/", bootDevice); + if ( CFG.widescreen ) + { + snprintf( CFG.theme_path, sizeof( CFG.theme_path ), "%s/wtheme/", bootDevice ); + } + else + { + snprintf( CFG.theme_path, sizeof( CFG.theme_path ), "%s/theme/", bootDevice ); } - if (widescreen == -1) { - snprintf(Settings.covers_path, sizeof(Settings.covers_path), "%s/images/", bootDevice); //default image path - snprintf(Settings.covers2d_path, sizeof(Settings.covers2d_path), "%s/images/2D/", bootDevice); //default image path - snprintf(Settings.disc_path, sizeof(Settings.disc_path), "%s/images/disc/", bootDevice); - snprintf(Settings.titlestxt_path, sizeof(Settings.titlestxt_path), "%s/config/", bootDevice);//default path for disc images + if ( widescreen == -1 ) + { + snprintf( Settings.covers_path, sizeof( Settings.covers_path ), "%s/images/", bootDevice ); //default image path + snprintf( Settings.covers2d_path, sizeof( Settings.covers2d_path ), "%s/images/2D/", bootDevice ); //default image path + snprintf( Settings.disc_path, sizeof( Settings.disc_path ), "%s/images/disc/", bootDevice ); + snprintf( Settings.titlestxt_path, sizeof( Settings.titlestxt_path ), "%s/config/", bootDevice );//default path for disc images char * empty = ""; - snprintf(Settings.unlockCode, sizeof(Settings.unlockCode), empty); // default password - snprintf(Settings.language_path, sizeof(Settings.language_path), "notset"); - snprintf(Settings.languagefiles_path, sizeof(Settings.languagefiles_path), "%s/config/language/", bootDevice); - snprintf(Settings.update_path, sizeof(Settings.update_path), "%s/apps/usbloader_gx/", bootDevice); - snprintf(Settings.theme_downloadpath, sizeof(Settings.theme_downloadpath), "%s/config/themes/", bootDevice); - snprintf(Settings.homebrewapps_path, sizeof(Settings.homebrewapps_path), "%s/apps/", bootDevice); - snprintf(Settings.Cheatcodespath, sizeof(Settings.Cheatcodespath), "%s/codes/", bootDevice); - snprintf(Settings.TxtCheatcodespath, sizeof(Settings.TxtCheatcodespath), "%s/txtcodes/", bootDevice); - snprintf(Settings.BcaCodepath, sizeof(Settings.BcaCodepath), "%s/bca/", bootDevice); - snprintf(Settings.WipCodepath, sizeof(Settings.WipCodepath), "%s/wip/", bootDevice); - snprintf(Settings.dolpath, sizeof(Settings.dolpath), "%s/", bootDevice); - strcpy(Settings.ogg_path, ""); - } - //always set Theme defaults - //all alignments are left top here - THEME.gamelist_x = 200; - THEME.gamelist_y = 49;//40; - THEME.gamelist_w = 396; - THEME.gamelist_h = 280; - THEME.gamegrid_w = 640; - THEME.gamegrid_h = 400; - THEME.gamegrid_x = 0; - THEME.gamegrid_y = 20; - THEME.gamecarousel_w = 640; - THEME.gamecarousel_h = 400; - THEME.gamecarousel_x = 0; - THEME.gamecarousel_y = -20; + snprintf( Settings.unlockCode, sizeof( Settings.unlockCode ), empty ); // default password + snprintf( Settings.language_path, sizeof( Settings.language_path ), "notset" ); + snprintf( Settings.languagefiles_path, sizeof( Settings.languagefiles_path ), "%s/config/language/", bootDevice ); + snprintf( Settings.update_path, sizeof( Settings.update_path ), "%s/apps/usbloader_gx/", bootDevice ); + snprintf( Settings.theme_downloadpath, sizeof( Settings.theme_downloadpath ), "%s/config/themes/", bootDevice ); + snprintf( Settings.homebrewapps_path, sizeof( Settings.homebrewapps_path ), "%s/apps/", bootDevice ); + snprintf( Settings.Cheatcodespath, sizeof( Settings.Cheatcodespath ), "%s/codes/", bootDevice ); + snprintf( Settings.TxtCheatcodespath, sizeof( Settings.TxtCheatcodespath ), "%s/txtcodes/", bootDevice ); + snprintf( Settings.BcaCodepath, sizeof( Settings.BcaCodepath ), "%s/bca/", bootDevice ); + snprintf( Settings.WipCodepath, sizeof( Settings.WipCodepath ), "%s/wip/", bootDevice ); + snprintf( Settings.dolpath, sizeof( Settings.dolpath ), "%s/", bootDevice ); + strcpy( Settings.ogg_path, "" ); + } + //always set Theme defaults + //all alignments are left top here + THEME.gamelist_x = 200; + THEME.gamelist_y = 49;//40; + THEME.gamelist_w = 396; + THEME.gamelist_h = 280; + THEME.gamegrid_w = 640; + THEME.gamegrid_h = 400; + THEME.gamegrid_x = 0; + THEME.gamegrid_y = 20; + THEME.gamecarousel_w = 640; + THEME.gamecarousel_h = 400; + THEME.gamecarousel_x = 0; + THEME.gamecarousel_y = -20; - THEME.covers_x = 26; - THEME.covers_y = 58; + THEME.covers_x = 26; + THEME.covers_y = 58; - THEME.show_id = 1; - THEME.id_x = 68; - THEME.id_y = 305; - THEME.show_region = 1; - THEME.region_x = 68; - THEME.region_y = 30; + THEME.show_id = 1; + THEME.id_x = 68; + THEME.id_y = 305; + THEME.show_region = 1; + THEME.region_x = 68; + THEME.region_y = 30; - THEME.sdcard_x = 160; - THEME.sdcard_y = 395; - THEME.homebrew_x = 410; - THEME.homebrew_y = 405; - THEME.power_x = 576; - THEME.power_y = 355; - THEME.home_x = 489;//215; - THEME.home_y = 371; - THEME.setting_x = 64;//-210 - THEME.setting_y = 371; - THEME.install_x = 16;//-280 - THEME.install_y = 355; + THEME.sdcard_x = 160; + THEME.sdcard_y = 395; + THEME.homebrew_x = 410; + THEME.homebrew_y = 405; + THEME.power_x = 576; + THEME.power_y = 355; + THEME.home_x = 489;//215; + THEME.home_y = 371; + THEME.setting_x = 64;//-210 + THEME.setting_y = 371; + THEME.install_x = 16;//-280 + THEME.install_y = 355; - THEME.clock = (GXColor) {138, 138, 138, 240}; - THEME.clock_align = CFG_ALIGN_CENTRE; - THEME.clock_x = 0; - THEME.clock_y = 335;//330; + THEME.clock = ( GXColor ) {138, 138, 138, 240}; + THEME.clock_align = CFG_ALIGN_CENTRE; + THEME.clock_x = 0; + THEME.clock_y = 335;//330; - THEME.info = (GXColor) {55, 190, 237, 255}; - THEME.show_hddinfo = 1; //default - THEME.hddinfo_align = CFG_ALIGN_CENTRE; - THEME.hddinfo_x = 0; - THEME.hddinfo_y = 400; - THEME.show_gamecount = 1; //default - THEME.gamecount_align = CFG_ALIGN_CENTRE; - THEME.gamecount_x = 0; - THEME.gamecount_y = 420; + THEME.info = ( GXColor ) {55, 190, 237, 255}; + THEME.show_hddinfo = 1; //default + THEME.hddinfo_align = CFG_ALIGN_CENTRE; + THEME.hddinfo_x = 0; + THEME.hddinfo_y = 400; + THEME.show_gamecount = 1; //default + THEME.gamecount_align = CFG_ALIGN_CENTRE; + THEME.gamecount_x = 0; + THEME.gamecount_y = 420; - THEME.show_tooltip = 1; //1 means use settings, 0 means force turn off - THEME.tooltipAlpha = 255; + THEME.show_tooltip = 1; //1 means use settings, 0 means force turn off + THEME.tooltipAlpha = 255; - THEME.prompttext = (GXColor) {0, 0, 0, 255}; - THEME.settingstext = (GXColor) {0, 0, 0, 255}; - THEME.gametext = (GXColor) {0, 0, 0, 255}; + THEME.prompttext = ( GXColor ) {0, 0, 0, 255}; + THEME.settingstext = ( GXColor ) {0, 0, 0, 255}; + THEME.gametext = ( GXColor ) {0, 0, 0, 255}; - THEME.pagesize = 9; + THEME.pagesize = 9; - THEME.gamelist_favorite_x = CFG.widescreen ? 256 : 220; - THEME.gamelist_favorite_y = 13; - THEME.gamelist_search_x = CFG.widescreen ? 288 : 260; - THEME.gamelist_search_y = 13; - THEME.gamelist_abc_x = CFG.widescreen ? 320 : 300; - THEME.gamelist_abc_y = 13; - THEME.gamelist_count_x = CFG.widescreen ? 352 : 340; - THEME.gamelist_count_y = 13; - THEME.gamelist_list_x = CFG.widescreen ? 384 : 380; - THEME.gamelist_list_y = 13; - THEME.gamelist_grid_x = CFG.widescreen ? 416 : 420; - THEME.gamelist_grid_y = 13; - THEME.gamelist_carousel_x = CFG.widescreen ? 448 : 460; - THEME.gamelist_carousel_y = 13; - THEME.gamelist_lock_x = CFG.widescreen ? 480 : 500; - THEME.gamelist_lock_y = 13; - THEME.gamelist_dvd_x = CFG.widescreen ? 512 : 540; - THEME.gamelist_dvd_y = 13; + THEME.gamelist_favorite_x = CFG.widescreen ? 256 : 220; + THEME.gamelist_favorite_y = 13; + THEME.gamelist_search_x = CFG.widescreen ? 288 : 260; + THEME.gamelist_search_y = 13; + THEME.gamelist_abc_x = CFG.widescreen ? 320 : 300; + THEME.gamelist_abc_y = 13; + THEME.gamelist_count_x = CFG.widescreen ? 352 : 340; + THEME.gamelist_count_y = 13; + THEME.gamelist_list_x = CFG.widescreen ? 384 : 380; + THEME.gamelist_list_y = 13; + THEME.gamelist_grid_x = CFG.widescreen ? 416 : 420; + THEME.gamelist_grid_y = 13; + THEME.gamelist_carousel_x = CFG.widescreen ? 448 : 460; + THEME.gamelist_carousel_y = 13; + THEME.gamelist_lock_x = CFG.widescreen ? 480 : 500; + THEME.gamelist_lock_y = 13; + THEME.gamelist_dvd_x = CFG.widescreen ? 512 : 540; + THEME.gamelist_dvd_y = 13; - THEME.gamegrid_favorite_x = CFG.widescreen ? 192 : 160; - THEME.gamegrid_favorite_y = 13; - THEME.gamegrid_search_x = CFG.widescreen ? 224 : 200; - THEME.gamegrid_search_y = 13; - THEME.gamegrid_abc_x = CFG.widescreen ? 256 : 240; - THEME.gamegrid_abc_y = 13; - THEME.gamegrid_count_x = CFG.widescreen ? 288 : 280; - THEME.gamegrid_count_y = 13; - THEME.gamegrid_list_x = CFG.widescreen ? 320 : 320; - THEME.gamegrid_list_y = 13; - THEME.gamegrid_grid_x = CFG.widescreen ? 352 : 360; - THEME.gamegrid_grid_y = 13; - THEME.gamegrid_carousel_x = CFG.widescreen ? 384 : 400; - THEME.gamegrid_carousel_y = 13; - THEME.gamegrid_lock_x = CFG.widescreen ? 416 : 440; - THEME.gamegrid_lock_y = 13; - THEME.gamegrid_dvd_x = CFG.widescreen ? 448 : 480; - THEME.gamegrid_dvd_y = 13; + THEME.gamegrid_favorite_x = CFG.widescreen ? 192 : 160; + THEME.gamegrid_favorite_y = 13; + THEME.gamegrid_search_x = CFG.widescreen ? 224 : 200; + THEME.gamegrid_search_y = 13; + THEME.gamegrid_abc_x = CFG.widescreen ? 256 : 240; + THEME.gamegrid_abc_y = 13; + THEME.gamegrid_count_x = CFG.widescreen ? 288 : 280; + THEME.gamegrid_count_y = 13; + THEME.gamegrid_list_x = CFG.widescreen ? 320 : 320; + THEME.gamegrid_list_y = 13; + THEME.gamegrid_grid_x = CFG.widescreen ? 352 : 360; + THEME.gamegrid_grid_y = 13; + THEME.gamegrid_carousel_x = CFG.widescreen ? 384 : 400; + THEME.gamegrid_carousel_y = 13; + THEME.gamegrid_lock_x = CFG.widescreen ? 416 : 440; + THEME.gamegrid_lock_y = 13; + THEME.gamegrid_dvd_x = CFG.widescreen ? 448 : 480; + THEME.gamegrid_dvd_y = 13; - THEME.gamecarousel_favorite_x = CFG.widescreen ? 192 : 160; - THEME.gamecarousel_favorite_y = 13; - THEME.gamecarousel_search_x = CFG.widescreen ? 224 : 200; - THEME.gamecarousel_search_y = 13; - THEME.gamecarousel_abc_x = CFG.widescreen ? 256 : 240; - THEME.gamecarousel_abc_y = 13; - THEME.gamecarousel_count_x = CFG.widescreen ? 288 : 280; - THEME.gamecarousel_count_y = 13; - THEME.gamecarousel_list_x = CFG.widescreen ? 320 : 320; - THEME.gamecarousel_list_y = 13; - THEME.gamecarousel_grid_x = CFG.widescreen ? 352 : 360; - THEME.gamecarousel_grid_y = 13; - THEME.gamecarousel_carousel_x = CFG.widescreen ? 384 : 400; - THEME.gamecarousel_carousel_y = 13; - THEME.gamecarousel_lock_x = CFG.widescreen ? 416 : 440; - THEME.gamecarousel_lock_y = 13; - THEME.gamecarousel_dvd_x = CFG.widescreen ? 448 : 480; - THEME.gamecarousel_dvd_y = 13; + THEME.gamecarousel_favorite_x = CFG.widescreen ? 192 : 160; + THEME.gamecarousel_favorite_y = 13; + THEME.gamecarousel_search_x = CFG.widescreen ? 224 : 200; + THEME.gamecarousel_search_y = 13; + THEME.gamecarousel_abc_x = CFG.widescreen ? 256 : 240; + THEME.gamecarousel_abc_y = 13; + THEME.gamecarousel_count_x = CFG.widescreen ? 288 : 280; + THEME.gamecarousel_count_y = 13; + THEME.gamecarousel_list_x = CFG.widescreen ? 320 : 320; + THEME.gamecarousel_list_y = 13; + THEME.gamecarousel_grid_x = CFG.widescreen ? 352 : 360; + THEME.gamecarousel_grid_y = 13; + THEME.gamecarousel_carousel_x = CFG.widescreen ? 384 : 400; + THEME.gamecarousel_carousel_y = 13; + THEME.gamecarousel_lock_x = CFG.widescreen ? 416 : 440; + THEME.gamecarousel_lock_y = 13; + THEME.gamecarousel_dvd_x = CFG.widescreen ? 448 : 480; + THEME.gamecarousel_dvd_y = 13; } -void Global_Default(void) { +void Global_Default( void ) +{ Settings.video = discdefault; Settings.vpatch = off; Settings.language = ConsoleLangDefault; Settings.ocarina = off; Settings.hddinfo = hr12; - Settings.sinfo = ((THEME.show_id) ? GameID : Neither); + Settings.sinfo = ( ( THEME.show_id ) ? GameID : Neither ); Settings.rumble = RumbleOn; - if (THEME.show_region) { - Settings.sinfo = ((Settings.sinfo == GameID) ? Both : GameRegion); + if ( THEME.show_region ) + { + Settings.sinfo = ( ( Settings.sinfo == GameID ) ? Both : GameRegion ); } Settings.volume = 80; Settings.sfxvolume = 80; Settings.gamesoundvolume = 80; Settings.tooltips = TooltipsOn; char * empty = ""; - snprintf(Settings.unlockCode, sizeof(Settings.unlockCode), empty); + snprintf( Settings.unlockCode, sizeof( Settings.unlockCode ), empty ); // Settings.godmode = 1; Settings.gamesound = 1; Settings.parentalcontrol = 0; @@ -353,77 +378,84 @@ void Global_Default(void) { Settings.gridRows = 3; Settings.error002 = 2; Settings.titlesOverride = 1; - snprintf(Settings.db_url, sizeof(Settings.db_url), empty); - snprintf(Settings.db_language, sizeof(Settings.db_language), empty); + snprintf( Settings.db_url, sizeof( Settings.db_url ), empty ); + snprintf( Settings.db_language, sizeof( Settings.db_language ), empty ); Settings.db_JPtoEN = 0; Settings.screensaver = 3; - Settings.musicloopmode = 1; - Settings.partition = -1; - Settings.marknewtitles = 1; - Settings.FatInstallToDir = 0; - Settings.partitions_to_install = install_game_only; - Settings.fullcopy = 0; - Settings.beta_upgrades = 0; + Settings.musicloopmode = 1; + Settings.partition = -1; + Settings.marknewtitles = 1; + Settings.FatInstallToDir = 0; + Settings.partitions_to_install = install_game_only; + Settings.fullcopy = 0; + Settings.beta_upgrades = 0; - memset(&Settings.parental, 0, sizeof(struct SParental)); + memset( &Settings.parental, 0, sizeof( struct SParental ) ); - char buf[0x4a]; - CONF_Init(); - s32 res = CONF_Get("IPL.PC", buf, 0x4A); - if (res > 0) { - if (buf[2] != 0x14) { - Settings.parental.enabled = 1; - Settings.parental.rating = buf[2]; - } - Settings.parental.question = buf[7]; - memcpy(Settings.parental.pin, buf + 3, 4); - memcpy(Settings.parental.answer, buf + 8, 32); - } - Settings.godmode = (Settings.parental.enabled == 0) ? 1 : 0; + char buf[0x4a]; + CONF_Init(); + s32 res = CONF_Get( "IPL.PC", buf, 0x4A ); + if ( res > 0 ) + { + if ( buf[2] != 0x14 ) + { + Settings.parental.enabled = 1; + Settings.parental.rating = buf[2]; + } + Settings.parental.question = buf[7]; + memcpy( Settings.parental.pin, buf + 3, 4 ); + memcpy( Settings.parental.answer, buf + 8, 32 ); + } + Settings.godmode = ( Settings.parental.enabled == 0 ) ? 1 : 0; } -char *cfg_get_title(u8 *id) +char *cfg_get_title( u8 *id ) { - if(!id) + if ( !id ) return NULL; int i; - for (i=0; iid); - 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) + 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); - } else { - struct ID_Title * tmpStruct = (struct ID_Title *) realloc(cfg_title, (num_title+1) * sizeof(struct ID_Title)); - if (!tmpStruct) { + 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 ) + { // error CFG_Cleanup(); num_title = 0; @@ -433,162 +465,192 @@ 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++; } } -void titles_default() { - int i; - for (i=0; iid); +u8 get_block( struct discHdr *header ) +{ + return cfg_get_block( header->id ); } -s8 get_pegi_block(struct discHdr *header) { - switch(get_block(header)) { - case 1: return 7; - case 2: return 12; - case 3: return 16; - case 4: return 18; - default: return -1; - } +s8 get_pegi_block( struct discHdr *header ) +{ + switch ( get_block( header ) ) + { + 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; } -void widescreen_set(char *name, char *val) { +void widescreen_set( char *name, char *val ) +{ cfg_name = name; cfg_val = val; short widescreen; - if (cfg_bool("widescreen", &widescreen) && CFG.widescreen != widescreen) - CFG_Default(widescreen); //reset default when forced an other Screenmode + if ( cfg_bool( "widescreen", &widescreen ) && CFG.widescreen != widescreen ) + CFG_Default( widescreen ); //reset default when forced an other Screenmode } -void path_set(char *name, char *val) { +void path_set( char *name, char *val ) +{ cfg_name = name; cfg_val = val; // if these are defined in txt file, use them. otherwise use defaults - if (!CFG.widescreen &&(strcmp(name, "theme_path") == 0)) {// if in 4:3 - strlcpy(CFG.theme_path, val, sizeof(CFG.theme_path)); + if ( !CFG.widescreen && ( strcmp( name, "theme_path" ) == 0 ) ) // if in 4:3 + { + strlcpy( CFG.theme_path, val, sizeof( CFG.theme_path ) ); return; } - if (CFG.widescreen && strcmp(name, "wtheme_path") == 0) { // if in 16:9 - strlcpy(CFG.theme_path, val, sizeof(CFG.theme_path)); + if ( CFG.widescreen && strcmp( name, "wtheme_path" ) == 0 ) // if in 16:9 + { + strlcpy( CFG.theme_path, val, sizeof( CFG.theme_path ) ); return; } - if (strcmp(name, "cover_path") == 0) { - strlcpy(Settings.covers_path, val, sizeof(Settings.covers_path)); + if ( strcmp( name, "cover_path" ) == 0 ) + { + strlcpy( Settings.covers_path, val, sizeof( Settings.covers_path ) ); return; } - if (strcmp(name, "cover2d_path") == 0) { - strlcpy(Settings.covers2d_path, val, sizeof(Settings.covers2d_path)); + if ( strcmp( name, "cover2d_path" ) == 0 ) + { + strlcpy( Settings.covers2d_path, val, sizeof( Settings.covers2d_path ) ); return; } - if (strcmp(name, "disc_path") == 0) { - strlcpy(Settings.disc_path, val, sizeof(Settings.disc_path)); + if ( strcmp( name, "disc_path" ) == 0 ) + { + strlcpy( Settings.disc_path, val, sizeof( Settings.disc_path ) ); return; } - if (strcmp(name, "titlestxt_path") == 0) { - strlcpy(Settings.titlestxt_path, val, sizeof(Settings.titlestxt_path)); + if ( strcmp( name, "titlestxt_path" ) == 0 ) + { + strlcpy( Settings.titlestxt_path, val, sizeof( Settings.titlestxt_path ) ); return; } - if (strcmp(name, "language_path") == 0) { - strlcpy(Settings.language_path, val, sizeof(Settings.language_path)); + if ( strcmp( name, "language_path" ) == 0 ) + { + strlcpy( Settings.language_path, val, sizeof( Settings.language_path ) ); return; } - if (strcmp(name, "languagefiles_path") == 0) { - strlcpy(Settings.languagefiles_path, val, sizeof(Settings.languagefiles_path)); + if ( strcmp( name, "languagefiles_path" ) == 0 ) + { + strlcpy( Settings.languagefiles_path, val, sizeof( Settings.languagefiles_path ) ); return; } - if (strcmp(name, "update_path") == 0) { - strlcpy(Settings.update_path, val, sizeof(Settings.update_path)); + if ( strcmp( name, "update_path" ) == 0 ) + { + strlcpy( Settings.update_path, val, sizeof( Settings.update_path ) ); return; } - if (strcmp(name, "theme_downloadpath") == 0) { - strlcpy(Settings.theme_downloadpath, val, sizeof(Settings.theme_downloadpath)); + if ( strcmp( name, "theme_downloadpath" ) == 0 ) + { + strlcpy( Settings.theme_downloadpath, val, sizeof( Settings.theme_downloadpath ) ); return; } - if (strcmp(name, "homebrewapps_path") == 0) { - strlcpy(Settings.homebrewapps_path, val, sizeof(Settings.homebrewapps_path)); + if ( strcmp( name, "homebrewapps_path" ) == 0 ) + { + strlcpy( Settings.homebrewapps_path, val, sizeof( Settings.homebrewapps_path ) ); return; } - if (strcmp(name, "Cheatcodespath") == 0) { - strlcpy(Settings.Cheatcodespath, val, sizeof(Settings.Cheatcodespath)); + if ( strcmp( name, "Cheatcodespath" ) == 0 ) + { + strlcpy( Settings.Cheatcodespath, val, sizeof( Settings.Cheatcodespath ) ); return; } - if (strcmp(name, "TxtCheatcodespath") == 0) { - strlcpy(Settings.TxtCheatcodespath, val, sizeof(Settings.TxtCheatcodespath)); + if ( strcmp( name, "TxtCheatcodespath" ) == 0 ) + { + strlcpy( Settings.TxtCheatcodespath, val, sizeof( Settings.TxtCheatcodespath ) ); return; } - if (strcmp(name, "dolpath") == 0) { - strlcpy(Settings.dolpath, val, sizeof(Settings.dolpath)); + if ( strcmp( name, "dolpath" ) == 0 ) + { + strlcpy( Settings.dolpath, val, sizeof( Settings.dolpath ) ); return; } - if (strcmp(name, "ogg_path") == 0) { - strlcpy(Settings.ogg_path, val, sizeof(Settings.ogg_path)); + if ( strcmp( name, "ogg_path" ) == 0 ) + { + strlcpy( Settings.ogg_path, val, sizeof( Settings.ogg_path ) ); return; } - if (strcmp(name, "BcaCodepath") == 0) { - strlcpy(Settings.BcaCodepath, val, sizeof(Settings.BcaCodepath)); + if ( strcmp( name, "BcaCodepath" ) == 0 ) + { + strlcpy( Settings.BcaCodepath, val, sizeof( Settings.BcaCodepath ) ); return; } - if (strcmp(name, "WipCodepath") == 0) { - strlcpy(Settings.WipCodepath, val, sizeof(Settings.WipCodepath)); + if ( strcmp( name, "WipCodepath" ) == 0 ) + { + strlcpy( Settings.WipCodepath, val, sizeof( Settings.WipCodepath ) ); return; } @@ -597,662 +659,800 @@ void path_set(char *name, char *val) { } 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 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) { \ - short x,y; \ - if (sscanf(val, "%hd,%hd", &x, &y) == 2) { \ - THEME.name##_x = x; \ - THEME.name##_y = y; \ - } \ - } \ - else if (CFG.widescreen && \ - strcmp(cfg_name, "w" #name "_coords") == 0) { \ - short x,y; \ - if (sscanf(val, "%hd,%hd", &x, &y) == 2) { \ - THEME.name##_x = x; \ - THEME.name##_y = y; \ - SET_wCOORD_FLAG(wcoords_idx); \ - } \ - } -#define CFG_COORDS4(name) \ - if ((wcoords_idx++, 1) && !GET_wCOORD_FLAG(wcoords_idx) && \ - strcmp(cfg_name, #name "_coords") == 0) { \ - short x,y,w,h; \ - if (sscanf(val, "%hd,%hd,%hd,%hd", &x, &y, &w, &h) == 4) { \ - THEME.name##_x = x; \ - THEME.name##_y = y; \ - THEME.name##_w = w; \ - THEME.name##_h = h; \ - } \ - } \ - else if (CFG.widescreen && \ - strcmp(cfg_name, "w" #name "_coords") == 0) { \ - short x,y,w,h; \ - if (sscanf(val, "%hd,%hd,%hd,%hd", &x, &y, &w, &h) == 4) { \ - THEME.name##_x = x; \ - THEME.name##_y = y; \ - THEME.name##_w = w; \ - THEME.name##_h = h; \ - SET_wCOORD_FLAG(wcoords_idx); \ - } \ - } -#define CFG_COLOR(name) \ - if (strcmp(cfg_name, #name "_color") == 0) { \ - short r,g,b,a; \ - int c = sscanf(val, "%hd,%hd,%hd,%hd", &r, &g, &b, &a); \ - if(c >= 3) { \ - THEME.name.r = r; \ - THEME.name.g = g; \ - THEME.name.b = b; \ - if(c >= 4) \ - THEME.name.a = a; \ - } \ - } -#define CFG_VAL(name) \ - if (strcmp(cfg_name, #name) == 0) { \ - short v; \ - if (sscanf(val, "%hd", &v) == 1) { \ - THEME.name = v; \ - } \ - } +#define CFG_COORDS2(name) \ + if ((wcoords_idx++, 1) && !GET_wCOORD_FLAG(wcoords_idx) && \ + strcmp(cfg_name, #name "_coords") == 0) { \ + short x,y; \ + if (sscanf(val, "%hd,%hd", &x, &y) == 2) { \ + THEME.name##_x = x; \ + THEME.name##_y = y; \ + } \ + } \ + else if (CFG.widescreen && \ + strcmp(cfg_name, "w" #name "_coords") == 0) { \ + short x,y; \ + if (sscanf(val, "%hd,%hd", &x, &y) == 2) { \ + THEME.name##_x = x; \ + THEME.name##_y = y; \ + SET_wCOORD_FLAG(wcoords_idx); \ + } \ + } +#define CFG_COORDS4(name) \ + if ((wcoords_idx++, 1) && !GET_wCOORD_FLAG(wcoords_idx) && \ + strcmp(cfg_name, #name "_coords") == 0) { \ + short x,y,w,h; \ + if (sscanf(val, "%hd,%hd,%hd,%hd", &x, &y, &w, &h) == 4) { \ + THEME.name##_x = x; \ + THEME.name##_y = y; \ + THEME.name##_w = w; \ + THEME.name##_h = h; \ + } \ + } \ + else if (CFG.widescreen && \ + strcmp(cfg_name, "w" #name "_coords") == 0) { \ + short x,y,w,h; \ + if (sscanf(val, "%hd,%hd,%hd,%hd", &x, &y, &w, &h) == 4) { \ + THEME.name##_x = x; \ + THEME.name##_y = y; \ + THEME.name##_w = w; \ + THEME.name##_h = h; \ + SET_wCOORD_FLAG(wcoords_idx); \ + } \ + } +#define CFG_COLOR(name) \ + if (strcmp(cfg_name, #name "_color") == 0) { \ + short r,g,b,a; \ + int c = sscanf(val, "%hd,%hd,%hd,%hd", &r, &g, &b, &a); \ + if(c >= 3) { \ + THEME.name.r = r; \ + THEME.name.g = g; \ + THEME.name.b = b; \ + if(c >= 4) \ + THEME.name.a = a; \ + } \ + } +#define CFG_VAL(name) \ + if (strcmp(cfg_name, #name) == 0) { \ + short v; \ + if (sscanf(val, "%hd", &v) == 1) { \ + THEME.name = v; \ + } \ + } -#define CFG_BOOL(name) if(cfg_bool(#name, &THEME.name)); +#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)); -#define OLD_FAV_ICON 1 -#define OLD_ABC_ICON 2 -#define OLD_COUNT_ICON 4 -#define OLD_LIST_ICON 8 -#define OLD_GRID_ICON 16 -#define OLD_CAROUSEL_ICON 32 -static short WorkAroundIconSet=0; -static short WorkAroundBarOffset=100; +#define OLD_FAV_ICON 1 +#define OLD_ABC_ICON 2 +#define OLD_COUNT_ICON 4 +#define OLD_LIST_ICON 8 +#define OLD_GRID_ICON 16 +#define OLD_CAROUSEL_ICON 32 +static short WorkAroundIconSet = 0; +static short WorkAroundBarOffset = 100; -void theme_set(char *name, char *val) { - cfg_name = name; - cfg_val = val; - int wcoords_idx = -1; +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(gamecarousel) + CFG_COORDS4( gamelist ) + else CFG_COORDS4( gamegrid ) + else CFG_COORDS4( gamecarousel ) - else CFG_COORDS2(covers) + else CFG_COORDS2( covers ) - else CFG_BOOL(show_id) - else CFG_COORDS2(id) + else CFG_BOOL( show_id ) + else CFG_COORDS2( id ) - else CFG_BOOL(show_region) - else CFG_COORDS2(region) + else CFG_BOOL( show_region ) + else CFG_COORDS2( region ) - else CFG_COORDS2(sdcard) - else CFG_COORDS2(homebrew) - else CFG_COORDS2(power) - else CFG_COORDS2(home) - else CFG_COORDS2(setting) - else CFG_COORDS2(install) + else CFG_COORDS2( sdcard ) + else CFG_COORDS2( homebrew ) + else CFG_COORDS2( power ) + else CFG_COORDS2( home ) + else CFG_COORDS2( setting ) + else CFG_COORDS2( install ) - else CFG_COORDS2(clock) - else CFG_ALIGN(clock) - else CFG_COLOR(clock) + else CFG_COORDS2( clock ) + else CFG_ALIGN( clock ) + else CFG_COLOR( clock ) - else CFG_COLOR(info) - else CFG_BOOL(show_hddinfo) - else CFG_ALIGN(hddinfo) - else CFG_COORDS2(hddinfo) + else CFG_COLOR( info ) + else CFG_BOOL( show_hddinfo ) + else CFG_ALIGN( hddinfo ) + else CFG_COORDS2( hddinfo ) - else CFG_BOOL(show_gamecount) - else CFG_ALIGN(gamecount) - else CFG_COORDS2(gamecount) + else CFG_BOOL( show_gamecount ) + else CFG_ALIGN( gamecount ) + else CFG_COORDS2( gamecount ) - else CFG_BOOL(show_tooltip) - else CFG_VAL(tooltipAlpha) + else CFG_BOOL( show_tooltip ) + else CFG_VAL( tooltipAlpha ) - else CFG_COLOR(prompttext) - else CFG_COLOR(settingstext) - else CFG_COLOR(gametext) + else CFG_COLOR( prompttext ) + else CFG_COLOR( settingstext ) + else CFG_COLOR( gametext ) - else CFG_VAL(pagesize) + else CFG_VAL( pagesize ) - else CFG_COORDS2(gamelist_favorite) - else CFG_COORDS2(gamegrid_favorite) - else CFG_COORDS2(gamecarousel_favorite) + else CFG_COORDS2( gamelist_favorite ) + 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(!CFG.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(!CFG.widescreen) x-= CFG.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(!CFG.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(!CFG.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(!CFG.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(!CFG.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(!CFG.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 + //********************************** + 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 ( !CFG.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 ( !CFG.widescreen ) x -= CFG.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 ( !CFG.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 ( !CFG.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 ( !CFG.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 ( !CFG.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 ( !CFG.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; - // old themes have no dvd_coords - // place the dvdIcon to the right side of the carouselIcon - if(!CFG.widescreen) x+= CFG.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; + // old themes have no dvd_coords + // place the dvdIcon to the right side of the carouselIcon + if ( !CFG.widescreen ) x += CFG.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; - x+= CFG.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; - } - } + x += CFG.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; - } - } + 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; + } + } } -void global_cfg_set(char *name, char *val) { +void global_cfg_set( char *name, char *val ) +{ cfg_name = name; cfg_val = val; - if (strcmp(name, "video") == 0) { + if ( strcmp( name, "video" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.video = i; } return; - } else if (strcmp(name, "vpatch") == 0) { + } + else if ( strcmp( name, "vpatch" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { - Settings.vpatch =i; + if ( sscanf( val, "%d", &i ) == 1 ) + { + Settings.vpatch = i; } return; } - else if (strcmp(name, "language") == 0) { + else if ( strcmp( name, "language" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.language = i; } return; - } else if (strcmp(name, "ocarina") == 0) { + } + else if ( strcmp( name, "ocarina" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.ocarina = i; } return; - } else if (strcmp(name, "sort") == 0) { + } + else if ( strcmp( name, "sort" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.sort = i; } return; - } else if (strcmp(name, "fave") == 0) { + } + else if ( strcmp( name, "fave" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.fave = i; } return; - } else if (strcmp(name, "keyset") == 0) { + } + else if ( strcmp( name, "keyset" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.keyset = i; } return; - } else if (strcmp(name, "hddinfo") == 0) { + } + else if ( strcmp( name, "hddinfo" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.hddinfo = i; } return; - } else if (strcmp(name, "sinfo") == 0) { + } + else if ( strcmp( name, "sinfo" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.sinfo = i; } return; - } else if (strcmp(name, "rumble") == 0) { + } + else if ( strcmp( name, "rumble" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.rumble = i; } return; - } else if (strcmp(name, "volume") == 0) { + } + else if ( strcmp( name, "volume" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.volume = i; } return; - } else if (strcmp(name, "sfxvolume") == 0) { + } + else if ( strcmp( name, "sfxvolume" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.sfxvolume = i; } return; - } else if (strcmp(name, "gamesoundvolume") == 0) { + } + else if ( strcmp( name, "gamesoundvolume" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.gamesoundvolume = i; } return; - } else if (strcmp(name, "tooltips") == 0) { + } + else if ( strcmp( name, "tooltips" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.tooltips = i; } return; - } else if (strcmp(name, "password") == 0) { - strlcpy(Settings.unlockCode, val, sizeof(Settings.unlockCode)); + } + else if ( strcmp( name, "password" ) == 0 ) + { + strlcpy( Settings.unlockCode, val, sizeof( Settings.unlockCode ) ); return; - } else if (strcmp(name, "parentalcontrol") == 0) { + } + else if ( strcmp( name, "parentalcontrol" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.parentalcontrol = i; } return; - } else if (strcmp(name, "cios") == 0) { + } + else if ( strcmp( name, "cios" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.cios = i; } return; - } else if (strcmp(name, "gridRows") == 0) { + } + else if ( strcmp( name, "gridRows" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.gridRows = i; } return; - } else if (strcmp(name, "xflip") == 0) { + } + else if ( strcmp( name, "xflip" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.xflip = i; } return; - } else if (strcmp(name, "qboot") == 0) { + } + else if ( strcmp( name, "qboot" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.qboot = i; } return; - } else if (strcmp(name, "wsprompt") == 0) { + } + else if ( strcmp( name, "wsprompt" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.wsprompt = i; } return; - } else if (strcmp(name, "wiilight") == 0) { + } + else if ( strcmp( name, "wiilight" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.wiilight = i; } return; - } else if (strcmp(name, "autonetwork") == 0) { + } + else if ( strcmp( name, "autonetwork" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.autonetwork = i; } return; - } else if (strcmp(name, "discart") == 0) { + } + else if ( strcmp( name, "discart" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.discart = i; } return; - } else if (strcmp(name, "patchcountrystrings") == 0) { + } + else if ( strcmp( name, "patchcountrystrings" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.patchcountrystrings = i; } return; - } else if (strcmp(name, "error002") == 0) { + } + else if ( strcmp( name, "error002" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.error002 = i; } return; - } else if (strcmp(name, "gamesound") == 0) { + } + else if ( strcmp( name, "gamesound" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.gamesound = i; } return; - } else if (strcmp(name, "titlesOverride") == 0) { + } + else if ( strcmp( name, "titlesOverride" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.titlesOverride = i; } return; - } else if (strcmp(name, "db_JPtoEN") == 0) { + } + else if ( strcmp( name, "db_JPtoEN" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.db_JPtoEN = i; } return; - } else if (strcmp(name, "gameDisplay") == 0) { + } + else if ( strcmp( name, "gameDisplay" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.gameDisplay = i; } return; - } else if (strcmp(name, "screensaver") == 0) { + } + else if ( strcmp( name, "screensaver" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.screensaver = i; } return; - } else if (strcmp(name, "musicloopmode") == 0) { + } + else if ( strcmp( name, "musicloopmode" ) == 0 ) + { int i; - if (sscanf(val, "%d", &i) == 1) { + if ( sscanf( val, "%d", &i ) == 1 ) + { Settings.musicloopmode = i; } return; - } else if (strcmp(name, "partition") == 0) { - int i; - if (sscanf(val, "%d", &i) == 1) { - Settings.partition = i; - } - return; - } else if (strcmp(name, "marknewtitles") == 0) { - int i; - if (sscanf(val, "%d", &i) == 1) { - Settings.marknewtitles = i; - } - return; - } else if (strcmp(name, "fatInstallToDir") == 0) { - int i; - if (sscanf(val, "%d", &i) == 1) { - Settings.FatInstallToDir = i; - } - } else if (strcmp(name, "partitions") == 0) { - int i; - if (sscanf(val, "%d", &i) == 1) { - Settings.partitions_to_install = i; - } - } else if (strcmp(name, "fullcopy") == 0) { - int i; - if (sscanf(val, "%d", &i) == 1) { - Settings.fullcopy = i; - } - } else if (strcmp(name, "beta_upgrades") == 0) { - int i; - if (sscanf(val, "%d", &i) == 1) { - Settings.beta_upgrades = i; - } - } + } + else if ( strcmp( name, "partition" ) == 0 ) + { + int i; + if ( sscanf( val, "%d", &i ) == 1 ) + { + Settings.partition = i; + } + return; + } + else if ( strcmp( name, "marknewtitles" ) == 0 ) + { + int i; + if ( sscanf( val, "%d", &i ) == 1 ) + { + Settings.marknewtitles = i; + } + return; + } + else if ( strcmp( name, "fatInstallToDir" ) == 0 ) + { + int i; + if ( sscanf( val, "%d", &i ) == 1 ) + { + Settings.FatInstallToDir = i; + } + } + else if ( strcmp( name, "partitions" ) == 0 ) + { + int i; + if ( sscanf( val, "%d", &i ) == 1 ) + { + Settings.partitions_to_install = i; + } + } + else if ( strcmp( name, "fullcopy" ) == 0 ) + { + int i; + if ( sscanf( val, "%d", &i ) == 1 ) + { + Settings.fullcopy = i; + } + } + else if ( strcmp( name, "beta_upgrades" ) == 0 ) + { + int i; + if ( sscanf( val, "%d", &i ) == 1 ) + { + Settings.beta_upgrades = i; + } + } - cfg_bool("godmode", &Settings.godmode); + cfg_bool( "godmode", &Settings.godmode ); return; } // split line to part1 delimiter part2 -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); +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 ); 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 { + 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* cfg_get_game( u8 *id ) +{ + 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) { - strncpy((char*)game->id, (char*)id, 6); +void cfg_set_game_opt( struct Game_CFG *game, u8 *id ) +{ + strncpy( ( char* )game->id, ( char* )id, 6 ); game->id[6] = 0; game->video = videoChoice; game->language = languageChoice; @@ -1283,130 +1485,140 @@ void cfg_set_game_opt(struct Game_CFG *game, u8 *id) { game->iosreloadblock = reloadblock; game->patchcountrystrings = countrystrings; game->loadalternatedol = alternatedol; - if (game->loadalternatedol == 0) { - alternatedoloffset = 0; - strcpy(alternatedname, ""); - } + if ( game->loadalternatedol == 0 ) + { + alternatedoloffset = 0; + strcpy( alternatedname, "" ); + } game->alternatedolstart = alternatedoloffset; - strlcpy(game->alternatedolname, alternatedname,sizeof(game->alternatedolname)); + strlcpy( game->alternatedolname, alternatedname, sizeof( game->alternatedolname ) ); } -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* 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; 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) { - strncpy((char*)game->id, (char*)id, 6); +void cfg_set_game_num( struct Game_NUM *game, u8 *id ) +{ + strncpy( ( char* )game->id, ( char* )id, 6 ); game->id[6] = 0; game->favorite = favoritevar; game->count = playcount; } -bool cfg_save_global() { // save global settings +bool cfg_save_global() // save global settings +{ char GXGlobal_cfg[26]; - sprintf(GXGlobal_cfg, "%s/config", bootDevice); + sprintf( GXGlobal_cfg, "%s/config", bootDevice ); struct stat st; - if (stat(GXGlobal_cfg, &st) != 0) { - mkdir(GXGlobal_cfg, 0777); + if ( stat( GXGlobal_cfg, &st ) != 0 ) + { + mkdir( GXGlobal_cfg, 0777 ); } FILE *f; - sprintf(GXGlobal_cfg, "%s/config/GXGlobal.cfg", bootDevice); - f = fopen(GXGlobal_cfg, "w"); - if (!f) { - printf("Error saving %s\n", GXGlobal_cfg); - sleep(1); + sprintf( GXGlobal_cfg, "%s/config/GXGlobal.cfg", bootDevice ); + f = fopen( GXGlobal_cfg, "w" ); + if ( !f ) + { + printf( "Error saving %s\n", GXGlobal_cfg ); + sleep( 1 ); return false; } - fprintf(f, "# USB Loader global settings file\n"); - fprintf(f, "# Note: This file is automatically generated\n"); - fclose(f); + fprintf( f, "# USB Loader global 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(GXGlobal_cfg, "w"); - fprintf(f, "# USB Loader global settings file\n"); - fprintf(f, "# Note: This file is automatically generated\n "); - fprintf(f, "video = %d\n ", Settings.video); - fprintf(f, "vpatch = %d\n ", Settings.vpatch); - fprintf(f, "language = %d\n ", Settings.language); - fprintf(f, "ocarina = %d\n ", Settings.ocarina); - fprintf(f, "hddinfo = %d\n ", Settings.hddinfo); - fprintf(f, "sinfo = %d\n ", Settings.sinfo); - fprintf(f, "rumble = %d\n ", Settings.rumble); - fprintf(f, "volume = %d\n ", Settings.volume); - fprintf(f, "sfxvolume = %d\n ", Settings.sfxvolume); - fprintf(f, "gamesoundvolume = %d\n ", Settings.gamesoundvolume); - fprintf(f, "tooltips = %d\n ", Settings.tooltips); - fprintf(f, "password = %s\n ", Settings.unlockCode); - fprintf(f, "sort = %d\n ", Settings.sort); - fprintf(f, "fave = %d\n ", Settings.fave); - fprintf(f, "cios = %d\n ", Settings.cios); - fprintf(f, "keyset = %d\n ", Settings.keyset); - fprintf(f, "xflip = %d\n ", Settings.xflip); - fprintf(f, "gridRows = %d\n ", Settings.gridRows); - fprintf(f, "qboot = %d\n ", Settings.qboot); - fprintf(f, "wsprompt = %d\n ", Settings.wsprompt); - fprintf(f, "parentalcontrol = %d\n ", Settings.parentalcontrol); - fprintf(f, "cover_path = %s\n ", Settings.covers_path); - fprintf(f, "cover2d_path = %s\n ", Settings.covers2d_path); - if (CFG.widescreen) { - fprintf(f, "wtheme_path = %s\n ", CFG.theme_path); - } else { - fprintf(f, "theme_path = %s\n ", CFG.theme_path); + f = fopen( GXGlobal_cfg, "w" ); + fprintf( f, "# USB Loader global settings file\n" ); + fprintf( f, "# Note: This file is automatically generated\n " ); + fprintf( f, "video = %d\n ", Settings.video ); + fprintf( f, "vpatch = %d\n ", Settings.vpatch ); + fprintf( f, "language = %d\n ", Settings.language ); + fprintf( f, "ocarina = %d\n ", Settings.ocarina ); + fprintf( f, "hddinfo = %d\n ", Settings.hddinfo ); + fprintf( f, "sinfo = %d\n ", Settings.sinfo ); + fprintf( f, "rumble = %d\n ", Settings.rumble ); + fprintf( f, "volume = %d\n ", Settings.volume ); + fprintf( f, "sfxvolume = %d\n ", Settings.sfxvolume ); + fprintf( f, "gamesoundvolume = %d\n ", Settings.gamesoundvolume ); + fprintf( f, "tooltips = %d\n ", Settings.tooltips ); + fprintf( f, "password = %s\n ", Settings.unlockCode ); + fprintf( f, "sort = %d\n ", Settings.sort ); + fprintf( f, "fave = %d\n ", Settings.fave ); + fprintf( f, "cios = %d\n ", Settings.cios ); + fprintf( f, "keyset = %d\n ", Settings.keyset ); + fprintf( f, "xflip = %d\n ", Settings.xflip ); + fprintf( f, "gridRows = %d\n ", Settings.gridRows ); + fprintf( f, "qboot = %d\n ", Settings.qboot ); + fprintf( f, "wsprompt = %d\n ", Settings.wsprompt ); + fprintf( f, "parentalcontrol = %d\n ", Settings.parentalcontrol ); + fprintf( f, "cover_path = %s\n ", Settings.covers_path ); + fprintf( f, "cover2d_path = %s\n ", Settings.covers2d_path ); + if ( CFG.widescreen ) + { + fprintf( f, "wtheme_path = %s\n ", CFG.theme_path ); } - fprintf(f, "disc_path = %s\n ", Settings.disc_path); - fprintf(f, "language_path = %s\n ", Settings.language_path); - fprintf(f, "languagefiles_path = %s\n ", Settings.languagefiles_path); - fprintf(f, "TxtCheatcodespath = %s\n ", Settings.TxtCheatcodespath); - fprintf(f, "titlestxt_path = %s\n ", Settings.titlestxt_path); - fprintf(f, "gamesound = %d\n ", Settings.gamesound); - fprintf(f, "dolpath = %s\n ", Settings.dolpath); - fprintf(f, "ogg_path = %s\n ", Settings.ogg_path); - fprintf(f, "wiilight = %d\n ", Settings.wiilight); - fprintf(f, "gameDisplay = %d\n ", Settings.gameDisplay); - fprintf(f, "update_path = %s\n ", Settings.update_path); - fprintf(f, "theme_downloadpath = %s\n ", Settings.theme_downloadpath); - fprintf(f, "homebrewapps_path = %s\n ", Settings.homebrewapps_path); - fprintf(f, "Cheatcodespath = %s\n ", Settings.Cheatcodespath); - fprintf(f, "BcaCodepath = %s\n ", Settings.BcaCodepath); - fprintf(f, "WipCodepath = %s\n ", Settings.WipCodepath); - fprintf(f, "titlesOverride = %d\n ", Settings.titlesOverride); + else + { + fprintf( f, "theme_path = %s\n ", CFG.theme_path ); + } + fprintf( f, "disc_path = %s\n ", Settings.disc_path ); + fprintf( f, "language_path = %s\n ", Settings.language_path ); + fprintf( f, "languagefiles_path = %s\n ", Settings.languagefiles_path ); + fprintf( f, "TxtCheatcodespath = %s\n ", Settings.TxtCheatcodespath ); + fprintf( f, "titlestxt_path = %s\n ", Settings.titlestxt_path ); + fprintf( f, "gamesound = %d\n ", Settings.gamesound ); + fprintf( f, "dolpath = %s\n ", Settings.dolpath ); + fprintf( f, "ogg_path = %s\n ", Settings.ogg_path ); + fprintf( f, "wiilight = %d\n ", Settings.wiilight ); + fprintf( f, "gameDisplay = %d\n ", Settings.gameDisplay ); + fprintf( f, "update_path = %s\n ", Settings.update_path ); + fprintf( f, "theme_downloadpath = %s\n ", Settings.theme_downloadpath ); + fprintf( f, "homebrewapps_path = %s\n ", Settings.homebrewapps_path ); + fprintf( f, "Cheatcodespath = %s\n ", Settings.Cheatcodespath ); + fprintf( f, "BcaCodepath = %s\n ", Settings.BcaCodepath ); + fprintf( f, "WipCodepath = %s\n ", Settings.WipCodepath ); + fprintf( f, "titlesOverride = %d\n ", Settings.titlesOverride ); //fprintf(f, "db_url = %s\n ", Settings.db_url); //fprintf(f, "db_JPtoEN = %d\n ", Settings.db_JPtoEN); //fprintf(f, "db_language = %d\n ", Settings.language); - fprintf(f, "patchcountrystrings = %d\n ", Settings.patchcountrystrings); - fprintf(f, "screensaver = %d\n ", Settings.screensaver); - fprintf(f, "musicloopmode = %d\n ", Settings.musicloopmode); - fprintf(f, "error002 = %d\n ", Settings.error002); - fprintf(f, "autonetwork = %d\n ", Settings.autonetwork); - fprintf(f, "discart = %d\n ", Settings.discart); - fprintf(f, "partition = %d\n ", Settings.partition); - fprintf(f, "marknewtitles = %d\n ", Settings.marknewtitles); - fprintf(f, "fatInstallToDir = %d\n ", Settings.FatInstallToDir); - fprintf(f, "partitions = %d\n ", Settings.partitions_to_install); - fprintf(f, "fullcopy = %d\n ", Settings.fullcopy); - fprintf(f, "beta_upgrades = %d\n ", Settings.beta_upgrades); - fclose(f); + fprintf( f, "patchcountrystrings = %d\n ", Settings.patchcountrystrings ); + fprintf( f, "screensaver = %d\n ", Settings.screensaver ); + fprintf( f, "musicloopmode = %d\n ", Settings.musicloopmode ); + fprintf( f, "error002 = %d\n ", Settings.error002 ); + fprintf( f, "autonetwork = %d\n ", Settings.autonetwork ); + fprintf( f, "discart = %d\n ", Settings.discart ); + fprintf( f, "partition = %d\n ", Settings.partition ); + fprintf( f, "marknewtitles = %d\n ", Settings.marknewtitles ); + fprintf( f, "fatInstallToDir = %d\n ", Settings.FatInstallToDir ); + fprintf( f, "partitions = %d\n ", Settings.partitions_to_install ); + fprintf( f, "fullcopy = %d\n ", Settings.fullcopy ); + fprintf( f, "beta_upgrades = %d\n ", Settings.beta_upgrades ); + fclose( f ); return true; } -void game_set(char *name, char *val) { +void game_set( char *name, char *val ) +{ // sample line: // game:RTNP41 = video:game; language:english; ocarina:0; // game:RYWP01 = video:patch; language:console; ocarina:1; //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 @@ -1414,115 +1626,144 @@ void game_set(char *name, char *val) { char opt[300], *p, *np; p = val; - while (p) { - np = strchr(p, ';'); - if (np) trim_n_copy(opt, p, np-p, sizeof(opt)); - else trimcopy(opt, p, sizeof(opt)); + while ( p ) + { + 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 (sscanf(opt_val, "%hd", &opt_c) == 1) { + if ( strcmp( "ocarina", opt_name ) == 0 ) + { + if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + { game->ocarina = opt_c; } } - if (strcmp("vipatch", opt_name) == 0) { - if (sscanf(opt_val, "%hd", &opt_c) == 1) { + if ( strcmp( "vipatch", opt_name ) == 0 ) + { + if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + { game->vipatch = opt_c; } } - if (strcmp("ios", opt_name) == 0) { - if (sscanf(opt_val, "%hd", &opt_c) == 1) { + if ( strcmp( "ios", opt_name ) == 0 ) + { + if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + { game->ios = opt_c; } } - if (strcmp("pctrl", opt_name) == 0) { - if (sscanf(opt_val, "%hd", &opt_c) == 1) { + if ( strcmp( "pctrl", opt_name ) == 0 ) + { + if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + { game->parentalcontrol = opt_c; } } - if (strcmp("errorfix002", opt_name) == 0) { - if (sscanf(opt_val, "%hd", &opt_c) == 1) { + if ( strcmp( "errorfix002", opt_name ) == 0 ) + { + if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + { game->errorfix002 = opt_c; } } - if (strcmp("iosreloadblock", opt_name) == 0) { - if (sscanf(opt_val, "%hd", &opt_c) == 1) { + if ( strcmp( "iosreloadblock", opt_name ) == 0 ) + { + if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + { game->iosreloadblock = opt_c; } } - if (strcmp("patchcountrystrings", opt_name) == 0) { - if (sscanf(opt_val, "%hd", &opt_c) == 1) { + if ( strcmp( "patchcountrystrings", opt_name ) == 0 ) + { + if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + { game->patchcountrystrings = opt_c; } } - if (strcmp("loadalternatedol", opt_name) == 0) { - if (sscanf(opt_val, "%hd", &opt_c) == 1) { + if ( strcmp( "loadalternatedol", opt_name ) == 0 ) + { + if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + { game->loadalternatedol = opt_c; } } - if (strcmp("alternatedolstart", opt_name) == 0) { - if (sscanf(opt_val, "%hd", &opt_c) == 1) { + if ( strcmp( "alternatedolstart", opt_name ) == 0 ) + { + 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( "alternatedolname", opt_name ) == 0 ) + { + strlcpy( game->alternatedolname, opt_val, sizeof( game->alternatedolname ) ); } } // 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; // game:RYWP01 = video:patch; language:console; ocarina:1; //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) { - np = strchr(p, ';'); - if (np) trim_n_copy(opt, p, np-p, sizeof(opt)); - else trimcopy(opt, p, sizeof(opt)); + while ( p ) + { + 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 (sscanf(opt_val, "%hd", &opt_c) == 1) { - cfg_control = realloc(cfg_control, (num_control+1) * sizeof(struct ID_Control)); - if (!cfg_control) { + if ( strcmp( "pctrl", opt_name ) == 0 ) + { + if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + { + 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++; } @@ -1530,19 +1771,20 @@ 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); + 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); + cfg_set_game_num( game, id ); // parse val @@ -1550,156 +1792,174 @@ void game_set_num(char *name, char *val) { char opt[200], *p, *np; p = val; - while (p) { - np = strchr(p, ';'); - if (np) trim_n_copy(opt, p, np-p, sizeof(opt)); - else trimcopy(opt, p, sizeof(opt)); + while ( p ) + { + 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 (sscanf(opt_val, "%hd", &opt_c) == 1) { + if ( strcmp( "favorite", opt_name ) == 0 ) + { + if ( sscanf( opt_val, "%hd", &opt_c ) == 1 ) + { game->favorite = opt_c; } } - if (strcmp("count", opt_name) == 0) { - if (sscanf(opt_val, "%hd", &opt_c) == 1) { + if ( strcmp( "count", opt_name ) == 0 ) + { + 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; } } -bool cfg_load_games() { +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() { +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() { +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) { - printf("Error saving %s\n", "GXGameSettings.cfg"); - sleep(1); + sprintf( GXGameSettings_cfg, "%s/config/GXGameSettings.cfg", bootDevice ); + f = fopen( GXGameSettings_cfg, "w" ); + if ( !f ) + { + 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 #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #include "usbloader/disc.h" @@ -16,9 +17,9 @@ extern "C" { #define CFG_VIDEO_DEFAULT 1 #define CFG_VIDEO_GAME 1 // game default #define CFG_VIDEO_PATCH 2 // patch mode -#define CFG_VIDEO_PAL50 3 // force PAL -#define CFG_VIDEO_PAL60 4 // force PAL60 -#define CFG_VIDEO_NTSC 5 // force NTSC +#define CFG_VIDEO_PAL50 3 // force PAL +#define CFG_VIDEO_PAL60 4 // force PAL60 +#define CFG_VIDEO_NTSC 5 // force NTSC #define CFG_VIDEO_COUNT 6 #define CFG_LANG_CONSOLE 0 @@ -44,434 +45,440 @@ extern "C" { extern char bootDevice[10]; //extern char *cfg_path; - struct CFG { - short widescreen; - char theme_path[100]; - }; + struct CFG + { + short widescreen; + char theme_path[100]; + }; - struct THEME { - short gamelist_x; - short gamelist_y; - short gamelist_w; - short gamelist_h; - short gamegrid_x; - short gamegrid_y; - short gamegrid_w; - short gamegrid_h; - short gamecarousel_x; - short gamecarousel_y; - short gamecarousel_w; - short gamecarousel_h; + struct THEME + { + short gamelist_x; + short gamelist_y; + short gamelist_w; + short gamelist_h; + short gamegrid_x; + short gamegrid_y; + short gamegrid_w; + short gamegrid_h; + short gamecarousel_x; + short gamecarousel_y; + short gamecarousel_w; + short gamecarousel_h; - short covers_x; - short covers_y; + short covers_x; + short covers_y; - short show_id; - short id_x; - short id_y; - short show_region; - short region_x; - short region_y; + short show_id; + short id_x; + short id_y; + short show_region; + short region_x; + short region_y; - short sdcard_x; - short sdcard_y; - short homebrew_x; - short homebrew_y; - short power_x; - short power_y; - short home_x; - short home_y; - short setting_x; - short setting_y; - short install_x; - short install_y; - GXColor clock; - short clock_align; - short clock_x; - short clock_y; + short sdcard_x; + short sdcard_y; + short homebrew_x; + short homebrew_y; + short power_x; + short power_y; + short home_x; + short home_y; + short setting_x; + short setting_y; + short install_x; + short install_y; + GXColor clock; + short clock_align; + short clock_x; + short clock_y; - GXColor info; - short show_hddinfo; - short hddinfo_align; - short hddinfo_x; - short hddinfo_y; + GXColor info; + short show_hddinfo; + short hddinfo_align; + short hddinfo_x; + short hddinfo_y; - short show_gamecount; - short gamecount_align; - short gamecount_x; - short gamecount_y; + short show_gamecount; + short gamecount_align; + short gamecount_x; + short gamecount_y; - short show_tooltip; - int tooltipAlpha; + short show_tooltip; + int tooltipAlpha; - GXColor prompttext; - GXColor settingstext; - GXColor gametext; - short pagesize; + GXColor prompttext; + GXColor settingstext; + GXColor gametext; + short pagesize; - // Toolbar Icons in GameList - /* - short favorite_x; - short favorite_y; - short search_x; - short search_y; - short abc_x; - short abc_y; - short count_x; - short count_y; - short list_x; - short list_y; - short grid_x; - short grid_y; - short carousel_x; - short carousel_y; - short sortBarOffset; - */ - // Toolbar Icons in GameList - short gamelist_favorite_x; - short gamelist_favorite_y; - short gamelist_search_x; - short gamelist_search_y; - short gamelist_abc_x; - short gamelist_abc_y; - short gamelist_count_x; - short gamelist_count_y; - short gamelist_list_x; - short gamelist_list_y; - short gamelist_grid_x; - short gamelist_grid_y; - short gamelist_carousel_x; - short gamelist_carousel_y; - short gamelist_dvd_x; - short gamelist_dvd_y; - short gamelist_lock_x; - short gamelist_lock_y; - // Toolbar Icons in GameGrid - short gamegrid_favorite_x; - short gamegrid_favorite_y; - short gamegrid_search_x; - short gamegrid_search_y; - short gamegrid_abc_x; - short gamegrid_abc_y; - short gamegrid_count_x; - short gamegrid_count_y; - short gamegrid_list_x; - short gamegrid_list_y; - short gamegrid_grid_x; - short gamegrid_grid_y; - short gamegrid_carousel_x; - short gamegrid_carousel_y; - short gamegrid_dvd_x; - short gamegrid_dvd_y; - short gamegrid_lock_x; - short gamegrid_lock_y; - // Toolbar Icons in GameCarousel - short gamecarousel_favorite_x; - short gamecarousel_favorite_y; - short gamecarousel_search_x; - short gamecarousel_search_y; - short gamecarousel_abc_x; - short gamecarousel_abc_y; - short gamecarousel_count_x; - short gamecarousel_count_y; - short gamecarousel_list_x; - short gamecarousel_list_y; - short gamecarousel_grid_x; - short gamecarousel_grid_y; - short gamecarousel_carousel_x; - short gamecarousel_carousel_y; - short gamecarousel_dvd_x; - short gamecarousel_dvd_y; - short gamecarousel_lock_x; - short gamecarousel_lock_y; - }; + // Toolbar Icons in GameList + /* + short favorite_x; + short favorite_y; + short search_x; + short search_y; + short abc_x; + short abc_y; + short count_x; + short count_y; + short list_x; + short list_y; + short grid_x; + short grid_y; + short carousel_x; + short carousel_y; + short sortBarOffset; + */ + // Toolbar Icons in GameList + short gamelist_favorite_x; + short gamelist_favorite_y; + short gamelist_search_x; + short gamelist_search_y; + short gamelist_abc_x; + short gamelist_abc_y; + short gamelist_count_x; + short gamelist_count_y; + short gamelist_list_x; + short gamelist_list_y; + short gamelist_grid_x; + short gamelist_grid_y; + short gamelist_carousel_x; + short gamelist_carousel_y; + short gamelist_dvd_x; + short gamelist_dvd_y; + short gamelist_lock_x; + short gamelist_lock_y; + // Toolbar Icons in GameGrid + short gamegrid_favorite_x; + short gamegrid_favorite_y; + short gamegrid_search_x; + short gamegrid_search_y; + short gamegrid_abc_x; + short gamegrid_abc_y; + short gamegrid_count_x; + short gamegrid_count_y; + short gamegrid_list_x; + short gamegrid_list_y; + short gamegrid_grid_x; + short gamegrid_grid_y; + short gamegrid_carousel_x; + short gamegrid_carousel_y; + short gamegrid_dvd_x; + short gamegrid_dvd_y; + short gamegrid_lock_x; + short gamegrid_lock_y; + // Toolbar Icons in GameCarousel + short gamecarousel_favorite_x; + short gamecarousel_favorite_y; + short gamecarousel_search_x; + short gamecarousel_search_y; + short gamecarousel_abc_x; + short gamecarousel_abc_y; + short gamecarousel_count_x; + short gamecarousel_count_y; + short gamecarousel_list_x; + short gamecarousel_list_y; + short gamecarousel_grid_x; + short gamecarousel_grid_y; + short gamecarousel_carousel_x; + short gamecarousel_carousel_y; + short gamecarousel_dvd_x; + short gamecarousel_dvd_y; + short gamecarousel_lock_x; + short gamecarousel_lock_y; + }; - extern struct CFG CFG; - extern struct THEME THEME; - extern u8 ocarinaChoice; - extern u16 playcnt; - extern u8 videoChoice; - extern u8 languageChoice; - extern u8 viChoice; - extern u8 iosChoice; - extern u8 parentalcontrolChoice; - extern u8 fix002; - extern u8 reloadblock; - extern u8 countrystrings; - extern u8 alternatedol; - extern u32 alternatedoloffset; - extern u8 xflip; - extern u8 qboot; - extern u8 sort; - extern u8 fave; - extern u8 wsprompt; - extern u8 keyset; - extern u8 gameDisplay; - extern u16 playcount; - extern u8 favoritevar; - extern char alternatedname[40]; + extern struct CFG CFG; + extern struct THEME THEME; + extern u8 ocarinaChoice; + extern u16 playcnt; + extern u8 videoChoice; + extern u8 languageChoice; + extern u8 viChoice; + extern u8 iosChoice; + extern u8 parentalcontrolChoice; + extern u8 fix002; + extern u8 reloadblock; + extern u8 countrystrings; + extern u8 alternatedol; + extern u32 alternatedoloffset; + extern u8 xflip; + extern u8 qboot; + extern u8 sort; + extern u8 fave; + extern u8 wsprompt; + extern u8 keyset; + extern u8 gameDisplay; + extern u16 playcount; + extern u8 favoritevar; + extern char alternatedname[40]; - struct Game_CFG { - u8 id[8]; - u8 video; - u8 language; - u8 ocarina; - u8 vipatch; - u8 ios; - u8 parentalcontrol; - u8 errorfix002; - u8 iosreloadblock; - u8 loadalternatedol; - u32 alternatedolstart; - u8 patchcountrystrings; - char alternatedolname[40]; - }; - struct Game_NUM { - u8 id[8]; - u8 favorite; - u16 count; - }; + struct Game_CFG + { + u8 id[8]; + u8 video; + u8 language; + u8 ocarina; + u8 vipatch; + u8 ios; + u8 parentalcontrol; + u8 errorfix002; + u8 iosreloadblock; + u8 loadalternatedol; + u32 alternatedolstart; + u8 patchcountrystrings; + char alternatedolname[40]; + }; + struct Game_NUM + { + u8 id[8]; + u8 favorite; + u16 count; + }; - void CFG_Default(int widescreen); // -1 = non forced mode - void CFG_Load(void); - struct Game_CFG* CFG_get_game_opt(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); + void CFG_Default( int widescreen ); // -1 = non forced mode + void CFG_Load( void ); + 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 ); - enum { - ConsoleLangDefault=0, - jap, - eng, - ger, - fren, - esp, - it, - dut, - schin, - tchin, - kor, - settings_language_max // always the last entry - }; + enum { + ConsoleLangDefault = 0, + jap, + eng, + ger, + fren, + esp, + it, + dut, + schin, + tchin, + kor, + settings_language_max // always the last entry + }; - enum { - systemdefault=0, - discdefault, - patch, - pal50, - pal60, - ntsc, - settings_video_max // always the last entry - }; + enum { + systemdefault = 0, + discdefault, + patch, + pal50, + pal60, + ntsc, + settings_video_max // always the last entry + }; - enum { - off=0, - on, - settings_off_on_max // always the last entry - }; - enum { - //off=0, - //on, - anti=2, - settings_error002_max // always the last entry - }; + enum { + off = 0, + on, + settings_off_on_max // always the last entry + }; + enum { + //off=0, + //on, + anti = 2, + settings_error002_max // always the last entry + }; - enum { - wiilight_off=0, - wiilight_on, - wiilight_forInstall, - settings_wiilight_max // always the last entry - }; + enum { + wiilight_off = 0, + wiilight_on, + wiilight_forInstall, + settings_wiilight_max // always the last entry + }; - enum { - GameID, - GameRegion, - Both, - Neither, - settings_sinfo_max // always the last entry - }; + enum { + GameID, + GameRegion, + Both, + Neither, + settings_sinfo_max // always the last entry + }; - enum { - i249=0, - i222, - i223, - i250, - settings_ios_max // always the last entry - }; + enum { + i249 = 0, + i222, + i223, + i250, + settings_ios_max // always the last entry + }; - enum { - ios249=0, - ios222, - ios223, - ios250, - settings_cios_max // always the last entry - }; + enum { + ios249 = 0, + ios222, + ios223, + ios250, + settings_cios_max // always the last entry + }; - enum { - hr12=0, - hr24, - Off, - settings_clock_max // always the last entry - }; - enum { - ALL=0, - PLAYCOUNT, - }; + enum { + hr12 = 0, + hr24, + Off, + settings_clock_max // always the last entry + }; + 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 { - us=0, - qwerty, - dvorak, - euro, - azerty, - settings_keyset_max // always the last entry - }; - enum { - list, - grid, - carousel, - settings_display_max - }; - enum { - scrollDefault, - scrollMarquee, - settings_scrolleffect_max // always the last entry - }; - enum { - install_game_only, - install_all, - install_all_but_update, - settings_partitions_max // always the last entry - }; - enum { - not_install_to_dir, - install_to_gameid_name, - install_to_name_gameid, - settings_installdir_max // always the last entry - }; - struct SParental { - u8 enabled; - u8 rating; - u8 pin[4]; - u8 question; - wchar_t answer[32]; // IS WCHAR! - }; - struct SSettings { - u8 video; - u8 language; - u8 ocarina; - u8 vpatch; - int ios; - u8 sinfo; - u8 hddinfo; - u8 rumble; - u8 xflip; - int volume; - int sfxvolume; - int gamesoundvolume; - u8 tooltips; - char unlockCode[20]; - u8 parentalcontrol; - u8 cios; - u8 qboot; - u8 wsprompt; - u8 keyset; - u8 sort; - u8 fave; - u8 wiilight; - u8 gameDisplay; - u8 patchcountrystrings; - u8 screensaver; - u8 partition; - u8 musicloopmode; - short godmode; - char covers_path[100]; - char covers2d_path[100]; - char theme_path[100]; - char wtheme_path[100]; - char theme_downloadpath[100]; - char disc_path[100]; - char titlestxt_path[100]; - char language_path[100]; - char languagefiles_path[100]; - char 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; - u8 titlesOverride; // db_titles - char db_url[200]; - char db_language[20]; - u8 db_JPtoEN; - u8 gridRows; - u8 autonetwork; - u8 discart; - short gamesound; - u8 marknewtitles; - u8 FatInstallToDir; - u8 partitions_to_install; - u8 fullcopy; - u8 beta_upgrades; - struct SParental parental; - }; - extern struct SSettings Settings; + enum { + no = 0, + yes, + sysmenu, + wtf, + disk3d, + settings_xflip_max // always the last entry + }; + enum { + us = 0, + qwerty, + dvorak, + euro, + azerty, + settings_keyset_max // always the last entry + }; + enum { + list, + grid, + carousel, + settings_display_max + }; + enum { + scrollDefault, + scrollMarquee, + settings_scrolleffect_max // always the last entry + }; + enum { + install_game_only, + install_all, + install_all_but_update, + settings_partitions_max // always the last entry + }; + enum { + not_install_to_dir, + install_to_gameid_name, + install_to_name_gameid, + settings_installdir_max // always the last entry + }; + struct SParental + { + u8 enabled; + u8 rating; + u8 pin[4]; + u8 question; + wchar_t answer[32]; // IS WCHAR! + }; + struct SSettings + { + u8 video; + u8 language; + u8 ocarina; + u8 vpatch; + int ios; + u8 sinfo; + u8 hddinfo; + u8 rumble; + u8 xflip; + int volume; + int sfxvolume; + int gamesoundvolume; + u8 tooltips; + char unlockCode[20]; + u8 parentalcontrol; + u8 cios; + u8 qboot; + u8 wsprompt; + u8 keyset; + u8 sort; + u8 fave; + u8 wiilight; + u8 gameDisplay; + u8 patchcountrystrings; + u8 screensaver; + u8 partition; + u8 musicloopmode; + short godmode; + char covers_path[100]; + char covers2d_path[100]; + char theme_path[100]; + char wtheme_path[100]; + char theme_downloadpath[100]; + char disc_path[100]; + char titlestxt_path[100]; + char language_path[100]; + char languagefiles_path[100]; + char 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; + u8 titlesOverride; // db_titles + char db_url[200]; + char db_language[20]; + u8 db_JPtoEN; + u8 gridRows; + u8 autonetwork; + u8 discart; + short gamesound; + u8 marknewtitles; + u8 FatInstallToDir; + u8 partitions_to_install; + u8 fullcopy; + u8 beta_upgrades; + struct SParental parental; + }; + extern struct SSettings Settings; - void CFG_LoadGlobal(void); - bool cfg_save_global(void); + void CFG_LoadGlobal( void ); + bool cfg_save_global( void ); - void GetLanguageToLangCode(int *langid, char *langcode); - bool OpenXMLDatabase(char* xmlfilepath, char* argdblang, bool argJPtoEN, bool openfile, bool loadtitles, bool freemem); + void GetLanguageToLangCode( int *langid, char *langcode ); + bool OpenXMLDatabase( char* xmlfilepath, char* argdblang, bool argJPtoEN, bool openfile, bool loadtitles, bool freemem ); - char *get_title(struct discHdr *header); - char *cfg_get_title(u8 *id) ; - void title_set(char *id, char *title); - void titles_default(); - u8 get_block(struct discHdr *header); - s8 get_pegi_block(struct discHdr *header); + char *get_title( struct discHdr *header ); + char *cfg_get_title( u8 *id ) ; + void title_set( char *id, char *title ); + void titles_default(); + u8 get_block( struct discHdr *header ); + s8 get_pegi_block( struct discHdr *header ); - void CFG_Cleanup(void); + void CFG_Cleanup( void ); #ifdef __cplusplus } diff --git a/source/settings/newtitles.cpp b/source/settings/newtitles.cpp index bbb8a45a..bbeba941 100644 --- a/source/settings/newtitles.cpp +++ b/source/settings/newtitles.cpp @@ -5,177 +5,206 @@ #include "newtitles.h" #define NEW_SECONDS 24 * 60 * 60 -#define GAMETITLES "gametitles.txt" +#define GAMETITLES "gametitles.txt" NewTitles *NewTitles::instance = NULL; NewTitles* NewTitles::Instance() { - if (instance == NULL) { - instance = new NewTitles(); - } - return instance; + if ( instance == NULL ) + { + instance = new NewTitles(); + } + return instance; } void NewTitles::DestroyInstance() { - if (instance != NULL) - { - delete instance; - instance = NULL; - } + if ( instance != NULL ) + { + delete instance; + instance = NULL; + } } NewTitles::NewTitles() { - firstTitle = lastTitle = NULL; - isDirty = isNewFile = false; + firstTitle = lastTitle = NULL; + isDirty = isNewFile = false; - // Read the text file - char path[255]; - strcpy(path, Settings.titlestxt_path); - path[strlen(Settings.titlestxt_path) - 1] = '/'; - strcat(path, GAMETITLES); + // Read the text file + char path[255]; + strcpy( path, Settings.titlestxt_path ); + path[strlen( Settings.titlestxt_path ) - 1] = '/'; + strcat( path, GAMETITLES ); - char line[20]; - FILE *fp = fopen(path, "r"); - if (fp != NULL) { - while (fgets(line, sizeof(line), fp)) { - // This is one line - if (line[0] != '#' || line[0] != ';') { - Title *title = new Title(); - if (sscanf(line, "%6c:%ld", (u8 *) &title->titleId, &title->timestamp) == 2) { - if (firstTitle == NULL) { - firstTitle = title; - lastTitle = title; - } else { - lastTitle->next = title; - lastTitle = title; - } - } - else { - delete title; // Invalid title entry, ignore - } - } - } + char line[20]; + FILE *fp = fopen( path, "r" ); + if ( fp != NULL ) + { + while ( fgets( line, sizeof( line ), fp ) ) + { + // This is one line + if ( line[0] != '#' || line[0] != ';' ) + { + Title *title = new Title(); + if ( sscanf( line, "%6c:%ld", ( u8 * ) &title->titleId, &title->timestamp ) == 2 ) + { + if ( firstTitle == NULL ) + { + firstTitle = title; + lastTitle = title; + } + else + { + lastTitle->next = title; + lastTitle = title; + } + } + else + { + delete title; // Invalid title entry, ignore + } + } + } - fclose(fp); - } else { - isNewFile = true; - } + fclose( fp ); + } + else + { + isNewFile = true; + } } NewTitles::~NewTitles() { - Save(); + Save(); - Title *t = firstTitle; - while (t != NULL) { - Title *temp = (Title *) t->next; - delete t; - t = temp; - } - firstTitle = lastTitle = NULL; + Title *t = firstTitle; + while ( t != NULL ) + { + 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) { - return; - } + if ( titleid == NULL || strlen( ( char * ) titleid ) == 0 ) + { + return; + } - Title *t = firstTitle; - while (t != NULL) { - // Loop all titles, search for the correct titleid - if (strcmp((const char *) titleid, (const char *) t->titleId) == 0) { - return; // Game found, which is excellent - } - t = (Title *) t->next; - } + Title *t = firstTitle; + while ( t != NULL ) + { + // Loop all titles, search for the correct titleid + if ( strcmp( ( const char * ) titleid, ( const char * ) t->titleId ) == 0 ) + { + return; // Game found, which is excellent + } + t = ( Title * ) t->next; + } - // Not found, add it - t = new Title(); - strncpy((char *) t->titleId, (char *) titleid, 6); - t->timestamp = time(NULL); - if (isNewFile) { - t->timestamp -= (NEW_SECONDS + 1); // Mark all games as not new if this is a new file - } + // Not found, add it + t = new Title(); + strncpy( ( char * ) t->titleId, ( char * ) titleid, 6 ); + t->timestamp = time( NULL ); + if ( isNewFile ) + { + t->timestamp -= ( NEW_SECONDS + 1 ); // Mark all games as not new if this is a new file + } - if (firstTitle == NULL) { - firstTitle = t; - lastTitle = t; - } else { - lastTitle -> next = t; - lastTitle = t; - } - isDirty = true; + if ( firstTitle == NULL ) + { + firstTitle = t; + lastTitle = t; + } + else + { + lastTitle -> next = t; + lastTitle = t; + } + isDirty = true; } -bool NewTitles::IsNew(u8 *titleid) +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; + Title *t = firstTitle; - while (t != NULL) { - // Loop all titles, search for the correct titleid - if (strcmp((const char *) titleid, (const char *) t->titleId) == 0) { - // This title is less than 24 hours old - if ((time(NULL) - t->timestamp) < NEW_SECONDS) { - // Only count the game as new when it's never been played through GX - Game_NUM *gnum = CFG_get_game_num(titleid); - return gnum == NULL || gnum->count == 0; - } - return false; - } - t = (Title *) t->next; - } - // We should never get here, since all files should be added by now! - CheckGame(titleid); + while ( t != NULL ) + { + // Loop all titles, search for the correct titleid + if ( strcmp( ( const char * ) titleid, ( const char * ) t->titleId ) == 0 ) + { + // This title is less than 24 hours old + if ( ( time( NULL ) - t->timestamp ) < NEW_SECONDS ) + { + // Only count the game as new when it's never been played through GX + Game_NUM *gnum = CFG_get_game_num( titleid ); + return gnum == NULL || gnum->count == 0; + } + return false; + } + t = ( Title * ) t->next; + } + // We should never get here, since all files should be added by now! + CheckGame( titleid ); - return !isNewFile; // If this is a new file, return false + 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) { - if (strcmp((const char *) titleid, (const char *) t->titleId) == 0) { - if (prev == NULL) { - firstTitle = (Title *) t->next; - } else { - prev->next = t->next; - } - delete t; - isDirty = true; + Title *t = firstTitle, *prev = NULL; + while ( t != NULL ) + { + if ( strcmp( ( const char * ) titleid, ( const char * ) t->titleId ) == 0 ) + { + if ( prev == NULL ) + { + firstTitle = ( Title * ) t->next; + } + else + { + prev->next = t->next; + } + delete t; + isDirty = true; - return; - } - prev = t; - t = (Title *) t->next; - } + return; + } + prev = t; + 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); + char path[255]; + strcpy( path, Settings.titlestxt_path ); + path[strlen( Settings.titlestxt_path ) - 1] = '/'; + strcat( path, GAMETITLES ); - FILE *fp = fopen(path, "w"); - if (fp != NULL) { - Title *t = firstTitle; - while (t != NULL && strlen((char *) t->titleId) > 0) { - fprintf(fp, "%s:%ld\n", t->titleId, t->timestamp); - t = (Title *) t->next; - } - fclose(fp); - } + FILE *fp = fopen( path, "w" ); + if ( fp != NULL ) + { + Title *t = firstTitle; + while ( t != NULL && strlen( ( char * ) t->titleId ) > 0 ) + { + fprintf( fp, "%s:%ld\n", t->titleId, t->timestamp ); + t = ( Title * ) t->next; + } + fclose( fp ); + } } diff --git a/source/settings/newtitles.h b/source/settings/newtitles.h index c6e2538a..0fc67db3 100644 --- a/source/settings/newtitles.h +++ b/source/settings/newtitles.h @@ -5,31 +5,32 @@ class NewTitles { -public: - static NewTitles *Instance(); - static void DestroyInstance(); - - void Save(); - void CheckGame(u8 *titleid); - bool IsNew(u8 *titleid); - void Remove(u8 *titleid); -private: - NewTitles(); - ~NewTitles(); - - static NewTitles *instance; - - class Title { - public: - u8 titleId[6]; - time_t timestamp; - void *next; - }; - - Title *firstTitle; - Title *lastTitle; - bool isDirty; - bool isNewFile; + public: + static NewTitles *Instance(); + static void DestroyInstance(); + + void Save(); + void CheckGame( u8 *titleid ); + bool IsNew( u8 *titleid ); + void Remove( u8 *titleid ); + private: + NewTitles(); + ~NewTitles(); + + static NewTitles *instance; + + class Title + { + public: + u8 titleId[6]; + time_t timestamp; + void *next; + }; + + Title *firstTitle; + Title *lastTitle; + bool isDirty; + bool isNewFile; }; #endif //_NEWTITLES_H diff --git a/source/svnrev.h b/source/svnrev.h index 23d489f5..6f1943e2 100644 --- a/source/svnrev.h +++ b/source/svnrev.h @@ -2,7 +2,8 @@ #define SVNREV_H #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif const char *GetRev(); diff --git a/source/sys.cpp b/source/sys.cpp index f4f19c0a..4177ef76 100644 --- a/source/sys.cpp +++ b/source/sys.cpp @@ -22,37 +22,42 @@ 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) - u32 val = (*_wiilight_reg&~0x20); - if (enable && Settings.wiilight) val |= 0x20; - *_wiilight_reg=val; +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; + *_wiilight_reg = val; } /* Variables */ 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() { +static void _ExitApp() +{ ExitGUIThreads(); StopGX(); ShutdownAudio(); @@ -60,96 +65,109 @@ 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(); STM_RebootSystem(); } -int Sys_ChangeIos(int ios) { - s32 prevIos = IOS_GetVersion(); +int Sys_ChangeIos( int ios ) +{ + s32 prevIos = IOS_GetVersion(); - SDCard_deInit(); - USBDevice_deInit(); - - WPAD_Flush(0); - WPAD_Disconnect(0); - WPAD_Shutdown(); - - WDVD_Close(); - - USBStorage2_Deinit(); - - s32 ret = IOS_ReloadIOSsafe(ios); - if (ret < 0) { - ios = prevIos; - } - - SDCard_Init(); - - if (ios == 222 || ios == 223) { - load_ehc_module(); - } - USBDevice_Init(); - - PAD_Init(); - Wpad_Init(); - WPAD_SetDataFormat(WPAD_CHAN_ALL,WPAD_FMT_BTNS_ACC_IR); - WPAD_SetVRes(WPAD_CHAN_ALL, screenwidth, screenheight); - - WBFS_Init(WBFS_DEVICE_USB); - Disc_Init(); - - if (Sys_IsHermes()) { - WBFS_OpenNamed((char *) &game_partition); - } else { - WBFS_Open(); - } - - return ret; -} - -int Sys_IosReload(int IOS) { - s32 ret = -1; - - //shutdown SD and USB before IOS Reload in DiscWait SDCard_deInit(); USBDevice_deInit(); - WPAD_Flush(0); - WPAD_Disconnect(0); + WPAD_Flush( 0 ); + WPAD_Disconnect( 0 ); WPAD_Shutdown(); WDVD_Close(); USBStorage2_Deinit(); - if (IOS == 249 || IOS == 222 || IOS == 223) { - for (int i = 0; i < 10; i++) { - ret = IOS_ReloadIOSsafe(IOS); - if (ret < 0) return ret; - if (IOS == 222 || IOS == 223) load_ehc_module(); - ret = WBFS_Init(WBFS_DEVICE_USB); - if (!(ret < 0)) break; - sleep(1); + s32 ret = IOS_ReloadIOSsafe( ios ); + if ( ret < 0 ) + { + ios = prevIos; + } + + SDCard_Init(); + + if ( ios == 222 || ios == 223 ) + { + load_ehc_module(); + } + USBDevice_Init(); + + PAD_Init(); + Wpad_Init(); + WPAD_SetDataFormat( WPAD_CHAN_ALL, WPAD_FMT_BTNS_ACC_IR ); + WPAD_SetVRes( WPAD_CHAN_ALL, screenwidth, screenheight ); + + WBFS_Init( WBFS_DEVICE_USB ); + Disc_Init(); + + if ( Sys_IsHermes() ) + { + WBFS_OpenNamed( ( char * ) &game_partition ); + } + else + { + WBFS_Open(); + } + + return ret; +} + +int Sys_IosReload( int IOS ) +{ + s32 ret = -1; + + //shutdown SD and USB before IOS Reload in DiscWait + SDCard_deInit(); + USBDevice_deInit(); + + WPAD_Flush( 0 ); + WPAD_Disconnect( 0 ); + WPAD_Shutdown(); + + WDVD_Close(); + + USBStorage2_Deinit(); + + if ( IOS == 249 || IOS == 222 || IOS == 223 ) + { + for ( int i = 0; i < 10; i++ ) + { + ret = IOS_ReloadIOSsafe( IOS ); + if ( ret < 0 ) return ret; + if ( IOS == 222 || IOS == 223 ) load_ehc_module(); + ret = WBFS_Init( WBFS_DEVICE_USB ); + if ( !( ret < 0 ) ) break; + sleep( 1 ); USBStorage2_Deinit(); } - if (ret>=0) { + if ( ret >= 0 ) + { ret = Disc_Init(); - if (ret>=0) { + if ( ret >= 0 ) + { ret = WBFS_Open(); } - } else Sys_BackToLoader(); + } + else Sys_BackToLoader(); } PAD_Init(); Wpad_Init(); - 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 ); //reinitialize SD and USB SDCard_Init(); USBDevice_Init(); @@ -157,154 +175,169 @@ int Sys_IosReload(int IOS) { return ret; } -#define ShutdownToDefault 0 -#define ShutdownToIdle 1 -#define ShutdownToStandby 2 +#define ShutdownToDefault 0 +#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(); - } else { + } + else + { /* Shutdown to standby */ STM_ShutdownToStandby(); } } -void Sys_Shutdown(void) { - _Sys_Shutdown(ShutdownToDefault); +void Sys_Shutdown( void ) +{ + _Sys_Shutdown( ShutdownToDefault ); } -void Sys_ShutdownToIdel(void) { - _Sys_Shutdown(ShutdownToIdle); +void Sys_ShutdownToIdel( void ) +{ + _Sys_Shutdown( ShutdownToIdle ); } -void Sys_ShutdownToStandby(void) { - _Sys_Shutdown(ShutdownToStandby); +void Sys_ShutdownToStandby( void ) +{ + _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(); } -bool Sys_IsHermes() { - return IOS_GetVersion() == 222 || IOS_GetVersion() == 223; +bool Sys_IsHermes() +{ + return IOS_GetVersion() == 222 || IOS_GetVersion() == 223; } #include "prompts/PromptWindows.h" -void ShowMemInfo() { - char buf[255]; +void ShowMemInfo() +{ + char buf[255]; struct mallinfo mymallinfo = mallinfo(); - sprintf((char *) &buf,"Total: %d, Used: %d, Can be freed: %d", mymallinfo.arena/1024, mymallinfo.uordblks/1024, mymallinfo.keepcost/1024); - WindowPrompt("Mem info", (char *) &buf, "OK"); + sprintf( ( char * ) &buf, "Total: %d, Used: %d, Can be freed: %d", mymallinfo.arena / 1024, mymallinfo.uordblks / 1024, mymallinfo.keepcost / 1024 ); + WindowPrompt( "Mem info", ( char * ) &buf, "OK" ); } -s32 IOS_ReloadIOSsafe(int ios) +s32 IOS_ReloadIOSsafe( int ios ) { - if( ios == 222 ) - { - s32 ios222rev = titles.VersionOf( 0x1000000deULL ); - if( !ios222rev ) - return -2; - if( ios222rev != 4 && ios222rev != 5 && ios222rev != 65535 ) - return -2; - } - else if (ios==223) - { - s32 ios223rev = titles.VersionOf( 0x1000000dfULL ); - if( !ios223rev ) - return -2; - if( ios223rev != 4 && ios223rev != 5 && ios223rev != 65535 ) - return -2; - } - else if (ios==249) - { - s32 ios249rev = titles.VersionOf( 0x1000000f9ULL ); - if( !ios249rev ) - return -2; - if( ios249rev < 9 || ios249rev == 65280 ) - return -2; - } - else if (ios==250) - { - s32 ios250rev = titles.VersionOf( 0x1000000faULL ); - if( !ios250rev ) - return -2; - if( ios250rev < 9 || ios250rev == 65280 ) - return -2; - } + if ( ios == 222 ) + { + s32 ios222rev = titles.VersionOf( 0x1000000deULL ); + if ( !ios222rev ) + return -2; + if ( ios222rev != 4 && ios222rev != 5 && ios222rev != 65535 ) + return -2; + } + else if ( ios == 223 ) + { + s32 ios223rev = titles.VersionOf( 0x1000000dfULL ); + if ( !ios223rev ) + return -2; + if ( ios223rev != 4 && ios223rev != 5 && ios223rev != 65535 ) + return -2; + } + else if ( ios == 249 ) + { + s32 ios249rev = titles.VersionOf( 0x1000000f9ULL ); + if ( !ios249rev ) + return -2; + if ( ios249rev < 9 || ios249rev == 65280 ) + return -2; + } + else if ( ios == 250 ) + { + s32 ios250rev = titles.VersionOf( 0x1000000faULL ); + if ( !ios250rev ) + return -2; + if ( ios250rev < 9 || ios250rev == 65280 ) + return -2; + } - s32 r = IOS_ReloadIOS(ios); - if( r >= 0 ) - { - WII_Initialize(); - } - return r; + s32 r = IOS_ReloadIOS( ios ); + if ( r >= 0 ) + { + WII_Initialize(); + } + return r; } s32 CheckForCIOS() { - gprintf("\tChecking for stub IOS\n"); + gprintf( "\tChecking for stub IOS\n" ); s32 ret = 1; - s32 ios222rev = titles.VersionOf( 0x00000001000000deULL ); - s32 ios249rev = titles.VersionOf( 0x00000001000000f9ULL ); + s32 ios222rev = titles.VersionOf( 0x00000001000000deULL ); + s32 ios249rev = titles.VersionOf( 0x00000001000000f9ULL ); - u8 ios222OK = !( ios222rev < 4 || ios222rev == 65280 ); - u8 ios249OK = !( ios249rev < 9 || ios249rev == 65280 ); + u8 ios222OK = !( ios222rev < 4 || ios222rev == 65280 ); + u8 ios249OK = !( ios249rev < 9 || ios249rev == 65280 ); - gprintf("222ok: %u\t 249ok: %u\n", ios222OK, ios249OK ); - return 1; + gprintf( "222ok: %u\t 249ok: %u\n", ios222OK, ios249OK ); + return 1; - //if we don't like either of the cIOS then scram - //if( !((ios222rev >= 4 && ios222rev < 65280) || (ios249rev >=9 && ios249rev < 65280))) - if( ios222rev < 4 || ios222rev == 65280 || ios249rev < 9 || ios249rev == 65280 ) - { - printf("\x1b[2J"); - if ((ios222rev < 0 && ios222rev != WII_EINSTALL) && (ios249rev < 0 && ios249rev != WII_EINSTALL)) { - printf("\n\n\n\tWARNING!"); - printf("\n\tUSB Loader GX needs unstubbed cIOS 222 v4 or 249 v9+"); - printf("\n\n\tWe cannot determine the versions on your system,\n\tsince you have no patched ios 36 or 236 installed."); - printf("\n\tTherefor, if loading of USB Loader GX fails, you\n\tprobably have installed the 4.2 update,"); - printf("\n\tand you should go figure out how to get some cios action going on\n\tin your Wii."); - printf("\n\n\tThis message will show every time."); - sleep(5); - } else { - printf("\n\n\n\tERROR!"); - printf("\n\tUSB Loader GX needs unstubbed cIOS 222 v4 or 249 v9+"); - printf("\n\n\tI found \n\t\t222 = %d%s",ios222rev,ios222rev==65280?" (Stubbed by 4.2 update)":""); - printf("\n\t\t249 = %d%s",ios249rev,ios249rev==65280?" (Stubbed by 4.2 update)":""); - printf("\n\n\tGo figure out how to get some cIOS action going on\n\tin your Wii and come back and see me."); + //if we don't like either of the cIOS then scram + //if( !((ios222rev >= 4 && ios222rev < 65280) || (ios249rev >=9 && ios249rev < 65280))) + if ( ios222rev < 4 || ios222rev == 65280 || ios249rev < 9 || ios249rev == 65280 ) + { + printf( "\x1b[2J" ); + if ( ( ios222rev < 0 && ios222rev != WII_EINSTALL ) && ( ios249rev < 0 && ios249rev != WII_EINSTALL ) ) + { + printf( "\n\n\n\tWARNING!" ); + printf( "\n\tUSB Loader GX needs unstubbed cIOS 222 v4 or 249 v9+" ); + printf( "\n\n\tWe cannot determine the versions on your system,\n\tsince you have no patched ios 36 or 236 installed." ); + printf( "\n\tTherefor, if loading of USB Loader GX fails, you\n\tprobably have installed the 4.2 update," ); + printf( "\n\tand you should go figure out how to get some cios action going on\n\tin your Wii." ); + printf( "\n\n\tThis message will show every time." ); + sleep( 5 ); + } + else + { + printf( "\n\n\n\tERROR!" ); + printf( "\n\tUSB Loader GX needs unstubbed cIOS 222 v4 or 249 v9+" ); + printf( "\n\n\tI found \n\t\t222 = %d%s", ios222rev, ios222rev == 65280 ? " (Stubbed by 4.2 update)" : "" ); + printf( "\n\t\t249 = %d%s", ios249rev, ios249rev == 65280 ? " (Stubbed by 4.2 update)" : "" ); + printf( "\n\n\tGo figure out how to get some cIOS action going on\n\tin your Wii and come back and see me." ); - sleep(15); - printf("\n\n\tBye"); + sleep( 15 ); + printf( "\n\n\tBye" ); - USBDevice_deInit(); - exit(0); - } - } + USBDevice_deInit(); + exit( 0 ); + } + } return ret; } @@ -317,37 +350,38 @@ int LoadAppCIOS() USBDevice_deInit();// unmount USB for reloading IOS USBStorage2_Deinit(); - if (Settings.cios == ios222 && IOS_GetVersion() != 222) + if ( Settings.cios == ios222 && IOS_GetVersion() != 222 ) { - printf("\n\tReloading IOS to config setting (222)..."); - ret = IOS_ReloadIOSsafe(222); - printf("%d", ret); - if (ret < 0) + printf( "\n\tReloading IOS to config setting (222)..." ); + ret = IOS_ReloadIOSsafe( 222 ); + printf( "%d", ret ); + if ( ret < 0 ) { Settings.cios = ios249; - IOS_ReloadIOSsafe(249); + IOS_ReloadIOSsafe( 249 ); } } - if ((Settings.cios == ios249 && IOS_GetVersion() != 249) - || (Settings.cios == ios250 && IOS_GetVersion() != 250)) + if ( ( Settings.cios == ios249 && IOS_GetVersion() != 249 ) + || ( Settings.cios == ios250 && IOS_GetVersion() != 250 ) ) { - printf("\n\tReloading IOS to config setting (%d)...", (Settings.cios == ios249) ? 249 : 250); - ret = IOS_ReloadIOSsafe((Settings.cios == ios249) ? 249 : 250); - printf("%d", ret); - if (ret < 0) { + printf( "\n\tReloading IOS to config setting (%d)...", ( Settings.cios == ios249 ) ? 249 : 250 ); + ret = IOS_ReloadIOSsafe( ( Settings.cios == ios249 ) ? 249 : 250 ); + printf( "%d", ret ); + if ( ret < 0 ) + { Settings.cios = ios222; - ret = IOS_ReloadIOSsafe(222); + ret = IOS_ReloadIOSsafe( 222 ); } - } + } SDCard_Init(); - if(IOS_GetVersion() == 222) + if ( IOS_GetVersion() == 222 ) load_ehc_module(); USBDevice_Init(); - return ret; + return ret; } @@ -355,16 +389,16 @@ int LoadAppCIOS() void ScreenShot() { - time_t rawtime; - struct tm * timeinfo; - char buffer [80]; - char buffer2 [80]; + time_t rawtime; + struct tm * timeinfo; + char buffer [80]; + char buffer2 [80]; - time ( &rawtime ); - timeinfo = localtime ( &rawtime ); - //USBLoader_GX_ScreenShot-Month_Day_Hour_Minute_Second_Year.png - strftime (buffer,80,"USBLoader_GX_ScreenShot-%b%d%H%M%S%y.png",timeinfo); - sprintf(buffer2, "%s/config/%s", bootDevice, buffer); + time ( &rawtime ); + timeinfo = localtime ( &rawtime ); + //USBLoader_GX_ScreenShot-Month_Day_Hour_Minute_Second_Year.png + strftime ( buffer, 80, "USBLoader_GX_ScreenShot-%b%d%H%M%S%y.png", timeinfo ); + sprintf( buffer2, "%s/config/%s", bootDevice, buffer ); - TakeScreenshot(buffer2); + TakeScreenshot( buffer2 ); } diff --git a/source/sys.h b/source/sys.h index 96dfb52d..1af137a3 100644 --- a/source/sys.h +++ b/source/sys.h @@ -1,20 +1,20 @@ #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); -int Sys_ChangeIos(int ios); -int Sys_IosReload(int IOS); +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 ); +int Sys_ChangeIos( int ios ); +int Sys_IosReload( int IOS ); bool Sys_IsHermes(); -s32 IOS_ReloadIOSsafe(int ios); +s32 IOS_ReloadIOSsafe( int ios ); void ScreenShot(); s32 CheckForCIOS(); int LoadAppCIOS(); diff --git a/source/themes/Theme_Downloader.cpp b/source/themes/Theme_Downloader.cpp index bb00dbe8..d1f179f9 100644 --- a/source/themes/Theme_Downloader.cpp +++ b/source/themes/Theme_Downloader.cpp @@ -36,247 +36,247 @@ extern u8 shutdown; extern u8 reset; -int DownloadTheme(const char *url, const char *title) +int DownloadTheme( const char *url, const char *title ) { - if(!url) + 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; } u32 done = 0; - int blocksize = 1024*5; + int blocksize = 1024 * 5; 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) + else if ( ret == 0 ) break; - fwrite(buffer, 1, blocksize, file); + fwrite( buffer, 1, blocksize, file ); done += ret; } delete [] buffer; - fclose(file); + 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", CFG.theme_path); - if(SearchFile(path, "GXtheme.cfg", real_themepath) == true) + sprintf( real_themepath, "%s", CFG.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(CFG.theme_path, sizeof(CFG.theme_path), "%s", real_themepath); + snprintf( CFG.theme_path, sizeof( CFG.theme_path ), "%s", real_themepath ); cfg_save_global(); CFG_Load(); CFG_LoadGlobal(); result = 2; } else - WindowPrompt(tr("ERROR: Can't set up theme."), tr("GXtheme.cfg not found in any subfolder."), tr("OK")); + 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")); + 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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%stheme_dialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, theme_dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%stheme_dialogue_box.png", CFG.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(CFG.widescreen); - downloadBtnImg.SetWidescreen(CFG.widescreen); + downloadBtnTxt.SetWidescreen( CFG.widescreen ); + downloadBtnImg.SetWidescreen( CFG.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(CFG.widescreen); - backBtnImg.SetWidescreen(CFG.widescreen); + backBtnTxt.SetWidescreen( CFG.widescreen ); + backBtnImg.SetWidescreen( CFG.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) + 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) + 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; @@ -290,61 +290,61 @@ 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); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - GuiSound btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnClick1( button_click_pcm, button_click_pcm_size, Settings.sfxvolume ); /*** Image Variables ***/ char imgPath[150]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); - snprintf(imgPath, sizeof(imgPath), "%stheme_box.png", CFG.theme_path); - GuiImageData theme_box_Data(imgPath, theme_box_png); + snprintf( imgPath, sizeof( imgPath ), "%stheme_box.png", CFG.theme_path ); + GuiImageData theme_box_Data( imgPath, theme_box_png ); - snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path); - GuiImageData bgData(imgPath, settings_background_png); + snprintf( imgPath, sizeof( imgPath ), "%ssettings_background.png", CFG.theme_path ); + GuiImageData bgData( imgPath, settings_background_png ); - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", CFG.theme_path); - GuiImageData arrow_left(imgPath, startgame_arrow_left_png); + snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_left.png", CFG.theme_path ); + GuiImageData arrow_left( imgPath, startgame_arrow_left_png ); - snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", CFG.theme_path); - GuiImageData arrow_right(imgPath, startgame_arrow_right_png); + snprintf( imgPath, sizeof( imgPath ), "%sstartgame_arrow_right.png", CFG.theme_path ); + GuiImageData arrow_right( imgPath, startgame_arrow_right_png ); - snprintf(imgPath, sizeof(imgPath), "%sWifi_btn.png", CFG.theme_path); - GuiImageData wifiImgData(imgPath, Wifi_btn_png); + snprintf( imgPath, sizeof( imgPath ), "%sWifi_btn.png", CFG.theme_path ); + GuiImageData wifiImgData( imgPath, Wifi_btn_png ); - snprintf(imgPath, sizeof(imgPath), "%spageindicator.png", CFG.theme_path); - GuiImageData PageindicatorImgData(imgPath, pageindicator_png); + snprintf( imgPath, sizeof( imgPath ), "%spageindicator.png", CFG.theme_path ); + GuiImageData PageindicatorImgData( imgPath, pageindicator_png ); - 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]; @@ -355,100 +355,100 @@ 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(CFG.widescreen); - backBtnImg.SetWidescreen(CFG.widescreen); + backBtnTxt.SetWidescreen( CFG.widescreen ); + backBtnImg.SetWidescreen( CFG.widescreen ); } - GuiButton backBtn(&backBtnImg,&backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2,1); - backBtn.SetLabel(&backBtnTxt); - backBtn.SetTrigger(&trigB); + GuiButton 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(CFG.widescreen); + wifiImg.SetWidescreen( CFG.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()) + if ( !IsNetworkInit() ) NetworkInitPrompt(); char url[300]; @@ -457,108 +457,108 @@ 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]) + if ( MainButtonTxt[n] ) delete MainButtonTxt[n]; - if(ImageData[n]) + if ( ImageData[n] ) delete ImageData[n]; - if(Image[n]) + if ( Image[n] ) delete Image[n]; MainButtonTxt[n] = NULL; ImageData[n] = NULL; Image[n] = NULL; - if(i < ThemesOnPage) + 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++; } @@ -566,69 +566,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 (); - 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); - currenttheme = currentpage*pagesize-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; @@ -638,28 +638,28 @@ 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]) + if ( MainButton[i] ) delete MainButton[i]; - if(theme_box_img[i]) + if ( theme_box_img[i] ) delete theme_box_img[i]; - if(ImageData[i]) + if ( ImageData[i] ) delete ImageData[i]; - if(Image[i]) + if ( Image[i] ) delete Image[i]; - if(MainButtonTxt[i]) + if ( MainButtonTxt[i] ) delete MainButtonTxt[i]; } - if(Theme) + if ( Theme ) delete Theme; Theme = NULL; diff --git a/source/themes/Theme_List.cpp b/source/themes/Theme_List.cpp index 5bf02bf4..7a7bc980 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,48 +50,48 @@ static void copyhtmlsting(const char *from, char *outtext, const char *stopat, u outtext[cnt2] = '\0'; } -Theme_List::Theme_List(const char * url) +Theme_List::Theme_List( const char * url ) { Theme = NULL; themescount = 0; - if (!IsNetworkInit()) + if ( !IsNetworkInit() ) { themescount = -1; return; } - struct block file = downloadfile(url); + 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) - { - free(file.data); + themescount = CountThemes( file.data ); + if ( themescount <= 0 ) + { + 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) + if ( Theme[i].themetitle ) delete [] Theme[i].themetitle; - if(Theme[i].author) + if ( Theme[i].author ) delete [] Theme[i].author; - if(Theme[i].imagelink) + if ( Theme[i].imagelink ) delete [] Theme[i].imagelink; - if(Theme[i].downloadlink) + if ( Theme[i].downloadlink ) delete [] Theme[i].downloadlink; Theme[i].themetitle = NULL; Theme[i].author = NULL; @@ -99,126 +99,126 @@ Theme_List::~Theme_List() Theme[i].downloadlink = NULL; } - if(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)); + char tmp[200]; + u32 cnt = 0; + u32 stringlength = strlen( ( const char * ) xmlfile ); + memset( tmp, 0, sizeof( tmp ) ); - while (cnt < stringlength) - { - if (stringcompare(xmlfile, "", cnt) == 0) - { - copyhtmlsting((const char *) xmlfile, tmp, ">", cnt); - break; - } - cnt++; - } - tmp[cnt+1] = 0; + while ( cnt < stringlength ) + { + if ( stringcompare( xmlfile, "", cnt ) == 0 ) + { + copyhtmlsting( ( const char * ) xmlfile, tmp, ">", cnt ); + break; + } + cnt++; + } + tmp[cnt+1] = 0; - return atoi(tmp); + return atoi( tmp ); } -bool Theme_List::ParseXML(const u8 * xmlfile) +bool Theme_List::ParseXML( const u8 * xmlfile ) { - char element_text[1024]; - memset(element_text, 0, sizeof(element_text)); - mxml_node_t *nodetree=NULL; - mxml_node_t *nodedata=NULL; - mxml_node_t *nodeid=NULL; - mxml_index_t *nodeindex=NULL; + char element_text[1024]; + memset( element_text, 0, sizeof( element_text ) ); + mxml_node_t *nodetree = NULL; + mxml_node_t *nodedata = NULL; + mxml_node_t *nodeid = NULL; + mxml_index_t *nodeindex = NULL; - nodetree = mxmlLoadString(NULL, (const char *) xmlfile, MXML_OPAQUE_CALLBACK); + nodetree = mxmlLoadString( NULL, ( const char * ) xmlfile, MXML_OPAQUE_CALLBACK ); - if (nodetree == NULL) - { - return false; - } - - nodedata = mxmlFindElement(nodetree, nodetree, "themes", NULL, NULL, MXML_DESCEND); - if (nodedata == NULL) - { + if ( nodetree == NULL ) + { return false; } - nodeindex = mxmlIndexNew(nodedata,"name", NULL); - nodeid = mxmlIndexReset(nodeindex); + nodedata = mxmlFindElement( nodetree, nodetree, "themes", NULL, NULL, MXML_DESCEND ); + if ( nodedata == NULL ) + { + return false; + } - Theme = new Theme_Info[themescount]; - memset(Theme, 0, sizeof(Theme)); + nodeindex = mxmlIndexNew( nodedata, "name", NULL ); + nodeid = mxmlIndexReset( nodeindex ); - for (int i = 0; i < themescount; i++) - { - nodeid = mxmlIndexFind(nodeindex,"name", NULL); - if (nodeid != NULL) + Theme = new Theme_Info[themescount]; + memset( Theme, 0, sizeof( Theme ) ); + + for ( int i = 0; i < themescount; i++ ) + { + nodeid = mxmlIndexFind( nodeindex, "name", NULL ); + if ( nodeid != NULL ) { - get_nodetext(nodeid, element_text, sizeof(element_text)); - 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); - nodetree=NULL; - nodedata=NULL; - nodeid=NULL; - nodeindex=NULL; + mxmlIndexDelete( nodeindex ); + free( nodetree ); + free( nodedata ); + free( nodeid ); + nodetree = NULL; + nodedata = NULL; + nodeid = NULL; + nodeindex = NULL; return true; } -const char * Theme_List::GetThemeTitle(int ind) +const char * Theme_List::GetThemeTitle( int ind ) { - if (ind > themescount || ind < 0 || !Theme || themescount <= 0) + if ( ind > themescount || ind < 0 || !Theme || themescount <= 0 ) return NULL; else return Theme[ind].themetitle; } -const char * Theme_List::GetThemeAuthor(int ind) +const char * Theme_List::GetThemeAuthor( int ind ) { - if (ind > themescount || ind < 0 || !Theme || themescount <= 0) + if ( ind > themescount || ind < 0 || !Theme || themescount <= 0 ) return NULL; else return Theme[ind].author; } -const char * Theme_List::GetImageLink(int ind) +const char * Theme_List::GetImageLink( int ind ) { - if (ind > themescount || ind < 0 || !Theme || themescount <= 0) + if ( ind > themescount || ind < 0 || !Theme || themescount <= 0 ) return NULL; else return Theme[ind].imagelink; } -const char * Theme_List::GetDownloadLink(int ind) +const char * Theme_List::GetDownloadLink( int ind ) { - if (ind > themescount || ind < 0 || !Theme || themescount <= 0) + if ( ind > themescount || ind < 0 || !Theme || themescount <= 0 ) return NULL; else return Theme[ind].downloadlink; @@ -229,14 +229,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 85a8b713..a72ab743 100644 --- a/source/themes/Theme_List.h +++ b/source/themes/Theme_List.h @@ -24,25 +24,25 @@ 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 5b4ddda7..bc90b714 100644 --- a/source/unzip/crypt.h +++ b/source/unzip/crypt.h @@ -32,25 +32,27 @@ /*********************************************************************** * 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 */ - 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) { - (*(pkeys+0)) = CRC32((*(pkeys+0)), c); - (*(pkeys+1)) += (*(pkeys+0)) & 0xff; - (*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1; +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; { - 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; } @@ -60,12 +62,14 @@ static int update_keys(unsigned long* pkeys,const unsigned long* pcrc_32_tab,int * 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) { - *(pkeys+0) = 305419896L; - *(pkeys+1) = 591751049L; - *(pkeys+2) = 878082192L; - while (*passwd != '\0') { - update_keys(pkeys,pcrc_32_tab,(int)*passwd); +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' ) + { + update_keys( pkeys, pcrc_32_tab, ( int )*passwd ); passwd++; } } @@ -84,7 +88,7 @@ static void init_keys(const char* passwd,unsigned long* pkeys,const unsigned lon # define ZCR_SEED2 3141592654UL /* use PI as default pattern */ # endif -static int crypthead(passwd, buf, bufSize, pkeys, pcrc_32_tab, crcForCrypting) +static int crypthead( passwd, buf, bufSize, pkeys, pcrc_32_tab, crcForCrypting ) const char *passwd; /* password string */ unsigned char *buf; /* where to write header */ int bufSize; @@ -98,28 +102,31 @@ unsigned long crcForCrypting; unsigned char header[RAND_HEAD_LEN-2]; /* random header */ static unsigned calls = 0; /* ensure different random header each time */ - if (bufSize> 7) & 0xff; - header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t); + init_keys( passwd, pkeys, pcrc_32_tab ); + for ( n = 0; n < RAND_HEAD_LEN - 2; n++ ) + { + c = ( rand() >> 7 ) & 0xff; + header[n] = ( unsigned char )zencode( pkeys, pcrc_32_tab, c, t ); } /* Encrypt random header (last two bytes is high word of crc) */ - init_keys(passwd, pkeys, pcrc_32_tab); - for (n = 0; n < RAND_HEAD_LEN-2; n++) { - buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t); + init_keys( passwd, pkeys, pcrc_32_tab ); + for ( n = 0; n < RAND_HEAD_LEN - 2; n++ ) + { + buf[n] = ( unsigned char )zencode( pkeys, pcrc_32_tab, header[n], t ); } - buf[n++] = zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t); - buf[n++] = zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t); + buf[n++] = zencode( pkeys, pcrc_32_tab, ( int )( crcForCrypting >> 16 ) & 0xff, t ); + buf[n++] = zencode( pkeys, pcrc_32_tab, ( int )( crcForCrypting >> 24 ) & 0xff, t ); return n; } diff --git a/source/unzip/inflate.c b/source/unzip/inflate.c index 3e97d934..affa7eed 100644 --- a/source/unzip/inflate.c +++ b/source/unzip/inflate.c @@ -3,7 +3,7 @@ #define CHUNK 1024 -int inflateFile(FILE *source, FILE *dest) +int inflateFile( FILE *source, FILE *dest ) { int ret; unsigned have; @@ -17,46 +17,53 @@ int inflateFile(FILE *source, FILE *dest) strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; - ret = inflateInit(&strm); - if (ret != Z_OK) + ret = inflateInit( &strm ); + 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)) { - (void)inflateEnd(&strm); + do + { + strm.avail_in = fread( in, 1, CHUNK, source ); + if ( ferror( source ) ) + { + ( void )inflateEnd( &strm ); return Z_ERRNO; } - if (strm.avail_in == 0) + if ( strm.avail_in == 0 ) break; strm.next_in = in; - + /* run inflate() on input until output buffer not full */ - do { + do + { strm.avail_out = CHUNK; strm.next_out = out; - ret = inflate(&strm, Z_NO_FLUSH); - switch (ret) { - case Z_NEED_DICT: - (void)inflateEnd(&strm); - return -20; - case Z_DATA_ERROR: - (void)inflateEnd(&strm); - return -21; - case Z_MEM_ERROR: - (void)inflateEnd(&strm); - return -22; + ret = inflate( &strm, Z_NO_FLUSH ); + switch ( ret ) + { + case Z_NEED_DICT: + ( void )inflateEnd( &strm ); + return -20; + case Z_DATA_ERROR: + ( void )inflateEnd( &strm ); + return -21; + case Z_MEM_ERROR: + ( void )inflateEnd( &strm ); + return -22; } have = CHUNK - strm.avail_out; - if (fwrite(out, 1, have, dest) != have || ferror(dest)) { - (void)inflateEnd(&strm); + if ( fwrite( out, 1, have, dest ) != have || ferror( dest ) ) + { + ( 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 f8556da3..4efe654b 100644 --- a/source/unzip/inflate.h +++ b/source/unzip/inflate.h @@ -6,10 +6,11 @@ #include #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -int inflateFile(FILE *source, FILE *dest); + int inflateFile( FILE *source, FILE *dest ); #ifdef __cplusplus } diff --git a/source/unzip/ioapi.c b/source/unzip/ioapi.c index d6ef68ac..2e514696 100644 --- a/source/unzip/ioapi.c +++ b/source/unzip/ioapi.c @@ -29,141 +29,140 @@ #define SEEK_SET 0 #endif -voidpf ZCALLBACK fopen_file_func OF(( - voidpf opaque, - const char* filename, - int mode)); +voidpf ZCALLBACK fopen_file_func OF( ( + voidpf opaque, + const char* filename, + int mode ) ); -uLong ZCALLBACK fread_file_func OF(( - voidpf opaque, - voidpf stream, - void* buf, - uLong size)); - -uLong ZCALLBACK fwrite_file_func OF(( +uLong ZCALLBACK fread_file_func OF( ( voidpf opaque, voidpf stream, - const void* buf, - uLong size)); + void* buf, + uLong size ) ); -long ZCALLBACK ftell_file_func OF(( - voidpf opaque, - voidpf stream)); +uLong ZCALLBACK fwrite_file_func OF( ( + voidpf opaque, + voidpf stream, + const void* buf, + uLong size ) ); -long ZCALLBACK fseek_file_func OF(( - voidpf opaque, - voidpf stream, - uLong offset, - int origin)); +long ZCALLBACK ftell_file_func OF( ( + voidpf opaque, + voidpf stream ) ); -int ZCALLBACK fclose_file_func OF(( - voidpf opaque, - voidpf stream)); +long ZCALLBACK fseek_file_func OF( ( + voidpf opaque, + voidpf stream, + uLong offset, + int origin ) ); -int ZCALLBACK ferror_file_func OF(( - voidpf opaque, - voidpf stream)); +int ZCALLBACK fclose_file_func OF( ( + voidpf opaque, + voidpf stream ) ); + +int ZCALLBACK ferror_file_func OF( ( + voidpf opaque, + voidpf stream ) ); -voidpf ZCALLBACK fopen_file_func (opaque, filename, mode) +voidpf ZCALLBACK fopen_file_func ( opaque, filename, mode ) voidpf opaque; const char* filename; int mode; { FILE* file = NULL; const char* mode_fopen = NULL; - if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) + if ( ( mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER ) == ZLIB_FILEFUNC_MODE_READ ) mode_fopen = "rb"; - else - if (mode & ZLIB_FILEFUNC_MODE_EXISTING) - mode_fopen = "r+b"; - else - if (mode & ZLIB_FILEFUNC_MODE_CREATE) - mode_fopen = "wb"; + else if ( mode & ZLIB_FILEFUNC_MODE_EXISTING ) + mode_fopen = "r+b"; + else if ( mode & ZLIB_FILEFUNC_MODE_CREATE ) + mode_fopen = "wb"; - if ((filename!=NULL) && (mode_fopen != NULL)) - file = fopen(filename, mode_fopen); + if ( ( filename != NULL ) && ( mode_fopen != NULL ) ) + file = fopen( filename, mode_fopen ); return file; } -uLong ZCALLBACK fread_file_func (opaque, stream, buf, size) +uLong ZCALLBACK fread_file_func ( opaque, stream, buf, size ) voidpf opaque; voidpf stream; void* buf; uLong size; { uLong ret; - ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream); + ret = ( uLong )fread( buf, 1, ( size_t )size, ( FILE * )stream ); return ret; } -uLong ZCALLBACK fwrite_file_func (opaque, stream, buf, size) +uLong ZCALLBACK fwrite_file_func ( opaque, stream, buf, size ) voidpf opaque; voidpf stream; const void* buf; uLong size; { uLong ret; - ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream); + ret = ( uLong )fwrite( buf, 1, ( size_t )size, ( FILE * )stream ); return ret; } -long ZCALLBACK ftell_file_func (opaque, stream) +long ZCALLBACK ftell_file_func ( opaque, stream ) voidpf opaque; voidpf stream; { long ret; - ret = ftell((FILE *)stream); + ret = ftell( ( FILE * )stream ); return ret; } -long ZCALLBACK fseek_file_func (opaque, stream, offset, origin) +long ZCALLBACK fseek_file_func ( opaque, stream, offset, origin ) voidpf opaque; voidpf stream; uLong offset; int origin; { - int fseek_origin=0; + int fseek_origin = 0; long ret; - switch (origin) { - case ZLIB_FILEFUNC_SEEK_CUR : - fseek_origin = SEEK_CUR; - break; - case ZLIB_FILEFUNC_SEEK_END : - fseek_origin = SEEK_END; - break; - case ZLIB_FILEFUNC_SEEK_SET : - fseek_origin = SEEK_SET; - break; - default: - return -1; + switch ( origin ) + { + case ZLIB_FILEFUNC_SEEK_CUR : + fseek_origin = SEEK_CUR; + break; + case ZLIB_FILEFUNC_SEEK_END : + fseek_origin = SEEK_END; + break; + case ZLIB_FILEFUNC_SEEK_SET : + fseek_origin = SEEK_SET; + break; + default: + return -1; } ret = 0; - fseek((FILE *)stream, offset, fseek_origin); + fseek( ( FILE * )stream, offset, fseek_origin ); return ret; } -int ZCALLBACK fclose_file_func (opaque, stream) +int ZCALLBACK fclose_file_func ( opaque, stream ) voidpf opaque; voidpf stream; { int ret; - ret = fclose((FILE *)stream); + ret = fclose( ( FILE * )stream ); return ret; } -int ZCALLBACK ferror_file_func (opaque, stream) +int ZCALLBACK ferror_file_func ( opaque, stream ) voidpf opaque; voidpf stream; { int ret; - ret = ferror((FILE *)stream); + ret = ferror( ( FILE * )stream ); return ret; } -void fill_fopen_filefunc (pzlib_filefunc_def) +void fill_fopen_filefunc ( pzlib_filefunc_def ) zlib_filefunc_def* pzlib_filefunc_def; { pzlib_filefunc_def->zopen_file = fopen_file_func; diff --git a/source/unzip/ioapi.h b/source/unzip/ioapi.h index e1bc49e4..31d31c40 100644 --- a/source/unzip/ioapi.h +++ b/source/unzip/ioapi.h @@ -32,18 +32,20 @@ #endif #ifdef __cplusplus -extern "C" { +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 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 struct zlib_filefunc_def_s { + typedef struct zlib_filefunc_def_s + { open_file_func zopen_file; read_file_func zread_file; write_file_func zwrite_file; @@ -56,7 +58,7 @@ extern "C" { - 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)) diff --git a/source/unzip/miniunz.c b/source/unzip/miniunz.c index 2bf8f26d..75a248ec 100644 --- a/source/unzip/miniunz.c +++ b/source/unzip/miniunz.c @@ -21,252 +21,296 @@ #define WRITEBUFFERSIZE (8192) #define MAXFILENAME (256) -static int mymkdir(const char* dirname) { - int ret=0; - ret = mkdir (dirname,0775); +static int mymkdir( const char* dirname ) +{ + int ret = 0; + ret = mkdir ( dirname, 0775 ); return ret; } -int makedir (char *newdir) { +int makedir ( char *newdir ) +{ char *buffer ; char *p; - int len = (int)strlen(newdir); + int len = ( int )strlen( newdir ); - if (len <= 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'; } - if (mymkdir(buffer) == 0) { - free(buffer); + if ( mymkdir( buffer ) == 0 ) + { + free( buffer ); return 1; } - p = buffer+1; - while (1) { + p = buffer + 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); + free( buffer ); return 0; } - if (hold == 0) + if ( hold == 0 ) break; *p++ = hold; } - free(buffer); + free( buffer ); return 1; } -static char *fullfilename(const char *basedir, char *filename) { - char *file = (char *) malloc(strlen(basedir) + strlen(filename) + 1); - if (basedir == NULL) { - strcpy(file, filename); - } else { - if (basedir[strlen(basedir) - 1] == '/') { - sprintf(file, "%s%s", basedir, filename); - } else { - sprintf(file, "%s/%s", basedir, filename); - } - } - return file; +static char *fullfilename( const char *basedir, char *filename ) +{ + char *file = ( char * ) malloc( strlen( basedir ) + strlen( filename ) + 1 ); + if ( basedir == NULL ) + { + strcpy( file, filename ); + } + else + { + if ( basedir[strlen( basedir ) - 1] == '/' ) + { + sprintf( file, "%s%s", basedir, filename ); + } + else + { + sprintf( file, "%s/%s", basedir, filename ); + } + } + return file; } -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; - char* filename_withpath; + char* filename_withpath; char* p; - int err=UNZ_OK; - FILE *fout=NULL; + int err = UNZ_OK; + FILE *fout = NULL; void* buf; 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); 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"); return UNZ_INTERNALERROR; } p = filename_withoutpath = filename_inzip; - filename_withpath = fullfilename(basedir, filename_inzip); - while ((*p) != '\0') { - if (((*p)=='/') || ((*p)=='\\')) - filename_withoutpath = p+1; + filename_withpath = fullfilename( basedir, filename_inzip ); + while ( ( *p ) != '\0' ) + { + if ( ( ( *p ) == '/' ) || ( ( *p ) == '\\' ) ) + filename_withoutpath = p + 1; p++; } - if ((*filename_withoutpath)=='\0') { - if ((*popt_extract_without_path)==0) { + if ( ( *filename_withoutpath ) == '\0' ) + { + if ( ( *popt_extract_without_path ) == 0 ) + { - // Fix the path, this will fail if the directoryname is the same as the first filename in the zip - char *path = (char *) malloc(strlen(filename_withpath)); - strcpy(path, filename_withpath); - char *ptr = strstr(path, filename_withoutpath); - *ptr = '\0'; + // Fix the path, this will fail if the directoryname is the same as the first filename in the zip + char *path = ( char * ) malloc( strlen( filename_withpath ) ); + strcpy( path, filename_withpath ); + char *ptr = strstr( path, filename_withoutpath ); + *ptr = '\0'; // printf("creating directory: %s\n",path); - mymkdir(path); + mymkdir( path ); - free(path); + free( path ); } - } else { + } + else + { char* write_filename; - int skip=0; + int skip = 0; - if ((*popt_extract_without_path)==0) + if ( ( *popt_extract_without_path ) == 0 ) write_filename = filename_withpath; 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); } - if (((*popt_overwrite)==0) && (err==UNZ_OK)) { - char rep=0; + if ( ( ( *popt_overwrite ) == 0 ) && ( err == UNZ_OK ) ) + { + char rep = 0; FILE* ftestexist; - ftestexist = fopen(write_filename,"rb"); - if (ftestexist!=NULL) { - fclose(ftestexist); - do { + ftestexist = fopen( write_filename, "rb" ); + if ( ftestexist != NULL ) + { + 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) { - exit(EXIT_FAILURE); + ret = scanf( "%1s", answer ); + if ( ret != 1 ) + { + exit( EXIT_FAILURE ); } rep = answer[0] ; - if ((rep>='a') && (rep<='z')) + if ( ( rep >= 'a' ) && ( rep <= 'z' ) ) rep -= 0x20; - } while ((rep!='Y') && (rep!='N') && (rep!='A')); + } + while ( ( rep != 'Y' ) && ( rep != 'N' ) && ( rep != 'A' ) ); } - if (rep == 'N') + if ( rep == 'N' ) skip = 1; - if (rep == 'A') - *popt_overwrite=1; + if ( rep == 'A' ) + *popt_overwrite = 1; } - if ((skip==0) && (err==UNZ_OK)) { - fout=fopen(write_filename,"wb"); + if ( ( skip == 0 ) && ( err == UNZ_OK ) ) + { + 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)) { - char c=*(filename_withoutpath-1); - *(filename_withoutpath-1)='\0'; + if ( ( fout == NULL ) && ( ( *popt_extract_without_path ) == 0 ) && + ( filename_withoutpath != ( char* )filename_inzip ) ) + { + char c = *( filename_withoutpath - 1 ); + *( filename_withoutpath - 1 ) = '\0'; - // Fix the path, this will fail if the directoryname is the same as the first filename in the zip - char *path = (char *) malloc(strlen(write_filename)); - strcpy(path, write_filename); - char *ptr = strstr(path, filename_withoutpath); - *ptr = '\0'; - makedir(path); - free(path); - - *(filename_withoutpath-1)=c; - fout=fopen(write_filename,"wb"); + // Fix the path, this will fail if the directoryname is the same as the first filename in the zip + char *path = ( char * ) malloc( strlen( write_filename ) ); + strcpy( path, write_filename ); + char *ptr = strstr( path, filename_withoutpath ); + *ptr = '\0'; + makedir( path ); + free( path ); + + *( filename_withoutpath - 1 ) = c; + fout = fopen( write_filename, "wb" ); } - if (fout==NULL) { + if ( fout == NULL ) + { // printf("error opening %s\n",write_filename); } } - if (fout!=NULL) { + if ( fout != NULL ) + { // printf(" extracting: %s\n",write_filename); - do { - err = unzReadCurrentFile(uf,buf,size_buf); - if (err<0) { + do + { + err = unzReadCurrentFile( uf, buf, size_buf ); + if ( err < 0 ) + { // printf("error %d with zipfile in unzReadCurrentFile\n",err); break; } - if (err>0) - if (fwrite(buf,err,1,fout)!=1) { + if ( err > 0 ) + if ( fwrite( buf, err, 1, fout ) != 1 ) + { // printf("error in writing extracted file\n"); - err=UNZ_ERRNO; + err = UNZ_ERRNO; break; } - } while (err>0); - if (fout) - fclose(fout); + } + while ( err > 0 ); + if ( fout ) + fclose( fout ); } - if (err==UNZ_OK) { - err = unzCloseCurrentFile (uf); - if (err!=UNZ_OK) { + if ( err == UNZ_OK ) + { + err = unzCloseCurrentFile ( uf ); + if ( err != UNZ_OK ) + { // 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) + err = unzGetGlobalInfo ( uf, &gi ); + if ( err != UNZ_OK ) // printf("error %d with zipfile in unzGetGlobalInfo \n",err); - for (i=0;i> 16); \ } while(0) -extern int ZEXPORT unzRepair(file, fileOut, fileOutTmp, nRecovered, bytesRecovered) - const char* file; +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; char header[30]; @@ -46,59 +47,80 @@ 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) { - unsigned int version = READ_16(header + 4); - unsigned int gpflag = READ_16(header + 6); - unsigned int method = READ_16(header + 8); - unsigned int filetime = READ_16(header + 10); - unsigned int filedate = READ_16(header + 12); - unsigned int crc = READ_32(header + 14); /* crc */ - unsigned int cpsize = READ_32(header + 18); /* compressed size */ - unsigned int uncpsize = READ_32(header + 22); /* uncompressed sz */ - unsigned int fnsize = READ_16(header + 26); /* file name length */ - unsigned int extsize = READ_16(header + 28); /* extra field length */ + if ( READ_32( header ) == 0x04034b50 ) + { + unsigned int version = READ_16( header + 4 ); + unsigned int gpflag = READ_16( header + 6 ); + unsigned int method = READ_16( header + 8 ); + unsigned int filetime = READ_16( header + 10 ); + unsigned int filedate = READ_16( header + 12 ); + unsigned int crc = READ_32( header + 14 ); /* crc */ + unsigned int cpsize = READ_32( header + 18 ); /* compressed size */ + unsigned int uncpsize = READ_32( header + 22 ); /* uncompressed sz */ + unsigned int fnsize = READ_16( header + 26 ); /* file name length */ + unsigned int extsize = READ_16( header + 28 ); /* extra field length */ filename[0] = extra[0] = '\0'; /* Header */ - if (fwrite(header, 1, 30, fpOut) == 30) { + if ( fwrite( header, 1, 30, fpOut ) == 30 ) + { offset += 30; - } else { + } + else + { err = Z_ERRNO; break; } /* Filename */ - if (fnsize > 0) { - if (fread(filename, 1, fnsize, fpZip) == fnsize) { - if (fwrite(filename, 1, fnsize, fpOut) == fnsize) { + if ( fnsize > 0 ) + { + if ( fread( filename, 1, fnsize, fpZip ) == fnsize ) + { + if ( fwrite( filename, 1, fnsize, fpOut ) == fnsize ) + { offset += fnsize; - } else { + } + else + { err = Z_ERRNO; break; } - } else { + } + else + { err = Z_ERRNO; break; } - } else { + } + else + { err = Z_STREAM_ERROR; break; } /* Extra field */ - if (extsize > 0) { - if (fread(extra, 1, extsize, fpZip) == extsize) { - if (fwrite(extra, 1, extsize, fpOut) == extsize) { + if ( extsize > 0 ) + { + if ( fread( extra, 1, extsize, fpZip ) == extsize ) + { + if ( fwrite( extra, 1, extsize, fpOut ) == extsize ) + { offset += extsize; - } else { + } + else + { err = Z_ERRNO; break; } - } else { + } + else + { err = Z_ERRNO; break; } @@ -107,27 +129,39 @@ uLong* bytesRecovered; /* Data */ { int dataSize = cpsize; - if (dataSize == 0) { + if ( dataSize == 0 ) + { dataSize = uncpsize; } - if (dataSize > 0) { - char* data = malloc(dataSize); - if (data != NULL) { - if ((int)fread(data, 1, dataSize, fpZip) == dataSize) { - if ((int)fwrite(data, 1, dataSize, fpOut) == dataSize) { + if ( dataSize > 0 ) + { + char* data = malloc( dataSize ); + if ( data != NULL ) + { + if ( ( int )fread( data, 1, dataSize, fpZip ) == dataSize ) + { + if ( ( int )fwrite( data, 1, dataSize, fpOut ) == dataSize ) + { offset += dataSize; totalBytes += dataSize; - } else { + } + else + { err = Z_ERRNO; } - } else { + } + else + { err = Z_ERRNO; } - free(data); - if (err != Z_OK) { + free( data ); + if ( err != Z_OK ) + { break; } - } else { + } + else + { err = Z_MEM_ERROR; break; } @@ -138,63 +172,80 @@ uLong* bytesRecovered; { char header[46]; char* comment = ""; - int comsize = (int) strlen(comment); - WRITE_32(header, 0x02014b50); - WRITE_16(header + 4, version); - WRITE_16(header + 6, version); - WRITE_16(header + 8, gpflag); - WRITE_16(header + 10, method); - WRITE_16(header + 12, filetime); - WRITE_16(header + 14, filedate); - WRITE_32(header + 16, crc); - WRITE_32(header + 20, cpsize); - WRITE_32(header + 24, uncpsize); - 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_32(header + 42, currentOffset); + int comsize = ( int ) strlen( comment ); + WRITE_32( header, 0x02014b50 ); + WRITE_16( header + 4, version ); + WRITE_16( header + 6, version ); + WRITE_16( header + 8, gpflag ); + WRITE_16( header + 10, method ); + WRITE_16( header + 12, filetime ); + WRITE_16( header + 14, filedate ); + WRITE_32( header + 16, crc ); + WRITE_32( header + 20, cpsize ); + WRITE_32( header + 24, uncpsize ); + 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_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 (fwrite(filename, 1, fnsize, fpOutCD) == fnsize) { + if ( fnsize > 0 ) + { + if ( fwrite( filename, 1, fnsize, fpOutCD ) == fnsize ) + { offsetCD += fnsize; - } else { + } + else + { err = Z_ERRNO; break; } - } else { + } + else + { err = Z_STREAM_ERROR; break; } /* Extra field */ - if (extsize > 0) { - if (fwrite(extra, 1, extsize, fpOutCD) == extsize) { + if ( extsize > 0 ) + { + if ( fwrite( extra, 1, extsize, fpOutCD ) == extsize ) + { offsetCD += extsize; - } else { + } + else + { err = Z_ERRNO; break; } } /* Comment field */ - if (comsize > 0) { - if ((int)fwrite(comment, 1, comsize, fpOutCD) == comsize) { + if ( comsize > 0 ) + { + if ( ( int )fwrite( comment, 1, comsize, fpOutCD ) == comsize ) + { offsetCD += comsize; - } else { + } + else + { err = Z_ERRNO; break; } } - } else { + } + else + { err = Z_ERRNO; break; } @@ -203,7 +254,9 @@ uLong* bytesRecovered; /* Success */ entries++; - } else { + } + else + { break; } } @@ -213,68 +266,83 @@ 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 + 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_32( header, 0x06054b50 ); + 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 */ /* Header */ - if (fwrite(header, 1, 22, fpOutCD) == 22) { + if ( fwrite( header, 1, 22, fpOutCD ) == 22 ) + { /* Comment field */ - if (comsize > 0) { - if ((int)fwrite(comment, 1, comsize, fpOutCD) != comsize) { + if ( comsize > 0 ) + { + if ( ( int )fwrite( comment, 1, comsize, fpOutCD ) != comsize ) + { err = Z_ERRNO; } } - } else { + } + else + { err = Z_ERRNO; } } /* Final merge (file + central directory) */ - fclose(fpOutCD); - if (err == Z_OK) { - fpOutCD = fopen(fileOutTmp, "rb"); - if (fpOutCD != NULL) { + fclose( fpOutCD ); + if ( err == Z_OK ) + { + fpOutCD = fopen( fileOutTmp, "rb" ); + if ( fpOutCD != NULL ) + { int nRead; char buffer[8192]; - while ( (nRead = (int)fread(buffer, 1, sizeof(buffer), fpOutCD)) > 0) { - if ((int)fwrite(buffer, 1, nRead, fpOut) != nRead) { + while ( ( nRead = ( int )fread( buffer, 1, sizeof( buffer ), fpOutCD ) ) > 0 ) + { + 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 (nRecovered != NULL) { + if ( err == Z_OK ) + { + if ( nRecovered != NULL ) + { *nRecovered = entries; } - if (bytesRecovered != NULL) { + if ( bytesRecovered != NULL ) + { *bytesRecovered = totalBytes; } } - } else { + } + else + { err = Z_STREAM_ERROR; } return err; diff --git a/source/unzip/mztools.h b/source/unzip/mztools.h index 1b1f4d31..09f419df 100644 --- a/source/unzip/mztools.h +++ b/source/unzip/mztools.h @@ -8,7 +8,8 @@ #define _zip_tools_H #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #ifndef _ZLIB_H @@ -22,10 +23,10 @@ extern "C" { 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); + 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 2d30ea9b..f90d2add 100644 --- a/source/unzip/unzip.c +++ b/source/unzip/unzip.c @@ -91,14 +91,16 @@ 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 { +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 */ -typedef struct { +typedef struct +{ char *read_buffer; /* internal buffer for compressed data */ z_stream stream; /* zLib stream structure for inflate */ @@ -123,7 +125,8 @@ typedef struct { /* unz_s contain internal information about the zipfile */ -typedef struct { +typedef struct +{ zlib_filefunc_def z_filefunc; voidpf filestream; /* io structore of the zipfile */ unz_global_info gi; /* public global information */ @@ -160,23 +163,26 @@ typedef struct { */ -local int unzlocal_getByte OF(( - const zlib_filefunc_def* pzlib_filefunc_def, - voidpf filestream, - int *pi)); +local int unzlocal_getByte OF( ( + const zlib_filefunc_def* pzlib_filefunc_def, + voidpf filestream, + int *pi ) ); -local int unzlocal_getByte(pzlib_filefunc_def,filestream,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) { - *pi = (int)c; + int err = ( int )ZREAD( *pzlib_filefunc_def, filestream, &c, 1 ); + if ( err == 1 ) + { + *pi = ( int )c; return UNZ_OK; - } else { - if (ZERROR(*pzlib_filefunc_def,filestream)) + } + else + { + if ( ZERROR( *pzlib_filefunc_def, filestream ) ) return UNZ_ERRNO; else return UNZ_EOF; @@ -187,12 +193,12 @@ int *pi; /* =========================================================================== 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)); +local int unzlocal_getShort OF( ( + const zlib_filefunc_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX ) ); -local int unzlocal_getShort (pzlib_filefunc_def,filestream,pX) +local int unzlocal_getShort ( pzlib_filefunc_def, filestream, pX ) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; uLong *pX; @@ -201,26 +207,26 @@ uLong *pX; 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; return err; } -local int unzlocal_getLong OF(( - const zlib_filefunc_def* pzlib_filefunc_def, - voidpf filestream, - uLong *pX)); +local int unzlocal_getLong OF( ( + const zlib_filefunc_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX ) ); -local int unzlocal_getLong (pzlib_filefunc_def,filestream,pX) +local int unzlocal_getLong ( pzlib_filefunc_def, filestream, pX ) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; uLong *pX; @@ -229,22 +235,22 @@ uLong *pX; 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; @@ -253,24 +259,25 @@ uLong *pX; /* My own strcmpi / strcasecmp */ -local int strcmpcasenosensitive_internal (fileName1,fileName2) +local int strcmpcasenosensitive_internal ( fileName1, fileName2 ) const char* fileName1; const char* fileName2; { - for (;;) { - char c1=*(fileName1++); - char c2=*(fileName2++); - if ((c1>='a') && (c1<='z')) + for ( ;; ) + { + char c1 = *( fileName1++ ); + char c2 = *( fileName2++ ); + if ( ( c1 >= 'a' ) && ( c1 <= 'z' ) ) c1 -= 0x20; - if ((c2>='a') && (c2<='z')) + if ( ( c2 >= 'a' ) && ( c2 <= 'z' ) ) c2 -= 0x20; - if (c1=='\0') - return ((c2=='\0') ? 0 : -1); - if (c2=='\0') + if ( c1 == '\0' ) + return ( ( c2 == '\0' ) ? 0 : -1 ); + if ( c2 == '\0' ) return 1; - if (c1c2) + if ( c1 > c2 ) return 1; } } @@ -295,18 +302,18 @@ const char* fileName2; (like 1 on Unix, 2 on Windows) */ -extern int ZEXPORT unzStringFileNameCompare (fileName1,fileName2,iCaseSensitivity) - const char* fileName1; +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 @@ -317,62 +324,64 @@ int iCaseSensitivity; Locate the Central directory of a zipfile (at the end, just before the global comment) */ -local uLong unzlocal_SearchCentralDir OF(( +local uLong unzlocal_SearchCentralDir OF( ( const zlib_filefunc_def* pzlib_filefunc_def, - voidpf filestream)); + voidpf filestream ) ); -local uLong unzlocal_SearchCentralDir(pzlib_filefunc_def,filestream) +local uLong unzlocal_SearchCentralDir( pzlib_filefunc_def, filestream ) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; { unsigned char* buf; uLong uSizeFile; uLong uBackRead; - uLong uMaxBack=0xffff; /* maximum size of global comment */ - uLong uPosFound=0; + uLong uMaxBack = 0xffff; /* maximum size of global comment */ + uLong uPosFound = 0; - if (ZSEEK(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) + if ( ZSEEK( *pzlib_filefunc_def, filestream, 0, ZLIB_FILEFUNC_SEEK_END ) != 0 ) return 0; - uSizeFile = ZTELL(*pzlib_filefunc_def,filestream); + uSizeFile = ZTELL( *pzlib_filefunc_def, filestream ); - if (uMaxBack>uSizeFile) + if ( uMaxBack > uSizeFile ) uMaxBack = uSizeFile; - buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); - if (buf==NULL) + buf = ( unsigned char* )ALLOC( BUFREADCOMMENT + 4 ); + if ( buf == NULL ) return 0; uBackRead = 4; - while (uBackReaduMaxBack) + if ( uBackRead + BUFREADCOMMENT > uMaxBack ) uBackRead = uMaxBack; else - uBackRead+=BUFREADCOMMENT; - uReadPos = uSizeFile-uBackRead ; + 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) + 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) + 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)) { - uPosFound = uReadPos+i; + 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) + if ( uPosFound != 0 ) break; } - TRYFREE(buf); + TRYFREE( buf ); return uPosFound; } @@ -385,13 +394,13 @@ voidpf filestream; 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; +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 central_pos, uL; uLong number_disk; /* number of the current dist, used for spaning ZIP, unsupported, always 0*/ @@ -401,96 +410,97 @@ zlib_filefunc_def* pzlib_filefunc_def; the central dir (same than number_entry on nospan) */ - int err=UNZ_OK; + int err = UNZ_OK; - if (unz_copyright[0]!=' ') + if ( unz_copyright[0] != ' ' ) return NULL; - if (pzlib_filefunc_def==NULL) - fill_fopen_filefunc(&us.z_filefunc); + 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) + 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; + 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_pospfile_in_zip_read!=NULL) - unzCloseCurrentFile(file); + if ( s->pfile_in_zip_read != NULL ) + unzCloseCurrentFile( file ); - ZCLOSE(s->z_filefunc, s->filestream); - TRYFREE(s); + ZCLOSE( s->z_filefunc, s->filestream ); + TRYFREE( s ); return UNZ_OK; } @@ -519,15 +529,15 @@ extern int ZEXPORT unzClose (file) 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; +extern int ZEXPORT unzGetGlobalInfo ( file, pglobal_info ) +unzFile file; unz_global_info *pglobal_info; { unz_s* s; - if (file==NULL) + if ( file == NULL ) return UNZ_PARAMERROR; - s=(unz_s*)file; - *pglobal_info=s->gi; + s = ( unz_s* )file; + *pglobal_info = s->gi; return UNZ_OK; } @@ -535,25 +545,25 @@ unz_global_info *pglobal_info; /* Translate date/time from Dos format to tm_unz (readable more easilty) */ -local void unzlocal_DosDateToTmuDate (ulDosDate, ptm) +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 */ -local int unzlocal_GetCurrentFileInfoInternal OF((unzFile file, +local int unzlocal_GetCurrentFileInfoInternal OF( ( unzFile file, unz_file_info *pfile_info, unz_file_info_internal *pfile_info_internal, @@ -562,14 +572,14 @@ local int unzlocal_GetCurrentFileInfoInternal OF((unzFile file, void *extraField, uLong extraFieldBufferSize, char *szComment, - uLong commentBufferSize)); + uLong commentBufferSize ) ); -local int unzlocal_GetCurrentFileInfoInternal (file, +local int unzlocal_GetCurrentFileInfoInternal ( file, pfile_info, pfile_info_internal, szFileName, fileNameBufferSize, extraField, extraFieldBufferSize, - szComment, commentBufferSize) + szComment, commentBufferSize ) unzFile file; unz_file_info *pfile_info; unz_file_info_internal *pfile_info_internal; @@ -583,139 +593,151 @@ uLong commentBufferSize; unz_s* s; unz_file_info file_info; unz_file_info_internal file_info_internal; - int err=UNZ_OK; + int err = UNZ_OK; uLong uMagic; - long lSeek=0; + long lSeek = 0; - if (file==NULL) + 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; + 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 (unzlocal_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) - err=UNZ_ERRNO; - else if (uMagic!=0x02014b50) - err=UNZ_BADZIPFILE; + if ( err == UNZ_OK ) + { + if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &uMagic ) != UNZ_OK ) + err = UNZ_ERRNO; + 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)) { + lSeek += file_info.size_filename; + if ( ( err == UNZ_OK ) && ( szFileName != NULL ) ) + { uLong uSizeRead ; - if (file_info.size_filename0) && (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_extraz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) - lSeek=0; + if ( lSeek != 0 ) + { + if ( ZSEEK( s->z_filefunc, s->filestream, lSeek, ZLIB_FILEFUNC_SEEK_CUR ) == 0 ) + lSeek = 0; else - err=UNZ_ERRNO; + 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_commentz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) - lSeek=0; + if ( lSeek != 0 ) + { + if ( ZSEEK( s->z_filefunc, s->filestream, lSeek, ZLIB_FILEFUNC_SEEK_CUR ) == 0 ) + lSeek = 0; else - err=UNZ_ERRNO; + 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; + 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; - 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; } @@ -727,12 +749,12 @@ uLong commentBufferSize; 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; +extern int ZEXPORT unzGetCurrentFileInfo ( file, + pfile_info, + szFileName, fileNameBufferSize, + extraField, extraFieldBufferSize, + szComment, commentBufferSize ) +unzFile file; unz_file_info *pfile_info; char *szFileName; uLong fileNameBufferSize; @@ -741,30 +763,30 @@ 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; +extern int ZEXPORT unzGoToFirstFile ( file ) +unzFile file; { - int err=UNZ_OK; + int err = UNZ_OK; unz_s* s; - if (file==NULL) + 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); + 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 ); return err; } @@ -773,28 +795,28 @@ extern int ZEXPORT unzGoToFirstFile (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; +extern int ZEXPORT unzGoToNextFile ( file ) +unzFile file; { unz_s* s; int err; - if (file==NULL) + if ( file == NULL ) return UNZ_PARAMERROR; - s=(unz_s*)file; - if (!s->current_file_ok) + 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) + 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->num_file++; - err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, + 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); + NULL, 0, NULL, 0, NULL, 0 ); + s->current_file_ok = ( err == UNZ_OK ); return err; } @@ -807,8 +829,8 @@ extern int ZEXPORT unzGoToNextFile (file) 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; +extern int ZEXPORT unzLocateFile ( file, szFileName, iCaseSensitivity ) +unzFile file; const char *szFileName; int iCaseSensitivity; { @@ -824,14 +846,14 @@ int iCaseSensitivity; uLong pos_in_central_dirSaved; - if (file==NULL) + if ( file == NULL ) return UNZ_PARAMERROR; - if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP) + if ( strlen( szFileName ) >= UNZ_MAXFILENAMEINZIP ) return UNZ_PARAMERROR; - s=(unz_s*)file; - if (!s->current_file_ok) + s = ( unz_s* )file; + if ( !s->current_file_ok ) return UNZ_END_OF_LIST_OF_FILE; /* Save the current state */ @@ -840,18 +862,20 @@ 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) { - if (unzStringFileNameCompare(szCurrentFileName, - szFileName,iCaseSensitivity)==0) + 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); + err = unzGoToNextFile( file ); } } @@ -884,16 +908,16 @@ typedef struct unz_file_pos_s } unz_file_pos; */ -extern int ZEXPORT unzGetFilePos(file, file_pos) - unzFile file; +extern int ZEXPORT unzGetFilePos( file, file_pos ) +unzFile file; unz_file_pos* file_pos; { unz_s* s; - if (file==NULL || file_pos==NULL) + if ( file == NULL || file_pos == NULL ) return UNZ_PARAMERROR; - s=(unz_s*)file; - if (!s->current_file_ok) + 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; @@ -902,27 +926,27 @@ unz_file_pos* file_pos; return UNZ_OK; } -extern int ZEXPORT unzGoToFilePos(file, file_pos) - unzFile file; +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) + if ( file == NULL || file_pos == NULL ) return UNZ_PARAMERROR; - s=(unz_s*)file; + 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; /* set the current file */ - err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, + err = unzlocal_GetCurrentFileInfoInternal( file, &s->cur_file_info, &s->cur_file_info_internal, - NULL,0,NULL,0,NULL,0); + NULL, 0, NULL, 0, NULL, 0 ); /* return results */ - s->current_file_ok = (err == UNZ_OK); + s->current_file_ok = ( err == UNZ_OK ); return err; } @@ -938,89 +962,90 @@ unz_file_pos* file_pos; store in *piSizeVar the size of extra info in local header (filename and size of extra field data) */ -local int unzlocal_CheckCurrentFileCoherencyHeader (s,piSizeVar, +local int unzlocal_CheckCurrentFileCoherencyHeader ( s, piSizeVar, poffset_local_extrafield, - psize_local_extrafield) + psize_local_extrafield ) unz_s* s; uInt* piSizeVar; uLong *poffset_local_extrafield; uInt *psize_local_extrafield; { - uLong uMagic,uData,uFlags; + uLong uMagic, uData, uFlags; uLong size_filename; uLong size_extra_field; - int err=UNZ_OK; + int err = UNZ_OK; *piSizeVar = 0; *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) + 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 (unzlocal_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) - err=UNZ_ERRNO; - else if (uMagic!=0x04034b50) - err=UNZ_BADZIPFILE; + if ( err == UNZ_OK ) + { + if ( unzlocal_getLong( &s->z_filefunc, s->filestream, &uMagic ) != UNZ_OK ) + err = UNZ_ERRNO; + 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) - err=UNZ_ERRNO; + 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 ) + err = UNZ_ERRNO; + else if ( ( err == UNZ_OK ) && ( uData != s->cur_file_info.compression_method ) ) + 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 ( ( 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 ) /* 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.crc) && - ((uFlags & 8)==0)) - err=UNZ_BADZIPFILE; + 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.crc ) && + ( ( uFlags & 8 ) == 0 ) ) + err = UNZ_BADZIPFILE; - 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 ) /* 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) /* size uncompr */ - err=UNZ_ERRNO; - 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 uncompr */ + err = UNZ_ERRNO; + else if ( ( err == UNZ_OK ) && ( uData != s->cur_file_info.uncompressed_size ) && + ( ( uFlags & 8 ) == 0 ) ) + err = UNZ_BADZIPFILE; - 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; + 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; + *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_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; } @@ -1029,14 +1054,14 @@ uInt *psize_local_extrafield; 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; +extern int ZEXPORT unzOpenCurrentFile3 ( file, method, level, raw, password ) +unzFile file; int* method; int* level; int raw; const char* password; { - int err=UNZ_OK; + int err = UNZ_OK; uInt iSizeVar; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; @@ -1045,86 +1070,91 @@ const char* password; # ifndef NOUNCRYPT char source[12]; # else - if (password != NULL) + if ( password != NULL ) return UNZ_PARAMERROR; # endif - if (file==NULL) + if ( file == NULL ) return UNZ_PARAMERROR; - s=(unz_s*)file; - if (!s->current_file_ok) + 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) + 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) + 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; + 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) { - TRYFREE(pfile_in_zip_read_info); + if ( pfile_in_zip_read_info->read_buffer == NULL ) + { + TRYFREE( pfile_in_zip_read_info ); return UNZ_INTERNALERROR; } - pfile_in_zip_read_info->stream_initialised=0; + 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) { - case 6 : - *level = 1; - break; - case 4 : - *level = 2; - break; - case 2 : - *level = 9; - break; + switch ( s->cur_file_info.flag & 0x06 ) + { + case 6 : + *level = 1; + break; + case 4 : + *level = 2; + break; + 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->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->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->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)) { - 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; + 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.avail_in = 0; - err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS); - if (err == Z_OK) - pfile_in_zip_read_info->stream_initialised=1; - else { - TRYFREE(pfile_in_zip_read_info); + err = inflateInit2( &pfile_in_zip_read_info->stream, -MAX_WBITS ); + if ( err == Z_OK ) + pfile_in_zip_read_info->stream_initialised = 1; + else + { + TRYFREE( pfile_in_zip_read_info ); return err; } /* windowBits is passed < 0 to tell that there is no zlib header. @@ -1145,28 +1175,29 @@ const char* password; 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) + 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) + if ( ZREAD( s->z_filefunc, s->filestream, source, 12 ) < 12 ) return UNZ_INTERNALERROR; - for (i = 0; i<12; i++) - zdecode(s->keys,s->pcrc_32_tab,source[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; - s->encrypted=1; + s->pfile_in_zip_read->pos_in_zipfile += 12; + s->encrypted = 1; } # endif @@ -1174,26 +1205,26 @@ const char* password; 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; +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; +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 ); } /* @@ -1206,118 +1237,124 @@ int raw; 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; +extern int ZEXPORT unzReadCurrentFile ( file, buf, len ) +unzFile file; voidp buf; unsigned len; { - int err=UNZ_OK; + int err = UNZ_OK; uInt iRead = 0; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; - if (file==NULL) + if ( file == NULL ) return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; + s = ( unz_s* )file; + pfile_in_zip_read_info = s->pfile_in_zip_read; - if (pfile_in_zip_read_info==NULL) + if ( pfile_in_zip_read_info == NULL ) return UNZ_PARAMERROR; - if ((pfile_in_zip_read_info->read_buffer == NULL)) + if ( ( pfile_in_zip_read_info->read_buffer == NULL ) ) return UNZ_END_OF_LIST_OF_FILE; - if (len==0) + 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))) + 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; + ( 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)) + 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+ + ( 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) { - if ((pfile_in_zip_read_info->stream.avail_in==0) && - (pfile_in_zip_read_info->rest_read_compressed>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 ) ) + { uInt uReadThis = UNZ_BUFSIZE; - if (pfile_in_zip_read_info->rest_read_compressedrest_read_compressed; - if (uReadThis == 0) + 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) + 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) + 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;iread_buffer[i] = - zdecode(s->keys,s->pcrc_32_tab, - 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->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; + ( 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)) { - uInt uDoCopy,i ; + if ( ( pfile_in_zip_read_info->compression_method == 0 ) || ( pfile_in_zip_read_info->raw ) ) + { + 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) + 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;istream.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->rest_read_uncompressed-=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; pfile_in_zip_read_info->stream.next_out += uDoCopy; pfile_in_zip_read_info->stream.next_in += uDoCopy; pfile_in_zip_read_info->stream.total_out += uDoCopy; iRead += uDoCopy; - } else { - uLong uTotalOutBefore,uTotalOutAfter; + } + else + { + uLong uTotalOutBefore, uTotalOutAfter; const Bytef *bufBefore; uLong uOutThis; - int flush=Z_SYNC_FLUSH; + int flush = Z_SYNC_FLUSH; uTotalOutBefore = pfile_in_zip_read_info->stream.total_out; bufBefore = pfile_in_zip_read_info->stream.next_out; @@ -1328,31 +1365,31 @@ unsigned len; (pfile_in_zip_read_info->rest_read_compressed == 0)) flush = Z_FINISH; */ - err=inflate(&pfile_in_zip_read_info->stream,flush); + err = inflate( &pfile_in_zip_read_info->stream, flush ); - if ((err>=0) && (pfile_in_zip_read_info->stream.msg!=NULL)) + 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; + uOutThis = uTotalOutAfter - uTotalOutBefore; pfile_in_zip_read_info->crc32 = - crc32(pfile_in_zip_read_info->crc32,bufBefore, - (uInt)(uOutThis)); + crc32( pfile_in_zip_read_info->crc32, bufBefore, + ( uInt )( 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) + if ( err == Z_STREAM_END ) + return ( iRead == 0 ) ? UNZ_EOF : iRead; + if ( err != Z_OK ) break; } } - if (err==Z_OK) + if ( err == Z_OK ) return iRead; return err; } @@ -1361,40 +1398,40 @@ unsigned len; /* Give the current position in uncompressed data */ -extern z_off_t ZEXPORT unztell (file) - unzFile file; +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) + if ( file == NULL ) return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; + s = ( unz_s* )file; + pfile_in_zip_read_info = s->pfile_in_zip_read; - if (pfile_in_zip_read_info==NULL) + 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; +extern int ZEXPORT unzeof ( file ) +unzFile file; { unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; - if (file==NULL) + if ( file == NULL ) return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; + s = ( unz_s* )file; + pfile_in_zip_read_info = s->pfile_in_zip_read; - if (pfile_in_zip_read_info==NULL) + 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; @@ -1414,8 +1451,8 @@ extern int ZEXPORT unzeof (file) 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; +extern int ZEXPORT unzGetLocalExtrafield ( file, buf, len ) +unzFile file; voidp buf; unsigned len; { @@ -1424,79 +1461,80 @@ unsigned len; uInt read_now; uLong size_to_read; - if (file==NULL) + if ( file == NULL ) return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; + s = ( unz_s* )file; + pfile_in_zip_read_info = s->pfile_in_zip_read; - if (pfile_in_zip_read_info==NULL) + 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; + if ( len > size_to_read ) + read_now = ( uInt )size_to_read; else - read_now = (uInt)len ; + read_now = ( uInt )len ; - if (read_now==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) + 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) + 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; +extern int ZEXPORT unzCloseCurrentFile ( file ) +unzFile file; { - int err=UNZ_OK; + int err = UNZ_OK; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; - if (file==NULL) + if ( file == NULL ) return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; + s = ( unz_s* )file; + pfile_in_zip_read_info = s->pfile_in_zip_read; - if (pfile_in_zip_read_info==NULL) + 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->crc32 != pfile_in_zip_read_info->crc32_wait) - err=UNZ_CRCERROR; + 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; } - TRYFREE(pfile_in_zip_read_info->read_buffer); + 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); + TRYFREE( pfile_in_zip_read_info ); - s->pfile_in_zip_read=NULL; + s->pfile_in_zip_read = NULL; return err; } @@ -1507,68 +1545,69 @@ extern int ZEXPORT unzCloseCurrentFile (file) 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; +extern int ZEXPORT unzGetGlobalComment ( file, szComment, uSizeBuf ) +unzFile file; char *szComment; uLong uSizeBuf; { unz_s* s; uLong uReadThis ; - if (file==NULL) + if ( file == NULL ) return UNZ_PARAMERROR; - s=(unz_s*)file; + s = ( unz_s* )file; uReadThis = uSizeBuf; - if (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) + if ( ZSEEK( s->z_filefunc, s->filestream, s->central_pos + 22, ZLIB_FILEFUNC_SEEK_SET ) != 0 ) return UNZ_ERRNO; - if (uReadThis>0) { - *szComment='\0'; - if (ZREAD(s->z_filefunc,s->filestream,szComment,uReadThis)!=uReadThis) + if ( uReadThis > 0 ) + { + *szComment = '\0'; + 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) + if ( file == NULL ) return UNZ_PARAMERROR; - s=(unz_s*)file; - if (!s->current_file_ok) + 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) + 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; +extern int ZEXPORT unzSetOffset ( file, pos ) +unzFile file; uLong pos; { unz_s* s; int err; - if (file==NULL) + if ( file == NULL ) return UNZ_PARAMERROR; - s=(unz_s*)file; + 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, + 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); + 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 948c3f2e..e18a7470 100644 --- a/source/unzip/unzip.h +++ b/source/unzip/unzip.h @@ -46,7 +46,8 @@ #define _unz_H #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #ifndef _ZLIB_H @@ -60,7 +61,8 @@ extern "C" { #if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP) /* like the STRICT of WIN32, we define a pointer that cannot be converted from (void*) without cast */ - typedef struct TagunzFile__ { + typedef struct TagunzFile__ + { int unused; } unzFile__; typedef unzFile__ *unzFile; @@ -79,7 +81,8 @@ extern "C" { #define UNZ_CRCERROR (-105) /* tm_unz contain date/time info */ - typedef struct tm_unz_s { + 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] */ @@ -90,7 +93,8 @@ extern "C" { /* unz_global_info structure contain global data about the ZIPfile These data comes from the end of central dir */ - typedef struct unz_global_info_s { + 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 */ @@ -98,7 +102,8 @@ extern "C" { /* unz_file_info contain information about a file in the zipfile */ - typedef struct unz_file_info_s { + 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 */ @@ -118,9 +123,9 @@ extern "C" { tm_unz tmu_date; } unz_file_info; - extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1, - const char* fileName2, - int iCaseSensitivity)); + extern int ZEXPORT unzStringFileNameCompare OF ( ( const char* fileName1, + const char* fileName2, + int iCaseSensitivity ) ); /* Compare two filename (fileName1,fileName2). If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) @@ -131,7 +136,7 @@ extern "C" { */ - extern unzFile ZEXPORT unzOpen OF((const char *path)); + 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 @@ -142,31 +147,31 @@ extern "C" { of this unzip package. */ - extern unzFile ZEXPORT unzOpen2 OF((const char *path, - zlib_filefunc_def* pzlib_filefunc_def)); + extern unzFile ZEXPORT unzOpen2 OF( ( const char *path, + 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) */ - extern int ZEXPORT unzClose OF((unzFile file)); + 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. */ - extern int ZEXPORT unzGetGlobalInfo OF((unzFile file, - unz_global_info *pglobal_info)); + extern int ZEXPORT unzGetGlobalInfo OF( ( 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 unzGetGlobalComment OF((unzFile file, - char *szComment, - uLong uSizeBuf)); + extern int ZEXPORT unzGetGlobalComment OF( ( 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. @@ -177,22 +182,22 @@ extern "C" { /***************************************************************************/ /* Unzip package allow you browse the directory of the zipfile */ - extern int ZEXPORT unzGoToFirstFile OF((unzFile file)); + 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 */ - extern int ZEXPORT unzGoToNextFile OF((unzFile file)); + 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. */ - extern int ZEXPORT unzLocateFile OF((unzFile file, - const char *szFileName, - int iCaseSensitivity)); + extern int ZEXPORT unzLocateFile OF( ( unzFile file, + const char *szFileName, + int iCaseSensitivity ) ); /* Try locate the file szFileName in the zipfile. For the iCaseSensitivity signification, see unzStringFileNameCompare @@ -206,29 +211,30 @@ extern "C" { /* ****************************************** */ /* Ryan supplied functions */ /* unz_file_info contain information about a file in the zipfile */ - typedef struct unz_file_pos_s { + 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; 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)); + extern int ZEXPORT unzGetCurrentFileInfo OF( ( unzFile file, + 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 @@ -247,24 +253,24 @@ extern "C" { from it, and close it (you can close it before reading all the file) */ - extern int ZEXPORT unzOpenCurrentFile OF((unzFile 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. */ - extern int ZEXPORT unzOpenCurrentFilePassword OF((unzFile file, - const char* password)); + extern int ZEXPORT unzOpenCurrentFilePassword OF( ( unzFile file, + 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. */ - extern int ZEXPORT unzOpenCurrentFile2 OF((unzFile file, - int* method, - int* level, - int raw)); + extern int ZEXPORT unzOpenCurrentFile2 OF( ( unzFile file, + int* method, + int* level, + int raw ) ); /* Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) if raw==1 @@ -274,11 +280,11 @@ extern "C" { but you CANNOT set method parameter as NULL */ - extern int ZEXPORT unzOpenCurrentFile3 OF((unzFile file, - int* method, - int* level, - int raw, - const char* password)); + extern int ZEXPORT unzOpenCurrentFile3 OF( ( unzFile file, + int* method, + int* level, + int raw, + const char* password ) ); /* Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) if raw==1 @@ -289,15 +295,15 @@ extern "C" { */ - extern int ZEXPORT unzCloseCurrentFile OF((unzFile file)); + 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 */ - extern int ZEXPORT unzReadCurrentFile OF((unzFile file, - voidp buf, - unsigned len)); + extern int ZEXPORT unzReadCurrentFile OF( ( unzFile file, + voidp buf, + unsigned len ) ); /* Read bytes from the current file (opened by unzOpenCurrentFile) buf contain buffer where data must be copied @@ -309,19 +315,19 @@ extern "C" { (UNZ_ERRNO for IO error, or zLib error for uncompress error) */ - extern z_off_t ZEXPORT unztell OF((unzFile file)); + extern z_off_t ZEXPORT unztell OF( ( unzFile file ) ); /* Give the current position in uncompressed data */ - extern int ZEXPORT unzeof OF((unzFile file)); + extern int ZEXPORT unzeof OF( ( unzFile file ) ); /* return 1 if the end of file was reached, 0 elsewhere */ - extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file, - voidp buf, - unsigned len)); + extern int ZEXPORT unzGetLocalExtrafield OF( ( unzFile file, + 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 @@ -338,10 +344,10 @@ extern "C" { /***************************************************************************/ /* Get the current file offset */ - extern uLong ZEXPORT unzGetOffset (unzFile file); + extern uLong ZEXPORT unzGetOffset ( unzFile file ); /* Set the current file offset */ - extern int ZEXPORT unzSetOffset (unzFile file, uLong pos); + extern int ZEXPORT unzSetOffset ( unzFile file, uLong pos ); diff --git a/source/usbloader/GameList.cpp b/source/usbloader/GameList.cpp index 590698fa..757fe84b 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,13 +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()) + if ( i < 0 || i >= ( int ) FilteredList.size() ) return NULL; return FilteredList[i]; @@ -64,218 +64,218 @@ int GameList::ReadGameList() // Retrieve all stuff from WBFS u32 cnt; - int ret = WBFS_GetCount(&cnt); - if (ret < 0) + 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) + 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(); + return LoadUnfiltered(); } -static bool WCharSortCallback(const wchar_t char1, const wchar_t char2) +static bool WCharSortCallback( const wchar_t char1, const wchar_t char2 ) { return char2 > char1; } -int GameList::FilterList(const wchar_t * gameFilter) +int GameList::FilterList( const wchar_t * gameFilter ) { - if(FullGameList.size() == 0) + if ( FullGameList.size() == 0 ) ReadGameList(); - if(gameFilter) - GameFilter.assign(gameFilter); + 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]; + struct discHdr *header = &FullGameList[i]; - /* Register game */ - NewTitles::Instance()->CheckGame(header->id); + /* Register game */ + NewTitles::Instance()->CheckGame( header->id ); - /* Filters */ - if (Settings.fave) - { - struct Game_NUM* game_num = CFG_get_game_num(header->id); - if (!game_num || game_num->favorite==0) - continue; - } + /* Filters */ + if ( Settings.fave ) + { + 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; + //ignore uLoader cfg "iso". i was told it is "__CFG_" but not confirmed + 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) - { - // Check game rating in WiiTDB, since the default Wii parental control setting is enabled - s32 rating = GetRatingForGame((char *) header->id); - if ((rating != -1 && rating > Settings.parental.rating) || - (rating == -1 && get_pegi_block(header) > Settings.parental.rating)) - { - continue; - } - } + /* Other parental control method */ + if ( Settings.parentalcontrol == 0 && Settings.godmode == 0 && Settings.parental.enabled == 1 ) + { + // Check game rating in WiiTDB, since the default Wii parental control setting is enabled + s32 rating = GetRatingForGame( ( char * ) header->id ); + if ( ( rating != -1 && rating > Settings.parental.rating ) || + ( rating == -1 && get_pegi_block( header ) > Settings.parental.rating ) ) + { + continue; + } + } - wchar_t *gameName = charToWideChar(get_title(header)); + wchar_t *gameName = charToWideChar( get_title( header ) ); - if(gameName && *GameFilter.c_str()) - { - if(wcsnicmp(gameName, GameFilter.c_str(), GameFilter.size()) != 0) - { - delete [] gameName; - continue; - } - } + if ( gameName && *GameFilter.c_str() ) + { + if ( wcsnicmp( gameName, GameFilter.c_str(), GameFilter.size() ) != 0 ) + { + delete [] gameName; + continue; + } + } - if(gameName) - { - if(wcslen(gameName) > GameFilter.size() && AvailableSearchChars.find(gameName[GameFilter.size()]) == std::string::npos) - AvailableSearchChars.push_back(gameName[GameFilter.size()]); + if ( 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(); + NewTitles::Instance()->Save(); - AvailableSearchChars.push_back(L'\0'); + AvailableSearchChars.push_back( L'\0' ); - if(FilteredList.size() < 2) + if ( FilteredList.size() < 2 ) AvailableSearchChars.clear(); - SortList(); + SortList(); - return FilteredList.size(); + return FilteredList.size(); } int GameList::LoadUnfiltered() { - if(FullGameList.size() == 0) + 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]; + struct discHdr *header = &FullGameList[i]; - /* Register game */ - NewTitles::Instance()->CheckGame(header->id); + /* Register game */ + NewTitles::Instance()->CheckGame( header->id ); - 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()]); + 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; - } + } - FilteredList.push_back(header); - } + FilteredList.push_back( header ); + } - NewTitles::Instance()->Save(); + NewTitles::Instance()->Save(); - AvailableSearchChars.push_back(L'\0'); + AvailableSearchChars.push_back( L'\0' ); - if(FilteredList.size() < 2) + if ( FilteredList.size() < 2 ) AvailableSearchChars.clear(); SortList(); - return FilteredList.size(); + return FilteredList.size(); } void GameList::SortList() { - if(FilteredList.size() < 2) + if ( FilteredList.size() < 2 ) return; - if (Settings.sort == PLAYCOUNT) - { - std::sort(FilteredList.begin(), FilteredList.end(), PlaycountSortCallback); - } - else if (Settings.fave) - { - std::sort(FilteredList.begin(), FilteredList.end(), FavoriteSortCallback); - } - else - { - std::sort(FilteredList.begin(), FilteredList.end(), NameSortCallback); - } + if ( Settings.sort == PLAYCOUNT ) + { + std::sort( FilteredList.begin(), FilteredList.end(), PlaycountSortCallback ); + } + else if ( Settings.fave ) + { + std::sort( FilteredList.begin(), FilteredList.end(), FavoriteSortCallback ); + } + else + { + 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 ); } -bool GameList::NameSortCallback(const struct discHdr *a, const struct discHdr *b) +bool GameList::NameSortCallback( const struct discHdr *a, const struct discHdr *b ) { - return (strcasecmp(get_title((struct discHdr *) a), get_title((struct discHdr *) b)) < 0); + return ( strcasecmp( get_title( ( struct discHdr * ) a ), get_title( ( struct discHdr * ) b ) ) < 0 ); } -bool GameList::PlaycountSortCallback(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) + if ( game_num1 ) count1 = game_num1->count; - if(game_num2) + if ( game_num2 ) count2 = game_num2->count; - if(count1 == count2) - return NameSortCallback(a, b); + if ( count1 == count2 ) + return NameSortCallback( a, b ); - return (count1 > count2); + return ( count1 > count2 ); } -bool GameList::FavoriteSortCallback(const struct discHdr *a, const struct discHdr *b) +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) + if ( game_num1 ) fav1 = game_num1->favorite; - if(game_num2) + if ( game_num2 ) fav2 = game_num2->favorite; - if(fav1 == fav2); - return NameSortCallback(a, b); + if ( fav1 == fav2 ); + return NameSortCallback( a, b ); - return (fav1 > fav2); + return ( fav1 > fav2 ); } diff --git a/source/usbloader/GameList.h b/source/usbloader/GameList.h index b5e6b113..2d23a6a2 100644 --- a/source/usbloader/GameList.h +++ b/source/usbloader/GameList.h @@ -12,18 +12,18 @@ class GameList int ReadGameList(); int size() { return FilteredList.size(); }; int GameCount() { return FullGameList.size(); }; - int FilterList(const wchar_t * gameFilter = NULL); + int FilterList( const wchar_t * gameFilter = NULL ); int LoadUnfiltered(); - struct discHdr * at(int i); - struct discHdr * operator[](int i) { return at(i); }; + 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 8e75a18b..cae1de0a 100644 --- a/source/usbloader/alternatedol.c +++ b/source/usbloader/alternatedol.c @@ -13,68 +13,75 @@ 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; void* dol_buffer; 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(); - file = fopen(fullpath, "rb"); + file = fopen( fullpath, "rb" ); - if (file == NULL) { - fclose(file); - // SDCard_deInit(); - // USBDevice_deInit(); + if ( file == NULL ) + { + 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) { - fclose(file); - // SDCard_deInit(); - // USBDevice_deInit(); + dol_buffer = malloc( filesize ); + if ( dol_buffer == NULL ) + { + fclose( file ); + // SDCard_deInit(); + // USBDevice_deInit(); return false; } - ret = fread( dol_buffer, 1, filesize, file); - if (ret != filesize) { - free(dol_buffer); - fclose(file); - // SDCard_deInit(); - // USBDevice_deInit(); + ret = fread( dol_buffer, 1, filesize, file ); + if ( ret != filesize ) + { + free( dol_buffer ); + fclose( file ); + // SDCard_deInit(); + // USBDevice_deInit(); return false; } - fclose(file); + fclose( file ); - // SDCard_deInit(); - // USBDevice_deInit(); + // SDCard_deInit(); + // USBDevice_deInit(); *buffer = dol_buffer; *dollen = filesize; return true; } -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 }; +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 }; void *Addr = Address; - void *Addr_end = Address+Size; + void *Addr_end = Address + Size; - while (Addr <= Addr_end-sizeof(SearchPattern)) { - if (memcmp(Addr, SearchPattern, sizeof(SearchPattern))==0) { - memcpy(Addr,PatchData,sizeof(PatchData)); + while ( Addr <= Addr_end - sizeof( SearchPattern ) ) + { + if ( memcmp( Addr, SearchPattern, sizeof( SearchPattern ) ) == 0 ) + { + memcpy( Addr, PatchData, sizeof( PatchData ) ); return true; } Addr += 4; @@ -82,7 +89,8 @@ bool Remove_001_Protection(void *Address, int Size) { return false; } -typedef struct _dolheader { +typedef struct _dolheader +{ u32 text_pos[7]; u32 data_pos[11]; u32 text_start[7]; @@ -97,28 +105,32 @@ 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) { - dolfile = (dolheader *) dolstart; - for (i = 0; i < 7; i++) { - if ((!dolfile->text_size[i]) || (dolfile->text_start[i] < 0x100)) continue; + if ( dolstart ) + { + 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]); - 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++) { - if ((!dolfile->data_size[i]) || (dolfile->data_start[i] < 0x100)) continue; + for ( i = 0; i < 11; i++ ) + { + 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); @@ -132,33 +144,45 @@ u32 load_dol_image(void *dolstart, u8 videoSelected, u8 patchcountrystring, u8 v static int i; static int phase; -u32 load_dol_start(void *dolstart) { - if (dolstart) { - dolfile = (dolheader *)dolstart; +u32 load_dol_start( void *dolstart ) +{ + if ( dolstart ) + { + dolfile = ( dolheader * )dolstart; return dolfile->entry_point; - } else { + } + else + { 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) { - if (phase == 0) { - if (i == 7) { +bool load_dol_image_modified( void **offset, u32 *pos, u32 *len ) +{ + if ( phase == 0 ) + { + if ( i == 7 ) + { phase = 1; i = 0; - } else { - if ((!dolfile->text_size[i]) || (dolfile->text_start[i] < 0x100)) { + } + else + { + if ( ( !dolfile->text_size[i] ) || ( dolfile->text_start[i] < 0x100 ) ) + { *offset = 0; *pos = 0; *len = 0; - } else { - *offset = (void *)dolfile->text_start[i]; + } + else + { + *offset = ( void * )dolfile->text_start[i]; *pos = dolfile->text_pos[i]; *len = dolfile->text_size[i]; } @@ -167,18 +191,23 @@ bool load_dol_image_modified(void **offset, u32 *pos, u32 *len) { } } - if (phase == 1) { - if (i == 11) { + if ( phase == 1 ) + { + 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; *len = 0; - } else { - *offset = (void *)dolfile->data_start[i]; + } + else + { + *offset = ( void * )dolfile->data_start[i]; *pos = dolfile->data_pos[i]; *len = dolfile->data_size[i]; } @@ -188,32 +217,36 @@ 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; + 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); - } + else + { + 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) { - free(dol_header); + if ( entrypoint == 0 ) + { + free( dol_header ); return -1; } @@ -221,19 +254,21 @@ u32 Load_Dol_from_disc(u32 doloffset, u8 videoSelected, u8 patchcountrystring, u u32 pos; u32 len; - while (load_dol_image_modified(&offset, &pos, &len)) { - if (len != 0) { - ret = WDVD_Read(offset, len, (doloffset<<2) + pos); + while ( load_dol_image_modified( &offset, &pos, &len ) ) + { + if ( len != 0 ) + { + 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 1912493e..56f2d604 100644 --- a/source/usbloader/alternatedol.h +++ b/source/usbloader/alternatedol.h @@ -2,15 +2,16 @@ #define _ALTERNATEDOL_H_ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif /* 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 56a541e3..27bdd84c 100644 --- a/source/usbloader/apploader.c +++ b/source/usbloader/apploader.c @@ -19,49 +19,48 @@ 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 +#define APPLDR_OFFSET 0x2440 /* Variables */ -static u32 buffer[0x20] ATTRIBUTE_ALIGN(32); +static u32 buffer[0x20] ATTRIBUTE_ALIGN( 32 ); -static void __noprint(const char *fmt, ...) { } - -void gamepatches(void * dst, int len, u8 videoSelected, u8 patchcountrystring, u8 vipatch, u8 cheat) +void gamepatches( void * 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, u8 cheat, u8 videoSelected, u8 vipatch, u8 patchcountrystring, u8 error002fix, u8 alternatedol, u32 alternatedoloffset) { +s32 Apploader_Run( entry_point *entry, u8 cheat, u8 videoSelected, u8 vipatch, u8 patchcountrystring, u8 error002fix, u8 alternatedol, u32 alternatedoloffset ) +{ app_entry appldr_entry; app_init appldr_init; app_main appldr_main; @@ -69,84 +68,84 @@ s32 Apploader_Run(entry_point *entry, u8 cheat, u8 videoSelected, u8 vipatch, u8 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(); + //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) + 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) + ret = WDVD_Read( appldr, appldr_len, APPLDR_OFFSET + 0x20 ); + if ( ret < 0 ) return ret; - /* Set apploader entry function */ - appldr_entry = (app_entry)buffer[4]; + /* Set apploader entry function */ + 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 ); - if (error002fix!=0) + if ( error002fix != 0 ) { /* ERROR 002 fix (thanks to WiiPower for sharing this)*/ - *(u32 *)0x80003188 = *(u32 *)0x80003140; + *( u32 * )0x80003188 = *( u32 * )0x80003140; } - for (;;) + for ( ;; ) { void *dst = NULL; int len = 0, offset = 0; /* Run apploader main function */ - ret = appldr_main(&dst, &len, &offset); - if (!ret) + 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 ); } *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, Settings.dolpath, videoSelected, patchcountrystring, vipatch, cheat); - if (dolloaded) + bool dolloaded = Load_Dol( &dolbuffer, &dollen, Settings.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 627555e0..126f4378 100644 --- a/source/usbloader/apploader.h +++ b/source/usbloader/apploader.h @@ -2,15 +2,16 @@ #define _APPLOADER_H_ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif /* Entry point */ - typedef void (*entry_point)(void); + typedef void ( *entry_point )( void ); /* Prototypes */ - s32 Apploader_Run(entry_point *, u8, u8, u8, u8, u8, u8, u32); - void gamepatches(void * dst, int len, u8 videoSelected, u8 patchcountrystring, u8 vipatch, u8 cheat); + s32 Apploader_Run( entry_point *, u8, u8, u8, u8, u8, u8, u32 ); + void gamepatches( void * 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 d3c76b94..b7b82d1c 100644 --- a/source/usbloader/disc.c +++ b/source/usbloader/disc.c @@ -19,17 +19,18 @@ #include "../fatmounter.h" /* Constants */ -#define PTABLE_OFFSET 0x40000 -#define WII_MAGIC 0x5D1C9EA3 +#define PTABLE_OFFSET 0x40000 +#define WII_MAGIC 0x5D1C9EA3 //appentrypoint 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 @@ -40,144 +41,153 @@ void __Disc_SetLowMem(void) { /* Setup low memory */ *Assembler = 0x38A00040; // Assembler - *(u32 *)0x800000E4 = 0x80431A80; + *( u32 * )0x800000E4 = 0x80431A80; *Dev_Debugger = 0x81800000; // Dev Debugger Monitor Address *Simulated_Mem = 0x01800000; // Simulated Memory Size - *(vu32 *)0xCD00643C = 0x00000000; // 32Mhz on Bus + *( 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(); + progressive = ( CONF_GetProgressiveScan() > 0 ) && VIDEO_HaveComponentCable(); tvmode = CONF_GetVideo(); /* Select video mode register */ - switch (tvmode) { - case CONF_VIDEO_PAL: - vmode_reg = (CONF_GetEuRGB60() > 0) ? 5 : 1; - break; + switch ( tvmode ) + { + case CONF_VIDEO_PAL: + vmode_reg = ( CONF_GetEuRGB60() > 0 ) ? 5 : 1; + break; - case CONF_VIDEO_MPAL: - vmode_reg = 4; - break; + case CONF_VIDEO_MPAL: + vmode_reg = 4; + break; - case CONF_VIDEO_NTSC: - vmode_reg = 0; - break; + case CONF_VIDEO_NTSC: + vmode_reg = 0; + break; } - switch (videoselected) { - case 0: + switch ( videoselected ) + { + case 0: - /* Select video mode */ - switch (diskid[3]) { - /* PAL */ - case 'P': - case 'D': - case 'F': - case 'I': - case 'S': - case 'H': - case 'X': - case 'Y': - case 'Z': - if (tvmode != CONF_VIDEO_PAL) { - vmode_reg = 5; - vmode = (progressive) ? &TVNtsc480Prog : &TVEurgb60Hz480IntDf; + /* Select video mode */ + switch ( diskid[3] ) + { + /* PAL */ + case 'P': + case 'D': + case 'F': + case 'I': + case 'S': + case 'H': + case 'X': + case 'Y': + case 'Z': + if ( tvmode != CONF_VIDEO_PAL ) + { + vmode_reg = 5; + vmode = ( progressive ) ? &TVNtsc480Prog : &TVEurgb60Hz480IntDf; + } + + break; + + /* NTSC or unknown */ + case 'E': + case 'J': + case 'K': + case 'W': + if ( tvmode != CONF_VIDEO_NTSC ) + { + vmode_reg = 0; + vmode = ( progressive ) ? &TVNtsc480Prog : &TVNtsc480IntDf; + } + + break; } - break; - /* NTSC or unknown */ - case 'E': - case 'J': - case 'K': - case 'W': - if (tvmode != CONF_VIDEO_NTSC) { - vmode_reg = 0; - vmode = (progressive) ? &TVNtsc480Prog : &TVNtsc480IntDf; - } - + case 1: + vmode = &TVPal528IntDf; + vmode_reg = ( vmode->viTVMode ) >> 2; break; - } - break; - - case 1: - 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; - break; - case 3: - progressive = (CONF_GetProgressiveScan() > 0) && VIDEO_HaveComponentCable(); - vmode = (progressive) ? &TVNtsc480Prog : &TVNtsc480IntDf; - vmode_reg = (vmode->viTVMode) >> 2; - break; - case 4: + case 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; + break; + case 4: // vmode = VIDEO_GetPreferredMode(NULL); - break; + break; } /* Set video mode register */ *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) + 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; u32 cnt, nb_partitions; s32 ret; /* Read partition info */ - ret = WDVD_UnencryptedRead(buffer, 0x20, PTABLE_OFFSET); - if (ret < 0) + ret = WDVD_UnencryptedRead( buffer, 0x20, PTABLE_OFFSET ); + if ( ret < 0 ) return ret; /* Get data */ @@ -185,21 +195,22 @@ s32 __Disc_FindPartition(u64 *outbuf) { table_offset = buffer[1] << 2; /* Read partition table */ - ret = WDVD_UnencryptedRead(buffer, 0x20, table_offset); - if (ret < 0) + 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) + if ( !type ) offset = buffer[cnt * 2] << 2; } /* No game partition found */ - if (!offset) + if ( !offset ) return -1; /* Set output buffer */ @@ -209,119 +220,130 @@ s32 __Disc_FindPartition(u64 *outbuf) { } -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) + 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) + ret = WDVD_GetCoverStatus( &cover ); + if ( ret < 0 ) return ret; } return 0; } -s32 Disc_SetUSB(const u8 *id) { - u32 part = 0; - if (wbfs_part_fs) { - part = wbfs_part_lba; - } else { - part = wbfs_part_idx ? wbfs_part_idx - 1 : 0; - } +s32 Disc_SetUSB( const u8 *id ) +{ + u32 part = 0; + if ( wbfs_part_fs ) + { + part = wbfs_part_lba; + } + else + { + part = wbfs_part_idx ? wbfs_part_idx - 1 : 0; + } /* 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) { - struct discHdr *header = (struct discHdr *)buffer; +s32 Disc_IsWii( void ) +{ + struct discHdr *header = ( struct discHdr * )buffer; s32 ret; /* Read disc header */ - ret = Disc_ReadHeader(header); - if (ret < 0) + ret = Disc_ReadHeader( header ); + if ( ret < 0 ) return ret; /* Check magic word */ - if (header->magic != WII_MAGIC) + if ( header->magic != WII_MAGIC ) return -1; return 0; } -s32 Disc_BootPartition(u64 offset, u8 videoselected, u8 cheat, u8 vipatch, u8 patchcountrystring, u8 error002fix, u8 alternatedol, u32 alternatedoloffset) { +s32 Disc_BootPartition( u64 offset, u8 videoselected, u8 cheat, u8 vipatch, u8 patchcountrystring, u8 error002fix, u8 alternatedol, u32 alternatedoloffset ) +{ entry_point p_entry; s32 ret; /* Open specified partition */ - ret = WDVD_OpenPartition(offset); - if (ret < 0) + 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); + char gameid[8]; + 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, cheat, videoselected, vipatch, patchcountrystring, error002fix, alternatedol, alternatedoloffset); - if (ret < 0) + ret = Apploader_Run( &p_entry, cheat, videoselected, vipatch, patchcountrystring, error002fix, alternatedol, alternatedoloffset ); + if ( ret < 0 ) return ret; free_wip(); bool cheatloaded = false; - if (cheat) + if ( cheat ) { /* OCARINA STUFF - FISHEARS*/ - if(ocarina_load_code((u8 *) gameid) > 0) + if ( ocarina_load_code( ( u8 * ) gameid ) > 0 ) { ocarina_do_code(); cheatloaded = true; } } - //kill the USB and SD - USBDevice_deInit(); + //kill the USB and SD + USBDevice_deInit(); SDCard_deInit(); /* Set an appropiate video mode */ - __Disc_SetVMode(videoselected); + __Disc_SetVMode( videoselected ); /* Set time */ __Disc_SetTime(); @@ -329,125 +351,131 @@ s32 Disc_BootPartition(u64 offset, u8 videoselected, u8 cheat, u8 vipatch, u8 pa //gprintf("\n\tDe-init SD & USB"); /* Disconnect Wiimote */ - WPAD_Flush(0); - WPAD_Disconnect(0); + WPAD_Flush( 0 ); + WPAD_Disconnect( 0 ); WPAD_Shutdown(); - // Anti-green screen fix - VIDEO_SetBlack(TRUE); - VIDEO_Flush(); - VIDEO_WaitVSync(); - gprintf("\n\nUSB Loader GX is done.\n\n"); + // Anti-green screen fix + VIDEO_SetBlack( TRUE ); + VIDEO_Flush(); + VIDEO_WaitVSync(); + gprintf( "\n\nUSB Loader GX is done.\n\n" ); /* Shutdown IOS subsystems */ - // fix for PeppaPig (from NeoGamma) - extern void __exception_closeall(); - IRQ_Disable(); - __IOS_ShutdownSubsystems(); - __exception_closeall(); + // fix for PeppaPig (from NeoGamma) + extern void __exception_closeall(); + IRQ_Disable(); + __IOS_ShutdownSubsystems(); + __exception_closeall(); - appentrypoint = (u32) p_entry; + appentrypoint = ( u32 ) p_entry; - 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" - ); - } - else - { - __asm__( - "lis %r3, appentrypoint@h\n" - "ori %r3, %r3, appentrypoint@l\n" - "lwz %r3, 0(%r3)\n" - "mtlr %r3\n" - "blr\n" - ); - } + 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" + ); + } + else + { + __asm__( + "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(u8 videoselected, u8 cheat, u8 vipatch, u8 patchcountrystring, u8 error002fix, u8 alternatedol, u32 alternatedoloffset) { +s32 Disc_WiiBoot( u8 videoselected, u8 cheat, u8 vipatch, u8 patchcountrystring, u8 error002fix, u8 alternatedol, u32 alternatedoloffset ) +{ u64 offset; s32 ret; /* Find game partition offset */ - ret = __Disc_FindPartition(&offset); - if (ret < 0) + ret = __Disc_FindPartition( &offset ); + if ( ret < 0 ) return ret; /* Boot partition */ - return Disc_BootPartition(offset, videoselected, cheat, vipatch, patchcountrystring, error002fix, alternatedol, alternatedoloffset); + return Disc_BootPartition( offset, videoselected, cheat, vipatch, patchcountrystring, error002fix, alternatedol, alternatedoloffset ); } -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 *Addr = ( u8* )Address; int wiiregion = CONF_GetRegion(); - switch (wiiregion) { - case CONF_REGION_JP: - SearchPattern[0] = 0x00; - SearchPattern[1] = 0x4A; // J - SearchPattern[2] = 0x50; // P - break; - case CONF_REGION_EU: - SearchPattern[0] = 0x02; - SearchPattern[1] = 0x45; // E - SearchPattern[2] = 0x55; // U - break; - case CONF_REGION_KR: - SearchPattern[0] = 0x04; - SearchPattern[1] = 0x4B; // K - SearchPattern[2] = 0x52; // R - break; - case CONF_REGION_CN: - SearchPattern[0] = 0x05; - SearchPattern[1] = 0x43; // C - SearchPattern[2] = 0x4E; // N - break; - case CONF_REGION_US: - default: - SearchPattern[0] = 0x01; - SearchPattern[1] = 0x55; // U - SearchPattern[2] = 0x53; // S + switch ( wiiregion ) + { + case CONF_REGION_JP: + SearchPattern[0] = 0x00; + SearchPattern[1] = 0x4A; // J + SearchPattern[2] = 0x50; // P + break; + case CONF_REGION_EU: + SearchPattern[0] = 0x02; + SearchPattern[1] = 0x45; // E + SearchPattern[2] = 0x55; // U + break; + case CONF_REGION_KR: + SearchPattern[0] = 0x04; + SearchPattern[1] = 0x4B; // K + SearchPattern[2] = 0x52; // R + break; + case CONF_REGION_CN: + SearchPattern[0] = 0x05; + SearchPattern[1] = 0x43; // C + SearchPattern[2] = 0x4E; // N + break; + case CONF_REGION_US: + default: + SearchPattern[0] = 0x01; + SearchPattern[1] = 0x55; // U + SearchPattern[2] = 0x53; // S } - switch (diskid[3]) { - case 'J': - PatchData[1] = 0x4A; // J - PatchData[2] = 0x50; // P - break; + switch ( diskid[3] ) + { + case 'J': + PatchData[1] = 0x4A; // J + PatchData[2] = 0x50; // P + break; - case 'D': - case 'F': - case 'P': - case 'X': - case 'Y': - PatchData[1] = 0x45; // E - PatchData[2] = 0x55; // U - break; + case 'D': + case 'F': + case 'P': + case 'X': + case 'Y': + PatchData[1] = 0x45; // E + PatchData[2] = 0x55; // U + break; - case 'E': - default: - PatchData[1] = 0x55; // U - PatchData[2] = 0x53; // S + case 'E': + default: + PatchData[1] = 0x55; // U + PatchData[2] = 0x53; // S } - while (Size >= 4) { - if (Addr[0] == SearchPattern[0] && Addr[1] == SearchPattern[1] && Addr[2] == SearchPattern[2] && Addr[3] == SearchPattern[3]) { + while ( Size >= 4 ) + { + if ( Addr[0] == SearchPattern[0] && Addr[1] == SearchPattern[1] && Addr[2] == SearchPattern[2] && Addr[3] == SearchPattern[3] ) + { //*Addr = PatchData[0]; Addr += 1; *Addr = PatchData[1]; @@ -457,7 +485,9 @@ void PatchCountryStrings(void *Address, int Size) { //*Addr = PatchData[3]; Addr += 1; Size -= 4; - } else { + } + else + { Addr += 4; Size -= 4; } diff --git a/source/usbloader/disc.h b/source/usbloader/disc.h index 4986782f..4a10608d 100644 --- a/source/usbloader/disc.h +++ b/source/usbloader/disc.h @@ -4,56 +4,57 @@ #include /* for define ATTRIBUTE_PACKED */ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -/* Disc header structure */ -struct discHdr -{ - /* Game ID */ - u8 id[6]; + /* Disc header structure */ + struct discHdr + { + /* 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, u8, u8, u8, u8, u8, u8, u32); -s32 Disc_WiiBoot(u8, u8, u8, u8, u8, u8, u32); -s32 __Disc_FindPartition(u64 *outbuf); -void PatchCountryStrings(void *Address, int Size); -s32 __Disc_FindPartition(u64 *outbuf); + /* 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, u8, u8, u8, u8, u8, u8, u32 ); + s32 Disc_WiiBoot( u8, u8, u8, u8, u8, u8, u32 ); + 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 c30c009b..be9463e3 100644 --- a/source/usbloader/frag.c +++ b/source/usbloader/frag.c @@ -14,165 +14,176 @@ 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)); - ff->maxnum = maxnum; + 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) { - n = ff->num - 1; - if (ff->num > 0 - && ff->frag[n].offset + ff->frag[n].count == offset - && ff->frag[n].sector + ff->frag[n].count == sector) - { - // merge - ff->frag[n].count += count; - } - else - { - // add - if (ff->num >= ff->maxnum) { - // too many fragments - return -500; - } - n = ff->num; - ff->frag[n].offset = offset; - ff->frag[n].sector = sector; - ff->frag[n].count = count; - ff->num++; - } - } - ff->size = offset + count; - return 0; + int n; + if ( count ) + { + n = ff->num - 1; + if ( ff->num > 0 + && ff->frag[n].offset + ff->frag[n].count == offset + && ff->frag[n].sector + ff->frag[n].count == sector ) + { + // merge + ff->frag[n].count += count; + } + else + { + // add + if ( ff->num >= ff->maxnum ) + { + // too many fragments + return -500; + } + n = ff->num; + ff->frag[n].offset = offset; + ff->frag[n].sector = sector; + ff->frag[n].count = count; + ff->num++; + } + } + ff->size = offset + count; + return 0; } -int _frag_append(void *ff, u32 offset, u32 sector, u32 count) +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; inum; i++) { - ret = frag_append(ff, size + src->frag[i].offset, - src->frag[i].sector, src->frag[i].count); - if (ret) return ret; - } - ff->size = size + src->size; - //printf("concat: -> %d %d\n", ff->num, ff->size); - return 0; + int 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++ ) + { + ret = frag_append( ff, size + src->frag[i].offset, + src->frag[i].sector, src->frag[i].count ); + if ( ret ) return ret; + } + ff->size = size + src->size; + //printf("concat: -> %d %d\n", ff->num, ff->size); + return 0; } // in case a sparse block is requested, // the returned poffset might not be equal to requested offset // the difference should be filled with 0 -int frag_get(FragList *ff, u32 offset, u32 count, - u32 *poffset, u32 *psector, u32 *pcount) +int frag_get( FragList *ff, u32 offset, u32 count, + u32 *poffset, u32 *psector, u32 *pcount ) { - int i; - u32 delta; - //printf("frag_get(%u %u)\n", offset, count); - for (i=0; inum; i++) { - if (ff->frag[i].offset <= offset - && ff->frag[i].offset + ff->frag[i].count > offset) - { - delta = offset - ff->frag[i].offset; - *poffset = offset; - *psector = ff->frag[i].sector + delta; - *pcount = ff->frag[i].count - delta; - if (*pcount > count) *pcount = count; - goto out; - } - if (ff->frag[i].offset > offset - && ff->frag[i].offset < offset + count) - { - delta = ff->frag[i].offset - offset; - *poffset = ff->frag[i].offset; - *psector = ff->frag[i].sector; - *pcount = ff->frag[i].count; - count -= delta; - if (*pcount > count) *pcount = count; - goto out; - } - } - // not found - if (offset + count > ff->size) { - // error: out of range! - return -1; - } - // if inside range, then it must be just sparse, zero filled - // return empty block at the end of requested - *poffset = offset + count; - *psector = 0; - *pcount = 0; - out: - //printf("=>(%u %u %u)\n", *poffset, *psector, *pcount); - return 0; + int i; + u32 delta; + //printf("frag_get(%u %u)\n", offset, count); + for ( i = 0; i < ff->num; i++ ) + { + if ( ff->frag[i].offset <= offset + && ff->frag[i].offset + ff->frag[i].count > offset ) + { + delta = offset - ff->frag[i].offset; + *poffset = offset; + *psector = ff->frag[i].sector + delta; + *pcount = ff->frag[i].count - delta; + if ( *pcount > count ) *pcount = count; + goto out; + } + if ( ff->frag[i].offset > offset + && ff->frag[i].offset < offset + count ) + { + delta = ff->frag[i].offset - offset; + *poffset = ff->frag[i].offset; + *psector = ff->frag[i].sector; + *pcount = ff->frag[i].count; + count -= delta; + if ( *pcount > count ) *pcount = count; + goto out; + } + } + // not found + if ( offset + count > ff->size ) + { + // error: out of range! + return -1; + } + // if inside range, then it must be just sparse, zero filled + // return empty block at the end of requested + *poffset = offset + count; + *psector = 0; + *pcount = 0; +out: + //printf("=>(%u %u %u)\n", *poffset, *psector, *pcount); + return 0; } -int frag_remap(FragList *ff, FragList *log, FragList *phy) +int frag_remap( FragList *ff, FragList *log, FragList *phy ) { - int i; - int ret; - u32 offset; - u32 sector; - u32 count; - u32 delta; - for (i=0; inum; i++) { - delta = 0; - count = 0; - do { - ret = frag_get(phy, - log->frag[i].sector + delta + count, - log->frag[i].count - delta - count, - &offset, §or, &count); - if (ret) return ret; // error - delta = offset - log->frag[i].sector; - ret = frag_append(ff, log->frag[i].offset + delta, sector, count); - if (ret) return ret; // error - } while (count + delta < log->frag[i].count); - } - return 0; + int i; + int ret; + u32 offset; + u32 sector; + u32 count; + u32 delta; + 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 + delta = offset - log->frag[i].sector; + ret = frag_append( ff, log->frag[i].offset + delta, sector, count ); + if ( ret ) return ret; // error + } + while ( count + delta < log->frag[i].count ); + } + return 0; } -int get_frag_list(u8 *id) +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_FAT) { - // fall back to old fat method -// printf("FAT: fallback to old method\n"); - return 0; - } - // ntfs has no fallback, return error - return -1; - } + if ( wbfs_part_fs == PART_FS_WBFS ) return 0; + if ( frag_list == NULL ) + { + if ( wbfs_part_fs == PART_FS_FAT ) + { + // fall back to old fat method +// printf("FAT: fallback to old method\n"); + return 0; + } + // ntfs has no fallback, return error + return -1; + } - // (+1 for header which is same size as fragment) - int size = sizeof(Fragment) * (frag_list->num + 1); - int ret = USBStorage_WBFS_SetFragList(frag_list, size); - if (ret) { -// printf("set_frag: %d\n", ret); - return ret; - } + // (+1 for header which is same size as fragment) + int size = sizeof( Fragment ) * ( frag_list->num + 1 ); + int ret = USBStorage_WBFS_SetFragList( frag_list, size ); + if ( ret ) + { +// printf("set_frag: %d\n", ret); + return ret; + } - // verify id matches - char discid[8]; - memset(discid, 0, sizeof(discid)); - ret = USBStorage_WBFS_Read(0, 6, discid); - return 0; + // verify id matches + char discid[8]; + memset( discid, 0, sizeof( discid ) ); + ret = USBStorage_WBFS_Read( 0, 6, discid ); + return 0; } diff --git a/source/usbloader/frag.h b/source/usbloader/frag.h index 1d83ff61..e82d6240 100644 --- a/source/usbloader/frag.h +++ b/source/usbloader/frag.h @@ -6,45 +6,46 @@ // 40000/4/3-1 = 21844 #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #include "libwbfs/libwbfs.h" -typedef struct -{ - u32 offset; // file offset, in sectors unit - u32 sector; - u32 count; -} Fragment; + typedef struct + { + u32 offset; // file offset, in sectors unit + u32 sector; + u32 count; + } Fragment; -typedef struct -{ - u32 size; // num sectors - u32 num; // num fragments - u32 maxnum; - Fragment frag[MAX_FRAG]; -} FragList; + typedef struct + { + u32 size; // num sectors + u32 num; // num fragments + u32 maxnum; + Fragment frag[MAX_FRAG]; + } FragList; -typedef int (*frag_append_t)(void *ff, u32 offset, u32 sector, u32 count); + typedef int ( *frag_append_t )( void *ff, u32 offset, u32 sector, u32 count ); -int _FAT_get_fragments (const char *path, _frag_append_t append_fragment, void *callback_data); + int _FAT_get_fragments ( const char *path, _frag_append_t append_fragment, void *callback_data ); -void frag_init(FragList *ff, int maxnum); -int frag_append(FragList *ff, u32 offset, u32 sector, u32 count); -int _frag_append(void *ff, u32 offset, u32 sector, u32 count); -int frag_concat(FragList *ff, FragList *src); + void frag_init( FragList *ff, int maxnum ); + int frag_append( FragList *ff, u32 offset, u32 sector, u32 count ); + int _frag_append( void *ff, u32 offset, u32 sector, u32 count ); + int frag_concat( FragList *ff, FragList *src ); // in case a sparse block is requested, // the returned poffset might not be equal to requested offset // the difference should be filled with 0 -int frag_get(FragList *ff, u32 offset, u32 count, - u32 *poffset, u32 *psector, u32 *pcount); + int frag_get( FragList *ff, u32 offset, u32 count, + u32 *poffset, u32 *psector, u32 *pcount ); -int frag_remap(FragList *ff, FragList *log, FragList *phy); + int frag_remap( FragList *ff, FragList *log, FragList *phy ); -int get_frag_list(u8 *id); -int set_frag_list(u8 *id); + int get_frag_list( u8 *id ); + int set_frag_list( u8 *id ); #ifdef __cplusplus } diff --git a/source/usbloader/fstfile.c b/source/usbloader/fstfile.c index ebaa5439..676ef986 100644 --- a/source/usbloader/fstfile.c +++ b/source/usbloader/fstfile.c @@ -3,35 +3,47 @@ #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) { - stringoffset = *(u32 *)&(fst[index]) % (256*256*256); - return (char *)((u32)fst + count*12 + stringoffset); - } else { + if ( index < count ) + { + stringoffset = *( u32 * ) & ( fst[index] ) % ( 256 * 256 * 256 ); + return ( char * )( ( u32 )fst + count*12 + stringoffset ); + } + else + { return NULL; } } -char *fstfilename(u32 index) { - FST_ENTRY *fst = (FST_ENTRY *)*(u32 *)0x80000038; +char *fstfilename( u32 index ) +{ + FST_ENTRY *fst = ( FST_ENTRY * ) * ( u32 * )0x80000038; u32 count = fst[0].filelen; u32 stringoffset; - if (index < count) { - stringoffset = *(u32 *)&(fst[index]) % (256*256*256); - return (char *)(*(u32 *)0x80000038 + count*12 + stringoffset); - } else { + if ( index < count ) + { + stringoffset = *( u32 * ) & ( fst[index] ) % ( 256 * 256 * 256 ); + return ( char * )( *( u32 * )0x80000038 + count*12 + stringoffset ); + } + else + { return NULL; } } -u32 fstfileoffset(u32 index) { - FST_ENTRY *fst = (FST_ENTRY *)*(u32 *)0x80000038; +u32 fstfileoffset( u32 index ) +{ + FST_ENTRY *fst = ( FST_ENTRY * ) * ( u32 * )0x80000038; u32 count = fst[0].filelen; - if (index < count) { + if ( index < count ) + { return fst[index].fileoffset; - } else { + } + else + { return 0; } } diff --git a/source/usbloader/fstfile.h b/source/usbloader/fstfile.h index 1fdbb480..a2ea42ff 100644 --- a/source/usbloader/fstfile.h +++ b/source/usbloader/fstfile.h @@ -2,19 +2,21 @@ #define _FSTFILE_H_ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif - typedef struct { + typedef struct + { u8 filetype; char name_offset[3]; u32 fileoffset; u32 filelen; - } __attribute__((packed)) FST_ENTRY; + } __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 590e2651..05a25dad 100644 --- a/source/usbloader/partition_usbloader.c +++ b/source/usbloader/partition_usbloader.c @@ -13,361 +13,392 @@ #include "libwbfs/libwbfs.h" /* 'partition table' structure */ -typedef struct { - /* Zero bytes */ - u8 padding[446]; +typedef struct +{ + /* Zero bytes */ + u8 padding[446]; - /* Partition table entries */ - partitionEntry entries[MAX_PARTITIONS]; + /* Partition table entries */ + partitionEntry entries[MAX_PARTITIONS]; } ATTRIBUTE_PACKED partitionTable; -s32 Partition_GetEntries(u32 device, partitionEntry *outbuf, u32 *outval) +s32 Partition_GetEntries( u32 device, partitionEntry *outbuf, u32 *outval ) { - static partitionTable table ATTRIBUTE_ALIGN(32); + static partitionTable table ATTRIBUTE_ALIGN( 32 ); - u32 cnt, sector_size; - s32 ret; + u32 cnt, sector_size; + s32 ret; - /* Read from specified device */ - switch (device) { - case WBFS_DEVICE_USB: { - /* Get sector size */ - ret = USBStorage2_GetCapacity(§or_size); - if (ret == 0) - return -1; + /* Read from specified device */ + switch ( device ) + { + case WBFS_DEVICE_USB: + { + /* 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; + case WBFS_DEVICE_SDHC: + { + /* SDHC sector size */ + sector_size = SDHC_SECTOR_SIZE; - /* Read partition table */ - ret = SDHC_ReadSectors(0, 1, &table); - if (!ret) - return -1; + /* Read partition table */ + ret = SDHC_ReadSectors( 0, 1, &table ); + if ( !ret ) + return -1; - break; - } + break; + } - default: - return -1; - } + default: + return -1; + } - /* Swap endianess */ - for (cnt = 0; cnt < 4; cnt++) { - partitionEntry *entry = &table.entries[cnt]; + /* Swap endianess */ + for ( cnt = 0; cnt < 4; cnt++ ) + { + partitionEntry *entry = &table.entries[cnt]; - entry->sector = swap32(entry->sector); - entry->size = swap32(entry->size); - } + entry->sector = swap32( entry->sector ); + entry->size = swap32( entry->size ); + } - /* Set partition entries */ - memcpy(outbuf, table.entries, sizeof(table.entries)); + /* Set partition entries */ + memcpy( outbuf, table.entries, sizeof( table.entries ) ); - /* Set sector size */ - *outval = sector_size; + /* Set sector size */ + *outval = sector_size; - return 0; + return 0; } -bool Device_ReadSectors(u32 device, u32 sector, u32 count, void *buffer) +bool Device_ReadSectors( u32 device, u32 sector, u32 count, void *buffer ) { - s32 ret; + s32 ret; - /* Read from specified device */ - switch (device) { - case WBFS_DEVICE_USB: - ret = USBStorage2_ReadSectors(sector, count, buffer); - if (ret < 0) - return false; - return true; + /* Read from specified device */ + switch ( device ) + { + case WBFS_DEVICE_USB: + ret = USBStorage2_ReadSectors( sector, count, buffer ); + if ( ret < 0 ) + return false; + return true; - case WBFS_DEVICE_SDHC: - return SDHC_ReadSectors(sector, count, buffer); - } + case WBFS_DEVICE_SDHC: + return SDHC_ReadSectors( sector, count, buffer ); + } - return false; + return false; } -bool Device_WriteSectors(u32 device, u32 sector, u32 count, void *buffer) +bool Device_WriteSectors( u32 device, u32 sector, u32 count, void *buffer ) { - s32 ret; + s32 ret; - /* Read from specified device */ - switch (device) { - case WBFS_DEVICE_USB: - ret = USBStorage2_WriteSectors(sector, count, buffer); - if (ret < 0) - return false; - return true; + /* Read from specified device */ + switch ( device ) + { + case WBFS_DEVICE_USB: + ret = USBStorage2_WriteSectors( sector, count, buffer ); + if ( ret < 0 ) + return false; + return true; - case WBFS_DEVICE_SDHC: - return SDHC_WriteSectors(sector, count, buffer); - } + case WBFS_DEVICE_SDHC: + return SDHC_WriteSectors( sector, count, buffer ); + } - return false; + return false; } -s32 Partition_GetEntriesEx(u32 device, partitionEntry *outbuf, u32 *psect_size, u8 *num) +s32 Partition_GetEntriesEx( u32 device, partitionEntry *outbuf, u32 *psect_size, u8 *num ) { - static partitionTable table ATTRIBUTE_ALIGN(32); - partitionEntry *entry; + static partitionTable table ATTRIBUTE_ALIGN( 32 ); + partitionEntry *entry; - u32 i, sector_size; - s32 ret; - int maxpart = *num; + u32 i, sector_size; + s32 ret; + int maxpart = *num; - // Get sector size - switch (device) { - case WBFS_DEVICE_USB: - ret = USBStorage2_GetCapacity(§or_size); - if (ret == 0) return -1; - break; - case WBFS_DEVICE_SDHC: - sector_size = SDHC_SECTOR_SIZE; - break; - default: - return -1; - } - /* Set sector size */ - *psect_size = sector_size; + // Get sector size + switch ( device ) + { + case WBFS_DEVICE_USB: + ret = USBStorage2_GetCapacity( §or_size ); + if ( ret == 0 ) return -1; + break; + case WBFS_DEVICE_SDHC: + sector_size = SDHC_SECTOR_SIZE; + break; + default: + return -1; + } + /* Set sector size */ + *psect_size = sector_size; - u32 ext = 0; - u32 next = 0; + u32 ext = 0; + u32 next = 0; - // Read partition table - ret = Device_ReadSectors(device, 0, 1, &table); - if (!ret) return -1; - // Check if it's a RAW WBFS disc, without partition table - if (get_fs_type(&table) == FS_TYPE_WBFS) { - memset(outbuf, 0, sizeof(table.entries)); - wbfs_head_t *head = (wbfs_head_t*)&table; - outbuf->size = wbfs_ntohl(head->n_hd_sec); - *num = 1; - return 0; - } - /* Swap endianess */ - for (i = 0; i < 4; i++) { - entry = &table.entries[i]; - entry->sector = swap32(entry->sector); - entry->size = swap32(entry->size); - if (!ext && part_is_extended(entry->type)) { - ext = entry->sector; - } - } - /* Set partition entries */ - memcpy(outbuf, table.entries, sizeof(table.entries)); - // num primary - *num = 4; + // Read partition table + ret = Device_ReadSectors( device, 0, 1, &table ); + if ( !ret ) return -1; + // Check if it's a RAW WBFS disc, without partition table + if ( get_fs_type( &table ) == FS_TYPE_WBFS ) + { + memset( outbuf, 0, sizeof( table.entries ) ); + wbfs_head_t *head = ( wbfs_head_t* ) & table; + outbuf->size = wbfs_ntohl( head->n_hd_sec ); + *num = 1; + return 0; + } + /* Swap endianess */ + for ( i = 0; i < 4; i++ ) + { + entry = &table.entries[i]; + entry->sector = swap32( entry->sector ); + entry->size = swap32( entry->size ); + if ( !ext && part_is_extended( entry->type ) ) + { + ext = entry->sector; + } + } + /* Set partition entries */ + memcpy( outbuf, table.entries, sizeof( table.entries ) ); + // num primary + *num = 4; - if (!ext) return 0; + if ( !ext ) return 0; - next = ext; - // scan extended partition for logical - for(i=0; isector = swap32(entry->sector); - entry->size = swap32(entry->size); - if (entry->type && entry->size && entry->sector) { - // rebase to abolute address - entry->sector += next; - // add logical - memcpy(&outbuf[*num], entry, sizeof(*entry)); - (*num)++; - // get next - entry++; - if (entry->type && entry->size && entry->sector) { - next = ext + swap32(entry->sector); - } else { - break; - } - } - } + next = ext; + // scan extended partition for logical + for ( i = 0; i < maxpart - 4; i++ ) + { + 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; + } + entry = &table.entries[0]; + 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 )++; + // get next + entry++; + if ( entry->type && entry->size && entry->sector ) + { + next = ext + swap32( entry->sector ); + } + else + { + break; + } + } + } - return 0; + return 0; } -bool part_is_extended(int type) +bool part_is_extended( int type ) { - if (type == 0x05) return true; - if (type == 0x0f) return true; - return false; + 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; - return false; + 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) { - return part_is_data(entry->type); - } - return false; + if ( entry->size && entry->type && entry->sector ) + { + return part_is_data( entry->type ); + } + return false; } -char* part_type_data(int type) +char* part_type_data( int type ) { - switch (type) { - case 0x01: return "FAT12"; - case 0x04: return "FAT16"; - case 0x06: return "FAT16"; //+ - case 0x07: return "NTFS"; - case 0x0b: return "FAT32"; - case 0x0c: return "FAT32"; - case 0x0e: return "FAT16"; - case 0x82: return "LxSWP"; - case 0x83: return "LINUX"; - case 0x8e: return "LxLVM"; - case 0xa8: return "OSX"; - case 0xab: return "OSXBT"; - case 0xaf: return "OSXHF"; - case 0xe8: return "LUKS"; - } - return NULL; + switch ( type ) + { + case 0x01: return "FAT12"; + case 0x04: return "FAT16"; + case 0x06: return "FAT16"; //+ + case 0x07: return "NTFS"; + case 0x0b: return "FAT32"; + case 0x0c: return "FAT32"; + case 0x0e: return "FAT16"; + case 0x82: return "LxSWP"; + case 0x83: return "LINUX"; + case 0x8e: return "LxLVM"; + case 0xa8: return "OSX"; + case 0xab: return "OSXBT"; + case 0xaf: return "OSXHF"; + case 0xe8: return "LUKS"; + } + return NULL; } -char *part_type_name(int type) +char *part_type_name( int type ) { - static char unk[8]; - if (type == 0) return "UNUSED"; - if (part_is_extended(type)) return "EXTEND"; - char *p = part_type_data(type); - if (p) return p; - sprintf(unk, "UNK-%02x", type); - return unk; + static char unk[8]; + if ( type == 0 ) return "UNUSED"; + if ( part_is_extended( type ) ) return "EXTEND"; + char *p = part_type_data( type ); + if ( p ) return p; + sprintf( unk, "UNK-%02x", type ); + return unk; } -int get_fs_type(void *buff) +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; - // 55AA - if (buf[0x1FE] == 0x55 && buf[0x1FF] == 0xAA) { - // FAT - if (memcmp(buf+0x36,"FAT",3) == 0) return FS_TYPE_FAT16; - if (memcmp(buf+0x52,"FAT",3) == 0) return FS_TYPE_FAT32; - // NTFS - if (memcmp(buf+0x03,"NTFS",4) == 0) return FS_TYPE_NTFS; - } - return FS_TYPE_UNK; + char *buf = buff; + // 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 ) + { + // FAT + if ( memcmp( buf + 0x36, "FAT", 3 ) == 0 ) return FS_TYPE_FAT16; + if ( memcmp( buf + 0x52, "FAT", 3 ) == 0 ) return FS_TYPE_FAT32; + // NTFS + if ( memcmp( buf + 0x03, "NTFS", 4 ) == 0 ) return FS_TYPE_NTFS; + } + return FS_TYPE_UNK; } -int get_part_fs(int fs_type) +int get_part_fs( int fs_type ) { - switch(fs_type) { - case FS_TYPE_FAT32: return PART_FS_FAT; - case FS_TYPE_NTFS: return PART_FS_NTFS; - case FS_TYPE_WBFS: return PART_FS_WBFS; - default: return -1; - } + switch ( fs_type ) + { + case FS_TYPE_FAT32: return PART_FS_FAT; + case FS_TYPE_NTFS: return PART_FS_NTFS; + case FS_TYPE_WBFS: return PART_FS_WBFS; + default: return -1; + } } -bool is_type_fat(int type) +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) { - 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 ""; + switch ( i ) + { + case FS_TYPE_FAT16: return "FAT16"; + case FS_TYPE_FAT32: return "FAT32"; + case FS_TYPE_NTFS: return "NTFS"; + case FS_TYPE_WBFS: return "WBFS"; + } + return ""; } -s32 Partition_GetList(u32 device, PartList *plist) +s32 Partition_GetList( u32 device, PartList *plist ) { - partitionEntry *entry = NULL; - PartInfo *pinfo = NULL; - int i, ret; + partitionEntry *entry = NULL; + PartInfo *pinfo = NULL; + int i, ret; - memset(plist, 0, sizeof(PartList)); + memset( plist, 0, sizeof( PartList ) ); - // Get partition entries - plist->num = MAX_PARTITIONS_EX; - ret = Partition_GetEntriesEx(device, plist->pentry, &plist->sector_size, &plist->num); - if (ret < 0) { - return -1; - } - // check for RAW WBFS disc - if (plist->num == 1) { - pinfo = &plist->pinfo[0]; - entry = &plist->pentry[0]; - plist->wbfs_n = 1; - pinfo->wbfs_i = pinfo->index = 1; - return 0; - } + // Get partition entries + plist->num = MAX_PARTITIONS_EX; + ret = Partition_GetEntriesEx( device, plist->pentry, &plist->sector_size, &plist->num ); + if ( ret < 0 ) + { + return -1; + } + // check for RAW WBFS disc + if ( plist->num == 1 ) + { + pinfo = &plist->pinfo[0]; + entry = &plist->pentry[0]; + plist->wbfs_n = 1; + pinfo->wbfs_i = pinfo->index = 1; + return 0; + } - char buf[plist->sector_size]; + char buf[plist->sector_size]; - // scan partitions for filesystem type - for (i = 0; i < plist->num; i++) { - pinfo = &plist->pinfo[i]; - entry = &plist->pentry[i]; - if (!entry->size) continue; - if (!entry->type) continue; - if (!entry->sector) continue; - // even though wrong, it's possible WBFS is on an extended part. - //if (!part_is_data(entry->type)) continue; - if (!Device_ReadSectors(device, entry->sector, 1, buf)) continue; - pinfo->fs_type = get_fs_type(buf); - if (pinfo->fs_type == FS_TYPE_WBFS) { - // multiple wbfs on sdhc not supported - if (device == WBFS_DEVICE_SDHC && (plist->wbfs_n > 1 || i > 4)) continue; - plist->wbfs_n++; - pinfo->wbfs_i = pinfo->index = plist->wbfs_n; - } else if (is_type_fat(pinfo->fs_type)) { - plist->fat_n++; - pinfo->fat_i = pinfo->index = plist->fat_n; - } else if (pinfo->fs_type == FS_TYPE_NTFS) { - plist->ntfs_n++; - pinfo->ntfs_i = pinfo->index = plist->ntfs_n; - } - pinfo->part_fs = get_part_fs(pinfo->fs_type); - } - return 0; + // scan partitions for filesystem type + for ( i = 0; i < plist->num; i++ ) + { + pinfo = &plist->pinfo[i]; + entry = &plist->pentry[i]; + if ( !entry->size ) continue; + if ( !entry->type ) continue; + if ( !entry->sector ) continue; + // even though wrong, it's possible WBFS is on an extended part. + //if (!part_is_data(entry->type)) continue; + if ( !Device_ReadSectors( device, entry->sector, 1, buf ) ) continue; + pinfo->fs_type = get_fs_type( buf ); + if ( pinfo->fs_type == FS_TYPE_WBFS ) + { + // multiple wbfs on sdhc not supported + if ( device == WBFS_DEVICE_SDHC && ( plist->wbfs_n > 1 || i > 4 ) ) continue; + plist->wbfs_n++; + pinfo->wbfs_i = pinfo->index = plist->wbfs_n; + } + else if ( is_type_fat( pinfo->fs_type ) ) + { + plist->fat_n++; + pinfo->fat_i = pinfo->index = plist->fat_n; + } + else if ( pinfo->fs_type == FS_TYPE_NTFS ) + { + plist->ntfs_n++; + pinfo->ntfs_i = pinfo->index = plist->ntfs_n; + } + pinfo->part_fs = get_part_fs( pinfo->fs_type ); + } + return 0; } -int Partition_FixEXT(u32 device, u8 part) +int Partition_FixEXT( u32 device, u8 part ) { - static partitionTable table ATTRIBUTE_ALIGN(32); - int ret; + static partitionTable table ATTRIBUTE_ALIGN( 32 ); + int ret; - 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)) { - table.entries[part].type = 0x0b; // FAT32 - ret = Device_WriteSectors(device, 0, 1, &table); - if (!ret) return -1; - return 0; - } - 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 ) ) + { + table.entries[part].type = 0x0b; // FAT32 + ret = Device_WriteSectors( device, 0, 1, &table ); + if ( !ret ) return -1; + return 0; + } + return -1; } diff --git a/source/usbloader/partition_usbloader.h b/source/usbloader/partition_usbloader.h index bf6bd061..5fde0665 100644 --- a/source/usbloader/partition_usbloader.h +++ b/source/usbloader/partition_usbloader.h @@ -2,33 +2,35 @@ #define _PARTITION_H_ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -/* 'partition entry' structure */ -typedef struct { - /* Boot indicator */ - u8 boot; + /* 'partition entry' structure */ + typedef struct + { + /* Boot indicator */ + u8 boot; - /* Starting CHS */ - u8 start[3]; + /* Starting CHS */ + u8 start[3]; - /* Partition type */ - u8 type; + /* Partition type */ + u8 type; - /* Ending CHS */ - u8 end[3]; + /* Ending CHS */ + u8 end[3]; - /* Partition sector */ - u32 sector; + /* Partition sector */ + u32 sector; - /* Partition size */ - u32 size; -} ATTRIBUTE_PACKED partitionEntry; + /* Partition size */ + u32 size; + } ATTRIBUTE_PACKED partitionEntry; -/* Constants */ -#define MAX_PARTITIONS 4 -#define MAX_PARTITIONS_EX 10 + /* Constants */ +#define MAX_PARTITIONS 4 +#define MAX_PARTITIONS_EX 10 #define FS_TYPE_UNK 0 #define FS_TYPE_FAT16 1 @@ -36,43 +38,43 @@ typedef struct { #define FS_TYPE_NTFS 3 #define FS_TYPE_WBFS 4 -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; -} PartInfo; + 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; + } 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]; -} PartList; + 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]; + } 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); + /* 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 ); -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 33e343a6..1cd20499 100644 --- a/source/usbloader/sdhc.c +++ b/source/usbloader/sdhc.c @@ -6,217 +6,231 @@ #include "sdhc.h" /* IOCTL comamnds */ -#define IOCTL_SDHC_INIT 0x01 -#define IOCTL_SDHC_READ 0x02 -#define IOCTL_SDHC_WRITE 0x03 -#define IOCTL_SDHC_ISINSERTED 0x04 +#define IOCTL_SDHC_INIT 0x01 +#define IOCTL_SDHC_READ 0x02 +#define IOCTL_SDHC_WRITE 0x03 +#define IOCTL_SDHC_ISINSERTED 0x04 -#define SDHC_HEAPSIZE 0x8000 -#define SDHC_MEM2_SIZE 0x10000 +#define SDHC_HEAPSIZE 0x8000 +#define SDHC_MEM2_SIZE 0x10000 int sdhc_mode_sd = 0; /* Variables */ -static char fs[] ATTRIBUTE_ALIGN(32) = "/dev/sdio/sdhc"; +static char fs[] ATTRIBUTE_ALIGN( 32 ) = "/dev/sdio/sdhc"; 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; + s32 ret; - if (sdhc_mode_sd) { - return __io_wiisd.startup(); - } + if ( sdhc_mode_sd ) + { + return __io_wiisd.startup(); + } - /* Already open */ - if (fd >= 0) - return true; + /* Already open */ + if ( fd >= 0 ) + return true; - /* Create heap */ - if (hid < 0) { - hid = iosCreateHeap(SDHC_HEAPSIZE); - if (hid < 0) - goto err; - } + /* Create heap */ + if ( hid < 0 ) + { + hid = iosCreateHeap( SDHC_HEAPSIZE ); + if ( hid < 0 ) + goto err; + } - // allocate buf2 - if (sdhc_buf2 == NULL) { - sdhc_buf2 = SYS_AllocArena2MemLo(SDHC_MEM2_SIZE, 32); - } + // allocate buf2 + if ( sdhc_buf2 == NULL ) + { + sdhc_buf2 = SYS_AllocArena2MemLo( SDHC_MEM2_SIZE, 32 ); + } - /* Open SDHC device */ - fd = IOS_Open(fs, 0); - if (fd < 0) - goto err; + /* Open SDHC device */ + fd = IOS_Open( fs, 0 ); + if ( fd < 0 ) + goto err; - /* Initialize SDHC */ - ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_INIT, ":"); - if (ret) - goto err; + /* Initialize SDHC */ + ret = IOS_IoctlvFormat( hid, fd, IOCTL_SDHC_INIT, ":" ); + if ( ret ) + goto err; - return true; + return true; err: - /* Close SDHC device */ - if (fd >= 0) { - IOS_Close(fd); - fd = -1; - } + /* Close SDHC device */ + if ( fd >= 0 ) + { + IOS_Close( fd ); + fd = -1; + } - return false; + return false; } -bool SDHC_Close(void) +bool SDHC_Close( void ) { - if (sdhc_mode_sd) { - return __io_wiisd.shutdown(); - } + if ( sdhc_mode_sd ) + { + return __io_wiisd.shutdown(); + } - /* Close SDHC device */ - if (fd >= 0) { - IOS_Close(fd); - fd = -1; - } + /* Close SDHC device */ + if ( fd >= 0 ) + { + IOS_Close( fd ); + fd = -1; + } - /*if (hid > 0) { - iosDestroyHeap(hid); - hid = -1; - }*/ + /*if (hid > 0) { + iosDestroyHeap(hid); + hid = -1; + }*/ - return true; + return true; } -bool SDHC_IsInserted(void) +bool SDHC_IsInserted( void ) { - s32 ret; - if (sdhc_mode_sd) { - return __io_wiisd.isInserted(); - } + s32 ret; + if ( sdhc_mode_sd ) + { + return __io_wiisd.isInserted(); + } - /* Check if SD card is inserted */ - ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_ISINSERTED, ":"); + /* Check if SD card is inserted */ + ret = IOS_IoctlvFormat( hid, fd, IOCTL_SDHC_ISINSERTED, ":" ); - return (!ret) ? true : false; + return ( !ret ) ? true : false; } -bool SDHC_ReadSectors(u32 sector, u32 count, void *buffer) +bool SDHC_ReadSectors( u32 sector, u32 count, void *buffer ) { - //printf("SD-R(%u %u)\n", sector, count); - if (sdhc_mode_sd) { - return __io_wiisd.readSectors(sector, count, buffer); - } + //printf("SD-R(%u %u)\n", sector, count); + if ( sdhc_mode_sd ) + { + return __io_wiisd.readSectors( sector, count, buffer ); + } - void *buf = (void *)buffer; - u32 len = (sector_size * count); + void *buf = ( void * )buffer; + u32 len = ( sector_size * count ); - s32 ret; + s32 ret; - /* Device not opened */ - if (fd < 0) - return false; + /* Device not opened */ + if ( fd < 0 ) + return false; - /* Buffer not aligned */ - if ((u32)buffer & 0x1F) { - /* Allocate memory */ - //buf = iosAlloc(hid, len); - buf = sdhc_buf2; - if (!buf) - return false; - } + /* Buffer not aligned */ + if ( ( u32 )buffer & 0x1F ) + { + /* Allocate memory */ + //buf = iosAlloc(hid, len); + buf = sdhc_buf2; + if ( !buf ) + return false; + } - /* Read data */ - ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_READ, "ii:d", sector, count, buf, len); + /* Read data */ + ret = IOS_IoctlvFormat( hid, fd, IOCTL_SDHC_READ, "ii:d", sector, count, buf, len ); - /* Copy data */ - if (buf != buffer) { - memcpy(buffer, buf, len); - //iosFree(hid, buf); - } + /* Copy data */ + if ( buf != buffer ) + { + memcpy( buffer, buf, len ); + //iosFree(hid, buf); + } - return (!ret) ? true : false; + return ( !ret ) ? true : false; } -bool SDHC_WriteSectors(u32 sector, u32 count, void *buffer) +bool SDHC_WriteSectors( u32 sector, u32 count, void *buffer ) { - if (sdhc_mode_sd) { - return __io_wiisd.writeSectors(sector, count, buffer); - } + if ( sdhc_mode_sd ) + { + return __io_wiisd.writeSectors( sector, count, buffer ); + } - void *buf = (void *)buffer; - u32 len = (sector_size * count); + void *buf = ( void * )buffer; + u32 len = ( sector_size * count ); - s32 ret; + s32 ret; - /* Device not opened */ - if (fd < 0) - return false; + /* Device not opened */ + if ( fd < 0 ) + return false; - /* Buffer not aligned */ - if ((u32)buffer & 0x1F) { - /* Allocate memory */ - //buf = iosAlloc(hid, len); - buf = sdhc_buf2; - if (!buf) - return false; + /* Buffer not aligned */ + if ( ( u32 )buffer & 0x1F ) + { + /* Allocate memory */ + //buf = iosAlloc(hid, len); + buf = sdhc_buf2; + if ( !buf ) + return false; - /* Copy data */ - memcpy(buf, buffer, len); - } + /* Copy data */ + memcpy( buf, buffer, len ); + } - /* Read data */ - ret = IOS_IoctlvFormat(hid, fd, IOCTL_SDHC_WRITE, "ii:d", sector, count, buf, len); + /* Read data */ + ret = IOS_IoctlvFormat( hid, fd, IOCTL_SDHC_WRITE, "ii:d", sector, count, buf, len ); - /* Free memory */ - //if (buf != buffer) - // iosFree(hid, buf); + /* Free memory */ + //if (buf != buffer) + // iosFree(hid, buf); - return (!ret) ? true : false; + return ( !ret ) ? true : false; } -bool SDHC_ClearStatus(void) +bool SDHC_ClearStatus( void ) { - return true; + return true; } -bool __io_SDHC_Close(void) +bool __io_SDHC_Close( void ) { - // do nothing. - return true; + // do nothing. + return true; } -bool __io_SDHC_NOP(void) +bool __io_SDHC_NOP( void ) { - // do nothing. - return true; + // 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 = +{ + 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_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 aee41457..34e76ca8 100644 --- a/source/usbloader/sdhc.h +++ b/source/usbloader/sdhc.h @@ -2,18 +2,19 @@ #define _SDHC_H_ /* Constants */ -#define SDHC_SECTOR_SIZE 0x200 +#define SDHC_SECTOR_SIZE 0x200 #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif /* Prototypes */ - 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; + 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 d2b01df3..f0a23dba 100644 --- a/source/usbloader/splits.c +++ b/source/usbloader/splits.c @@ -17,301 +17,339 @@ #define FMT_llu "%llu" #define FMT_lld "%lld" -#define split_error(x) do { printf("\nsplit error: %s\n\n",x); } while(0) +#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) { - strcat(fname, ".tmp"); - } else if (idx > 0) { - char *c = fname + strlen(fname) - 1; - *c = '0' + idx; - } + strcpy( fname, s->fname ); + if ( idx == 0 && s->create_mode ) + { + strcat( fname, ".tmp" ); + } + else if ( idx > 0 ) + { + char *c = fname + strlen( fname ) - 1; + *c = '0' + idx; + } } -int split_open_file(split_info_t *s, int idx) +int split_open_file( split_info_t *s, int idx ) { - int fd = s->fd[idx]; - if (fd>=0) return fd; - char fname[1024]; - split_get_fname(s, idx, fname); - //char *mode = s->create_mode ? "wb+" : "rb+"; - int mode = s->create_mode ? (O_CREAT | O_RDWR) : O_RDWR ; - //printf("SPLIT OPEN %s %s %d\n", fname, mode, idx); //Wpad_WaitButtons(); - //f = fopen(fname, mode); - fd = open(fname, mode); - if (fd<0) return -1; - if (idx > 0 && s->create_mode) { - printf("%s Split: %d %s \n", - s->create_mode ? "Create" : "Read", - idx, fname); - } - s->fd[idx] = fd; - return fd; + int fd = s->fd[idx]; + if ( fd >= 0 ) return fd; + char fname[1024]; + split_get_fname( s, idx, fname ); + //char *mode = s->create_mode ? "wb+" : "rb+"; + int mode = s->create_mode ? ( O_CREAT | O_RDWR ) : O_RDWR ; + //printf("SPLIT OPEN %s %s %d\n", fname, mode, idx); //Wpad_WaitButtons(); + //f = fopen(fname, mode); + fd = open( fname, mode ); + if ( fd < 0 ) return -1; + if ( idx > 0 && s->create_mode ) + { + printf( "%s Split: %d %s \n", + s->create_mode ? "Create" : "Read", + idx, fname ); + } + s->fd[idx] = fd; + return fd; } // faster as it uses larger chunks than ftruncate internally -int write_zero(int fd, off_t size) +int write_zero( int fd, off_t size ) { - int buf[0x4000]; //64kb - int chunk; - int ret; - memset(buf, 0, sizeof(buf)); - while (size) { - chunk = size; - if (chunk > sizeof(buf)) chunk = sizeof(buf); - ret = write(fd, buf, chunk); - //printf("WZ %d %d / %lld \n", ret, chunk, size); - size -= chunk; - if (ret < 0) return ret; - } - return 0; + int buf[0x4000]; //64kb + int chunk; + int ret; + memset( buf, 0, sizeof( buf ) ); + while ( size ) + { + chunk = size; + if ( chunk > sizeof( buf ) ) chunk = sizeof( buf ); + ret = write( fd, buf, chunk ); + //printf("WZ %d %d / %lld \n", ret, chunk, size); + size -= chunk; + if ( ret < 0 ) return ret; + } + return 0; } -int split_fill(split_info_t *s, int idx, u64 size) +int split_fill( split_info_t *s, int idx, u64 size ) { - int fd = split_open_file(s, idx); - off64_t fsize = lseek(fd, 0, SEEK_END); - if (fsize < size) { - //printf("TRUNC %d "FMT_lld"\n", idx, size); Wpad_WaitButtons(); - //ftruncate(fd, size); - write_zero(fd, size - fsize); - return 1; - } - return 0; + int fd = split_open_file( s, idx ); + off64_t fsize = lseek( fd, 0, SEEK_END ); + if ( fsize < size ) + { + //printf("TRUNC %d "FMT_lld"\n", idx, size); Wpad_WaitButtons(); + //ftruncate(fd, size); + write_zero( fd, size - fsize ); + return 1; + } + return 0; } -int split_get_file(split_info_t *s, u32 lba, u32 *sec_count, int fill) +int split_get_file( split_info_t *s, u32 lba, u32 *sec_count, int fill ) { - int fd; - if (lba >= s->total_sec) { - fprintf(stderr, "SPLIT: invalid sector %u / %u\n", lba, (u32)s->total_sec); - return -1; - } - int idx; - idx = lba / s->split_sec; - if (idx >= s->max_split) { - fprintf(stderr, "SPLIT: invalid split %d / %d\n", idx, s->max_split - 1); - return -1; - } - fd = s->fd[idx]; - if (fd<0) { - // opening new, make sure all previous are full - int i; - for (i=0; isplit_size)) { - printf("FILL %d\n", i); - } - } - fd = split_open_file(s, idx); - } - if (fd<0) { - fprintf(stderr, "SPLIT %d: no file\n", idx); - return -1; - } - u32 sec = lba % s->split_sec; // inside file - off64_t off = (off64_t)sec * 512; - // num sectors till end of file - u32 to_end = s->split_sec - sec; - if (*sec_count > to_end) *sec_count = to_end; - if (s->create_mode) { - if (fill) { - // extend, so that read will be succesfull - split_fill(s, idx, off + 512 * (*sec_count)); - } else { - // fill up so that write continues from end of file - // shouldn't be necessary, but libfat looks buggy - // and this is faster - split_fill(s, idx, off); - } - } - lseek(fd, off, SEEK_SET); - return fd; + int fd; + if ( lba >= s->total_sec ) + { + fprintf( stderr, "SPLIT: invalid sector %u / %u\n", lba, ( u32 )s->total_sec ); + return -1; + } + int idx; + idx = lba / s->split_sec; + if ( idx >= s->max_split ) + { + fprintf( stderr, "SPLIT: invalid split %d / %d\n", idx, s->max_split - 1 ); + return -1; + } + fd = s->fd[idx]; + if ( fd < 0 ) + { + // opening new, make sure all previous are full + int i; + for ( i = 0; i < idx; i++ ) + { + if ( split_fill( s, i, s->split_size ) ) + { + printf( "FILL %d\n", i ); + } + } + fd = split_open_file( s, idx ); + } + if ( fd < 0 ) + { + fprintf( stderr, "SPLIT %d: no file\n", idx ); + return -1; + } + u32 sec = lba % s->split_sec; // inside file + off64_t off = ( off64_t )sec * 512; + // num sectors till end of file + u32 to_end = s->split_sec - sec; + if ( *sec_count > to_end ) *sec_count = to_end; + if ( s->create_mode ) + { + if ( fill ) + { + // extend, so that read will be succesfull + split_fill( s, idx, off + 512 * ( *sec_count ) ); + } + else + { + // fill up so that write continues from end of file + // shouldn't be necessary, but libfat looks buggy + // and this is faster + split_fill( s, idx, off ); + } + } + lseek( fd, off, SEEK_SET ); + return fd; } -int split_read_sector(void *_fp,u32 lba,u32 count,void*buf) +int split_read_sector( void *_fp, u32 lba, u32 count, void*buf ) { - split_info_t *s = _fp; - int fd; - u64 off = lba; - off *= 512ULL; - int i; - u32 chunk; - size_t ret; - //fprintf(stderr,"READ %d %d\n", lba, count); - for (i=0; i<(int)count; i+=chunk) { - chunk = count - i; - fd = split_get_file(s, lba+i, &chunk, 1); - if (fd<0) { - fprintf(stderr,"\n\n"FMT_lld" %d %p\n",off,count,_fp); - split_error("error seeking in disc partition"); - return 1; - } - 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); - split_error("error reading disc"); - return 1; - } - } - return 0; + split_info_t *s = _fp; + int fd; + u64 off = lba; + off *= 512ULL; + int i; + u32 chunk; + size_t ret; + //fprintf(stderr,"READ %d %d\n", lba, count); + for ( i = 0; i < ( int )count; i += chunk ) + { + chunk = count - i; + fd = split_get_file( s, lba + i, &chunk, 1 ); + if ( fd < 0 ) + { + fprintf( stderr, "\n\n"FMT_lld" %d %p\n", off, count, _fp ); + split_error( "error seeking in disc partition" ); + return 1; + } + 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 ); + split_error( "error reading disc" ); + return 1; + } + } + 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; - u64 off = lba; - off*=512ULL; - int i; - u32 chunk; - size_t ret; - //printf("WRITE %d %d %p \n", lba, count, buf); - for (i=0; i<(int)count; i+=chunk) { - chunk = count - i; - fd = split_get_file(s, lba+i, &chunk, 0); - //if (chunk != count) - // fprintf(stderr, "WRITE CHUNK %d %d/%d\n", lba+i, chunk, count); - if (fd<0 || !chunk) { - fprintf(stderr,"\n\n"FMT_lld" %d %p\n",off,count,_fp); - split_error("error seeking in disc partition"); - return 1; - } - //if (fwrite(buf+i*512, 512ULL, chunk, f) != chunk) { - //printf("write %d %p %d \n", fd, buf+i*512, chunk * 512); - void *ptr = ((u8 *)buf) + (i*512); - ret = write(fd, ptr, chunk * 512); - //printf("write ret = %d \n", ret); - if (ret != chunk * 512) { - split_error("error writing disc"); - return 1; - } - } - return 0; + split_info_t *s = _fp; + int fd; + u64 off = lba; + off *= 512ULL; + int i; + u32 chunk; + size_t ret; + //printf("WRITE %d %d %p \n", lba, count, buf); + for ( i = 0; i < ( int )count; i += chunk ) + { + chunk = count - i; + fd = split_get_file( s, lba + i, &chunk, 0 ); + //if (chunk != count) + // fprintf(stderr, "WRITE CHUNK %d %d/%d\n", lba+i, chunk, count); + if ( fd < 0 || !chunk ) + { + fprintf( stderr, "\n\n"FMT_lld" %d %p\n", off, count, _fp ); + split_error( "error seeking in disc partition" ); + return 1; + } + //if (fwrite(buf+i*512, 512ULL, chunk, f) != chunk) { + //printf("write %d %p %d \n", fd, buf+i*512, chunk * 512); + void *ptr = ( ( u8 * )buf ) + ( i * 512 ); + ret = write( fd, ptr, chunk * 512 ); + //printf("write ret = %d \n", ret); + if ( ret != chunk * 512 ) + { + split_error( "error writing disc" ); + return 1; + } + } + return 0; } -void split_init(split_info_t *s, char *fname) +void split_init( split_info_t *s, char *fname ) { - int i; - char *p; - //fprintf(stderr, "SPLIT_INIT %s\n", fname); - memset(s, 0, sizeof(*s)); - for (i=0; ifd[i] = -1; - } - strcpy(s->fname, fname); - s->max_split = 1; - p = strrchr(fname, '.'); - if (p && (strcasecmp(p, ".wbfs") == 0)) { - s->max_split = MAX_SPLIT; - } + int i; + char *p; + //fprintf(stderr, "SPLIT_INIT %s\n", fname); + memset( s, 0, sizeof( *s ) ); + for ( i = 0; i < MAX_SPLIT; i++ ) + { + s->fd[i] = -1; + } + strcpy( s->fname, fname ); + s->max_split = 1; + p = strrchr( fname, '.' ); + if ( p && ( strcasecmp( p, ".wbfs" ) == 0 ) ) + { + s->max_split = MAX_SPLIT; + } } -void split_set_size(split_info_t *s, u64 split_size, u64 total_size) +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_size = total_size; + s->split_size = split_size; + s->total_sec = total_size / 512; + s->split_sec = split_size / 512; } -void split_close(split_info_t *s) +void split_close( split_info_t *s ) { - int i; - char fname[1024]; - char tmpname[1024]; - for (i=0; imax_split; i++) { - if (s->fd[i] >= 0) { - close(s->fd[i]); - } - } - if (s->create_mode) { - split_get_fname(s, -1, fname); - split_get_fname(s, 0, tmpname); - rename(tmpname, fname); - } - memset(s, 0, sizeof(*s)); + int i; + char fname[1024]; + char tmpname[1024]; + for ( i = 0; i < s->max_split; i++ ) + { + if ( s->fd[i] >= 0 ) + { + close( s->fd[i] ); + } + } + if ( s->create_mode ) + { + split_get_fname( s, -1, fname ); + split_get_fname( s, 0, tmpname ); + rename( tmpname, fname ); + } + memset( s, 0, sizeof( *s ) ); } -int split_create(split_info_t *s, char *fname, - u64 split_size, u64 total_size, bool overwrite) +int split_create( split_info_t *s, char *fname, + u64 split_size, u64 total_size, bool overwrite ) { - int i; - int fd; - char sname[1024]; - int error = 0; - split_init(s, fname); - s->create_mode = 1; - // check if any file already exists - for (i=-1; imax_split; i++) { - split_get_fname(s, i, sname); - if (overwrite) { - remove(sname); - } else { - fd = open(sname, O_RDONLY); - if (fd >= 0) { - fprintf(stderr, "Error: file already exists: %s\n", sname); - close(fd); - error = 1; - } - } - } - if (error) { - split_init(s, ""); - return -1; - } - split_set_size(s, split_size, total_size); - return 0; + int i; + int fd; + char sname[1024]; + int error = 0; + split_init( s, fname ); + s->create_mode = 1; + // check if any file already exists + for ( i = -1; i < s->max_split; i++ ) + { + split_get_fname( s, i, sname ); + if ( overwrite ) + { + remove( sname ); + } + else + { + fd = open( sname, O_RDONLY ); + if ( fd >= 0 ) + { + fprintf( stderr, "Error: file already exists: %s\n", sname ); + close( fd ); + error = 1; + } + } + } + if ( error ) + { + split_init( s, "" ); + return -1; + } + split_set_size( s, split_size, total_size ); + return 0; } -int split_open(split_info_t *s, char *fname) +int split_open( split_info_t *s, char *fname ) { - int i; - u64 size = 0; - u64 total_size = 0; - u64 split_size = 0; - int fd; - split_init(s, fname); - for (i=0; imax_split; i++) { - fd = split_open_file(s, i); - if (fd<0) { - if (i==0) goto err; - break; - } - // check previous size - all splits except last must be same size - if (i > 0 && size != split_size) { - fprintf(stderr, "split %d: invalid size "FMT_lld"", i, size); - goto err; - } - // get size - //fseeko(f, 0, SEEK_END); - //size = ftello(f); - size = lseek(fd, 0, SEEK_END); - // check sector alignment - if (size % 512) { - fprintf(stderr, "split %d: size ("FMT_lld") not sector (512) aligned!", - i, size); - } - // first sets split size - if (i==0) { - split_size = size; - } - total_size += size; - } - split_set_size(s, split_size, total_size); - return 0; + int 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++ ) + { + fd = split_open_file( s, i ); + if ( fd < 0 ) + { + if ( i == 0 ) goto err; + break; + } + // check previous size - all splits except last must be same size + if ( i > 0 && size != split_size ) + { + fprintf( stderr, "split %d: invalid size "FMT_lld"", i, size ); + goto err; + } + // get size + //fseeko(f, 0, SEEK_END); + //size = ftello(f); + size = lseek( fd, 0, SEEK_END ); + // check sector alignment + if ( size % 512 ) + { + fprintf( stderr, "split %d: size ("FMT_lld") not sector (512) aligned!", + i, size ); + } + // first sets split size + if ( i == 0 ) + { + split_size = size; + } + total_size += size; + } + split_set_size( s, split_size, total_size ); + return 0; err: - split_close(s); - return -1; + split_close( s ); + return -1; } diff --git a/source/usbloader/splits.h b/source/usbloader/splits.h index 54e814ff..8055a999 100644 --- a/source/usbloader/splits.h +++ b/source/usbloader/splits.h @@ -2,41 +2,42 @@ #define _SPLITS_H #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #define MAX_SPLIT 10 -typedef struct split_info -{ - char fname[1024]; - //FILE *f[MAX_SPLIT]; - int fd[MAX_SPLIT]; - //u64 fsize[MAX_SPLIT]; - u32 split_sec; - u32 total_sec; - u64 split_size; - u64 total_size; - int create_mode; - int max_split; -} split_info_t; + typedef struct split_info + { + char fname[1024]; + //FILE *f[MAX_SPLIT]; + int fd[MAX_SPLIT]; + //u64 fsize[MAX_SPLIT]; + u32 split_sec; + u32 total_sec; + u64 split_size; + u64 total_size; + int create_mode; + int max_split; + } split_info_t; // 1 sector less than 4gb -extern u64 OPT_split_size; + extern u64 OPT_split_size; -void split_get_fname(split_info_t *s, int idx, char *fname); + 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); + 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 989d9c5a..b070ff54 100644 --- a/source/usbloader/usbstorage2.c +++ b/source/usbloader/usbstorage2.c @@ -13,15 +13,15 @@ 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 +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 +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 +3. This notice may not be removed or altered from any source distribution. -------------------------------------------------------------*/ @@ -33,397 +33,409 @@ distribution. #include "usbstorage2.h" /* IOCTL commands */ -#define UMS_BASE (('U'<<24)|('M'<<16)|('S'<<8)) -#define USB_IOCTL_UMS_INIT (UMS_BASE+0x1) +#define UMS_BASE (('U'<<24)|('M'<<16)|('S'<<8)) +#define USB_IOCTL_UMS_INIT (UMS_BASE+0x1) #define USB_IOCTL_UMS_GET_CAPACITY (UMS_BASE+0x2) #define USB_IOCTL_UMS_READ_SECTORS (UMS_BASE+0x3) -#define USB_IOCTL_UMS_WRITE_SECTORS (UMS_BASE+0x4) -#define USB_IOCTL_UMS_READ_STRESS (UMS_BASE+0x5) -#define USB_IOCTL_UMS_SET_VERBOSE (UMS_BASE+0x6) -#define USB_IOCTL_UMS_UMOUNT (UMS_BASE+0x10) -#define USB_IOCTL_UMS_WATCHDOG (UMS_BASE+0x80) +#define USB_IOCTL_UMS_WRITE_SECTORS (UMS_BASE+0x4) +#define USB_IOCTL_UMS_READ_STRESS (UMS_BASE+0x5) +#define USB_IOCTL_UMS_SET_VERBOSE (UMS_BASE+0x6) +#define USB_IOCTL_UMS_UMOUNT (UMS_BASE+0x10) +#define USB_IOCTL_UMS_WATCHDOG (UMS_BASE+0x80) -#define USB_IOCTL_UMS_TESTMODE (UMS_BASE+0x81) +#define USB_IOCTL_UMS_TESTMODE (UMS_BASE+0x81) #define WBFS_BASE (('W'<<24)|('F'<<16)|('S'<<8)) -#define USB_IOCTL_WBFS_OPEN_DISC (WBFS_BASE+0x1) -#define USB_IOCTL_WBFS_READ_DISC (WBFS_BASE+0x2) -#define USB_IOCTL_WBFS_READ_DIRECT_DISC (WBFS_BASE+0x3) -#define USB_IOCTL_WBFS_STS_DISC (WBFS_BASE+0x4) -#define USB_IOCTL_WBFS_SET_DEVICE (WBFS_BASE+0x50) +#define USB_IOCTL_WBFS_OPEN_DISC (WBFS_BASE+0x1) +#define USB_IOCTL_WBFS_READ_DISC (WBFS_BASE+0x2) +#define USB_IOCTL_WBFS_READ_DIRECT_DISC (WBFS_BASE+0x3) +#define USB_IOCTL_WBFS_STS_DISC (WBFS_BASE+0x4) +#define USB_IOCTL_WBFS_SET_DEVICE (WBFS_BASE+0x50) #define USB_IOCTL_WBFS_SET_FRAGLIST (WBFS_BASE+0x51) -#define UMS_HEAPSIZE 0x1000 //0x10000 +#define UMS_HEAPSIZE 0x1000 //0x10000 /* Variables */ -static char fs[] ATTRIBUTE_ALIGN(32) = "/dev/usb2"; -static char fs2[] ATTRIBUTE_ALIGN(32) = "/dev/usb/ehc"; +static char fs[] ATTRIBUTE_ALIGN( 32 ) = "/dev/usb2"; +static char fs2[] ATTRIBUTE_ALIGN( 32 ) = "/dev/usb/ehc"; -static char fsoff[] ATTRIBUTE_ALIGN(32) = "/dev/usb2/OFF"; +static char fsoff[] ATTRIBUTE_ALIGN( 32 ) = "/dev/usb2/OFF"; static s32 hid = -1, fd = -1; static u32 sector_size; -static int mounted=0; +static int mounted = 0; -s32 USBStorage2_Umount(void) +s32 USBStorage2_Umount( void ) { - if (fd >= 0 && mounted) { - s32 ret; + 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; - } + return ret; + } - return IPC_ENOENT; + return IPC_ENOENT; } -s32 USBStorage2_Watchdog(u32 on_off) +s32 USBStorage2_Watchdog( u32 on_off ) { - if (fd >= 0) { - s32 ret; + 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; - } + return ret; + } - return IPC_ENOENT; + return IPC_ENOENT; } -s32 USBStorage2_TestMode(u32 on_off) +s32 USBStorage2_TestMode( u32 on_off ) { - if (fd >= 0) { - s32 ret; + 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; - } + return ret; + } - return IPC_ENOENT; + 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) { - s32 ret; + 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; - } + return ret; + } - return IPC_ENOENT; + return IPC_ENOENT; } -s32 USBStorage2_EHC_Off(void) +s32 USBStorage2_EHC_Off( void ) { - USBStorage2_Deinit(); - fd=IOS_Open(fsoff, 0); - USBStorage2_Deinit(); - return 0; + USBStorage2_Deinit(); + 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; + s32 ret, ret2; + static u32 sector_size = 0; - /* Already open */ - if (fd >= 0) - return 0; + /* Already open */ + if ( fd >= 0 ) + return 0; - /* Create heap */ - if (hid < 0) { - hid = iosCreateHeap(UMS_HEAPSIZE); - if (hid < 0) - return IPC_ENOMEM; - } + /* Create heap */ + if ( hid < 0 ) + { + 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); + /* Open USB device */ + 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; - ret2=ret; + /* Initialize USB storage */ + 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=-1; - goto err; - } - 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 - { - ret=-20002; - goto err; - } - mounted=1; - return ret2; // 0->HDD, 1->DVD + /* Get device capacity */ + ret = USBStorage2_GetCapacity( §or_size ); + if ( !ret ) + { + ret = -1; + goto err; + } + 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 + { + ret = -20002; + goto err; + } + mounted = 1; + return ret2; // 0->HDD, 1->DVD err: - /* Close USB device */ - if (fd >= 0) { - IOS_Close(fd); - fd = -1; - } + /* Close USB device */ + if ( fd >= 0 ) + { + IOS_Close( fd ); + fd = -1; + } - return ret; + return ret; } -void USBStorage2_Deinit(void) +void USBStorage2_Deinit( void ) { -mounted = 0; + mounted = 0; - /* Close USB device */ - if (fd >= 0) { - IOS_Close(fd); - fd = -1; - } + /* Close USB device */ + if ( fd >= 0 ) + { + 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; +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; + s32 ret; - /* Device not opened */ - if (fd < 0) - return fd; - if(!mem2_ptr) mem2_ptr=SYS_AllocArena2MemLo(2048*256,32); - /* MEM1 buffer */ - if (!__USBStorage2_isMEM2Buffer(buffer)) { - /* Allocate memory */ - buf = mem2_ptr; //iosAlloc(hid, len); - if (!buf) - return IPC_ENOMEM; - } + /* Device not opened */ + if ( fd < 0 ) + return fd; + if ( !mem2_ptr ) mem2_ptr = SYS_AllocArena2MemLo( 2048 * 256, 32 ); + /* MEM1 buffer */ + if ( !__USBStorage2_isMEM2Buffer( buffer ) ) + { + /* Allocate memory */ + buf = mem2_ptr; //iosAlloc(hid, len); + if ( !buf ) + return IPC_ENOMEM; + } - /* Read data */ - ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_UMS_READ_SECTORS, "ii:d", sector, numSectors, buf, len); + /* Read data */ + ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_UMS_READ_SECTORS, "ii:d", sector, numSectors, buf, len ); - /* Copy data */ - if (buf != buffer) { - memcpy(buffer, buf, len); - //iosFree(hid, buf); - } + /* Copy data */ + if ( buf != buffer ) + { + memcpy( buffer, buf, len ); + //iosFree(hid, buf); + } - return ret; + 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; + s32 ret; - /* Device not opened */ - if (fd < 0) - return fd; - if(!mem2_ptr) mem2_ptr=SYS_AllocArena2MemLo(2048*256,32); + /* Device not opened */ + if ( fd < 0 ) + return fd; + if ( !mem2_ptr ) mem2_ptr = SYS_AllocArena2MemLo( 2048 * 256, 32 ); - /* MEM1 buffer */ - if (!__USBStorage2_isMEM2Buffer(buffer)) { - /* Allocate memory */ - buf = mem2_ptr; //buf = iosAlloc(hid, len); - if (!buf) - return IPC_ENOMEM; + /* MEM1 buffer */ + if ( !__USBStorage2_isMEM2Buffer( buffer ) ) + { + /* Allocate memory */ + buf = mem2_ptr; //buf = iosAlloc(hid, len); + if ( !buf ) + return IPC_ENOMEM; - /* Copy data */ - memcpy(buf, buffer, len); - } + /* Copy data */ + memcpy( buf, buffer, len ); + } - /* Write data */ - ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_UMS_WRITE_SECTORS, "ii:d", sector, numSectors, buf, len); + /* Write data */ + ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_UMS_WRITE_SECTORS, "ii:d", sector, numSectors, buf, len ); - /* Free memory */ - if (buf != buffer) - iosFree(hid, buf); + /* Free memory */ + if ( buf != buffer ) + iosFree( hid, buf ); - return ret; + return ret; } -static bool __usbstorage_Startup(void) +static bool __usbstorage_Startup( void ) { - return USBStorage2_Init()==0; + 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; + s32 retval; - retval = USBStorage2_ReadSectors( sector, numSectors, buffer); + retval = USBStorage2_ReadSectors( sector, numSectors, buffer ); - if(retval < 0) - return false; - return true; + 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; + 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; + return true; } -static bool __usbstorage_ClearStatus(void) +static bool __usbstorage_ClearStatus( void ) { - return true; + return true; } -static bool __usbstorage_Shutdown(void) +static bool __usbstorage_Shutdown( void ) { - //if(mounted) USBStorage2_Umount(); - USBStorage2_Deinit(); + //if(mounted) USBStorage2_Umount(); + USBStorage2_Deinit(); - mounted = 0; - return true; + mounted = 0; + 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); - return ret > 0; + 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); - return ret > 0; + 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; + // 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; + s32 ret; - /* Device not opened */ - if (fd < 0) - return fd; + /* Device not opened */ + if ( fd < 0 ) + return fd; - extern u32 wbfs_part_lba; - u32 part = wbfs_part_lba; + extern u32 wbfs_part_lba; + u32 part = wbfs_part_lba; - /* Read data */ - ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_OPEN_DISC, "dd:", buffer, len, &part, 4); + /* Read data */ + ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_WBFS_OPEN_DISC, "dd:", buffer, len, &part, 4 ); - return ret; + return ret; } // woffset is in 32bit words, len is in bytes -s32 USBStorage_WBFS_Read(u32 woffset, u32 len, void *buffer) +s32 USBStorage_WBFS_Read( u32 woffset, u32 len, void *buffer ) { - s32 ret; + s32 ret; - USBStorage2_Init(); - /* Device not opened */ - if (fd < 0) - return fd; + USBStorage2_Init(); + /* Device not opened */ + if ( fd < 0 ) + return fd; - /* Read data */ - ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_READ_DISC, "ii:d", woffset, len, buffer, len); + /* Read data */ + ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_WBFS_READ_DISC, "ii:d", woffset, len, buffer, len ); - return ret; + return ret; } -s32 USBStorage_WBFS_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; - // ioctl - ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_SET_DEVICE, "i:i", dev, &retval); - if (retval) return retval; - return ret; + s32 ret; + static s32 retval = 0; + retval = 0; + USBStorage2_Init(); + // Device not opened + if ( fd < 0 ) return fd; + // ioctl + ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_WBFS_SET_DEVICE, "i:i", dev, &retval ); + if ( retval ) return retval; + return ret; } -s32 USBStorage_WBFS_SetFragList(void *p, int size) +s32 USBStorage_WBFS_SetFragList( void *p, int size ) { - s32 ret; - USBStorage2_Init(); - // Device not opened - if (fd < 0) return fd; - // ioctl - ret = IOS_IoctlvFormat(hid, fd, USB_IOCTL_WBFS_SET_FRAGLIST, "d:", p, size); - return ret; + s32 ret; + USBStorage2_Init(); + // Device not opened + if ( fd < 0 ) return fd; + // ioctl + ret = IOS_IoctlvFormat( hid, fd, USB_IOCTL_WBFS_SET_FRAGLIST, "d:", p, size ); + return ret; } diff --git a/source/usbloader/usbstorage2.h b/source/usbloader/usbstorage2.h index a4d81421..94c998a9 100644 --- a/source/usbloader/usbstorage2.h +++ b/source/usbloader/usbstorage2.h @@ -4,31 +4,32 @@ #include "ogc/disc_io.h" #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -/* Prototypes */ -s32 USBStorage2_GetCapacity(u32 *); -s32 USBStorage2_Init(void); -void USBStorage2_Deinit(void); -s32 USBStorage2_Umount(void); + /* Prototypes */ + 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') -extern const DISC_INTERFACE __io_usbstorage2; + extern const DISC_INTERFACE __io_usbstorage2; #ifdef __cplusplus } diff --git a/source/usbloader/utils.c b/source/usbloader/utils.c index 5e28c2f2..4ae4dd61 100644 --- a/source/usbloader/utils.c +++ b/source/usbloader/utils.c @@ -2,6 +2,7 @@ #include -u32 swap32(u32 x) { - return (x >> 24) | ((x << 8) & 0x00FF0000UL) | ((x >> 8) & 0x0000FF00UL) | (x << 24); +u32 swap32( u32 x ) +{ + return ( x >> 24 ) | ( ( x << 8 ) & 0x00FF0000UL ) | ( ( x >> 8 ) & 0x0000FF00UL ) | ( x << 24 ); } diff --git a/source/usbloader/utils.h b/source/usbloader/utils.h index 95e6254d..f617f55d 100644 --- a/source/usbloader/utils.h +++ b/source/usbloader/utils.h @@ -2,21 +2,22 @@ #define _UTILS_H_ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -/* Constants */ -#define KB_SIZE 1024.0 -#define MB_SIZE 1048576.0 -#define GB_SIZE 1073741824.0 + /* Constants */ +#define KB_SIZE 1024.0 +#define MB_SIZE 1048576.0 +#define GB_SIZE 1073741824.0 -/* Macros */ -#define round_up(x,n) (-(-(x) & -(n))) + /* Macros */ +#define round_up(x,n) (-(-(x) & -(n))) #define SAFE_FREE(P) if(P){free(P);P=NULL;} -/* Prototypes */ -u32 swap32(u32); + /* Prototypes */ + u32 swap32( u32 ); #ifdef __cplusplus } diff --git a/source/usbloader/wbfs.cpp b/source/usbloader/wbfs.cpp index 29dc803b..65ca535d 100644 --- a/source/usbloader/wbfs.cpp +++ b/source/usbloader/wbfs.cpp @@ -26,266 +26,305 @@ int wbfs_part_fs = PART_FS_WBFS; u32 wbfs_part_idx = 0; u32 wbfs_part_lba = 0; -wbfs_disc_t* WBFS_OpenDisc(u8 *discid) { - return current->OpenDisc(discid); +wbfs_disc_t* WBFS_OpenDisc( u8 *discid ) +{ + return current->OpenDisc( discid ); } -void WBFS_CloseDisc(wbfs_disc_t *disc) { - current->CloseDisc(disc); +void WBFS_CloseDisc( wbfs_disc_t *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) { - WBFS_Close(); +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; + wbfs_part_fs = wbfs_part_idx = wbfs_part_lba = 0; + wbfs_part_idx = 1; - return current->Open(); + 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(); + // close + WBFS_Close(); - if (part_fs == PART_FS_FAT) { - current = new Wbfs_Fat(wbfsDev, part_lba, part_size); - strcpy(wbfs_fs_drive, "USB:"); + if ( part_fs == PART_FS_FAT ) + { + 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) { - current = new Wbfs_Ntfs(wbfsDev, part_lba, part_size); - strcpy(wbfs_fs_drive, "NTFS:"); + } + else if ( part_fs == PART_FS_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); + } + else + { + 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()) - { - delete current; - current = NULL; - return -1; - } + } + if ( current->Open() ) + { + delete current; + current = NULL; + return -1; + } - // success - wbfs_part_fs = part_fs; - wbfs_part_idx = part_idx; - wbfs_part_lba = part_lba; + // success + wbfs_part_fs = part_fs; + wbfs_part_idx = part_idx; + wbfs_part_lba = part_lba; - 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); - return 0; + 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 ); + return 0; } -s32 WBFS_OpenNamed(char *partition) +s32 WBFS_OpenNamed( char *partition ) { - u32 i; - u32 part_fs = PART_FS_WBFS; - u32 part_idx = 0; - u32 part_lba = 0; - s32 ret = 0; - PartList plist; + u32 i; + u32 part_fs = PART_FS_WBFS; + u32 part_idx = 0; + u32 part_lba = 0; + s32 ret = 0; + PartList plist; - // close - WBFS_Close(); + // close + WBFS_Close(); - // parse partition option - if (strncasecmp(partition, "WBFS", 4) == 0) { - i = atoi(partition+4); - if (i < 1 || i > 4) goto err; - part_fs = PART_FS_WBFS; - part_idx = i; - } else if (strncasecmp(partition, "FAT", 3) == 0) { - if (wbfsDev != WBFS_DEVICE_USB) goto err; - i = atoi(partition+3); - if (i < 1 || i > 9) goto err; - part_fs = PART_FS_FAT; - part_idx = i; - } else if (strncasecmp(partition, "NTFS", 4) == 0) { - i = atoi(partition+4); - if (i < 1 || i > 9) goto err; - part_fs = PART_FS_NTFS; - part_idx = i; - } else { - goto err; - } + // parse partition option + if ( strncasecmp( partition, "WBFS", 4 ) == 0 ) + { + i = atoi( partition + 4 ); + if ( i < 1 || i > 4 ) goto err; + part_fs = PART_FS_WBFS; + part_idx = i; + } + else if ( strncasecmp( partition, "FAT", 3 ) == 0 ) + { + if ( wbfsDev != WBFS_DEVICE_USB ) goto err; + i = atoi( partition + 3 ); + if ( i < 1 || i > 9 ) goto err; + part_fs = PART_FS_FAT; + part_idx = i; + } + else if ( strncasecmp( partition, "NTFS", 4 ) == 0 ) + { + i = atoi( partition + 4 ); + if ( i < 1 || i > 9 ) goto err; + part_fs = PART_FS_NTFS; + part_idx = i; + } + else + { + goto err; + } - // Get partition entries - ret = Partition_GetList(wbfsDev, &plist); - if (ret || plist.num == 0) return -1; + // Get partition entries + ret = Partition_GetList( wbfsDev, &plist ); + if ( ret || plist.num == 0 ) return -1; - if (part_fs == PART_FS_WBFS) { - if (part_idx > plist.wbfs_n) goto err; - for (i=0; i plist.fat_n) goto err; - for (i=0; i plist.ntfs_n) goto err; - for (i=0; i= plist.num) goto err; - // set partition lba sector - part_lba = plist.pentry[i].sector; + if ( part_fs == PART_FS_WBFS ) + { + if ( part_idx > plist.wbfs_n ) goto err; + for ( i = 0; i < plist.num; i++ ) + { + if ( plist.pinfo[i].wbfs_i == part_idx ) break; + } + } + else if ( part_fs == PART_FS_FAT ) + { + if ( part_idx > plist.fat_n ) goto err; + for ( i = 0; i < plist.num; i++ ) + { + if ( plist.pinfo[i].fat_i == part_idx ) break; + } + } + else if ( part_fs == PART_FS_NTFS ) + { + 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 ( i >= plist.num ) goto err; + // set partition lba sector + part_lba = plist.pentry[i].sector; - if (WBFS_OpenPart(part_fs, part_idx, part_lba, plist.pentry[i].size, partition)) { - goto err; - } - // success - return 0; + if ( WBFS_OpenPart( part_fs, part_idx, part_lba, plist.pentry[i].size, partition ) ) + { + goto err; + } + // success + return 0; err: - return -1; + return -1; } -s32 WBFS_OpenLBA(u32 lba, u32 size) +s32 WBFS_OpenLBA( u32 lba, u32 size ) { - Wbfs *part = new Wbfs_Wbfs(wbfsDev, lba, size); - if (part->Open() != 0) - { - delete part; - return -1; - } + Wbfs *part = new Wbfs_Wbfs( wbfsDev, lba, size ); + if ( part->Open() != 0 ) + { + delete part; + return -1; + } - WBFS_Close(); - current = part; - return 0; + WBFS_Close(); + current = part; + return 0; } -bool WBFS_Close(void) +bool WBFS_Close( void ) { - if (current != NULL) { - current->Close(); - delete current; - current = NULL; - } + if ( current != NULL ) + { + current->Close(); + delete current; + current = NULL; + } - wbfs_part_fs = 0; - wbfs_part_idx = 0; - wbfs_part_lba = 0; - wbfs_fs_drive[0] = '\0'; + wbfs_part_fs = 0; + wbfs_part_idx = 0; + wbfs_part_lba = 0; + wbfs_fs_drive[0] = '\0'; - gameList.clear(); + gameList.clear(); return 0; } bool WBFS_Mounted() { - return (current != NULL && current->Mounted()); + return ( current != NULL && current->Mounted() ); } -s32 WBFS_Format(u32 lba, u32 size) { - return current->Format(); +s32 WBFS_Format( u32 lba, u32 size ) +{ + return current->Format(); } -s32 WBFS_GetCount(u32 *count) { - return current->GetCount(count); +s32 WBFS_GetCount( u32 *count ) +{ + return current->GetCount( count ); } -s32 WBFS_GetHeaders(struct discHdr *outbuf, u32 cnt, u32 len) { - return current->GetHeaders(outbuf, cnt, len); +s32 WBFS_GetHeaders( struct discHdr *outbuf, u32 cnt, u32 len ) +{ + return current->GetHeaders( outbuf, cnt, len ); } -s32 WBFS_CheckGame(u8 *discid) { - return current->CheckGame(discid); +s32 WBFS_CheckGame( u8 *discid ) +{ + return current->CheckGame( discid ); } -s32 WBFS_AddGame(void) { - s32 retval = current->AddGame(); - if (retval == 0) - gameList.clear(); +s32 WBFS_AddGame( void ) +{ + s32 retval = current->AddGame(); + if ( retval == 0 ) + gameList.clear(); - return retval; + return retval; } -s32 WBFS_RemoveGame(u8 *discid) { - s32 retval = current->RemoveGame(discid); - if (retval == 0) - gameList.clear(); +s32 WBFS_RemoveGame( u8 *discid ) +{ + s32 retval = current->RemoveGame( discid ); + if ( retval == 0 ) + gameList.clear(); - return retval; + return retval; } -s32 WBFS_GameSize(u8 *discid, f32 *size) { - return current->GameSize(discid, size); +s32 WBFS_GameSize( u8 *discid, f32 *size ) +{ + return current->GameSize( discid, size ); } -s32 WBFS_DiskSpace(f32 *used, f32 *free) { - return current->DiskSpace(used, free); +s32 WBFS_DiskSpace( f32 *used, f32 *free ) +{ + return current->DiskSpace( used, free ); } -s32 WBFS_RenameGame(u8 *discid, const void *newname) { - s32 retval = current->RenameGame(discid, newname); - if (retval == 0) - gameList.clear(); +s32 WBFS_RenameGame( u8 *discid, const void *newname ) +{ + s32 retval = current->RenameGame( discid, newname ); + if ( retval == 0 ) + gameList.clear(); - return retval; + return retval; } -s32 WBFS_ReIDGame(u8 *discid, const void *newID) { - s32 retval = current->ReIDGame(discid, newID); - if (retval == 0) - gameList.clear(); +s32 WBFS_ReIDGame( u8 *discid, const void *newID ) +{ + s32 retval = current->ReIDGame( discid, newID ); + if ( retval == 0 ) + gameList.clear(); - return retval; + return retval; } -f32 WBFS_EstimeGameSize(void) { - return current->EstimateGameSize(); +f32 WBFS_EstimeGameSize( void ) +{ + return current->EstimateGameSize(); } -int WBFS_GetFragList(u8 *id) { - return current->GetFragList(id); +int WBFS_GetFragList( u8 *id ) +{ + return current->GetFragList( id ); } -bool WBFS_ShowFreeSpace(void) { - return current->ShowFreeSpace(); +bool WBFS_ShowFreeSpace( void ) +{ + return current->ShowFreeSpace(); } int MountWBFS() { int ret = -1; - time_t currTime = time(0); + time_t currTime = time( 0 ); - while(time(0)-currTime < 15) + while ( time( 0 ) - currTime < 15 ) { USBDevice_deInit(); USBStorage2_Deinit(); USBDevice_Init(); - ret = WBFS_Init(WBFS_DEVICE_USB); - printf("%i...", int(time(0)-currTime)); - if(ret < 0) - sleep(1); + 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 9e19df4a..b90ec426 100644 --- a/source/usbloader/wbfs.h +++ b/source/usbloader/wbfs.h @@ -5,55 +5,56 @@ #include "usbloader/disc.h" #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif - #define PART_FS_WBFS 0 - #define PART_FS_FAT 1 - #define PART_FS_NTFS 2 +#define PART_FS_WBFS 0 +#define PART_FS_FAT 1 +#define PART_FS_NTFS 2 /* Macros */ - #define WBFS_MIN_DEVICE 1 - #define WBFS_MAX_DEVICE 2 +#define WBFS_MIN_DEVICE 1 +#define WBFS_MAX_DEVICE 2 - extern s32 wbfsDev; - extern int wbfs_part_fs; - extern u32 wbfs_part_idx; - extern u32 wbfs_part_lba; - extern char wbfs_fs_drive[16]; + extern s32 wbfsDev; + extern int wbfs_part_fs; + extern u32 wbfs_part_idx; + extern u32 wbfs_part_lba; + extern char wbfs_fs_drive[16]; /* Prototypes */ - 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_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); + 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); -/* - s32 __WBFS_ReadUSB(void *fp, u32 lba, u32 count, void *iobuf); - s32 __WBFS_WriteUSB(void *fp, u32 lba, u32 count, void *iobuf); -*/ + 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_OpenPart(u32 part_fat, u32 part_idx, u32 part_lba, u32 part_size, char *partition); - s32 WBFS_OpenNamed(char *partition); - s32 WBFS_OpenLBA(u32 lba, u32 size); - wbfs_disc_t* WBFS_OpenDisc(u8 *discid); - void WBFS_CloseDisc(wbfs_disc_t *disc); - bool WBFS_Close(); - bool WBFS_Mounted(); - bool WBFS_Selected(); + s32 WBFS_OpenPart( u32 part_fat, u32 part_idx, u32 part_lba, u32 part_size, char *partition ); + s32 WBFS_OpenNamed( char *partition ); + s32 WBFS_OpenLBA( u32 lba, u32 size ); + wbfs_disc_t* WBFS_OpenDisc( u8 *discid ); + void WBFS_CloseDisc( wbfs_disc_t *disc ); + bool WBFS_Close(); + bool WBFS_Mounted(); + bool WBFS_Selected(); int MountWBFS(); diff --git a/source/usbloader/wbfs/wbfs_base.cpp b/source/usbloader/wbfs/wbfs_base.cpp index b5f57315..4eb6c413 100644 --- a/source/usbloader/wbfs/wbfs_base.cpp +++ b/source/usbloader/wbfs/wbfs_base.cpp @@ -15,53 +15,59 @@ 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; + 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) { - case WBFS_DEVICE_USB: - /* Initialize USB storage */ - ret = USBStorage2_Init(); - if (ret >= 0) { - /* Setup callbacks */ - readCallback = __ReadUSB; - writeCallback = __WriteUSB; - /* Device info */ - /* Get USB capacity */ - nb_sectors = USBStorage2_GetCapacity(§or_size); - if (!nb_sectors) + switch ( device ) + { + case WBFS_DEVICE_USB: + /* Initialize USB storage */ + ret = USBStorage2_Init(); + 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; + } + else + return ret; + break; + case WBFS_DEVICE_SDHC: + /* Initialize SDHC */ + ret = SDHC_Init(); + + if ( ret ) + { + /* Setup callbacks */ + readCallback = __ReadSDHC; + writeCallback = __WriteSDHC; + + /* Device info */ + nb_sectors = 0; + sector_size = SDHC_SECTOR_SIZE; + } + else return -1; - } else - return ret; - break; - case WBFS_DEVICE_SDHC: - /* Initialize SDHC */ - ret = SDHC_Init(); - - if (ret) { - /* Setup callbacks */ - readCallback = __ReadSDHC; - writeCallback = __WriteSDHC; - - /* Device info */ - nb_sectors = 0; - sector_size = SDHC_SECTOR_SIZE; - } else - return -1; - break; + break; } return 0; @@ -69,29 +75,31 @@ s32 Wbfs::Init(u32 device) void Wbfs::Close() { - if (hdd) { - wbfs_close(hdd); - hdd = NULL; - } + if ( hdd ) + { + wbfs_close( hdd ); + hdd = NULL; + } - WBFSDevice_deInit(); + WBFSDevice_deInit(); } // Default behavior: can't format s32 Wbfs::Format() { - return -1; + 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; } @@ -99,25 +107,25 @@ 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) + 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; } @@ -129,20 +137,20 @@ wbfs_t *Wbfs::GetHddInfo() bool Wbfs::Mounted() { - return hdd == NULL; + return hdd == NULL; } -int Wbfs::GetFragList(u8 *id) +int Wbfs::GetFragList( u8 *id ) { - return 0; + 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; + return 0; } -bool Wbfs::ShowFreeSpace(void) +bool Wbfs::ShowFreeSpace( void ) { - return true; + return true; } diff --git a/source/usbloader/wbfs/wbfs_base.h b/source/usbloader/wbfs/wbfs_base.h index 9d1d76ef..893aab76 100644 --- a/source/usbloader/wbfs/wbfs_base.h +++ b/source/usbloader/wbfs/wbfs_base.h @@ -7,48 +7,48 @@ class Wbfs { -public: - Wbfs(u32, u32, u32); + public: + Wbfs( u32, u32, u32 ); - void GetProgressValue(s32 * d, s32 * m); - static s32 Init(u32); - void Close(); - 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); + void GetProgressValue( s32 * d, s32 * m ); + static s32 Init( u32 ); + void Close(); + 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 s32 Open() = 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 Open() = 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; -/* - 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; + /* + 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; - /* WBFS HDD */ - wbfs_t *hdd; + /* WBFS HDD */ + wbfs_t *hdd; - u32 device, lba, size; -private: + u32 device, lba, size; + private: - static s32 total, done; + static s32 total, done; }; #endif //_H diff --git a/source/usbloader/wbfs/wbfs_fat.cpp b/source/usbloader/wbfs/wbfs_fat.cpp index be539ebe..a5cc4e0b 100644 --- a/source/usbloader/wbfs/wbfs_fat.cpp +++ b/source/usbloader/wbfs/wbfs_fat.cpp @@ -33,815 +33,899 @@ u32 Wbfs_Fat::fat_hdr_count = 0; extern "C" { - int _FAT_get_fragments (const char *path, _frag_append_t append_fragment, void *callback_data); - extern FragList *frag_list; + 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) { - strcpy(wbfs_fs_drive, "USB:"); - } else if (device == WBFS_DEVICE_SDHC && lba == fat_sd_sec) { - strcpy(wbfs_fs_drive, "SD:"); - } else { - if (WBFSDevice_Init(lba)) return -1; - strcpy(wbfs_fs_drive, "WBFS:"); - } + if ( device == WBFS_DEVICE_USB && lba == fat_usb_sec ) + { + strcpy( wbfs_fs_drive, "USB:" ); + } + else if ( device == WBFS_DEVICE_SDHC && lba == fat_sd_sec ) + { + strcpy( wbfs_fs_drive, "SD:" ); + } + else + { + if ( WBFSDevice_Init( lba ) ) return -1; + strcpy( wbfs_fs_drive, "WBFS:" ); + } - return 0; + return 0; } -wbfs_disc_t* Wbfs_Fat::OpenDisc(u8 *discid) +wbfs_disc_t* Wbfs_Fat::OpenDisc( u8 *discid ) { - char fname[MAX_FAT_PATH]; + char fname[MAX_FAT_PATH]; - // wbfs 'partition' file - if (!FindFilename(discid, fname, sizeof(fname)) ) return NULL; + // wbfs 'partition' file + if ( !FindFilename( discid, fname, sizeof( fname ) ) ) return NULL; - 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; - // 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; - return iso_file; - } + if ( strcasecmp( strrchr( fname, '.' ), ".iso" ) == 0 ) + { + // .iso file + // create a fake wbfs_disc + int fd; + fd = open( fname, O_RDONLY ); + if ( fd == -1 ) return NULL; + wbfs_disc_t *iso_file = ( 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; + 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; - wbfs_t *part = disc->p; + if ( !disc ) return; + wbfs_t *part = disc->p; - // is this really a .iso file? - if (part == &wbfs_iso_file) { - close((int)disc->header); - free(disc); - return; - } + // is this really a .iso file? + if ( part == &wbfs_iso_file ) + { + close( ( int )disc->header ); + free( disc ); + return; + } - wbfs_close_disc(disc); - ClosePart(part); - return; + 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) { - // 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) { - memcpy(buf, fat_hdr_list, size); - SAFE_FREE(fat_hdr_list); - fat_hdr_list = buf; - } - } - *count = fat_hdr_count; - return 0; + *count = 0; + GetHeadersCount(); + if ( fat_hdr_count && fat_hdr_list ) + { + // for compacter mem - move up as it will be freed later + int size = fat_hdr_count * sizeof( struct discHdr ); + struct discHdr *buf = ( struct discHdr * ) malloc( size ); + if ( buf ) + { + memcpy( buf, fat_hdr_list, size ); + SAFE_FREE( fat_hdr_list ); + fat_hdr_list = buf; + } + } + *count = fat_hdr_count; + return 0; } -s32 Wbfs_Fat::GetHeaders(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)) { - len = sizeof(struct discHdr); - } + u32 i; + if ( len > sizeof( struct discHdr ) ) + { + len = sizeof( struct discHdr ); + } #ifdef DEBUG_WBFS - gprintf("\n\tGetHeaders"); + gprintf( "\n\tGetHeaders" ); #endif - for (i=0; iwii_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; + wii_sec_sz = part->wii_sec_sz; - partition_selector_t part_sel; - if (Settings.fullcopy) { - part_sel = ALL_PARTITIONS; - } else { - part_sel = Settings.partitions_to_install == install_game_only ? ONLY_GAME_PARTITION : ALL_PARTITIONS; - } - return wbfs_estimate_disc(part, __ReadDVD, NULL, part_sel); + partition_selector_t part_sel; + if ( Settings.fullcopy ) + { + part_sel = ALL_PARTITIONS; + } + else + { + part_sel = Settings.partitions_to_install == install_game_only ? ONLY_GAME_PARTITION : ALL_PARTITIONS; + } + return wbfs_estimate_disc( part, __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); - // cut at '[' - 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] == '_' ) { - fname_title[n - 1] = 0; - } - if (strlen(fname_title) == 0) return false; - if (id) { - memcpy(id, &fname[len-7], 6); - id[6] = 0; - } - return true; + 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; + // cut trailing _ or ' ' + if ( fname_title[n - 1] == ' ' || fname_title[n - 1] == '_' ) + { + fname_title[n - 1] = 0; + } + if ( strlen( fname_title ) == 0 ) return false; + if ( id ) + { + memcpy( id, &fname[len-7], 6 ); + id[6] = 0; + } + return true; } s32 Wbfs_Fat::GetHeadersCount() { - char path[MAX_FAT_PATH]; - char fname[MAX_FAT_PATH]; - char fpath[MAX_FAT_PATH]; - struct discHdr tmpHdr; - struct stat st; - wbfs_t *part = NULL; - u8 id[8]; - int ret; - char *p; - u32 size; - int is_dir; - int len; - char dir_title[65]; - char fname_title[TITLE_LEN]; - char *title; - DIR_ITER *dir_iter; + char path[MAX_FAT_PATH]; + char fname[MAX_FAT_PATH]; + char fpath[MAX_FAT_PATH]; + struct discHdr tmpHdr; + struct stat st; + wbfs_t *part = NULL; + u8 id[8]; + int ret; + char *p; + u32 size; + int is_dir; + int len; + char dir_title[65]; + char fname_title[TITLE_LEN]; + char *title; + DIR_ITER *dir_iter; - //dbg_time1(); + //dbg_time1(); - SAFE_FREE(fat_hdr_list); - fat_hdr_count = 0; + SAFE_FREE( fat_hdr_list ); + fat_hdr_count = 0; - strcpy(path, wbfs_fs_drive); - strcat(path, wbfs_fat_dir); + 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) { - //printf("found: %s\n", fname); Wpad_WaitButtonsCommon(); - if ((char)fname[0] == '.') continue; - len = strlen(fname); - if (len < 8) continue; // "GAMEID_x" + while ( dirnext( dir_iter, fname, &st ) == 0 ) + { + //printf("found: %s\n", fname); Wpad_WaitButtonsCommon(); + if ( ( char )fname[0] == '.' ) continue; + len = strlen( fname ); + if ( len < 8 ) continue; // "GAMEID_x" - memcpy(id, fname, 6); - id[6] = 0; - *fname_title = 0; + 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) { - int lay_a = 0; - int lay_b = 0; - if (fname[6] == '_' && is_gameid((char*)id)) { - // usb:/wbfs/GAMEID_TITLE/GAMEID.wbfs - lay_a = 1; - } - if (CheckLayoutB(fname, len, NULL, fname_title)) { - // usb:/wbfs/TITLE[GAMEID]/GAMEID.wbfs - lay_b = 1; - } - if (!lay_a && !lay_b) continue; - if (lay_a) { - strncpy(dir_title, &fname[7], sizeof(dir_title)); - } else { - try_lay_b: - if (!CheckLayoutB(fname, len, id, fname_title)) continue; - } - snprintf(fpath, sizeof(fpath), "%s/%s/%s.wbfs", path, fname, id); - //printf("path2: %s\n", fpath); - // if more than 50 games, skip second stat to improve speed - // but if ambiguous layout check anyway - if (fat_hdr_count < 50 || (lay_a && lay_b)) { - if (stat(fpath, &st) == -1) { - //printf("missing: %s\n", fpath); - // try .iso - strcpy(strrchr(fpath, '.'), ".iso"); // replace .wbfs with .iso - if (stat(fpath, &st) == -1) { - //printf("missing: %s\n", fpath); - // try .ciso - strcpy(strrchr(fpath, '.'), ".ciso"); // replace .iso with .ciso - if (stat(fpath, &st) == -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 - lay_b = 2; - // retry with layout b - goto try_lay_b; - } - continue; - } - } - } - } else { - st.st_size = 1024*1024; - } - } else { - // usb:/wbfs/GAMEID.wbfs - // or usb:/wbfs/GAMEID.iso - // 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; - int n = p - fname; // length withouth .wbfs - if (n != 6) { - // TITLE [GAMEID].wbfs - if (!CheckLayoutB(fname, n, id, fname_title)) continue; - } - snprintf(fpath, sizeof(fpath), "%s/%s", path, fname); - } + is_dir = S_ISDIR( st.st_mode ); + //printf("mode: %d %d %x\n", is_dir, st.st_mode, st.st_mode); + if ( is_dir ) + { + int lay_a = 0; + int lay_b = 0; + if ( fname[6] == '_' && is_gameid( ( char* )id ) ) + { + // usb:/wbfs/GAMEID_TITLE/GAMEID.wbfs + lay_a = 1; + } + if ( CheckLayoutB( fname, len, NULL, fname_title ) ) + { + // usb:/wbfs/TITLE[GAMEID]/GAMEID.wbfs + lay_b = 1; + } + if ( !lay_a && !lay_b ) continue; + if ( lay_a ) + { + strncpy( dir_title, &fname[7], sizeof( dir_title ) ); + } + else + { +try_lay_b: + if ( !CheckLayoutB( fname, len, id, fname_title ) ) continue; + } + snprintf( fpath, sizeof( fpath ), "%s/%s/%s.wbfs", path, fname, id ); + //printf("path2: %s\n", fpath); + // if more than 50 games, skip second stat to improve speed + // but if ambiguous layout check anyway + if ( fat_hdr_count < 50 || ( lay_a && lay_b ) ) + { + if ( stat( fpath, &st ) == -1 ) + { + //printf("missing: %s\n", fpath); + // try .iso + strcpy( strrchr( fpath, '.' ), ".iso" ); // replace .wbfs with .iso + if ( stat( fpath, &st ) == -1 ) + { + //printf("missing: %s\n", fpath); + // try .ciso + strcpy( strrchr( fpath, '.' ), ".ciso" ); // replace .iso with .ciso + if ( stat( fpath, &st ) == -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 + lay_b = 2; + // retry with layout b + goto try_lay_b; + } + continue; + } + } + } + } + else + { + st.st_size = 1024 * 1024; + } + } + else + { + // usb:/wbfs/GAMEID.wbfs + // or usb:/wbfs/GAMEID.iso + // 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; + int n = p - fname; // length withouth .wbfs + if ( n != 6 ) + { + // TITLE [GAMEID].wbfs + if ( !CheckLayoutB( fname, n, id, fname_title ) ) continue; + } + snprintf( fpath, sizeof( fpath ), "%s/%s", path, fname ); + } - //printf("found: %s %d MB\n", fpath, (int)(st.st_size/1024/1024)); - // size must be at least 1MB to be considered a valid wbfs file - if (st.st_size < 1024*1024) continue; - // if we have titles.txt entry use that - title = cfg_get_title(id); - // if no titles.txt get title from dir or file name - if (!title && *fname_title) { - title = fname_title; - } - if (title) { - memset(&tmpHdr, 0, sizeof(tmpHdr)); - memcpy(tmpHdr.id, id, 6); - strncpy(tmpHdr.title, title, sizeof(tmpHdr.title)-1); - tmpHdr.magic = 0x5D1C9EA3; - goto add_hdr; - } + //printf("found: %s %d MB\n", fpath, (int)(st.st_size/1024/1024)); + // size must be at least 1MB to be considered a valid wbfs file + if ( st.st_size < 1024*1024 ) continue; + // if we have titles.txt entry use that + title = cfg_get_title( id ); + // if no titles.txt get title from dir or file name + if ( !title && *fname_title ) + { + title = fname_title; + } + if ( title ) + { + memset( &tmpHdr, 0, sizeof( tmpHdr ) ); + memcpy( tmpHdr.id, id, 6 ); + strncpy( tmpHdr.title, title, sizeof( tmpHdr.title ) - 1 ); + tmpHdr.magic = 0x5D1C9EA3; + goto add_hdr; + } - // else read it from file directly - if (strcasecmp(strrchr(fpath,'.'), ".wbfs") == 0) { - // wbfs file directly - FILE *fp = fopen(fpath, "rb"); - if (fp != NULL) { - fseek(fp, 512, SEEK_SET); - fread(&tmpHdr, sizeof(struct discHdr), 1, fp); - fclose(fp); - tmpHdr.is_ciso = 0; - if ((tmpHdr.magic == 0x5D1C9EA3) && (memcmp(tmpHdr.id, id, 6) == 0)) { - goto add_hdr; - } - } - // no title found, read it from wbfs file - // but this is a little bit slower - // open 'partition' file - part = 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) { - goto add_hdr; - } - } else if (strcasecmp(strrchr(fpath,'.'), ".iso") == 0) { - // iso file - FILE *fp = fopen(fpath, "rb"); - if (fp != NULL) { - fseek(fp, 0, SEEK_SET); - fread(&tmpHdr, sizeof(struct discHdr), 1, fp); - fclose(fp); - tmpHdr.is_ciso = 0; - if ((tmpHdr.magic == 0x5D1C9EA3) && (memcmp(tmpHdr.id, id, 6) == 0)) { - goto add_hdr; - } - } - } else if (strcasecmp(strrchr(fpath,'.'), ".ciso") == 0) { - // ciso file - FILE *fp = fopen(fpath, "rb"); - if (fp != NULL) { - 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)) { - goto add_hdr; - } - } - } - // fail: - continue; + // else read it from file directly + if ( strcasecmp( strrchr( fpath, '.' ), ".wbfs" ) == 0 ) + { + // wbfs file directly + FILE *fp = fopen( fpath, "rb" ); + if ( fp != NULL ) + { + fseek( fp, 512, SEEK_SET ); + fread( &tmpHdr, sizeof( struct discHdr ), 1, fp ); + fclose( fp ); + tmpHdr.is_ciso = 0; + if ( ( tmpHdr.magic == 0x5D1C9EA3 ) && ( memcmp( tmpHdr.id, id, 6 ) == 0 ) ) + { + goto add_hdr; + } + } + // no title found, read it from wbfs file + // but this is a little bit slower + // open 'partition' file + part = 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 ) + { + goto add_hdr; + } + } + else if ( strcasecmp( strrchr( fpath, '.' ), ".iso" ) == 0 ) + { + // iso file + FILE *fp = fopen( fpath, "rb" ); + if ( fp != NULL ) + { + fseek( fp, 0, SEEK_SET ); + fread( &tmpHdr, sizeof( struct discHdr ), 1, fp ); + fclose( fp ); + tmpHdr.is_ciso = 0; + if ( ( tmpHdr.magic == 0x5D1C9EA3 ) && ( memcmp( tmpHdr.id, id, 6 ) == 0 ) ) + { + goto add_hdr; + } + } + } + else if ( strcasecmp( strrchr( fpath, '.' ), ".ciso" ) == 0 ) + { + // ciso file + FILE *fp = fopen( fpath, "rb" ); + if ( fp != NULL ) + { + 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 ) ) + { + goto add_hdr; + } + } + } + // fail: + continue; - // succes: add tmpHdr to list: - add_hdr: - memset(&st, 0, sizeof(st)); - //printf("added: %.6s %.20s\n", tmpHdr.id, tmpHdr.title); Wpad_WaitButtons(); - fat_hdr_count++; - fat_hdr_list = (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); - //dbg_time2("\nFAT_GetCount"); Wpad_WaitButtonsCommon(); + // succes: add tmpHdr to list: +add_hdr: + memset( &st, 0, sizeof( st ) ); + //printf("added: %.6s %.20s\n", tmpHdr.id, tmpHdr.title); Wpad_WaitButtons(); + fat_hdr_count++; + fat_hdr_list = ( 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 ); + //dbg_time2("\nFAT_GetCount"); Wpad_WaitButtonsCommon(); - return 0; + 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; - // look for direct .iso file - 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; - // direct file not found, check subdirs - *fname = 0; - DIR_ITER *dir_iter; - char path[MAX_FAT_PATH]; - char name[MAX_FAT_PATH]; - strcpy(path, wbfs_fs_drive); - strcat(path, wbfs_fat_dir); - dir_iter = diropen(path); - //printf("dir: %s %p\n", path, dir); Wpad_WaitButtons(); - if (!dir_iter) { - return 0; - } - while (dirnext(dir_iter, name, &st) == 0) { - //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[6] == '_') { - // GAMEID_TITLE - if (strncmp(name, (char*)id, 6) != 0) goto try_alter; - } else { - try_alter: - // TITLE [GAMEID] - if (name[n-8] != '[' || name[n-1] != ']') continue; - if (strncmp(&name[n-7], (char*)id, 6) != 0) continue; - } - // look for .wbfs file - snprintf(fname, len, "%s/%s/%.6s.wbfs", path, name, id); - if (stat(fname, &st) == 0) break; - // look for .iso file - snprintf(fname, len, "%s/%s/%.6s.iso", path, name, id); - if (stat(fname, &st) == 0) break; - // look for .ciso file - 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; - 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 (stat(fname, &st) == 0) break; - *fname = 0; - } - dirclose(dir_iter); - if (*fname) { - // found - //printf("found:%s\n", fname); - return 2; - } - // not found - return 0; + struct stat st; + // look for direct .wbfs file + 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; + // look for direct .ciso file + 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 ); + //printf("dir: %s %p\n", path, dir); Wpad_WaitButtons(); + if ( !dir_iter ) + { + return 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[6] == '_' ) + { + // GAMEID_TITLE + if ( strncmp( name, ( char* )id, 6 ) != 0 ) goto try_alter; + } + else + { +try_alter: + // TITLE [GAMEID] + if ( name[n-8] != '[' || name[n-1] != ']' ) continue; + if ( strncmp( &name[n-7], ( char* )id, 6 ) != 0 ) continue; + } + // look for .wbfs file + snprintf( fname, len, "%s/%s/%.6s.wbfs", path, name, id ); + if ( stat( fname, &st ) == 0 ) break; + // look for .iso file + snprintf( fname, len, "%s/%s/%.6s.iso", path, name, id ); + if ( stat( fname, &st ) == 0 ) break; + // look for .ciso file + 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; + 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 ( stat( fname, &st ) == 0 ) break; + *fname = 0; + } + dirclose( dir_iter ); + if ( *fname ) + { + // found + //printf("found:%s\n", fname); + return 2; + } + // not found + return 0; } -wbfs_t* Wbfs_Fat::OpenPart(char *fname) +wbfs_t* Wbfs_Fat::OpenPart( char *fname ) { - wbfs_t *part = NULL; - int ret; + 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) { - split_close(&split); - } - return part; + // wbfs 'partition' file + ret = split_open( &split, fname ); + if ( ret ) return NULL; + part = wbfs_open_partition( + split_read_sector, + nop_rw_sector, //readonly //split_write_sector, + &split, fat_sector_size, split.total_sec, 0, 0 ); + if ( !part ) + { + 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) { - snprintf(fname, len, "%s%s/%.6s.wbfs", wbfs_fs_drive, wbfs_fat_dir, id); - } else { - snprintf(fname, len, "%s/%.6s.wbfs", path, id); - } + if ( path == NULL ) + { + snprintf( fname, len, "%s%s/%.6s.wbfs", wbfs_fs_drive, wbfs_fat_dir, id ); + } + else + { + snprintf( fname, len, "%s/%.6s.wbfs", path, id ); + } } -void Wbfs_Fat::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) { - strcat(path, "/"); - int layout = 0; - if (Settings.FatInstallToDir == 2) layout = 1; - mk_gameid_title(header, path + strlen(path), 0, layout); - } + strcpy( path, wbfs_fs_drive ); + strcat( path, wbfs_fat_dir ); + if ( Settings.FatInstallToDir ) + { + strcat( path, "/" ); + int layout = 0; + if ( Settings.FatInstallToDir == 2 ) layout = 1; + mk_gameid_title( header, path + strlen( path ), 0, layout ); + } } -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; - u32 n_sector = size / 512; - int ret; + char fname[MAX_FAT_PATH]; + wbfs_t *part = NULL; + u64 size = ( u64 )143432 * 2 * 0x8000ULL; + u32 n_sector = size / 512; + int ret; - //printf("CREATE PART %s %lld %d\n", id, size, n_sector); - snprintf(fname, sizeof(fname), "%s%s", wbfs_fs_drive, wbfs_fat_dir); - mkdir(fname, 0777); // base usb:/wbfs - mkdir(path, 0777); // game subdir - 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; + //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; - // force create first file - u32 scnt = 0; - int fd = split_get_file(&split, 0, &scnt, 0); - if (fd<0) { - printf("ERROR creating file\n"); - sleep(2); - split_close(&split); - return NULL; - } + // force create first file + u32 scnt = 0; + int fd = split_get_file( &split, 0, &scnt, 0 ); + if ( fd < 0 ) + { + printf( "ERROR creating file\n" ); + sleep( 2 ); + split_close( &split ); + return NULL; + } - part = wbfs_open_partition( - split_read_sector, - split_write_sector, - &split, fat_sector_size, n_sector, 0, 1); - if (!part) { - split_close(&split); - } - return part; + part = wbfs_open_partition( + split_read_sector, + split_write_sector, + &split, fat_sector_size, n_sector, 0, 1 ); + if ( !part ) + { + split_close( &split ); + } + return part; } -void Wbfs_Fat::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; + 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]; + int i, len; + char title[65]; + char id[8]; - memcpy(name, header->id, 6); - name[6] = 0; - strncpy(title, get_title(header), sizeof(title)); - title_filename(title); + memcpy( name, header->id, 6 ); + name[6] = 0; + strncpy( title, get_title( header ), sizeof( title ) ); + title_filename( title ); - if (layout == 0) { - sprintf(name, "%s_%s", id, title); - } else { - sprintf(name, "%s [%s]", title, id); - } + if ( layout == 0 ) + { + sprintf( name, "%s_%s", id, title ); + } + else + { + sprintf( name, "%s [%s]", title, id ); + } - // replace space with '_' - if (re_space) { - len = strlen(name); - for (i = 0; i < len; i++) { - if(name[i]==' ') name[i] = '_'; - } - } + // replace space with '_' + if ( re_space ) + { + len = strlen( name ); + for ( i = 0; i < len; i++ ) + { + if ( name[i] == ' ' ) name[i] = '_'; + } + } } -void Wbfs_Fat::title_filename(char *title) +void Wbfs_Fat::title_filename( char *title ) { int i, len; // trim leading space - len = strlen(title); - while (*title == ' ') { - memmove(title, title+1, len); - len--; - } + len = strlen( title ); + while ( *title == ' ' ) + { + memmove( title, title + 1, len ); + len--; + } // trim trailing space - not allowed on windows directories - while (len && title[len-1] == ' ') { - title[len-1] = 0; - len--; + while ( len && title[len-1] == ' ' ) + { + title[len-1] = 0; + len--; } // replace silly chars with '_' - for (i=0; i 0) { - fname[strlen(fname)-1] = '0' + i; - if (stat(fname, &st) == -1) break; - } - strcpy(fname1, fname); - if ((ret = GetFragList((char *) &fname, &_frag_append, fs))) - { - ret_val = ret; - goto out; - } - frag_concat(fa, fs); - } - 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); - // DEBUG: - //frag_list->num = MAX_FRAG-10; // stress test - ret = frag_remap(frag_list, fw, fa); - if (ret) goto out; - } else { - // .iso does not need remap just copy - //printf("fa:\n"); - memcpy(frag_list, fa, sizeof(FragList)); - } + for ( i = 0; i < 10; i++ ) + { + frag_init( fs, MAX_FRAG ); + if ( i > 0 ) + { + fname[strlen( fname )-1] = '0' + i; + if ( stat( fname, &st ) == -1 ) break; + } + strcpy( fname1, fname ); + if ( ( ret = GetFragList( ( char * ) & fname, &_frag_append, fs ) ) ) + { + ret_val = ret; + goto out; + } + frag_concat( fa, fs ); + } + 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 ); + // DEBUG: + //frag_list->num = MAX_FRAG-10; // stress test + ret = frag_remap( frag_list, fw, fa ); + if ( ret ) goto out; + } + else + { + // .iso does not need remap just copy + //printf("fa:\n"); + memcpy( frag_list, fa, sizeof( FragList ) ); + } - ret_val = 0; + ret_val = 0; out: - if (ret_val) { - // error - SAFE_FREE(frag_list); - } - SAFE_FREE(fs); - SAFE_FREE(fa); - SAFE_FREE(fw); - return ret_val; + if ( ret_val ) + { + // error + SAFE_FREE( frag_list ); + } + SAFE_FREE( fs ); + SAFE_FREE( fa ); + SAFE_FREE( fw ); + return ret_val; } -int 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; + return false; } diff --git a/source/usbloader/wbfs/wbfs_fat.h b/source/usbloader/wbfs/wbfs_fat.h index 4d1e73b3..b3947d40 100644 --- a/source/usbloader/wbfs/wbfs_fat.h +++ b/source/usbloader/wbfs/wbfs_fat.h @@ -8,57 +8,57 @@ class Wbfs_Fat : public Wbfs { -public: - Wbfs_Fat(u32 device, u32 lba, u32 size); - ~Wbfs_Fat(); + public: + Wbfs_Fat( u32 device, u32 lba, u32 size ); + ~Wbfs_Fat(); - virtual s32 Open(); - wbfs_disc_t* OpenDisc(u8 *); - void CloseDisc(wbfs_disc_t *); + virtual s32 Open(); + 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 AddGame(); + 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(); + 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]; -private: - split_info_t split; + protected: + static char wbfs_fs_drive[16]; + private: + split_info_t split; - static u32 fat_sector_size; - static char wbfs_fat_dir[16]; - static char invalid_path[]; - static struct discHdr *fat_hdr_list; - static u32 fat_hdr_count; + static u32 fat_sector_size; + static char wbfs_fat_dir[16]; + static char invalid_path[]; + 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); - s32 GetHeadersCount(); - void GetDir(struct discHdr *header, char *path); + 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 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 ecdc7175..db227280 100644 --- a/source/usbloader/wbfs/wbfs_ntfs.cpp +++ b/source/usbloader/wbfs/wbfs_ntfs.cpp @@ -4,25 +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) { - return ret; - } + int ret = _NTFS_get_fragments( filename, append_fragment, fs ); + if ( ret ) + { + return ret; + } - // offset to start of partition - for (unsigned int j=0; jnum; j++) { - fs->frag[j].sector += fs_ntfs_sec; - } - return ret; + // offset to start of partition + 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; + return true; } diff --git a/source/usbloader/wbfs/wbfs_ntfs.h b/source/usbloader/wbfs/wbfs_ntfs.h index cdcc0eec..9a386a35 100644 --- a/source/usbloader/wbfs/wbfs_ntfs.h +++ b/source/usbloader/wbfs/wbfs_ntfs.h @@ -5,13 +5,13 @@ class Wbfs_Ntfs : public Wbfs_Fat { -public: - Wbfs_Ntfs(u32 device, u32 lba, u32 size) : Wbfs_Fat(device, lba, size) {} + public: + Wbfs_Ntfs( u32 device, u32 lba, u32 size ) : Wbfs_Fat( device, lba, size ) {} - virtual s32 Open(); + 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 5a2f056b..06a4de01 100644 --- a/source/usbloader/wbfs/wbfs_rw.c +++ b/source/usbloader/wbfs/wbfs_rw.c @@ -8,18 +8,19 @@ #include "wbfs_rw.h" /* Constants */ -#define MAX_NB_SECTORS 32 +#define MAX_NB_SECTORS 32 u32 sector_size = 512; 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; u64 offset; @@ -27,34 +28,36 @@ 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; size = len - mod; /* Read aligned data */ - if (size) { - ret = WDVD_UnencryptedRead(iobuf, size, offset); - if (ret < 0) + if ( size ) + { + 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) + buffer = memalign( 32, 0x20 ); + if ( !buffer ) return -1; /* Read data */ - ret = WDVD_UnencryptedRead(buffer, 0x20, offset + size); - if (ret < 0) + 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 */ @@ -62,28 +65,30 @@ s32 __ReadDVD(void *fp, u32 lba, u32 len, void *iobuf) { 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) { - void *ptr = ((u8 *)iobuf) + (cnt * sector_size); - u32 sectors = (count - cnt); + while ( cnt < count ) + { + void *ptr = ( ( u8 * )iobuf ) + ( cnt * sector_size ); + u32 sectors = ( count - cnt ); /* Read sectors is too big */ - if (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) + ret = USBStorage2_ReadSectors( lba + cnt, sectors, ptr ); + if ( ret < 0 ) return ret; /* Increment counter */ @@ -93,22 +98,24 @@ 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) { - void *ptr = ((u8 *)iobuf) + (cnt * sector_size); - u32 sectors = (count - cnt); + while ( cnt < count ) + { + void *ptr = ( ( u8 * )iobuf ) + ( cnt * sector_size ); + u32 sectors = ( count - cnt ); /* Write sectors is too big */ - if (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) + ret = USBStorage2_WriteSectors( lba + cnt, sectors, ptr ); + if ( ret < 0 ) return ret; /* Increment counter */ @@ -118,22 +125,24 @@ 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) { - void *ptr = ((u8 *)iobuf) + (cnt * sector_size); - u32 sectors = (count - cnt); + while ( cnt < count ) + { + void *ptr = ( ( u8 * )iobuf ) + ( cnt * sector_size ); + u32 sectors = ( count - cnt ); /* Read sectors is too big */ - if (sectors > MAX_NB_SECTORS) + if ( sectors > MAX_NB_SECTORS ) sectors = MAX_NB_SECTORS; /* SDHC read */ - ret = SDHC_ReadSectors(lba + cnt, sectors, ptr); - if (!ret) + ret = SDHC_ReadSectors( lba + cnt, sectors, ptr ); + if ( !ret ) return -1; /* Increment counter */ @@ -143,22 +152,24 @@ 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) { - void *ptr = ((u8 *)iobuf) + (cnt * sector_size); - u32 sectors = (count - cnt); + while ( cnt < count ) + { + void *ptr = ( ( u8 * )iobuf ) + ( cnt * sector_size ); + u32 sectors = ( count - cnt ); /* Write sectors is too big */ - if (sectors > MAX_NB_SECTORS) + if ( sectors > MAX_NB_SECTORS ) sectors = MAX_NB_SECTORS; /* SDHC write */ - ret = SDHC_WriteSectors(lba + cnt, sectors, ptr); - if (!ret) + ret = SDHC_WriteSectors( lba + cnt, sectors, ptr ); + if ( !ret ) return -1; /* Increment counter */ diff --git a/source/usbloader/wbfs/wbfs_rw.h b/source/usbloader/wbfs/wbfs_rw.h index 2357fa37..898f9289 100644 --- a/source/usbloader/wbfs/wbfs_rw.h +++ b/source/usbloader/wbfs/wbfs_rw.h @@ -2,20 +2,21 @@ #define _WBFS_RW_H #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #include "libwbfs/libwbfs.h" -extern u32 sector_size; -extern rw_sector_callback_t readCallback; -extern rw_sector_callback_t writeCallback; + extern u32 sector_size; + 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 } diff --git a/source/usbloader/wbfs/wbfs_wbfs.cpp b/source/usbloader/wbfs/wbfs_wbfs.cpp index 20b713b1..3b8b5613 100644 --- a/source/usbloader/wbfs/wbfs_wbfs.cpp +++ b/source/usbloader/wbfs/wbfs_wbfs.cpp @@ -7,40 +7,40 @@ extern u32 sector_size; s32 Wbfs_Wbfs::Open() { - wbfs_t *part = NULL; + wbfs_t *part = NULL; - /* Open partition */ - part = wbfs_open_partition(readCallback, writeCallback, NULL, sector_size, size, lba, 0); - if (!part) return -1; + /* Open partition */ + part = wbfs_open_partition( readCallback, writeCallback, NULL, sector_size, size, lba, 0 ); + if ( !part ) return -1; - /* Close current hard disk */ - Close(); - hdd = part; + /* Close current hard disk */ + Close(); + hdd = part; - // Save the new sector size, so it will be used in read and write calls - sector_size = 1 << hdd->head->hd_sec_sz_s; + // Save the new sector size, so it will be used in read and write calls + sector_size = 1 << hdd->head->hd_sec_sz_s; - return 0; + 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; + /* No device open */ + if ( !hdd ) + return NULL; - /* Open disc */ - return wbfs_open_disc(hdd, discid); + /* Open disc */ + return wbfs_open_disc( hdd, discid ); } -void Wbfs_Wbfs::CloseDisc(wbfs_disc_t *disc) +void Wbfs_Wbfs::CloseDisc( wbfs_disc_t *disc ) { - /* No device open */ - if (!hdd || !disc) - return; + /* No device open */ + if ( !hdd || !disc ) + return; - /* Close disc */ - wbfs_close_disc(disc); + /* Close disc */ + wbfs_close_disc( disc ); } s32 Wbfs_Wbfs::Format() @@ -48,43 +48,44 @@ s32 Wbfs_Wbfs::Format() wbfs_t *partition = NULL; /* Reset partition */ - partition = wbfs_open_partition(readCallback, writeCallback, NULL, sector_size, size, lba, 1); - if (!partition) + 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) + 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) + if ( !hdd ) return -1; - for (idx = 0; idx < cnt; idx++) { - u8 *ptr = ((u8 *)outbuf) + (idx * len); + for ( idx = 0; idx < cnt; idx++ ) + { + u8 *ptr = ( ( u8 * )outbuf ) + ( idx * len ); /* Get header */ - ret = wbfs_get_disc_info(hdd, idx, ptr, len, &size); - if (ret < 0) + ret = wbfs_get_disc_info( hdd, idx, ptr, len, &size ); + if ( ret < 0 ) return ret; } @@ -96,88 +97,91 @@ s32 Wbfs_Wbfs::AddGame() s32 ret; /* No device open */ - if (!hdd) + if ( !hdd ) return -1; /* Add game to device */ - partition_selector_t part_sel; - int copy_1_1 = 0; + partition_selector_t part_sel; + int copy_1_1 = 0; - if (Settings.fullcopy) { - part_sel = ALL_PARTITIONS; - copy_1_1 = 1; - } else { - part_sel = Settings.partitions_to_install == install_game_only ? ONLY_GAME_PARTITION : ALL_PARTITIONS; - } + if ( Settings.fullcopy ) + { + part_sel = ALL_PARTITIONS; + copy_1_1 = 1; + } + else + { + part_sel = Settings.partitions_to_install == install_game_only ? ONLY_GAME_PARTITION : ALL_PARTITIONS; + } - ret = wbfs_add_disc(hdd, __ReadDVD, NULL, ProgressCallback, part_sel, copy_1_1); - if (ret < 0) + 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) + if ( !hdd ) return -1; /* Remove game from USB device */ - ret = wbfs_rm_disc(hdd, discid); - if (ret < 0) + 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) + 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) + if ( !hdd ) return -1; - ret = wbfs_ren_disc(hdd, discid,(u8*)newname); - if (ret < 0) + 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) + if ( !hdd ) return -1; - ret = wbfs_rID_disc(hdd, discid,(u8*)newID); - if (ret < 0) + ret = wbfs_rID_disc( hdd, discid, ( u8* )newID ); + if ( ret < 0 ) return ret; return 0; @@ -185,22 +189,25 @@ s32 Wbfs_Wbfs::ReIDGame(u8 *discid, const void *newID) f32 Wbfs_Wbfs::EstimateGameSize() { - partition_selector_t part_sel = ONLY_GAME_PARTITION; - if (Settings.fullcopy) { - part_sel = ALL_PARTITIONS; - } else { - switch(Settings.partitions_to_install) - { - case install_game_only: - part_sel = ONLY_GAME_PARTITION; - break; - case install_all: - part_sel = ALL_PARTITIONS; - break; - case install_all_but_update: - part_sel = REMOVE_UPDATE_PARTITION; - break; - } - } - return wbfs_estimate_disc(hdd, __ReadDVD, NULL, part_sel); + partition_selector_t part_sel = ONLY_GAME_PARTITION; + if ( Settings.fullcopy ) + { + part_sel = ALL_PARTITIONS; + } + else + { + switch ( Settings.partitions_to_install ) + { + case install_game_only: + part_sel = ONLY_GAME_PARTITION; + break; + case install_all: + part_sel = ALL_PARTITIONS; + break; + case install_all_but_update: + part_sel = REMOVE_UPDATE_PARTITION; + break; + } + } + return wbfs_estimate_disc( hdd, __ReadDVD, NULL, part_sel ); } diff --git a/source/usbloader/wbfs/wbfs_wbfs.h b/source/usbloader/wbfs/wbfs_wbfs.h index 0124f853..813d0e02 100644 --- a/source/usbloader/wbfs/wbfs_wbfs.h +++ b/source/usbloader/wbfs/wbfs_wbfs.h @@ -6,26 +6,26 @@ class Wbfs_Wbfs : public Wbfs { -public: - Wbfs_Wbfs(u32 device, u32 lba, u32 size) : Wbfs(device, lba, size) {} + public: + Wbfs_Wbfs( u32 device, u32 lba, u32 size ) : Wbfs( device, lba, size ) {} - s32 Open(); - wbfs_disc_t* OpenDisc(u8 *); - void CloseDisc(wbfs_disc_t *); + s32 Open(); + wbfs_disc_t* OpenDisc( u8 * ); + void CloseDisc( wbfs_disc_t * ); - s32 Format(); - s32 GetCount(u32 *); - s32 GetHeaders(struct discHdr *, u32, u32); + s32 Format(); + s32 GetCount( u32 * ); + s32 GetHeaders( struct discHdr *, u32, u32 ); - s32 AddGame(); - s32 RemoveGame(u8 *); + s32 AddGame(); + 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(); + f32 EstimateGameSize(); }; #endif //_WBFS_WBFS_H diff --git a/source/usbloader/wdvd.c b/source/usbloader/wdvd.c index 2143ad79..da22a1c9 100644 --- a/source/usbloader/wdvd.c +++ b/source/usbloader/wdvd.c @@ -4,285 +4,305 @@ #include /* Constants */ -#define IOCTL_DI_READID 0x70 -#define IOCTL_DI_READ 0x71 -#define IOCTL_DI_WAITCVRCLOSE 0x79 -#define IOCTL_DI_GETCOVER 0x88 -#define IOCTL_DI_RESET 0x8A -#define IOCTL_DI_OPENPART 0x8B -#define IOCTL_DI_CLOSEPART 0x8C -#define IOCTL_DI_UNENCREAD 0x8D -#define IOCTL_DI_SEEK 0xAB -#define IOCTL_DI_STOPLASER 0xD2 -#define IOCTL_DI_OFFSET 0xD9 -#define IOCTL_DI_DISC_BCA 0xDA -#define IOCTL_DI_STOPMOTOR 0xE3 -#define IOCTL_DI_SETUSBMODE 0xF4 -#define IOCTL_DI_DISABLERESET 0xF6 +#define IOCTL_DI_READID 0x70 +#define IOCTL_DI_READ 0x71 +#define IOCTL_DI_WAITCVRCLOSE 0x79 +#define IOCTL_DI_GETCOVER 0x88 +#define IOCTL_DI_RESET 0x8A +#define IOCTL_DI_OPENPART 0x8B +#define IOCTL_DI_CLOSEPART 0x8C +#define IOCTL_DI_UNENCREAD 0x8D +#define IOCTL_DI_SEEK 0xAB +#define IOCTL_DI_STOPLASER 0xD2 +#define IOCTL_DI_OFFSET 0xD9 +#define IOCTL_DI_DISC_BCA 0xDA +#define IOCTL_DI_STOPMOTOR 0xE3 +#define IOCTL_DI_SETUSBMODE 0xF4 +#define IOCTL_DI_DISABLERESET 0xF6 /** Hermes IOS222 **/ -#define DI_SETWBFSMODE 0xfe +#define DI_SETWBFSMODE 0xfe #define DI_SETOFFSETBASE 0xf1 /* Variables */ -static u32 inbuf[8] ATTRIBUTE_ALIGN(32); -static u32 outbuf[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 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) { - di_fd = IOS_Open(di_fs, 0); - if (di_fd < 0) + if ( di_fd < 0 ) + { + 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) { - IOS_Close(di_fd); + if ( di_fd >= 0 ) + { + 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) + 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) + ret = IOS_Ioctl( di_fd, IOCTL_DI_READID, inbuf, sizeof( inbuf ), outbuf, sizeof( outbuf ) ); + if ( ret < 0 ) return ret; - if (ret == 1) { - memcpy(id, outbuf, sizeof(dvddiskid)); + if ( ret == 1 ) + { + 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) + 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) + 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) + 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) + 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; u32 *buffer = NULL; s32 ret; /* Allocate memory */ - buffer = (u32 *)memalign(32, 0x5000); - if (!buffer) + 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) + 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) + 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) + 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) + 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) + 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) + 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; } @@ -290,67 +310,72 @@ 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) + 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) { - memcpy(&inbuf[2], id, 6); - if (IOS_GetVersion() != 249) { - inbuf[5] = partition; - } + if ( id ) + { + 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) + 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; + s32 ret; - memset(inbuf, 0, sizeof(inbuf)); + memset( inbuf, 0, sizeof( inbuf ) ); - /* Disc read */ - inbuf[0] = IOCTL_DI_DISC_BCA << 24; - //inbuf[1] = 64; + /* Disc read */ + inbuf[0] = IOCTL_DI_DISC_BCA << 24; + //inbuf[1] = 64; - ret = IOS_Ioctl(di_fd, IOCTL_DI_DISC_BCA, inbuf, sizeof(inbuf), buf, 64); - if (ret < 0) - return ret; + ret = IOS_Ioctl( di_fd, IOCTL_DI_DISC_BCA, inbuf, sizeof( inbuf ), buf, 64 ); + if ( ret < 0 ) + return ret; - return (ret == 1) ? 0 : -ret; + return ( ret == 1 ) ? 0 : -ret; } diff --git a/source/usbloader/wdvd.h b/source/usbloader/wdvd.h index 0f7848ff..fee4bb03 100644 --- a/source/usbloader/wdvd.h +++ b/source/usbloader/wdvd.h @@ -1,29 +1,30 @@ #ifndef _WDVD_H_ -#define _WDVD_H_ +#define _WDVD_H_ #ifdef __cplusplus -extern "C" { +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); + 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 } diff --git a/source/video.cpp b/source/video.cpp index 782c897e..65215ec9 100644 --- a/source/video.cpp +++ b/source/video.cpp @@ -24,7 +24,7 @@ static unsigned int *xfb[2] = { NULL, NULL }; // Double buffered static int whichfb = 0; // Switch static GXRModeObj *vmode; // Menu video mode -static unsigned char gp_fifo[DEFAULT_FIFO_SIZE] ATTRIBUTE_ALIGN (32); +static unsigned char gp_fifo[DEFAULT_FIFO_SIZE] ATTRIBUTE_ALIGN ( 32 ); static Mtx GXmodelView2D; int screenheight; int screenwidth; @@ -39,18 +39,19 @@ u8 * gameScreenTex2 = NULL; // a GX texture screen capture of the game (copy) * Initialises GX and sets it up for use ***************************************************************************/ static void -StartGX () { +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 ); } /**************************************************************************** @@ -59,36 +60,37 @@ StartGX () { * Reset the video/rendering mode for the menu ****************************************************************************/ void -ResetVideo_Menu() { +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()) + 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); + 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); + if ( vmode->aa ) + GX_SetPixelFmt( GX_PF_RGB565_Z16, GX_ZC_LINEAR ); else - GX_SetPixelFmt(GX_PF_RGB8_Z24, GX_ZC_LINEAR); + GX_SetPixelFmt( GX_PF_RGB8_Z24, GX_ZC_LINEAR ); // setup the vertex descriptor // tells the flipper to expect direct data @@ -96,31 +98,31 @@ ResetVideo_Menu() { 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 ); } /**************************************************************************** @@ -131,34 +133,36 @@ ResetVideo_Menu() { ***************************************************************************/ void -InitVideo () { +InitVideo () +{ VIDEO_Init(); - vmode = VIDEO_GetPreferredMode(NULL); // get default video mode + vmode = VIDEO_GetPreferredMode( NULL ); // get default video mode // widescreen fix - if (CFG.widescreen) { - vmode->viWidth = VI_MAX_WIDTH_PAL-12; - vmode->viXOrigin = ((VI_MAX_WIDTH_PAL - vmode->viWidth) / 2) + 2; + if ( CFG.widescreen ) + { + vmode->viWidth = VI_MAX_WIDTH_PAL - 12; + vmode->viXOrigin = ( ( VI_MAX_WIDTH_PAL - vmode->viWidth ) / 2 ) + 2; } - 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_SetBlack ( FALSE ); VIDEO_Flush (); VIDEO_WaitVSync (); - if (vmode->viTVMode & VI_NON_INTERLACE) + if ( vmode->viTVMode & VI_NON_INTERLACE ) VIDEO_WaitVSync (); StartGX(); @@ -166,43 +170,45 @@ InitVideo () { // 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 ); } static unsigned int *xfbDB = NULL; -void InitVideodebug () { +void InitVideodebug () +{ VIDEO_Init(); - GXRModeObj *vmode = VIDEO_GetPreferredMode(NULL); // get default video mode + GXRModeObj *vmode = VIDEO_GetPreferredMode( NULL ); // get default video mode // widescreen fix - VIDEO_Configure (vmode); + VIDEO_Configure ( vmode ); // Allocate the video buffers - xfbDB = (u32 *) MEM_K0_TO_K1 (SYS_AllocateFramebuffer (vmode)); + xfbDB = ( u32 * ) MEM_K0_TO_K1 ( SYS_AllocateFramebuffer ( vmode ) ); // A console is always useful while debugging - console_init (xfbDB, 20, 64, vmode->fbWidth, vmode->xfbHeight, vmode->fbWidth * 2); + console_init ( xfbDB, 20, 64, vmode->fbWidth, vmode->xfbHeight, vmode->fbWidth * 2 ); // Clear framebuffers etc. - VIDEO_ClearFrameBuffer (vmode, xfbDB, COLOR_BLACK); - VIDEO_SetNextFramebuffer (xfbDB); + VIDEO_ClearFrameBuffer ( vmode, xfbDB, COLOR_BLACK ); + VIDEO_SetNextFramebuffer ( xfbDB ); - 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 (); } /**************************************************************************** * StopGX * * Stops GX (when exiting) ***************************************************************************/ -void StopGX() { +void StopGX() +{ GX_AbortFrame(); GX_Flush(); - VIDEO_SetBlack(TRUE); + VIDEO_SetBlack( TRUE ); VIDEO_Flush(); } @@ -211,14 +217,15 @@ void StopGX() { * * Renders everything current sent to GX, and flushes video ***************************************************************************/ -void Menu_Render() { +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_SetZMode( GX_TRUE, GX_LEQUAL, GX_TRUE ); + GX_SetColorUpdate( GX_TRUE ); + GX_CopyDisp( xfb[whichfb], GX_TRUE ); GX_DrawDone (); - VIDEO_SetNextFramebuffer(xfb[whichfb]); + VIDEO_SetNextFramebuffer( xfb[whichfb] ); VIDEO_Flush(); VIDEO_WaitVSync(); frameCount++; @@ -229,61 +236,63 @@ 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) { - if (data == NULL) +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; 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); - guVector axis = (guVector) { + Mtx m, m1, m2, mv; + width *= .5; + height *= .5; + 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); + guMtxRotAxisDeg ( m2, &axis, degrees ); +// 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 ); } @@ -292,181 +301,194 @@ void Menu_DrawImg(f32 xpos, f32 ypos, f32 zpos, f32 width, f32 height, u8 data[] * * 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}}; + 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}}; - if (!filled) { + if ( !filled ) + { fmt = GX_LINESTRIP; n = 5; - } else { + } + else + { fmt = GX_TRIANGLEFAN; n = 4; } - GX_Begin(fmt, GX_VTXFMT0, n); - for (i=0; ifbWidth, vmode->efbHeight,xfb[whichfb],0); - PNGU_ReleaseImageContext (ctx); - gprintf(":%d", ret); - return 1; + 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 205f9950..8322b1df 100644 --- a/source/video.h +++ b/source/video.h @@ -16,12 +16,12 @@ 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 ); extern int screenheight; extern int screenwidth; diff --git a/source/wad/nandtitle.cpp b/source/wad/nandtitle.cpp index 1c18226e..59aab496 100644 --- a/source/wad/nandtitle.cpp +++ b/source/wad/nandtitle.cpp @@ -3,7 +3,7 @@ extern "C" { - extern s32 MagicPatches(s32); + extern s32 MagicPatches( s32 ); } static u8 tmd_buf[ MAX_SIGNED_TMD_SIZE ] ATTRIBUTE_ALIGN( 32 ); @@ -19,16 +19,16 @@ NandTitle::NandTitle() NandTitle::~NandTitle() { - if( list ) + if ( list ) { - free( list ); - list = NULL; + free( list ); + list = NULL; } - if( nameList ) + if ( nameList ) { - free( nameList ); - nameList = NULL; + free( nameList ); + nameList = NULL; } } @@ -36,40 +36,40 @@ s32 NandTitle::Get() { s32 ret; - if( list ) + if ( list ) { - free( list ); - list = NULL; + free( list ); + list = NULL; } - if( nameList ) + if ( nameList ) { - free( nameList ); - nameList = NULL; + free( nameList ); + nameList = NULL; } ret = ES_GetNumTitles( &numTitles ); - if(ret < 0) - return WII_EINTERNAL; + 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; + return -1; } ret = ES_GetTitles( list, numTitles ); - if( ret < 0 ) + if ( ret < 0 ) { - free( list ); - return WII_EINTERNAL; + free( list ); + return WII_EINTERNAL; } - nameList = (char*)malloc( IMET_MAX_NAME_LEN * numTitles ); - if( !nameList ) + nameList = ( char* )malloc( IMET_MAX_NAME_LEN * numTitles ); + if ( !nameList ) { - free( nameList ); - return -2; + free( nameList ); + return -2; } memset( nameList, 0, IMET_MAX_NAME_LEN * numTitles ); @@ -79,16 +79,16 @@ s32 NandTitle::Get() wchar_t name[ IMET_MAX_NAME_LEN ]; - for( u32 i = 0; i < numTitles; i++) + for ( u32 i = 0; i < numTitles; i++ ) { - bool r = GetName( list[ i ], language, name ); - if( r ) - { - wString *wsname = new wString( name ); - memcpy( nameList + ( IMET_MAX_NAME_LEN * i ), (wsname->toUTF8()).c_str(), strlen( (wsname->toUTF8()).c_str() ) ); - //gprintf("adding: %s\n", (wsname->toUTF8()).c_str() ); - delete wsname; - } + bool r = GetName( list[ i ], language, name ); + if ( r ) + { + wString *wsname = new wString( name ); + memcpy( nameList + ( IMET_MAX_NAME_LEN * i ), ( wsname->toUTF8() ).c_str(), strlen( ( wsname->toUTF8() ).c_str() ) ); + //gprintf("adding: %s\n", (wsname->toUTF8()).c_str() ); + delete wsname; + } } ISFS_Deinitialize(); @@ -99,23 +99,23 @@ s32 NandTitle::Get() 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; + //gprintf("!size\n"); + return NULL; } s32 ret = ES_GetStoredTMD( tid, s_tmd, tmd_size ); - if( ret < 0 ) + if ( ret < 0 ) { - //gprintf("!tmd - %04x\n", ret ); - return NULL; + //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; @@ -123,96 +123,96 @@ tmd* NandTitle::GetTMD( u64 tid ) 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 ) ); + IMET *imet = ( IMET* )memalign( 32, sizeof( IMET ) ); tmd* titleTmd = GetTMD( tid ); - if( !titleTmd ) + if ( !titleTmd ) { - //gprintf("no TMD\n"); - free( imet ); - return false; + //gprintf("no TMD\n"); + 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 ) - { - ok = true; - break; - } + if ( !titleTmd->contents[ i ].index ) + { + ok = true; + break; + } } - if( !ok ) + if ( !ok ) { - free( imet ); - return false; + free( imet ); + return false; } 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 ) + if ( fd < 0 ) { - //gprintf("fd: %d\n", fd ); - free( imet ); - return false; + //gprintf("fd: %d\n", fd ); + 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 ); - return false; + 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 ); - return false; + ISFS_Close( fd ); + free( imet ); + return false; } ISFS_Close( fd ); - if( imet->sig != IMET_SIGNATURE ) + if ( imet->sig != IMET_SIGNATURE ) { - free( imet ); - return false; + 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 ) - { - language = CONF_LANG_ENGLISH; - } - else - { - // channel name is also not available on english, get ascii name - for (int i = 0; i < 4; i++) - { - name[ i ] = ( TITLE_LOWER( tid ) >> ( 24 - i * 8 ) ) & 0xFF; - } - name[ 4 ] = 0; - free( imet ); - return true; - } + // channel name is not available in system language + 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++ ) + { + name[ i ] = ( TITLE_LOWER( tid ) >> ( 24 - i * 8 ) ) & 0xFF; + } + 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 ); @@ -224,27 +224,27 @@ bool NandTitle::Exists( u64 tid ) { char app[ ISFS_MAXPATH ]; tmd* titleTmd = GetTMD( tid ); - if( !titleTmd ) - return false; + 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 ) - { - ok = true; - break; - } + 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 ); + 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 @@ -253,26 +253,26 @@ bool NandTitle::Exists( u64 tid ) bool NandTitle::ExistsFromIndex( u32 i ) { - if( i > numTitles || i < 0 ) - return false; + if ( i > numTitles || i < 0 ) + return false; return Exists( list[ i ] ); } u64 NandTitle::At( u32 i ) { - if( i > numTitles || i < 0 ) - return 0; + if ( i > numTitles || i < 0 ) + return 0; return list[ i ]; } int NandTitle::IndexOf( u64 tid ) { - for( u32 i = 0; i < numTitles; i++ ) + for ( u32 i = 0; i < numTitles; i++ ) { - if( list[ i ] == tid ) - return i; + if ( list[ i ] == tid ) + return i; } return WII_EINSTALL; @@ -280,15 +280,15 @@ int NandTitle::IndexOf( u64 tid ) char* NandTitle::NameOf( u64 tid ) { - for( u32 i = 0; i < numTitles; i++ ) + for ( u32 i = 0; i < numTitles; i++ ) { - if( list[ i ] == tid ) - { - if( !nameList[ IMET_MAX_NAME_LEN * i ] ) - return NULL; + if ( list[ i ] == tid ) + { + if ( !nameList[ IMET_MAX_NAME_LEN * i ] ) + return NULL; - return nameList + ( IMET_MAX_NAME_LEN * i ); - } + return nameList + ( IMET_MAX_NAME_LEN * i ); + } } return NULL; @@ -297,27 +297,27 @@ char* NandTitle::NameOf( u64 tid ) char* NandTitle::NameFromIndex( u32 i ) { - if( i > numTitles || i < 0 ) - return NULL; + if ( i > numTitles || i < 0 ) + return NULL; - if( !nameList[ IMET_MAX_NAME_LEN * i ] ) - return NULL; + if ( !nameList[ IMET_MAX_NAME_LEN * i ] ) + return NULL; return nameList + ( IMET_MAX_NAME_LEN * i ); } u16 NandTitle::VersionOf( u64 tid ) { - for( u32 i = 0; i < numTitles; i++ ) + for ( u32 i = 0; i < numTitles; i++ ) { - if( list[ i ] == tid ) - { - tmd* Tmd = GetTMD( tid ); - if( !Tmd ) - break; + if ( list[ i ] == tid ) + { + tmd* Tmd = GetTMD( tid ); + if ( !Tmd ) + break; - return Tmd->title_version; - } + return Tmd->title_version; + } } return 0; @@ -325,12 +325,12 @@ u16 NandTitle::VersionOf( u64 tid ) u16 NandTitle::VersionFromIndex( u32 i ) { - if( i > numTitles || i < 0 ) - return 0; + if ( i > numTitles || i < 0 ) + return 0; tmd* Tmd = GetTMD( list[ i ] ); - if( !Tmd ) - return 0; + if ( !Tmd ) + return 0; return Tmd->title_version; } @@ -338,12 +338,12 @@ u16 NandTitle::VersionFromIndex( u32 i ) u32 NandTitle::CountType( u32 type ) { u32 ret = 0; - for( u32 i = 0; i < numTitles; i++ ) + for ( u32 i = 0; i < numTitles; i++ ) { - if( TITLE_UPPER( list[ i ] ) == type ) - { - ret++; - } + if ( TITLE_UPPER( list[ i ] ) == type ) + { + ret++; + } } return ret; } @@ -361,21 +361,21 @@ u64 NandTitle::Next() u64 ret = 0; //gprintf("Next( %08x, %u )\n", currentType, currentIndex ); u32 i; - for( i = currentIndex; i < numTitles; i++ ) + for ( i = currentIndex; i < numTitles; i++ ) { - if( currentType ) - { - if( currentType == TITLE_UPPER( list[ i ] ) ) - { - ret = list[ i ]; - break; - } - } - else - { - ret = list[ i ]; - break; - } + if ( currentType ) + { + if ( currentType == TITLE_UPPER( list[ i ] ) ) + { + ret = list[ i ]; + break; + } + } + else + { + ret = list[ i ]; + break; + } } currentIndex = i + 1; @@ -393,17 +393,17 @@ void NandTitle::AsciiTID( u64 tid, char* out ) out[ 0 ] = ascii( TITLE_3( tid ) ); out[ 1 ] = ascii( TITLE_2( tid ) ); out[ 2 ] = ascii( TITLE_1( tid ) ); - out[ 3 ] = ascii( (u8)( tid ) ); + out[ 3 ] = ascii( ( u8 )( tid ) ); out[ 4 ] = 0; //gprintf("%s\n", out ); } void NandTitle::AsciiFromIndex( u32 i, char* out ) { - if( i > numTitles || i < 0 ) + if ( i > numTitles || i < 0 ) { - out[ 0 ] = 0; - return; + out[ 0 ] = 0; + return; } AsciiTID( list[ i ], out ); @@ -417,19 +417,19 @@ 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; @@ -439,8 +439,8 @@ s32 NandTitle::GetTicketViews( u64 tid, tikview **outbuf, u32 *outlen ) err: /* Free memory */ - if (views) - free(views); + if ( views ) + free( views ); return ret; } diff --git a/source/wad/nandtitle.h b/source/wad/nandtitle.h index 85014302..231e7137 100644 --- a/source/wad/nandtitle.h +++ b/source/wad/nandtitle.h @@ -10,17 +10,17 @@ #include "wstring.hpp" -#define TITLE_ID(x,y) (((u64)(x) << 32) | (y)) -#define TITLE_UPPER(x) ((u32)((x) >> 32)) -#define TITLE_LOWER(x) ((u32)(x)) +#define TITLE_ID(x,y) (((u64)(x) << 32) | (y)) +#define TITLE_UPPER(x) ((u32)((x) >> 32)) +#define TITLE_LOWER(x) ((u32)(x)) -#define TITLE_1(x) ((u8)((x) >> 8)) -#define TITLE_2(x) ((u8)((x) >> 16)) -#define TITLE_3(x) ((u8)((x) >> 24)) -#define TITLE_4(x) ((u8)((x) >> 32)) -#define TITLE_5(x) ((u8)((x) >> 40)) -#define TITLE_6(x) ((u8)((x) >> 48)) -#define TITLE_7(x) ((u8)((x) >> 56)) +#define TITLE_1(x) ((u8)((x) >> 8)) +#define TITLE_2(x) ((u8)((x) >> 16)) +#define TITLE_3(x) ((u8)((x) >> 24)) +#define TITLE_4(x) ((u8)((x) >> 32)) +#define TITLE_5(x) ((u8)((x) >> 40)) +#define TITLE_6(x) ((u8)((x) >> 48)) +#define TITLE_7(x) ((u8)((x) >> 56)) #define IMET_MAX_NAME_LEN 0x2a @@ -35,71 +35,71 @@ 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 { -public: - NandTitle(); - ~NandTitle(); + public: + NandTitle(); + ~NandTitle(); - s32 Get(); - u64 At( u32 i ); - int IndexOf( u64 tid ); - u32 Count(){ return numTitles; } + s32 Get(); + u64 At( u32 i ); + int IndexOf( u64 tid ); + u32 Count() { return numTitles; } - char* NameOf( u64 tid ); - char* NameFromIndex( u32 i ); + char* NameOf( u64 tid ); + 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 ); - u64 Next(); - void ResetCounter(); + 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 ); - 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: - u64* list; - char* nameList; - u32 numTitles; - bool GetName( u64 tid, int language, wchar_t* name ); - tmd* GetTMD( u64 tid ); + private: + u64* list; + char* nameList; + u32 numTitles; + bool GetName( u64 tid, int language, wchar_t* name ); + tmd* GetTMD( u64 tid ); - u32 currentIndex; - u32 currentType; + u32 currentIndex; + u32 currentType; }; extern NandTitle titles; diff --git a/source/wad/utils.h b/source/wad/utils.h index d4208bd8..14bea927 100644 --- a/source/wad/utils.h +++ b/source/wad/utils.h @@ -1,19 +1,20 @@ #ifndef _UTILS_H_ -#define _UTILS_H_ +#define _UTILS_H_ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif - /* Constants */ -#define KB_SIZE 1024.0 -#define MB_SIZE 1048576.0 -#define GB_SIZE 1073741824.0 + /* Constants */ +#define KB_SIZE 1024.0 +#define MB_SIZE 1048576.0 +#define GB_SIZE 1073741824.0 /* Macros */ -#define round_up(x,n) (-(-(x) & -(n))) +#define round_up(x,n) (-(-(x) & -(n))) /* Prototypes */ - u32 swap32(u32); + u32 swap32( u32 ); #ifdef __cplusplus } diff --git a/source/wad/wad.cpp b/source/wad/wad.cpp index 4c382442..6e562c15 100644 --- a/source/wad/wad.cpp +++ b/source/wad/wad.cpp @@ -26,625 +26,660 @@ extern GuiWindow * mainWindow; /* 'WAD Header' structure */ -typedef struct { - /* Header length */ - u32 header_len; +typedef struct +{ + /* Header length */ + u32 header_len; - /* WAD type */ - u16 type; + /* WAD type */ + u16 type; - u16 padding; + u16 padding; - /* Data length */ - u32 certs_len; - u32 crl_len; - u32 tik_len; - u32 tmd_len; - u32 data_len; - u32 footer_len; + /* Data length */ + u32 certs_len; + u32 crl_len; + u32 tik_len; + u32 tmd_len; + u32 data_len; + u32 footer_len; } ATTRIBUTE_PACKED wadHeader; /* Variables */ -static u8 wadBuffer[BLOCK_SIZE] ATTRIBUTE_ALIGN(32); +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; + s32 ret; - /* Seek to offset */ - fseek(fp, offset, SEEK_SET); + /* Seek to offset */ + fseek( fp, offset, SEEK_SET ); - /* Read data */ - ret = fread(outbuf, len, 1, fp); - if (ret < 0) - return ret; + /* Read data */ + ret = fread( outbuf, len, 1, fp ); + if ( ret < 0 ) + return ret; - return 0; + return 0; } -s32 __Wad_ReadAlloc(FILE *fp, void **outbuf, u32 offset, u32 len) +s32 __Wad_ReadAlloc( FILE *fp, void **outbuf, u32 offset, u32 len ) { - void *buffer = NULL; - s32 ret; + void *buffer = NULL; + s32 ret; - /* Allocate memory */ - buffer = memalign(32, len); - if (!buffer) - return -1; + /* Allocate memory */ + buffer = memalign( 32, len ); + if ( !buffer ) + return -1; - /* Read file */ - ret = __Wad_ReadFile(fp, buffer, offset, len); - if (ret < 0) { - free(buffer); - return ret; - } + /* Read file */ + ret = __Wad_ReadFile( fp, buffer, offset, len ); + if ( ret < 0 ) + { + free( buffer ); + return ret; + } - /* Set pointer */ - *outbuf = buffer; - return 0; + /* Set pointer */ + *outbuf = buffer; + return 0; } -s32 __Wad_GetTitleID(FILE *fp, wadHeader *header, u64 *tid) +s32 __Wad_GetTitleID( FILE *fp, wadHeader *header, u64 *tid ) { - //signed_blob *p_tik = NULL; - void *p_tik = NULL; - tik *tik_data = NULL; + //signed_blob *p_tik = NULL; + void *p_tik = NULL; + tik *tik_data = NULL; - u32 offset = 0; - s32 ret; + u32 offset = 0; + s32 ret; - /* Ticket offset */ - offset += round_up(header->header_len, 64); - offset += round_up(header->certs_len, 64); - offset += round_up(header->crl_len, 64); + /* Ticket offset */ + offset += round_up( header->header_len, 64 ); + offset += round_up( header->certs_len, 64 ); + offset += round_up( header->crl_len, 64 ); - /* Read ticket */ - ret = __Wad_ReadAlloc(fp, &p_tik, offset, header->tik_len); - if (ret < 0) - goto out; + /* Read ticket */ + ret = __Wad_ReadAlloc( fp, &p_tik, offset, header->tik_len ); + if ( ret < 0 ) + goto out; - /* Ticket data */ - tik_data = (tik *)SIGNATURE_PAYLOAD((signed_blob *)p_tik); + /* Ticket data */ + tik_data = ( tik * )SIGNATURE_PAYLOAD( ( signed_blob * )p_tik ); - /* Copy title ID */ - *tid = tik_data->titleid; + /* Copy title ID */ + *tid = tik_data->titleid; out: - /* Free memory */ - if (p_tik) - free(p_tik); + /* Free memory */ + if ( p_tik ) + free( p_tik ); - return ret; + return ret; } -s32 Wad_Install(FILE *fp) +s32 Wad_Install( FILE *fp ) { - //////start the gui shit - GuiWindow promptWindow(472,320); - promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - promptWindow.SetPosition(0, -10); + //////start the gui shit + GuiWindow promptWindow( 472, 320 ); + promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); + promptWindow.SetPosition( 0, -10 ); - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); - GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + char imgPath[100]; + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", CFG.theme_path ); + GuiImageData dialogBox( imgPath, dialogue_box_png ); + GuiTrigger trigA; + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); - GuiImage dialogBoxImg(&dialogBox); - if (Settings.wsprompt == yes){ - dialogBoxImg.SetWidescreen(CFG.widescreen);} + GuiImage dialogBoxImg( &dialogBox ); + if ( Settings.wsprompt == yes ) + { + dialogBoxImg.SetWidescreen( CFG.widescreen ); + } - GuiText btn1Txt(tr("OK"), 22, THEME.prompttext); - GuiImage btn1Img(&btnOutline); - if (Settings.wsprompt == yes){ - btn1Txt.SetWidescreen(CFG.widescreen); - btn1Img.SetWidescreen(CFG.widescreen);} - GuiButton btn1(&btn1Img,&btn1Img, 2, 4, 0, -35, &trigA, &btnSoundOver, btnClick2,1); - btn1.SetLabel(&btn1Txt); - btn1.SetState(STATE_SELECTED); + GuiText btn1Txt( tr( "OK" ), 22, THEME.prompttext ); + GuiImage btn1Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn1Txt.SetWidescreen( CFG.widescreen ); + btn1Img.SetWidescreen( CFG.widescreen ); + } + GuiButton btn1( &btn1Img, &btn1Img, 2, 4, 0, -35, &trigA, &btnSoundOver, btnClick2, 1 ); + btn1.SetLabel( &btn1Txt ); + btn1.SetState( STATE_SELECTED ); - snprintf(imgPath, sizeof(imgPath), "%sprogressbar_outline.png", CFG.theme_path); - GuiImageData progressbarOutline(imgPath, progressbar_outline_png); - GuiImage progressbarOutlineImg(&progressbarOutline); - if (Settings.wsprompt == yes){ - progressbarOutlineImg.SetWidescreen(CFG.widescreen);} - progressbarOutlineImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarOutlineImg.SetPosition(25, 50); + snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_outline.png", CFG.theme_path ); + GuiImageData progressbarOutline( imgPath, progressbar_outline_png ); + GuiImage progressbarOutlineImg( &progressbarOutline ); + if ( Settings.wsprompt == yes ) + { + progressbarOutlineImg.SetWidescreen( CFG.widescreen ); + } + progressbarOutlineImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + progressbarOutlineImg.SetPosition( 25, 50 ); - snprintf(imgPath, sizeof(imgPath), "%sprogressbar_empty.png", CFG.theme_path); - GuiImageData progressbarEmpty(imgPath, progressbar_empty_png); - GuiImage progressbarEmptyImg(&progressbarEmpty); - progressbarEmptyImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarEmptyImg.SetPosition(25, 50); - progressbarEmptyImg.SetTile(100); + snprintf( imgPath, sizeof( imgPath ), "%sprogressbar_empty.png", CFG.theme_path ); + GuiImageData progressbarEmpty( imgPath, progressbar_empty_png ); + GuiImage progressbarEmptyImg( &progressbarEmpty ); + progressbarEmptyImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + progressbarEmptyImg.SetPosition( 25, 50 ); + progressbarEmptyImg.SetTile( 100 ); - snprintf(imgPath, sizeof(imgPath), "%sprogressbar.png", CFG.theme_path); - GuiImageData progressbar(imgPath, progressbar_png); - GuiImage progressbarImg(&progressbar); - progressbarImg.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE); - progressbarImg.SetPosition(25, 50); + snprintf( imgPath, sizeof( imgPath ), "%sprogressbar.png", CFG.theme_path ); + GuiImageData progressbar( imgPath, progressbar_png ); + GuiImage progressbarImg( &progressbar ); + progressbarImg.SetAlignment( ALIGN_LEFT, ALIGN_MIDDLE ); + progressbarImg.SetPosition( 25, 50 ); char title[50]; - sprintf(title, "%s", tr("Installing wad")); - GuiText titleTxt(title, 26, THEME.prompttext); - titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - titleTxt.SetPosition(0,40); + sprintf( title, "%s", tr( "Installing wad" ) ); + GuiText titleTxt( title, 26, THEME.prompttext ); + titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + titleTxt.SetPosition( 0, 40 ); char msg[50]; - sprintf(msg, " "); - // sprintf(msg, "%s", tr("Initializing Network")); - GuiText msg1Txt((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); + 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 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) && (CFG.widescreen)){/////////////adjust for widescreen - progressbarOutlineImg.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - progressbarOutlineImg.SetPosition(0, 50); - progressbarEmptyImg.SetPosition(80,50); - progressbarEmptyImg.SetTile(78); - progressbarImg.SetPosition(80, 50); + if ( ( Settings.wsprompt == yes ) && ( CFG.widescreen ) ) /////////////adjust for widescreen + { + progressbarOutlineImg.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); + progressbarOutlineImg.SetPosition( 0, 50 ); + progressbarEmptyImg.SetPosition( 80, 50 ); + progressbarEmptyImg.SetTile( 78 ); + progressbarImg.SetPosition( 80, 50 ); - msg1Txt.SetPosition(90,75); - msg2Txt.SetPosition(90, 98); - msg3Txt.SetPosition(90, 121); - msg4Txt.SetPosition(90, 144); - msg5Txt.SetPosition(90, 167); + msg1Txt.SetPosition( 90, 75 ); + msg2Txt.SetPosition( 90, 98 ); + msg3Txt.SetPosition( 90, 121 ); + msg4Txt.SetPosition( 90, 144 ); + msg5Txt.SetPosition( 90, 167 ); - } - promptWindow.Append(&dialogBoxImg); - promptWindow.Append(&titleTxt); - promptWindow.Append(&msg5Txt); - promptWindow.Append(&msg4Txt); - promptWindow.Append(&msg3Txt); - promptWindow.Append(&msg1Txt); - promptWindow.Append(&msg2Txt); + } + promptWindow.Append( &dialogBoxImg ); + promptWindow.Append( &titleTxt ); + promptWindow.Append( &msg5Txt ); + promptWindow.Append( &msg4Txt ); + promptWindow.Append( &msg3Txt ); + promptWindow.Append( &msg1Txt ); + promptWindow.Append( &msg2Txt ); - //promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50); + //promptWindow.SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_IN, 50); - HaltGui(); - mainWindow->SetState(STATE_DISABLED); - mainWindow->Append(&promptWindow); - mainWindow->ChangeFocus(&promptWindow); - //sleep(1); + HaltGui(); + mainWindow->SetState( STATE_DISABLED ); + mainWindow->Append( &promptWindow ); + mainWindow->ChangeFocus( &promptWindow ); + //sleep(1); - ///start the wad shit - bool fail = false; - wadHeader *header = NULL; - void *pvoid; - signed_blob *p_certs = NULL, *p_crl = NULL, *p_tik = NULL, *p_tmd = NULL; + ///start the wad shit + bool fail = false; + wadHeader *header = NULL; + void *pvoid; + signed_blob *p_certs = NULL, *p_crl = NULL, *p_tik = NULL, *p_tmd = NULL; - tmd *tmd_data = NULL; + tmd *tmd_data = NULL; - u32 cnt, offset = 0; - s32 ret = 666; + u32 cnt, offset = 0; + s32 ret = 666; - ResumeGui(); - msg1Txt.SetText(tr(">> Reading WAD data...")); - HaltGui(); + ResumeGui(); + msg1Txt.SetText( tr( ">> Reading WAD data..." ) ); + HaltGui(); #define SetPointer(a, p) a=(typeof(a))p - // WAD header - //ret = __Wad_ReadAlloc(fp, (void *)header, offset, sizeof(wadHeader)); - ret = __Wad_ReadAlloc(fp, &pvoid, offset, sizeof(wadHeader)); + // WAD header + //ret = __Wad_ReadAlloc(fp, (void *)header, offset, sizeof(wadHeader)); + ret = __Wad_ReadAlloc( fp, &pvoid, offset, sizeof( wadHeader ) ); - if (ret < 0) - goto err; - SetPointer(header, pvoid); - offset += round_up(header->header_len, 64); + if ( ret < 0 ) + goto err; + SetPointer( header, pvoid ); + offset += round_up( header->header_len, 64 ); - // WAD certificates - //ret = __Wad_ReadAlloc(fp, (void *)&p_certs, offset, header->certs_len); - ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->certs_len); - if (ret < 0) - goto err; - SetPointer(p_certs, pvoid); - offset += round_up(header->certs_len, 64); + // WAD certificates + //ret = __Wad_ReadAlloc(fp, (void *)&p_certs, offset, header->certs_len); + ret = __Wad_ReadAlloc( fp, &pvoid, offset, header->certs_len ); + if ( ret < 0 ) + goto err; + SetPointer( p_certs, pvoid ); + offset += round_up( header->certs_len, 64 ); - // WAD crl + // WAD crl - if (header->crl_len) { - //ret = __Wad_ReadAlloc(fp, (void *)&p_crl, offset, header->crl_len); - ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->crl_len); - if (ret < 0) - goto err; - SetPointer(p_crl, pvoid); - offset += round_up(header->crl_len, 64); - } + if ( header->crl_len ) + { + //ret = __Wad_ReadAlloc(fp, (void *)&p_crl, offset, header->crl_len); + ret = __Wad_ReadAlloc( fp, &pvoid, offset, header->crl_len ); + if ( ret < 0 ) + goto err; + SetPointer( p_crl, pvoid ); + offset += round_up( header->crl_len, 64 ); + } - // WAD ticket - //ret = __Wad_ReadAlloc(fp, (void *)&p_tik, offset, header->tik_len); - ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->tik_len); - if (ret < 0) - goto err; - SetPointer(p_tik, pvoid); - offset += round_up(header->tik_len, 64); + // WAD ticket + //ret = __Wad_ReadAlloc(fp, (void *)&p_tik, offset, header->tik_len); + ret = __Wad_ReadAlloc( fp, &pvoid, offset, header->tik_len ); + if ( ret < 0 ) + goto err; + SetPointer( p_tik, pvoid ); + offset += round_up( header->tik_len, 64 ); - // WAD TMD - //ret = __Wad_ReadAlloc(fp, (void *)&p_tmd, offset, header->tmd_len); - ret = __Wad_ReadAlloc(fp, &pvoid, offset, header->tmd_len); - if (ret < 0) - goto err; - SetPointer(p_tmd, pvoid); - offset += round_up(header->tmd_len, 64); + // WAD TMD + //ret = __Wad_ReadAlloc(fp, (void *)&p_tmd, offset, header->tmd_len); + ret = __Wad_ReadAlloc( fp, &pvoid, offset, header->tmd_len ); + if ( ret < 0 ) + goto err; + SetPointer( p_tmd, pvoid ); + offset += round_up( header->tmd_len, 64 ); - ResumeGui(); - msg1Txt.SetText(tr("Reading WAD data... Ok!")); - msg2Txt.SetText(tr(">> Installing ticket...")); - HaltGui(); - // Install ticket - ret = ES_AddTicket(p_tik, header->tik_len, p_certs, header->certs_len, p_crl, header->crl_len); - if (ret < 0) - goto err; + ResumeGui(); + msg1Txt.SetText( tr( "Reading WAD data... Ok!" ) ); + msg2Txt.SetText( tr( ">> Installing ticket..." ) ); + HaltGui(); + // Install ticket + ret = ES_AddTicket( p_tik, header->tik_len, p_certs, header->certs_len, p_crl, header->crl_len ); + if ( ret < 0 ) + goto err; - ResumeGui(); - msg2Txt.SetText(tr("Installing ticket... Ok!")); - msg3Txt.SetText(tr(">> Installing title...")); - //WindowPrompt(">> Installing title...",0,0,0,0,0,200); - HaltGui(); - // Install title - ret = ES_AddTitleStart(p_tmd, header->tmd_len, p_certs, header->certs_len, p_crl, header->crl_len); - if (ret < 0) - goto err; + ResumeGui(); + msg2Txt.SetText( tr( "Installing ticket... Ok!" ) ); + msg3Txt.SetText( tr( ">> Installing title..." ) ); + //WindowPrompt(">> Installing title...",0,0,0,0,0,200); + HaltGui(); + // Install title + ret = ES_AddTitleStart( p_tmd, header->tmd_len, p_certs, header->certs_len, p_crl, header->crl_len ); + if ( ret < 0 ) + goto err; - // Get TMD info - tmd_data = (tmd *)SIGNATURE_PAYLOAD(p_tmd); + // Get TMD info + tmd_data = ( tmd * )SIGNATURE_PAYLOAD( p_tmd ); - // Install contents - //ResumeGui(); - //HaltGui(); - promptWindow.Append(&progressbarEmptyImg); - promptWindow.Append(&progressbarImg); - promptWindow.Append(&progressbarOutlineImg); - promptWindow.Append(&prTxt); - ResumeGui(); - msg3Txt.SetText(tr("Installing title... Ok!")); - for (cnt = 0; cnt < tmd_data->num_contents; cnt++) { + // Install contents + //ResumeGui(); + //HaltGui(); + promptWindow.Append( &progressbarEmptyImg ); + promptWindow.Append( &progressbarImg ); + promptWindow.Append( &progressbarOutlineImg ); + promptWindow.Append( &prTxt ); + ResumeGui(); + msg3Txt.SetText( tr( "Installing title... Ok!" ) ); + for ( cnt = 0; cnt < tmd_data->num_contents; cnt++ ) + { - tmd_content *content = &tmd_data->contents[cnt]; + tmd_content *content = &tmd_data->contents[cnt]; - u32 idx = 0, len; - s32 cfd; - ResumeGui(); + u32 idx = 0, len; + s32 cfd; + ResumeGui(); - //printf("\r\t\t>> Installing content #%02d...", content->cid); - // Encrypted content size - len = round_up(content->size, 64); + //printf("\r\t\t>> Installing content #%02d...", content->cid); + // Encrypted content size + len = round_up( content->size, 64 ); - // Install content - cfd = ES_AddContentStart(tmd_data->title_id, content->cid); - if (cfd < 0) { - ret = cfd; - goto err; - } - snprintf(imgPath, sizeof(imgPath), "%s%d...",tr(">> Installing content #"),content->cid); - msg4Txt.SetText(imgPath); - // Install content data - while (idx < len) { + // Install content + cfd = ES_AddContentStart( tmd_data->title_id, content->cid ); + if ( cfd < 0 ) + { + ret = cfd; + goto err; + } + snprintf( imgPath, sizeof( imgPath ), "%s%d...", tr( ">> Installing content #" ), content->cid ); + msg4Txt.SetText( imgPath ); + // Install content data + while ( idx < len ) + { //VIDEO_WaitVSync (); - u32 size; + u32 size; - // Data length - size = (len - idx); - if (size > BLOCK_SIZE) - size = BLOCK_SIZE; + // Data length + size = ( len - idx ); + if ( size > BLOCK_SIZE ) + size = BLOCK_SIZE; - // Read data - ret = __Wad_ReadFile(fp, &wadBuffer, offset, size); - if (ret < 0) - goto err; + // Read data + ret = __Wad_ReadFile( fp, &wadBuffer, offset, size ); + if ( ret < 0 ) + goto err; - // Install data - ret = ES_AddContentData(cfd, wadBuffer, size); - if (ret < 0) - goto err; + // Install data + ret = ES_AddContentData( cfd, wadBuffer, size ); + if ( ret < 0 ) + goto err; - // Increase variables - idx += size; - offset += size; - - //snprintf(imgPath, sizeof(imgPath), "%s%d (%d)...",tr(">> Installing content #"),content->cid,idx); + // Increase variables + idx += size; + offset += size; - //msg4Txt.SetText(imgPath); + //snprintf(imgPath, sizeof(imgPath), "%s%d (%d)...",tr(">> Installing content #"),content->cid,idx); - prTxt.SetTextf("%i%%", 100*(cnt*len+idx)/(tmd_data->num_contents*len)); - if ((Settings.wsprompt == yes) && (CFG.widescreen)) { - progressbarImg.SetTile(78*(cnt*len+idx)/(tmd_data->num_contents*len)); - } else { - progressbarImg.SetTile(100*(cnt*len+idx)/(tmd_data->num_contents*len)); - } + //msg4Txt.SetText(imgPath); - } + prTxt.SetTextf( "%i%%", 100*( cnt*len + idx ) / ( tmd_data->num_contents*len ) ); + if ( ( Settings.wsprompt == yes ) && ( CFG.widescreen ) ) + { + progressbarImg.SetTile( 78*( cnt*len + idx ) / ( tmd_data->num_contents*len ) ); + } + else + { + progressbarImg.SetTile( 100*( cnt*len + idx ) / ( tmd_data->num_contents*len ) ); + } - // Finish content installation - ret = ES_AddContentFinish(cfd); - if (ret < 0) - goto err; - } + } - msg4Txt.SetText(tr("Installing content... Ok!")); - msg5Txt.SetText(tr(">> Finishing installation...")); + // Finish content installation + ret = ES_AddContentFinish( cfd ); + if ( ret < 0 ) + goto err; + } + + msg4Txt.SetText( tr( "Installing content... Ok!" ) ); + msg5Txt.SetText( tr( ">> Finishing installation..." ) ); - // Finish title install - ret = ES_AddTitleFinish(); - if (ret >= 0) { -// printf(" OK!\n"); - goto out; - } + // Finish title install + ret = ES_AddTitleFinish(); + if ( ret >= 0 ) + { +// printf(" OK!\n"); + goto out; + } err: - //char titties[100]; - ResumeGui(); - prTxt.SetTextf("%s%d", tr("Error..."),ret); - promptWindow.Append(&prTxt); - fail = true; - //snprintf(titties, sizeof(titties), "%d", ret); - //printf(" ERROR! (ret = %d)\n", ret); - //WindowPrompt("ERROR!",titties,"Back",0,0); - // Cancel install - ES_AddTitleCancel(); - goto exit; - //return ret; + //char titties[100]; + ResumeGui(); + prTxt.SetTextf( "%s%d", tr( "Error..." ), ret ); + promptWindow.Append( &prTxt ); + fail = true; + //snprintf(titties, sizeof(titties), "%d", ret); + //printf(" ERROR! (ret = %d)\n", ret); + //WindowPrompt("ERROR!",titties,"Back",0,0); + // Cancel install + ES_AddTitleCancel(); + goto exit; + //return ret; out: - // Free memory - if (header) - free(header); - if (p_certs) - free(p_certs); - if (p_crl) - free(p_crl); - if (p_tik) - free(p_tik); - if (p_tmd) - free(p_tmd); - goto exit; + // Free memory + if ( header ) + free( header ); + if ( p_certs ) + free( p_certs ); + if ( p_crl ) + free( p_crl ); + if ( p_tik ) + free( p_tik ); + if ( p_tmd ) + free( p_tmd ); + goto exit; exit: - if (!fail)msg5Txt.SetText(tr("Finishing installation... Ok!")); - promptWindow.Append(&btn1); - while(btn1.GetState() != STATE_CLICKED){ - } + if ( !fail )msg5Txt.SetText( tr( "Finishing installation... Ok!" ) ); + promptWindow.Append( &btn1 ); + while ( btn1.GetState() != STATE_CLICKED ) + { + } - HaltGui(); - mainWindow->Remove(&promptWindow); - mainWindow->SetState(STATE_DEFAULT); - ResumeGui(); + HaltGui(); + mainWindow->Remove( &promptWindow ); + mainWindow->SetState( STATE_DEFAULT ); + ResumeGui(); - return ret; + return ret; } -s32 Wad_Uninstall(FILE *fp) +s32 Wad_Uninstall( FILE *fp ) { - //////start the gui shit - GuiWindow promptWindow(472,320); - promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); - promptWindow.SetPosition(0, -10); + //////start the gui shit + GuiWindow promptWindow( 472, 320 ); + promptWindow.SetAlignment( ALIGN_CENTRE, ALIGN_MIDDLE ); + promptWindow.SetPosition( 0, -10 ); - GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume); - // because destroy GuiSound must wait while sound playing is finished, we use a global sound - if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); + GuiSound btnSoundOver( button_over_pcm, button_over_pcm_size, Settings.sfxvolume ); + // because destroy GuiSound must wait while sound playing is finished, we use a global sound + if ( !btnClick2 ) btnClick2 = new GuiSound( button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume ); + // GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume); - char imgPath[100]; - snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path); - GuiImageData btnOutline(imgPath, button_dialogue_box_png); - snprintf(imgPath, sizeof(imgPath), "%sdialogue_box.png", CFG.theme_path); - GuiImageData dialogBox(imgPath, dialogue_box_png); - GuiTrigger trigA; - trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); + char imgPath[100]; + snprintf( imgPath, sizeof( imgPath ), "%sbutton_dialogue_box.png", CFG.theme_path ); + GuiImageData btnOutline( imgPath, button_dialogue_box_png ); + snprintf( imgPath, sizeof( imgPath ), "%sdialogue_box.png", CFG.theme_path ); + GuiImageData dialogBox( imgPath, dialogue_box_png ); + GuiTrigger trigA; + trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); - GuiImage dialogBoxImg(&dialogBox); - if (Settings.wsprompt == yes){ - dialogBoxImg.SetWidescreen(CFG.widescreen);} + GuiImage dialogBoxImg( &dialogBox ); + if ( Settings.wsprompt == yes ) + { + dialogBoxImg.SetWidescreen( CFG.widescreen ); + } - GuiText btn1Txt(tr("OK"), 22, THEME.prompttext); - GuiImage btn1Img(&btnOutline); - if (Settings.wsprompt == yes){ - btn1Txt.SetWidescreen(CFG.widescreen); - btn1Img.SetWidescreen(CFG.widescreen);} - GuiButton btn1(&btn1Img,&btn1Img, 2, 4, 0, -55, &trigA, &btnSoundOver, btnClick2,1); - btn1.SetLabel(&btn1Txt); - btn1.SetState(STATE_SELECTED); + GuiText btn1Txt( tr( "OK" ), 22, THEME.prompttext ); + GuiImage btn1Img( &btnOutline ); + if ( Settings.wsprompt == yes ) + { + btn1Txt.SetWidescreen( CFG.widescreen ); + btn1Img.SetWidescreen( CFG.widescreen ); + } + GuiButton btn1( &btn1Img, &btn1Img, 2, 4, 0, -55, &trigA, &btnSoundOver, btnClick2, 1 ); + btn1.SetLabel( &btn1Txt ); + btn1.SetState( STATE_SELECTED ); char title[50]; - sprintf(title, "%s", tr("Uninstalling wad")); - GuiText titleTxt(title, 26, THEME.prompttext); - titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); - titleTxt.SetPosition(0,40); + sprintf( title, "%s", tr( "Uninstalling wad" ) ); + GuiText titleTxt( title, 26, THEME.prompttext ); + titleTxt.SetAlignment( ALIGN_CENTRE, ALIGN_TOP ); + titleTxt.SetPosition( 0, 40 ); - GuiText msg1Txt((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) && (CFG.widescreen)){/////////////adjust for widescreen + if ( ( Settings.wsprompt == yes ) && ( CFG.widescreen ) ) /////////////adjust for widescreen + { - msg1Txt.SetPosition(70,95); - msg2Txt.SetPosition(70, 118); - msg3Txt.SetPosition(70, 141); - msg4Txt.SetPosition(70, 164); - msg5Txt.SetPosition(70, 187); + msg1Txt.SetPosition( 70, 95 ); + msg2Txt.SetPosition( 70, 118 ); + msg3Txt.SetPosition( 70, 141 ); + msg4Txt.SetPosition( 70, 164 ); + msg5Txt.SetPosition( 70, 187 ); - } - promptWindow.Append(&dialogBoxImg); - promptWindow.Append(&titleTxt); - promptWindow.Append(&msg5Txt); - promptWindow.Append(&msg4Txt); - promptWindow.Append(&msg3Txt); - promptWindow.Append(&msg1Txt); - promptWindow.Append(&msg2Txt); + } + promptWindow.Append( &dialogBoxImg ); + promptWindow.Append( &titleTxt ); + promptWindow.Append( &msg5Txt ); + promptWindow.Append( &msg4Txt ); + promptWindow.Append( &msg3Txt ); + promptWindow.Append( &msg1Txt ); + promptWindow.Append( &msg2Txt ); - HaltGui(); - mainWindow->SetState(STATE_DISABLED); - mainWindow->Append(&promptWindow); - mainWindow->ChangeFocus(&promptWindow); - ResumeGui(); - //sleep(3); + HaltGui(); + mainWindow->SetState( STATE_DISABLED ); + mainWindow->Append( &promptWindow ); + mainWindow->ChangeFocus( &promptWindow ); + ResumeGui(); + //sleep(3); - ///start the wad shit - wadHeader *header = NULL; - void *pvoid = NULL; - tikview *viewData = NULL; + ///start the wad shit + wadHeader *header = NULL; + void *pvoid = NULL; + tikview *viewData = NULL; - u64 tid; - u32 viewCnt; - s32 ret; + u64 tid; + u32 viewCnt; + s32 ret; - msg1Txt.SetText(tr(">> Reading WAD data...")); + msg1Txt.SetText( tr( ">> Reading WAD data..." ) ); - // WAD header - ret = __Wad_ReadAlloc(fp, &pvoid, 0, sizeof(wadHeader)); - if (ret < 0) { - char errTxt[50]; - sprintf(errTxt,"%sret = %d",tr(">> Reading WAD data...ERROR! "),ret); - msg1Txt.SetText(errTxt); - //printf(" ERROR! (ret = %d)\n", ret); - goto out; - } - SetPointer(header, pvoid); + // WAD header + ret = __Wad_ReadAlloc( fp, &pvoid, 0, sizeof( wadHeader ) ); + if ( ret < 0 ) + { + char errTxt[50]; + sprintf( errTxt, "%sret = %d", tr( ">> Reading WAD data...ERROR! " ), ret ); + msg1Txt.SetText( errTxt ); + //printf(" ERROR! (ret = %d)\n", ret); + goto out; + } + SetPointer( header, pvoid ); - // Get title ID - ret = __Wad_GetTitleID(fp, header, &tid); - if (ret < 0) { - //printf(" ERROR! (ret = %d)\n", ret); - char errTxt[50]; - sprintf(errTxt,"%sret = %d",tr(">> Reading WAD data...ERROR! "),ret); - msg1Txt.SetText(errTxt); - goto out; - } + // Get title ID + ret = __Wad_GetTitleID( fp, header, &tid ); + if ( ret < 0 ) + { + //printf(" ERROR! (ret = %d)\n", ret); + char errTxt[50]; + sprintf( errTxt, "%sret = %d", tr( ">> Reading WAD data...ERROR! " ), ret ); + msg1Txt.SetText( errTxt ); + goto out; + } - msg1Txt.SetText(tr(">> Reading WAD data...Ok!")); - msg2Txt.SetText(tr(">> Deleting tickets...")); + msg1Txt.SetText( tr( ">> Reading WAD data...Ok!" ) ); + msg2Txt.SetText( tr( ">> Deleting tickets..." ) ); - // Get ticket views - ret = titles.GetTicketViews(tid, &viewData, &viewCnt); - if (ret < 0){ - char errTxt[50]; - sprintf(errTxt,"%sret = %d",tr(">> Deleting tickets...ERROR! "),ret); - msg2Txt.SetText(errTxt); - //printf(" ERROR! (ret = %d)\n", ret); - } - // Delete tickets - if (ret >= 0) { - u32 cnt; + // Get ticket views + ret = titles.GetTicketViews( tid, &viewData, &viewCnt ); + if ( ret < 0 ) + { + char errTxt[50]; + sprintf( errTxt, "%sret = %d", tr( ">> Deleting tickets...ERROR! " ), ret ); + msg2Txt.SetText( errTxt ); + //printf(" ERROR! (ret = %d)\n", ret); + } + // Delete tickets + if ( ret >= 0 ) + { + u32 cnt; - // Delete all tickets - for (cnt = 0; cnt < viewCnt; cnt++) { - ret = ES_DeleteTicket(&viewData[cnt]); - if (ret < 0) - break; - } + // Delete all tickets + for ( cnt = 0; cnt < viewCnt; cnt++ ) + { + ret = ES_DeleteTicket( &viewData[cnt] ); + if ( ret < 0 ) + break; + } - if (ret < 0){ - char errTxt[50]; - sprintf(errTxt,"%sret = %d",tr(">> Deleting tickets...ERROR! "),ret); - msg2Txt.SetText(errTxt);} - //printf(" ERROR! (ret = %d\n", ret); - else - //printf(" OK!\n"); - msg2Txt.SetText(tr(">> Deleting tickets...Ok! ")); + if ( ret < 0 ) + { + char errTxt[50]; + sprintf( errTxt, "%sret = %d", tr( ">> Deleting tickets...ERROR! " ), ret ); + msg2Txt.SetText( errTxt ); + } + //printf(" ERROR! (ret = %d\n", ret); + else + //printf(" OK!\n"); + msg2Txt.SetText( tr( ">> Deleting tickets...Ok! " ) ); - } + } - msg3Txt.SetText(tr(">> Deleting title contents...")); - //WindowPrompt(">> Deleting title contents...",0,"Back",0,0); + msg3Txt.SetText( tr( ">> Deleting title contents..." ) ); + //WindowPrompt(">> Deleting title contents...",0,"Back",0,0); - // Delete title contents - ret = ES_DeleteTitleContent(tid); - if (ret < 0){ - char errTxt[50]; - sprintf(errTxt,"%sret = %d",tr(">> Deleting title contents...ERROR! "),ret); - msg3Txt.SetText(errTxt);} - //printf(" ERROR! (ret = %d)\n", ret); - else - //printf(" OK!\n"); - msg3Txt.SetText(tr(">> Deleting title contents...Ok!")); + // Delete title contents + ret = ES_DeleteTitleContent( tid ); + if ( ret < 0 ) + { + char errTxt[50]; + sprintf( errTxt, "%sret = %d", tr( ">> Deleting title contents...ERROR! " ), ret ); + msg3Txt.SetText( errTxt ); + } + //printf(" ERROR! (ret = %d)\n", ret); + else + //printf(" OK!\n"); + msg3Txt.SetText( tr( ">> Deleting title contents...Ok!" ) ); - msg4Txt.SetText(tr(">> Deleting title...")); - // Delete title - ret = ES_DeleteTitle(tid); - if (ret < 0){ - char errTxt[50]; - sprintf(errTxt,"%sret = %d",tr(">> Deleting title ...ERROR! "),ret); - msg4Txt.SetText(errTxt);} - //printf(" ERROR! (ret = %d)\n", ret); - else - //printf(" OK!\n"); - msg4Txt.SetText(tr(">> Deleting title ...Ok!")); + msg4Txt.SetText( tr( ">> Deleting title..." ) ); + // Delete title + ret = ES_DeleteTitle( tid ); + if ( ret < 0 ) + { + char errTxt[50]; + sprintf( errTxt, "%sret = %d", tr( ">> Deleting title ...ERROR! " ), ret ); + msg4Txt.SetText( errTxt ); + } + //printf(" ERROR! (ret = %d)\n", ret); + else + //printf(" OK!\n"); + msg4Txt.SetText( tr( ">> Deleting title ...Ok!" ) ); out: - // Free memory - if (header) - free(header); + // Free memory + if ( header ) + free( header ); - goto exit; + goto exit; exit: - msg5Txt.SetText(tr("Done!")); - promptWindow.Append(&btn1); - while(btn1.GetState() != STATE_CLICKED){ - } + msg5Txt.SetText( tr( "Done!" ) ); + promptWindow.Append( &btn1 ); + while ( btn1.GetState() != STATE_CLICKED ) + { + } - HaltGui(); - mainWindow->Remove(&promptWindow); - mainWindow->SetState(STATE_DEFAULT); - ResumeGui(); + HaltGui(); + mainWindow->Remove( &promptWindow ); + mainWindow->SetState( STATE_DEFAULT ); + ResumeGui(); - return ret; + return ret; } diff --git a/source/wad/wad.h b/source/wad/wad.h index f65edf64..672283c4 100644 --- a/source/wad/wad.h +++ b/source/wad/wad.h @@ -3,9 +3,9 @@ /* Prototypes */ -#define BLOCK_SIZE 1024 +#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 e4050e11..64631390 100644 --- a/source/wpad.c +++ b/source/wpad.c @@ -6,61 +6,69 @@ #include "wpad.h" /* Constants */ -#define MAX_WIIMOTES 4 +#define MAX_WIIMOTES 4 extern u8 shutdown; -void __Wpad_PowerCallback(s32 chan) { +void __Wpad_PowerCallback( s32 chan ) +{ /* Poweroff console */ shutdown = 1; } -void WPad_SetIdleTime(u32 seconds) { +void WPad_SetIdleTime( u32 seconds ) +{ /*Set idle time for wiimote*/ - WPAD_SetIdleTimeout(seconds); + WPAD_SetIdleTimeout( seconds ); } -s32 Wpad_Init(void) { +s32 Wpad_Init( void ) +{ s32 ret; /* Initialize Wiimote subsystem */ ret = WPAD_Init(); - if (ret < 0) + if ( ret < 0 ) return ret; /* Set POWER button callback */ - WPAD_SetPowerButtonCallback(__Wpad_PowerCallback); + WPAD_SetPowerButtonCallback( __Wpad_PowerCallback ); return ret; } -void Wpad_Disconnect(void) { +void Wpad_Disconnect( void ) +{ u32 cnt; /* Disconnect Wiimotes */ - for (cnt = 0; cnt < MAX_WIIMOTES; cnt++) - WPAD_Disconnect(cnt); + for ( cnt = 0; cnt < MAX_WIIMOTES; cnt++ ) + WPAD_Disconnect( cnt ); /* Shutdown Wiimote subsystem */ WPAD_Shutdown(); } -bool IsWpadConnected() { +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) { + for ( i = 0; i < 4; i++ ) + { + if ( WPAD_Probe( i, &test ) == WPAD_ERR_NO_CONTROLLER ) + { notconnected++; } } - if (notconnected < 4) + if ( notconnected < 4 ) return true; else return false; } -u32 ButtonsHold(void) { +u32 ButtonsHold( void ) +{ int i; u32 buttons = 0; @@ -68,49 +76,52 @@ u32 ButtonsHold(void) { 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) - ) - */ - -} + 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) + ) + */ + +} diff --git a/source/wpad.h b/source/wpad.h index c054d83a..ba6b7ef1 100644 --- a/source/wpad.h +++ b/source/wpad.h @@ -4,16 +4,17 @@ #include #ifdef __cplusplus -extern "C" { -#endif +extern "C" +{ +#endif /* Prototypes */ - s32 Wpad_Init(void); - void Wpad_Disconnect(void); - u32 ButtonsPressed(void); - u32 ButtonsHold(void); - bool IsWpadConnected(); - void WPad_SetIdleTime(u32 seconds); + s32 Wpad_Init( void ); + void Wpad_Disconnect( void ); + u32 ButtonsPressed( void ); + u32 ButtonsHold( void ); + bool IsWpadConnected(); + void WPad_SetIdleTime( u32 seconds ); #ifdef __cplusplus } diff --git a/source/wstring.cpp b/source/wstring.cpp index 939b94a2..86dda7c8 100644 --- a/source/wstring.cpp +++ b/source/wstring.cpp @@ -3,166 +3,167 @@ 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; + 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]; + size = s.size(); + 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; + 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]; - return *this; + size = s.size(); + 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 ((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)); - i += 4; - } - 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)); - i += 3; - } - else if ((s[i] & 0xE0) == 0xC0) - { - push_back(((wchar_t)(s[i] & 0x1F) << 6) | (wchar_t)(s[i + 1] & 0x3F)); - i += 2; - } - else - { - push_back((wchar_t)s[i]); - ++i; - } - } -} - -string wString::toUTF8(void) const -{ - string s; - size_t len = 0; - wchar_t wc; - - for (size_t i = 0; i < size(); ++i) - { - wc = operator[](i); - if (wc < 0x80) - ++len; - else if (wc < 0x800) - len += 2; - else if (wc < 0x10000) - len += 3; - else - len += 4; - } - 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) - { - s.push_back((char)((wc >> 6) | 0xC0)); - s.push_back((char)((wc & 0x3F) | 0x80)); - } - 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)); - } - 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)); - } - } - return s; -} - -size_t utf8Len(const char *s) -{ - size_t len = 0; - - for (int i = 0; s[i] != 0; ) - { - if ((s[i] & 0xF8) == 0xF0) - { - 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) - { - if (((s[i + 1] & 0xC0) != 0x80) || ((s[i + 2] & 0xC0) != 0x80)) - return 0; - ++len; - i += 3; - } - else if ((s[i] & 0xE0) == 0xC0) - { - if (((s[i + 1] & 0xC0) != 0x80)) - return 0; - ++len; - i += 2; - } - else if ((s[i] & 0x80) == 0x00) - { - ++len; - ++i; - } - else - return 0; - } - return len; -} - -int wcsnicmp(const wchar_t *s1, const wchar_t *s2, int len) -{ - if (len <= 0) - return (0); - - do + clear(); + if ( len == 0 ) + return; + reserve( len ); + for ( int i = 0; s[i] != 0; ) { - int r = towupper(*s1) - towupper(*s2++); - if (r) return r; - if (*s1++ == 0) - break; - } while (--len != 0); - - return (0); + 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 ) ); + i += 4; + } + 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 ) ); + i += 3; + } + else if ( ( s[i] & 0xE0 ) == 0xC0 ) + { + push_back( ( ( wchar_t )( s[i] & 0x1F ) << 6 ) | ( wchar_t )( s[i + 1] & 0x3F ) ); + i += 2; + } + else + { + push_back( ( wchar_t )s[i] ); + ++i; + } + } +} + +string wString::toUTF8( void ) const +{ + string s; + size_t len = 0; + wchar_t wc; + + for ( size_t i = 0; i < size(); ++i ) + { + wc = operator[]( i ); + if ( wc < 0x80 ) + ++len; + else if ( wc < 0x800 ) + len += 2; + else if ( wc < 0x10000 ) + len += 3; + else + len += 4; + } + 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 ) + { + s.push_back( ( char )( ( wc >> 6 ) | 0xC0 ) ); + s.push_back( ( char )( ( wc & 0x3F ) | 0x80 ) ); + } + 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 ) ); + } + 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 ) ); + } + } + return s; +} + +size_t utf8Len( const char *s ) +{ + size_t len = 0; + + for ( int i = 0; s[i] != 0; ) + { + if ( ( s[i] & 0xF8 ) == 0xF0 ) + { + 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 ) + { + if ( ( ( s[i + 1] & 0xC0 ) != 0x80 ) || ( ( s[i + 2] & 0xC0 ) != 0x80 ) ) + return 0; + ++len; + i += 3; + } + else if ( ( s[i] & 0xE0 ) == 0xC0 ) + { + if ( ( ( s[i + 1] & 0xC0 ) != 0x80 ) ) + return 0; + ++len; + i += 2; + } + else if ( ( s[i] & 0x80 ) == 0x00 ) + { + ++len; + ++i; + } + else + return 0; + } + return len; +} + +int wcsnicmp( const wchar_t *s1, const wchar_t *s2, int len ) +{ + if ( len <= 0 ) + return ( 0 ); + + do + { + int r = towupper( *s1 ) - towupper( *s2++ ); + if ( r ) return r; + if ( *s1++ == 0 ) + break; + } + while ( --len != 0 ); + + return ( 0 ); } diff --git a/source/xml/xml.c b/source/xml/xml.c index d9b287f5..6d6b4836 100644 --- a/source/xml/xml.c +++ b/source/xml/xml.c @@ -12,8 +12,8 @@ Load game information from XML - Lustar //#include "xml.h" extern struct SSettings Settings; // for loader GX -extern void title_set(char *id, char *title); -extern char* trimcopy(char *dest, char *src, int size); +extern void title_set( char *id, char *title ); +extern char* trimcopy( char *dest, char *src, int size ); extern char game_partition[6]; @@ -53,137 +53,161 @@ static char langcodes[11][5] = {{""}, }; static char element_text[5000]; -static mxml_node_t *nodetree=NULL; -static mxml_node_t *nodedata=NULL; -static mxml_node_t *nodeid=NULL; -static mxml_node_t *nodeidtmp=NULL; -static mxml_node_t *nodefound=NULL; -static mxml_index_t *nodeindex=NULL; -static mxml_index_t *nodeindextmp=NULL; +static mxml_node_t *nodetree = NULL; +static mxml_node_t *nodedata = NULL; +static mxml_node_t *nodeid = NULL; +static mxml_node_t *nodeidtmp = NULL; +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) { - if (!xml_loaded) { +bool OpenXMLDatabase( char* xmlfilepath, char* argdblang, bool argJPtoEN, bool openfile, bool loadtitles, bool keepopen ) +{ + 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), "%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 ), "%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 ); } - if (!opensuccess && openfile) { + if ( !opensuccess && openfile ) + { CloseXMLDatabase(); return false; } - 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(); + } + else + { + if ( loadtitles ) LoadTitlesFromXML( argdblang, argJPtoEN ); + if ( !keepopen ) CloseXMLDatabase(); + } return true; } -void CloseXMLDatabase() { +void CloseXMLDatabase() +{ /* free memory */ - if (xml_loaded) { - mxmlDelete(nodedata); - mxmlDelete(nodetree); + if ( xml_loaded ) + { + mxmlDelete( nodedata ); + mxmlDelete( nodetree ); xml_loaded = false; } } -void GetTextFromNode(mxml_node_t *currentnode, mxml_node_t *topnode, char *nodename, - char *attributename, char *value, int descend, char *dest, int destsize) { +void GetTextFromNode( mxml_node_t *currentnode, mxml_node_t *topnode, char *nodename, + char *attributename, char *value, int descend, char *dest, int destsize ) +{ *element_text = 0; - nodefound = mxmlFindElement(currentnode, topnode, nodename, attributename, value, descend); - if (nodefound != NULL) { - if (attributename != NULL) { - strlcpy(dest,mxmlElementGetAttr(nodefound, attributename),destsize); - } else { - get_nodetext(nodefound, element_text, sizeof(element_text)); - strlcpy(dest,element_text,destsize); + nodefound = mxmlFindElement( currentnode, topnode, nodename, attributename, value, descend ); + if ( nodefound != NULL ) + { + if ( attributename != NULL ) + { + strlcpy( dest, mxmlElementGetAttr( nodefound, attributename ), destsize ); } - } else { - strcpy(dest,""); + else + { + get_nodetext( nodefound, element_text, sizeof( element_text ) ); + strlcpy( dest, element_text, destsize ); + } + } + else + { + strcpy( dest, "" ); } } -bool OpenXMLFile(char *filename) { +bool OpenXMLFile( char *filename ) +{ //if (xmldebug) dbg_time1(); - if (xml_loaded) + if ( xml_loaded ) return false; gameinfo = gameinfo_reset; - nodedata=NULL; - nodetree=NULL; - nodeid=NULL; - nodeidtmp=NULL; - nodefound=NULL; + nodedata = NULL; + nodetree = NULL; + nodeid = NULL; + 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) + 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 { + } + else + { /* load zipped XML file */ - unzFile unzfile = unzOpen(filename); - if (unzfile == NULL) + unzFile unzfile = unzOpen( filename ); + if ( unzfile == NULL ) return false; - unzOpenCurrentFile(unzfile); + 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) { - unzCloseCurrentFile(unzfile); - unzClose(unzfile); + if ( zipfilebuffersize >= xmlmaxsize ) + { + unzCloseCurrentFile( unzfile ); + unzClose( unzfile ); return false; } - char * zipfilebuffer = malloc(zipfilebuffersize); - memset(zipfilebuffer, 0, zipfilebuffersize); - if (zipfilebuffer == NULL) { - unzCloseCurrentFile(unzfile); - unzClose(unzfile); + char * zipfilebuffer = malloc( zipfilebuffersize ); + memset( zipfilebuffer, 0, zipfilebuffersize ); + if ( zipfilebuffer == NULL ) + { + 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) + 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; - } else { - //if (xmldebug) xmlloadtime = dbg_time2(NULL); + } + else + { + //if (xmldebug) xmlloadtime = dbg_time2(NULL); xml_loaded = true; return true; } @@ -191,13 +215,17 @@ 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; - } else { + } + else + { //langcode = CFG.language; // for Configurable Loader langcode = Settings.language; // for Loader GX } @@ -207,352 +235,406 @@ char *GetLangSettingFromGame(char *gameid) { /* convert language text into ISO 639 two-letter language code (+ZHTW/ZHCN) */ -char *ConvertLangTextToCode(char *languagetxt) { - // do not convert if languagetext seems to be a language code (can be 2 or 4 letters) - if (strlen(languagetxt) <= 4) - return languagetxt; +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; int i; - for (i=0;i<=10;i++) { - if (!strcasecmp(languagetxt,langlist[i])) // case insensitive comparison + for ( i = 0; i <= 10; 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, char *torating, char *destvalue, int destsize) { - if (!strcmp(fromrating,torating)) { - strlcpy(destvalue,ratingvalue,destsize); +void ConvertRating( char *ratingvalue, char *fromrating, char *torating, char *destvalue, int destsize ) +{ + if ( !strcmp( fromrating, torating ) ) + { + strlcpy( destvalue, ratingvalue, destsize ); return; } - strcpy(destvalue,""); + strcpy( destvalue, "" ); int type = -1; int desttype = -1; - type = ConvertRatingToIndex(fromrating); - desttype = ConvertRatingToIndex(torating); - if (type == -1 || desttype == -1) + type = ConvertRatingToIndex( fromrating ); + desttype = ConvertRatingToIndex( 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][4] = { - {{"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][4] = + { + {{"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++) { - if (!strcmp(ratingtable[i][type],ratingvalue)) { - strlcpy(destvalue,ratingtable[i][desttype],destsize); + for ( i = 0; i <= 11; i++ ) + { + if ( !strcmp( ratingtable[i][type], ratingvalue ) ) + { + 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) + if ( nodedata == NULL ) return; bool forcelang = false; - if (strcmp(langtxt,"")) + 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) { - nodeid = mxmlIndexFind(nodeindex,"id", NULL); - if (nodeid != NULL) { - strcpy(title_text,""); - strcpy(title_text_EN,""); + while ( nodeid != NULL ) + { + nodeid = mxmlIndexFind( nodeindex, "id", NULL ); + if ( nodeid != NULL ) + { + 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) { - langtxt = GetLangSettingFromGame(id_text); - strcpy(langcode,ConvertLangTextToCode(langtxt)); + if ( !forcelang ) + { + 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) { - GetTextFromNode(nodefound, nodedata, "title", NULL, NULL, MXML_DESCEND, title_text_EN,sizeof(title_text_EN)); + 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 ) ); } - 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)); + 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 ) ); } /* fall back to English title if prefered language was not found */ - if (!strcmp(title_text,"")) { - strcpy(title_text,title_text_EN); + if ( !strcmp( title_text, "" ) ) + { + 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; + *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) { - nodeidtmp = mxmlIndexFind(nodeindextmp,"company", NULL); - if (nodeidtmp != NULL) { - strlcpy(element_text,mxmlElementGetAttr(nodeidtmp, "code"),sizeof(element_text)); - } else { + while ( strcmp( element_text, publishercode ) != 0 ) + { + nodeidtmp = mxmlIndexFind( nodeindextmp, "company", NULL ); + if ( nodeidtmp != NULL ) + { + strlcpy( element_text, mxmlElementGetAttr( nodeidtmp, "code" ), sizeof( element_text ) ); + } + else + { break; } } - if (!strcmp(element_text,publishercode)) { - strlcpy(dest,mxmlElementGetAttr(nodeidtmp, "name"),destsize); - } else { - strcpy(dest,""); + if ( !strcmp( element_text, publishercode ) ) + { + strlcpy( dest, mxmlElementGetAttr( nodeidtmp, "name" ), destsize ); + } + else + { + 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) + bool exist = false; + 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) { - nodeid = mxmlIndexFind(nodeindex,"id", NULL); - if (nodeid != NULL) { - get_nodetext(nodeid, element_text, sizeof(element_text)); - if (!strcmp(element_text,gameid)) { + while ( 1 ) + { + nodeid = mxmlIndexFind( nodeindex, "id", NULL ); + if ( nodeid != NULL ) + { + get_nodetext( nodeid, element_text, sizeof( element_text ) ); + if ( !strcmp( element_text, gameid ) ) + { break; } - } else { + } + else + { break; } } - 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) { - 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", "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 ) ); } - 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)); + 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 ) ); } // fall back to English title and synopsis if prefered language was not found - if (!strcmp(gameinfo.title,"")) { - strlcpy(gameinfo.title,gameinfo.title_EN,sizeof(gameinfo.title)); + if ( !strcmp( gameinfo.title, "" ) ) + { + strlcpy( gameinfo.title, gameinfo.title_EN, sizeof( gameinfo.title ) ); } - if (!strcmp(gameinfo.synopsis,"")) { - strlcpy(gameinfo.synopsis,gameinfo.synopsis_EN,sizeof(gameinfo.synopsis)); + if ( !strcmp( 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) { - nodefound = mxmlFindElement(nodefound, nodedata, "locale", "lang", NULL, MXML_NO_DESCEND); + 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 ); } } } /* 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) { - nodeidtmp = mxmlIndexFind(nodeindextmp,"feature", NULL); - if (nodeidtmp != NULL) { + nodeindextmp = mxmlIndexNew( nodefound, "feature", NULL ); + nodeidtmp = mxmlIndexReset( nodeindextmp ); + while ( 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) + 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) { - gameinfo.descriptorCnt=0; - nodeindextmp = mxmlIndexNew(nodefound,"descriptor", NULL); - nodeidtmp = mxmlIndexReset(nodeindextmp); - while (nodeidtmp != NULL) { - nodeidtmp = mxmlIndexFind(nodeindextmp,"descriptor", NULL); - if (nodeidtmp != 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 ) + { + 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) + 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) { - gameinfo.accessoryCnt=0; - gameinfo.accessoryReqCnt=0; - nodeindextmp = mxmlIndexNew(nodefound,"control", NULL); - nodeidtmp = mxmlIndexReset(nodeindextmp); - while (nodeidtmp != NULL) { - nodeidtmp = mxmlIndexFind(nodeindextmp,"control", NULL); - if (nodeidtmp != NULL) { - if (!strcmp(mxmlElementGetAttr(nodeidtmp, "required"),"true") && gameinfo.accessoryReqCnt < XML_ELEMMAX) { + 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 ) + { + nodeidtmp = mxmlIndexFind( nodeindextmp, "control", NULL ); + if ( nodeidtmp != NULL ) + { + 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])); - } else if (gameinfo.accessoryCnt < XML_ELEMMAX) { + strlcpy( gameinfo.accessoriesReq[gameinfo.accessoryReqCnt], mxmlElementGetAttr( nodeidtmp, "type" ), + sizeof( gameinfo.accessoriesReq[gameinfo.accessoryReqCnt] ) ); + } + 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) { - gameinfo.genreCnt=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) { - splitresult = strtok(NULL, delimgenre); - if (splitresult != NULL && strcmp(splitresult,"")!=0) { + 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 ) + { ++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) + 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; } } @@ -560,94 +642,108 @@ bool LoadGameInfoFromXML(char* gameid, char* langtxt) } - exist=true; - } else { + exist = true; + } + else + { /*game not found */ - exist=false; + exist = false; } // if game was not found or info is missing // guess publisher from game id in case it is missing - if (!strcmp(gameinfo.publisher,"")) { - GetPublisherFromGameid(gameid,gameinfo.publisherfromid,sizeof(gameinfo.publisherfromid)); - strlcpy(gameinfo.publisher,gameinfo.publisherfromid,sizeof(gameinfo.publisher)); + if ( !strcmp( 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 (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 ( !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 ) ); } // free memory - mxmlIndexDelete(nodeindex); + mxmlIndexDelete( nodeindex ); return exist; } -void PrintGameInfo(bool showfullinfo) { - if (showfullinfo) { +void PrintGameInfo( bool showfullinfo ) +{ + if ( showfullinfo ) + { //Con_Clear(); //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(" %s",gameinfo.locales[i]); + printf( "languages:" ); + for ( i = 1; strcmp( gameinfo.locales[i], "" ) != 0; 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(" %s",gameinfo.ratingdescriptors[i]); + printf( "content descriptors:" ); + for ( i = 1; strcmp( gameinfo.wififeatures[i], "" ) != 0; 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(" %s",gameinfo.wififeatures[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("\n"); - printf("required accessories:"); - for (i=1;strcmp(gameinfo.accessoriesReq[i],"") != 0;i++) { - printf(" %s",gameinfo.accessoriesReq[i]); + printf( "\n" ); + printf( "required accessories:" ); + for ( i = 1; strcmp( gameinfo.accessoriesReq[i], "" ) != 0; i++ ) + { + printf( " %s", gameinfo.accessoriesReq[i] ); } - printf("\n"); - printf("accessories:"); - for (i=1;strcmp(gameinfo.accessories[i],"") != 0;i++) { - printf(" %s",gameinfo.accessories[i]); + printf( "\n" ); + printf( "accessories:" ); + for ( i = 1; strcmp( gameinfo.accessories[i], "" ) != 0; 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); - } else { + } + else + { char linebuf[1000] = ""; - if (xmldebug) { + if ( xmldebug ) + { //char xmltime[100]; //sprintf(xmltime,"%d",xmlloadtime); //printf("xml load time: %s\n",xmltime); @@ -659,57 +755,61 @@ void PrintGameInfo(bool showfullinfo) { sprintf(xmljptoen,"%d",CFG.db_JPtoEN); printf("xml JPtoEN: %s\n",xmljptoen); */ - printf(MemInfo()); // guidebug + 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) { - 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.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 ); } - 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); + 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 ); } - printf("%s\n",linebuf); - strcpy(linebuf,""); + printf( "%s\n", linebuf ); + strcpy( linebuf, "" ); } } -char *MemInfo() { +char *MemInfo() +{ char linebuf[300] = ""; char memtotal[20]; char memused[20]; 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; @@ -719,64 +819,75 @@ char *MemInfo() { /*-------------------------------------------------------------------------------------*/ /* 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 *ptr, *end; /* Pointer into buffer, End of buffer */ - int len; /* Length of node */ - mxml_node_t *current; /* Current node */ +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 */ ptr = buffer; end = buffer + buflen - 1; - for (current = node->child; current && ptr < end; current = current->next) { - if (current->type == MXML_TEXT) { - if (current->value.text.whitespace) + for ( current = node->child; current && ptr < end; current = current->next ) + { + 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); + 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) { - len = (int)strlen(current->value.opaque); - if (len > (int)(end - ptr)) - len = (int)(end - ptr); - memcpy(ptr, current->value.opaque, len); + } + 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 ); ptr += len; } } *ptr = '\0'; - return (buffer); + return ( buffer ); } -int GetRatingForGame(char *gameid) +int GetRatingForGame( char *gameid ) { - int retval=-1; - if (!xml_loaded || nodedata == NULL) + int retval = -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) { - nodeid = mxmlIndexFind(nodeindex,"id", NULL); - if (nodeid != NULL) { - get_nodetext(nodeid, element_text, sizeof(element_text)); - if (!strcmp(element_text,gameid)) { + while ( 1 ) + { + nodeid = mxmlIndexFind( nodeindex, "id", NULL ); + if ( nodeid != NULL ) + { + get_nodetext( nodeid, element_text, sizeof( element_text ) ); + if ( !strcmp( element_text, gameid ) ) + { break; } - } else { + } + else + { break; } } - if (!strcmp(element_text,gameid)) { - char type[5], value[5], dest[5]; + 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); - } - return retval; + retval = atoi( dest ); + } + return retval; } diff --git a/source/xml/xml.h b/source/xml/xml.h index 7b93a3e2..1b2b3065 100644 --- a/source/xml/xml.h +++ b/source/xml/xml.h @@ -6,18 +6,20 @@ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif // 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 { + struct gameXMLinfo + { char id[7]; char version[50]; char region[7]; @@ -56,17 +58,17 @@ extern "C" { char iso_sha1[41]; } ; - bool OpenXMLFile(char* filename); - void LoadTitlesFromXML(char *langcode, bool forcejptoen); - void GetPublisherFromGameid(char *idtxt, char *dest, int destsize); - char *ConvertLangTextToCode(char *langtext); - void ConvertRating(char *ratingvalue, char *fromrating, char *torating, char *destvalue, int destsize); - void PrintGameInfo(bool showfullinfo); + bool OpenXMLFile( char* filename ); + void LoadTitlesFromXML( char *langcode, bool forcejptoen ); + void GetPublisherFromGameid( char *idtxt, char *dest, int destsize ); + char *ConvertLangTextToCode( char *langtext ); + void ConvertRating( char *ratingvalue, char *fromrating, char *torating, char *destvalue, int destsize ); + void PrintGameInfo( bool showfullinfo ); char *MemInfo(); - void GetTextFromNode(mxml_node_t *currentnode, mxml_node_t *topnode, char *nodename, - char *attributename, char *value, int descend, char *dest, int destsize); - int GetRatingForGame(char *gameid); - char * get_nodetext(mxml_node_t *node, char *buffer, int buflen); + void GetTextFromNode( mxml_node_t *currentnode, mxml_node_t *topnode, char *nodename, + char *attributename, char *value, int descend, char *dest, int destsize ); + int GetRatingForGame( char *gameid ); + char * get_nodetext( mxml_node_t *node, char *buffer, int buflen ); #ifdef __cplusplus }