1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
|
/*
* Copyright (c) 1999-2010 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/*
File: makehfs.c
Contains: Initialization code for HFS and HFS Plus volumes.
Copyright: � 1984-1999 by Apple Computer, Inc., all rights reserved.
*/
#include <sys/param.h>
#include <sys/types.h>
#include <sys/time.h>
#if LINUX
#include <time.h>
#include "missing.h"
#endif
#include <sys/errno.h>
#include <sys/stat.h>
#include <linux/sysctl.h>
#if !LINUX
#include <sys/vmmeter.h>
#endif
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <paths.h>
#include <pwd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#if !LINUX
#include <wipefs.h>
#endif
/*
* CommonCrypto is meant to be a more stable API than OpenSSL.
* Defining COMMON_DIGEST_FOR_OPENSSL gives API-compatibility
* with OpenSSL, so we don't have to change the code.
*/
#define COMMON_DIGEST_FOR_OPENSSL
#if !LINUX
#include <CommonCrypto/CommonDigest.h>
#include <libkern/OSByteOrder.h>
#include <CoreFoundation/CFString.h>
#include <CoreFoundation/CFStringEncodingExt.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/storage/IOMedia.h>
#include <TargetConditionals.h>
extern Boolean _CFStringGetFileSystemRepresentation(CFStringRef string, UInt8 *buffer, CFIndex maxBufLen);
#else
#include <openssl/sha.h>
#endif
#include <hfs/hfs_format.h>
#include <hfs/hfs_mount.h>
#include "hfs_endian.h"
#include "newfs_hfs.h"
#include "readme.h"
#define HFS_BOOT_DATA "/usr/share/misc/hfsbootdata"
#define HFS_JOURNAL_FILE ".journal"
#define HFS_JOURNAL_INFO ".journal_info_block"
#define kJournalFileType 0x6a726e6c /* 'jrnl' */
typedef HFSMasterDirectoryBlock HFS_MDB;
struct filefork {
UInt16 startBlock;
UInt16 blockCount;
UInt32 logicalSize;
UInt32 physicalSize;
};
struct filefork gDTDBFork, gSystemFork, gReadMeFork;
static void WriteMDB __P((const DriveInfo *driveInfo, HFS_MDB *mdbp));
static void InitMDB __P((hfsparams_t *defaults, UInt32 driveBlocks, HFS_MDB *mdbp));
static void WriteVH __P((const DriveInfo *driveInfo, HFSPlusVolumeHeader *hp));
static void InitVH __P((hfsparams_t *defaults, UInt64 sectors,
HFSPlusVolumeHeader *header));
static void WriteBitmap __P((const DriveInfo *dip, UInt32 startingSector,
UInt32 alBlksUsed, UInt8 *buffer));
static void AllocateExtent(UInt8 *buffer, UInt32 startBlock, UInt32 blockCount);
static void WriteExtentsFile __P((const DriveInfo *dip, UInt64 startingSector,
const hfsparams_t *dp, HFSExtentDescriptor *bbextp, void *buffer,
UInt32 *bytesUsed, UInt32 *mapNodes));
static void InitExtentsRoot __P((UInt16 btNodeSize, HFSExtentDescriptor *bbextp,
void *buffer));
static void WriteAttributesFile(const DriveInfo *driveInfo, UInt64 startingSector,
const hfsparams_t *dp, HFSExtentDescriptor *bbextp, void *buffer,
UInt32 *bytesUsed, UInt32 *mapNodes);
static void WriteCatalogFile __P((const DriveInfo *dip, UInt64 startingSector,
const hfsparams_t *dp, HFSPlusVolumeHeader *header, void *buffer,
UInt32 *bytesUsed, UInt32 *mapNodes));
static int WriteJournalInfo(const DriveInfo *driveInfo, UInt64 startingSector,
const hfsparams_t *dp, HFSPlusVolumeHeader *header,
void *buffer);
static void InitCatalogRoot_HFSPlus __P((const hfsparams_t *dp, const HFSPlusVolumeHeader *header, void * buffer));
static void InitCatalogRoot_HFS __P((const hfsparams_t *dp, void * buffer));
static void InitFirstCatalogLeaf __P((const hfsparams_t *dp, void * buffer,
int wrapper));
static void InitSecondCatalogLeaf __P((const hfsparams_t *dp, void *buffer));
static void WriteDesktopDB(const hfsparams_t *dp, const DriveInfo *driveInfo,
UInt32 startingSector, void *buffer, UInt32 *mapNodes);
static void WriteSystemFile __P((const DriveInfo *dip, UInt32 startingSector,
UInt32 *filesize));
static void WriteReadMeFile __P((const DriveInfo *dip, UInt32 startingSector,
UInt32 *filesize));
static void WriteMapNodes __P((const DriveInfo *driveInfo, UInt64 diskStart,
UInt32 firstMapNode, UInt32 mapNodes, UInt16 btNodeSize, void *buffer));
static void WriteBuffer __P((const DriveInfo *driveInfo, UInt64 startingSector,
UInt64 byteCount, const void *buffer));
static UInt32 Largest __P((UInt32 a, UInt32 b, UInt32 c, UInt32 d ));
static void MarkBitInAllocationBuffer __P((HFSPlusVolumeHeader *header,
UInt32 allocationBlock, void* sectorBuffer, UInt64 *sector));
#if !LINUX
static UInt32 GetDefaultEncoding();
#endif
static UInt32 UTCToLocal __P((UInt32 utcTime));
static UInt32 DivideAndRoundUp __P((UInt32 numerator, UInt32 denominator));
static int ConvertUTF8toUnicode __P((const UInt8* source, size_t bufsize,
UniChar* unibuf, UInt16 *charcount));
static int getencodinghint(unsigned char *name);
#define VOLUMEUUIDVALUESIZE 2
typedef union VolumeUUID {
UInt32 value[VOLUMEUUIDVALUESIZE];
struct {
UInt32 high;
UInt32 low;
} v;
} VolumeUUID;
void GenerateVolumeUUID(VolumeUUID *newVolumeID);
void SETOFFSET (void *buffer, UInt16 btNodeSize, SInt16 recOffset, SInt16 vecOffset);
#define SETOFFSET(buf,ndsiz,offset,rec) \
(*(SInt16 *)((UInt8 *)(buf) + (ndsiz) + (-2 * (rec))) = (SWAP_BE16 (offset)))
#define BYTESTOBLKS(bytes,blks) DivideAndRoundUp((bytes),(blks))
#define ROUNDUP(x, u) (((x) % (u) == 0) ? (x) : ((x)/(u) + 1) * (u))
#if LINUX
#define ENCODING_TO_BIT(e) (e)
#else
#if TARGET_OS_EMBEDDED
#define ENCODING_TO_BIT(e) \
((e) < 48 ? (e) : 0)
#else
#define ENCODING_TO_BIT(e) \
((e) < 48 ? (e) : \
((e) == kCFStringEncodingMacUkrainian ? 48 : \
((e) == kCFStringEncodingMacFarsi ? 49 : 0)))
#endif
#endif
#if !LINUX
/*
* wipefs() in -lutil knows about multiple filesystem formats.
* This replaces the code:
* WriteBuffer(driveInfo, 0, diskBlocksUsed * kBytesPerSector, NULL);
* WriteBuffer(driveInfo, driveInfo->totalSectors - 8, 4 * 1024, NULL);
* which was used to erase the beginning and end of the filesystem.
*
*/
static int
dowipefs(int fd)
{
int err;
wipefs_ctx handle;
err = wipefs_alloc(fd, 0/*sectorSize*/, &handle);
if (err == 0) {
err = wipefs_wipe(handle);
}
wipefs_free(&handle);
return err;
}
#endif
/*
* make_hfs
*
* This routine writes an initial HFS volume structure onto a volume.
* It is assumed that the disk has already been formatted and verified.
*
* For information on the HFS volume format see "Data Organization on Volumes"
* in "Inside Macintosh: Files" (p. 2-52).
*
*/
int
make_hfs(const DriveInfo *driveInfo,
hfsparams_t *defaults,
UInt32 *plusSectors,
UInt32 *plusOffset)
{
UInt32 sector;
UInt32 diskBlocksUsed;
UInt32 mapNodes;
UInt32 sectorsPerBlock;
void *nodeBuffer = NULL;
HFS_MDB *mdbp = NULL;
UInt32 bytesUsed;
*plusSectors = 0;
*plusOffset = 0;
/* assume sectorSize <= blockSize */
sectorsPerBlock = defaults->blockSize / driveInfo->sectorSize;
/*--- CREATE A MASTER DIRECTORY BLOCK: */
mdbp = (HFS_MDB*)malloc((size_t)kBytesPerSector);
nodeBuffer = malloc(8192); /* max bitmap bytes is 8192 bytes */
if (nodeBuffer == NULL || mdbp == NULL)
err(1, NULL);
defaults->encodingHint = getencodinghint(defaults->volumeName);
/* MDB Initialized in native byte order */
InitMDB(defaults, driveInfo->totalSectors, mdbp);
/*--- ZERO OUT BEGINNING OF DISK (bitmap and b-trees): */
diskBlocksUsed = (mdbp->drAlBlSt + 1) +
(mdbp->drXTFlSize + mdbp->drCTFlSize) / kBytesPerSector;
if (defaults->flags & kMakeHFSWrapper) {
diskBlocksUsed += MAX(kDTDB_Size, mdbp->drAlBlkSiz) / kBytesPerSector;
diskBlocksUsed += MAX(sizeof(hfswrap_readme), mdbp->drAlBlkSiz) / kBytesPerSector;
diskBlocksUsed += MAX(24 * 1024, mdbp->drAlBlkSiz) / kBytesPerSector;
}
WriteBuffer(driveInfo, 0, diskBlocksUsed * kBytesPerSector, NULL);
/* also clear out last 8 sectors (4K) */
WriteBuffer(driveInfo, driveInfo->totalSectors - 8, 4 * 1024, NULL);
/* If this is a wrapper, add boot files... */
if (defaults->flags & kMakeHFSWrapper) {
sector = mdbp->drAlBlSt +
mdbp->drXTFlSize/kBytesPerSector +
mdbp->drCTFlSize/kBytesPerSector;
WriteDesktopDB(defaults, driveInfo, sector, nodeBuffer, &mapNodes);
if (mapNodes > 0)
WriteMapNodes(driveInfo, (sector + 1), 1, mapNodes, kHFSNodeSize, nodeBuffer);
gDTDBFork.logicalSize = MAX(kDTDB_Size, mdbp->drAlBlkSiz);
gDTDBFork.startBlock = (sector - mdbp->drAlBlSt) / sectorsPerBlock;
gDTDBFork.blockCount = BYTESTOBLKS(gDTDBFork.logicalSize, mdbp->drAlBlkSiz);
gDTDBFork.physicalSize = gDTDBFork.blockCount * mdbp->drAlBlkSiz;
sector += gDTDBFork.physicalSize / kBytesPerSector;
WriteReadMeFile(driveInfo, sector, &gReadMeFork.logicalSize);
gReadMeFork.startBlock = gDTDBFork.startBlock + gDTDBFork.blockCount;
gReadMeFork.blockCount = BYTESTOBLKS(gReadMeFork.logicalSize, mdbp->drAlBlkSiz);
gReadMeFork.physicalSize = gReadMeFork.blockCount * mdbp->drAlBlkSiz;
sector += gReadMeFork.physicalSize / kBytesPerSector;
WriteSystemFile(driveInfo, sector, &gSystemFork.logicalSize);
gSystemFork.startBlock = gReadMeFork.startBlock + gReadMeFork.blockCount;
gSystemFork.blockCount = BYTESTOBLKS(gSystemFork.logicalSize, mdbp->drAlBlkSiz);
gSystemFork.physicalSize = gSystemFork.blockCount * mdbp->drAlBlkSiz;
mdbp->drFreeBks -= gDTDBFork.blockCount + gReadMeFork.blockCount + gSystemFork.blockCount;
mdbp->drEmbedExtent.startBlock = mdbp->drNmAlBlks - (UInt16)mdbp->drFreeBks;
mdbp->drEmbedExtent.blockCount = (UInt16)mdbp->drFreeBks;
mdbp->drFreeBks = 0;
}
/*--- WRITE ALLOCATION BITMAP TO DISK: */
WriteBitmap(driveInfo, mdbp->drVBMSt, mdbp->drNmAlBlks - (UInt16)mdbp->drFreeBks, nodeBuffer);
/*--- WRITE FILE EXTENTS B*-TREE TO DISK: */
sector = mdbp->drAlBlSt; /* reset */
WriteExtentsFile(driveInfo, sector, defaults, &mdbp->drEmbedExtent, nodeBuffer, &bytesUsed, &mapNodes);
if (mapNodes > 0)
WriteMapNodes(driveInfo, (sector + bytesUsed/kBytesPerSector),
bytesUsed/kHFSNodeSize, mapNodes, kHFSNodeSize, nodeBuffer);
sector += (mdbp->drXTFlSize/kBytesPerSector);
/*--- WRITE CATALOG B*-TREE TO DISK: */
WriteCatalogFile(driveInfo, sector, defaults, NULL, nodeBuffer, &bytesUsed, &mapNodes);
if (mapNodes > 0)
WriteMapNodes(driveInfo, (sector + bytesUsed/kBytesPerSector),
bytesUsed/kHFSNodeSize, mapNodes, kHFSNodeSize, nodeBuffer);
/*--- WRITE MASTER DIRECTORY BLOCK TO DISK: */
*plusSectors = mdbp->drEmbedExtent.blockCount *
(mdbp->drAlBlkSiz / driveInfo->sectorSize);
*plusOffset = mdbp->drAlBlSt + mdbp->drEmbedExtent.startBlock *
(mdbp->drAlBlkSiz / driveInfo->sectorSize);
/* write mdb last in case we fail along the way */
/* Writes both copies of the MDB */
WriteMDB (driveInfo, mdbp);
/* MDB is now big-endian */
free(nodeBuffer);
free(mdbp);
return (0);
}
/*
* make_hfsplus
*
* This routine writes an initial HFS Plus volume structure onto a volume.
* It is assumed that the disk has already been formatted and verified.
*
*/
int
make_hfsplus(const DriveInfo *driveInfo, hfsparams_t *defaults)
{
UInt16 btNodeSize;
UInt32 sectorsPerBlock;
UInt32 mapNodes;
UInt32 sectorsPerNode;
UInt32 temp;
UInt32 bytesUsed;
UInt32 endOfAttributes;
void *nodeBuffer = NULL;
HFSPlusVolumeHeader *header = NULL;
UInt64 sector;
UInt64 bytesToZero;
#if !LINUX
/* Use wipefs() API to clear old metadata from the device.
* This should be done before we start writing anything on the
* device as wipefs will internally call ioctl(DKIOCDISCARD) on the
* entire device.
*/
(void) dowipefs(driveInfo->fd);
#endif
/* --- Create an HFS Plus header: */
header = (HFSPlusVolumeHeader*)malloc((size_t)kBytesPerSector);
if (header == NULL)
err(1, NULL);
defaults->encodingHint = getencodinghint(defaults->volumeName);
/* VH Initialized in native byte order */
InitVH(defaults, driveInfo->totalSectors, header);
sectorsPerBlock = header->blockSize / kBytesPerSector;
/*--- ZERO OUT BEGINNING OF DISK: */
/*
* Clear out the space to be occupied by the bitmap and B-Trees.
* The first chunk is the boot sectors, volume header, allocation bitmap,
* journal, Extents B-tree, and Attributes B-tree (if any).
* The second chunk is the Catalog B-tree.
*/
endOfAttributes = header->extentsFile.extents[0].startBlock +
header->extentsFile.extents[0].blockCount +
header->attributesFile.extents[0].blockCount;
bytesToZero = (UInt64) endOfAttributes * header->blockSize;
WriteBuffer(driveInfo, 0, bytesToZero, NULL);
bytesToZero = (UInt64) header->catalogFile.extents[0].blockCount * header->blockSize;
sector = header->catalogFile.extents[0].startBlock * sectorsPerBlock;
WriteBuffer(driveInfo, sector, bytesToZero, NULL);
/*--- Allocate a buffer for the rest of our IO: */
temp = Largest( defaults->catalogNodeSize * 2,
defaults->extentsNodeSize,
header->blockSize,
(header->catalogFile.extents[0].startBlock + header->catalogFile.extents[0].blockCount + 7) / 8 );
/*
* If size is not a mutiple of 512, round up to nearest sector
*/
if ( (temp & 0x01FF) != 0 )
temp = (temp + kBytesPerSector) & 0xFFFFFE00;
nodeBuffer = valloc((size_t)temp);
if (nodeBuffer == NULL)
err(1, NULL);
/*--- WRITE ALLOCATION BITMAP BITS TO DISK: */
sector = header->allocationFile.extents[0].startBlock * sectorsPerBlock;
bzero(nodeBuffer, temp);
AllocateExtent(nodeBuffer, 0, endOfAttributes);
AllocateExtent(nodeBuffer,
header->catalogFile.extents[0].startBlock,
header->catalogFile.extents[0].blockCount);
WriteBuffer(driveInfo, sector, temp, nodeBuffer);
/*
* Write alternate Volume Header bitmap bit to allocations file at
* 2nd to last sector on HFS+ volume
*/
if (header->totalBlocks > kBitsPerSector)
bzero(nodeBuffer, kBytesPerSector);
MarkBitInAllocationBuffer( header, header->totalBlocks - 1, nodeBuffer, §or );
if ( header->blockSize == 512 ) {
UInt64 sector2;
MarkBitInAllocationBuffer( header, header->totalBlocks - 2,
nodeBuffer, §or2 );
/* cover the case when altVH and last block are on different bitmap sectors. */
if ( sector2 != sector ) {
bzero(nodeBuffer, kBytesPerSector);
MarkBitInAllocationBuffer(header, header->totalBlocks - 1,
nodeBuffer, §or);
WriteBuffer(driveInfo, sector, kBytesPerSector, nodeBuffer);
bzero(nodeBuffer, kBytesPerSector);
MarkBitInAllocationBuffer(header, header->totalBlocks - 2,
nodeBuffer, §or);
}
}
WriteBuffer(driveInfo, sector, kBytesPerSector, nodeBuffer);
/*--- WRITE FILE EXTENTS B-TREE TO DISK: */
btNodeSize = defaults->extentsNodeSize;
sectorsPerNode = btNodeSize/kBytesPerSector;
sector = header->extentsFile.extents[0].startBlock * sectorsPerBlock;
WriteExtentsFile(driveInfo, sector, defaults, NULL, nodeBuffer, &bytesUsed, &mapNodes);
if (mapNodes > 0) {
WriteMapNodes(driveInfo, (sector + bytesUsed/kBytesPerSector),
bytesUsed/btNodeSize, mapNodes, btNodeSize, nodeBuffer);
}
/*--- WRITE FILE ATTRIBUTES B-TREE TO DISK: */
if (defaults->attributesClumpSize) {
btNodeSize = defaults->attributesNodeSize;
sectorsPerNode = btNodeSize/kBytesPerSector;
sector = header->attributesFile.extents[0].startBlock * sectorsPerBlock;
WriteAttributesFile(driveInfo, sector, defaults, NULL, nodeBuffer, &bytesUsed, &mapNodes);
if (mapNodes > 0) {
WriteMapNodes(driveInfo, (sector + bytesUsed/kBytesPerSector),
bytesUsed/btNodeSize, mapNodes, btNodeSize, nodeBuffer);
}
}
/*--- WRITE CATALOG B-TREE TO DISK: */
btNodeSize = defaults->catalogNodeSize;
sectorsPerNode = btNodeSize/kBytesPerSector;
sector = header->catalogFile.extents[0].startBlock * sectorsPerBlock;
WriteCatalogFile(driveInfo, sector, defaults, header, nodeBuffer, &bytesUsed, &mapNodes);
if (mapNodes > 0) {
WriteMapNodes(driveInfo, (sector + bytesUsed/kBytesPerSector),
bytesUsed/btNodeSize, mapNodes, btNodeSize, nodeBuffer);
}
/*--- JOURNALING SETUP */
if (defaults->journaledHFS) {
sector = header->journalInfoBlock * sectorsPerBlock;
if (WriteJournalInfo(driveInfo, sector, defaults, header, nodeBuffer) != 0) {
err(EINVAL, "Failed to create the journal");
}
}
/*--- WRITE VOLUME HEADER TO DISK: */
/* write header last in case we fail along the way */
/* Writes both copies of the volume header */
WriteVH (driveInfo, header);
/* VH is now big-endian */
free(nodeBuffer);
free(header);
return (0);
}
/*
* WriteMDB
*
* Writes the Master Directory Block (MDB) to disk.
*
* The MDB is byte-swapped if necessary to big endian. Since this
* is always the last operation, there's no point in unswapping it.
*/
static void
WriteMDB (const DriveInfo *driveInfo, HFS_MDB *mdbp)
{
SWAP_HFSMDB (mdbp);
WriteBuffer(driveInfo, kMDBStart, kBytesPerSector, mdbp);
WriteBuffer(driveInfo, driveInfo->totalSectors - 2, kBytesPerSector, mdbp);
}
/*
* InitMDB
*
* Initialize a Master Directory Block (MDB) record.
*
* If the alignment parameter is non-zero, it indicates the aligment
* (in 512 byte sectors) that should be used for allocation blocks.
* For example, if alignment is 8, then allocation blocks will begin
* on a 4K boundary relative to the start of the partition.
*
*/
static void
InitMDB(hfsparams_t *defaults, UInt32 driveBlocks, HFS_MDB *mdbp)
{
UInt32 alBlkSize;
UInt16 numAlBlks;
UInt32 timeStamp;
UInt16 bitmapBlocks;
UInt32 alignment;
VolumeUUID newVolumeUUID;
VolumeUUID* finderInfoUUIDPtr;
alignment = defaults->hfsAlignment;
bzero(mdbp, kBytesPerSector);
alBlkSize = defaults->blockSize;
/* calculate the number of sectors needed for bitmap (rounded up) */
if (defaults->flags & kMakeMaxHFSBitmap)
bitmapBlocks = kHFSMaxAllocationBlks / kBitsPerSector;
else
bitmapBlocks = ((driveBlocks / (alBlkSize >> kLog2SectorSize)) +
kBitsPerSector-1) / kBitsPerSector;
mdbp->drAlBlSt = kVolBitMapStart + bitmapBlocks; /* in sectors (disk blocks) */
/* If requested, round up block start to a multiple of "alignment" blocks */
if (alignment != 0)
mdbp->drAlBlSt = ((mdbp->drAlBlSt + alignment - 1) / alignment) * alignment;
/* Now find out how many whole allocation blocks remain... */
numAlBlks = (driveBlocks - mdbp->drAlBlSt - kTailBlocks) /
(alBlkSize >> kLog2SectorSize);
timeStamp = UTCToLocal(defaults->createDate);
mdbp->drSigWord = kHFSSigWord;
mdbp->drCrDate = timeStamp;
mdbp->drLsMod = timeStamp;
mdbp->drAtrb = kHFSVolumeUnmountedMask;
mdbp->drVBMSt = kVolBitMapStart;
mdbp->drNmAlBlks = numAlBlks;
mdbp->drAlBlkSiz = alBlkSize;
mdbp->drClpSiz = defaults->dataClumpSize;
mdbp->drNxtCNID = defaults->nextFreeFileID;
mdbp->drFreeBks = numAlBlks;
/* Set Volume name to 'untitled' */
mdbp->drVN[0] = strlen(kDefaultVolumeNameStr);
bcopy(kDefaultVolumeNameStr, &mdbp->drVN[1], mdbp->drVN[0]);
defaults->encodingHint = 0;
/* defaults->volumeName is used later for the root dir key */
bcopy(&mdbp->drVN[1], defaults->volumeName, mdbp->drVN[0]);
defaults->volumeName[mdbp->drVN[0]] = '\0';
/* Save the encoding hint in the Finder Info (field 4). */
mdbp->drFndrInfo[4] = SET_HFS_TEXT_ENCODING(defaults->encodingHint);
mdbp->drWrCnt = kWriteSeqNum;
mdbp->drXTFlSize = mdbp->drXTClpSiz = defaults->extentsClumpSize;
mdbp->drXTExtRec[0].startBlock = 0;
mdbp->drXTExtRec[0].blockCount = mdbp->drXTFlSize / alBlkSize;
mdbp->drFreeBks -= mdbp->drXTExtRec[0].blockCount;
mdbp->drCTFlSize = mdbp->drCTClpSiz = defaults->catalogClumpSize;
mdbp->drCTExtRec[0].startBlock = mdbp->drXTExtRec[0].startBlock +
mdbp->drXTExtRec[0].blockCount;
mdbp->drCTExtRec[0].blockCount = mdbp->drCTFlSize / alBlkSize;
mdbp->drFreeBks -= mdbp->drCTExtRec[0].blockCount;
if (defaults->flags & kMakeHFSWrapper) {
mdbp->drFilCnt = mdbp->drNmFls = kWapperFileCount;
mdbp->drNxtCNID += kWapperFileCount;
/* set blessed system folder to be root folder (2) */
mdbp->drFndrInfo[0] = kHFSRootFolderID;
mdbp->drEmbedSigWord = kHFSPlusSigWord;
/* software lock it and tag as having "bad" blocks */
mdbp->drAtrb |= kHFSVolumeSparedBlocksMask;
mdbp->drAtrb |= kHFSVolumeSoftwareLockMask;
}
/* Generate and write UUID for the HFS disk */
GenerateVolumeUUID(&newVolumeUUID);
finderInfoUUIDPtr = (VolumeUUID *)(&mdbp->drFndrInfo[6]);
finderInfoUUIDPtr->v.high = OSSwapHostLongToBig(newVolumeUUID.v.high);
finderInfoUUIDPtr->v.low = OSSwapHostLongToBig(newVolumeUUID.v.low);
}
/*
* WriteVH
*
* Writes the Volume Header (VH) to disk.
*
* The VH is byte-swapped if necessary to big endian. Since this
* is always the last operation, there's no point in unswapping it.
*/
static void
WriteVH (const DriveInfo *driveInfo, HFSPlusVolumeHeader *hp)
{
SWAP_HFSPLUSVH (hp);
WriteBuffer(driveInfo, 2, kBytesPerSector, hp);
WriteBuffer(driveInfo, driveInfo->totalSectors - 2, kBytesPerSector, hp);
}
/*
* InitVH
*
* Initialize a Volume Header record.
*/
static void
InitVH(hfsparams_t *defaults, UInt64 sectors, HFSPlusVolumeHeader *hp)
{
UInt32 blockSize;
UInt32 blockCount;
UInt32 blocksUsed;
UInt32 bitmapBlocks;
UInt16 burnedBlocksBeforeVH = 0;
UInt16 burnedBlocksAfterAltVH = 0;
UInt32 nextBlock;
VolumeUUID newVolumeUUID;
VolumeUUID* finderInfoUUIDPtr;
UInt64 hotFileBandSize;
UInt64 volsize;
/*
* 2 MB is the minimum size for the new behavior with
* space after the attr b-tree, and hotfile stuff.
*/
#define MINVOLSIZE_WITHSPACE 2097152
bzero(hp, kBytesPerSector);
blockSize = defaults->blockSize;
blockCount = sectors / (blockSize >> kLog2SectorSize);
/*
* HFSPlusVolumeHeader is located at sector 2, so we may need
* to invalidate blocks before HFSPlusVolumeHeader.
*/
if ( blockSize == 512 ) {
burnedBlocksBeforeVH = 2; /* 2 before VH */
burnedBlocksAfterAltVH = 1; /* 1 after altVH */
} else if ( blockSize == 1024 ) {
burnedBlocksBeforeVH = 1;
}
nextBlock = burnedBlocksBeforeVH + 1; /* +1 for VH itself */
bitmapBlocks = defaults->allocationClumpSize / blockSize;
/* note: add 2 for the Alternate VH, and VH */
blocksUsed = 2 + burnedBlocksBeforeVH + burnedBlocksAfterAltVH + bitmapBlocks;
if (defaults->flags & kMakeCaseSensitive) {
hp->signature = kHFSXSigWord;
hp->version = kHFSXVersion;
} else {
hp->signature = kHFSPlusSigWord;
hp->version = kHFSPlusVersion;
}
hp->attributes = kHFSVolumeUnmountedMask | kHFSUnusedNodeFixMask;
if (defaults->flags & kMakeContentProtect) {
hp->attributes |= kHFSContentProtectionMask;
}
hp->lastMountedVersion = kHFSPlusMountVersion;
/* NOTE: create date is in local time, not GMT! */
hp->createDate = UTCToLocal(defaults->createDate);
hp->modifyDate = defaults->createDate;
hp->backupDate = 0;
hp->checkedDate = defaults->createDate;
// hp->fileCount = 0;
// hp->folderCount = 0;
hp->blockSize = blockSize;
hp->totalBlocks = blockCount;
hp->freeBlocks = blockCount; /* will be adjusted at the end */
volsize = (UInt64) blockCount * (UInt64) blockSize;
hp->rsrcClumpSize = defaults->rsrcClumpSize;
hp->dataClumpSize = defaults->dataClumpSize;
hp->nextCatalogID = defaults->nextFreeFileID;
hp->encodingsBitmap = 1 | (1 << ENCODING_TO_BIT(defaults->encodingHint));
/* set up allocation bitmap file */
hp->allocationFile.clumpSize = defaults->allocationClumpSize;
hp->allocationFile.logicalSize = defaults->allocationClumpSize;
hp->allocationFile.totalBlocks = bitmapBlocks;
hp->allocationFile.extents[0].startBlock = nextBlock;
hp->allocationFile.extents[0].blockCount = bitmapBlocks;
nextBlock += hp->allocationFile.extents[0].blockCount;
/* set up journal files */
if (defaults->journaledHFS) {
hp->fileCount = 2;
hp->attributes |= kHFSVolumeJournaledMask;
hp->nextCatalogID += 2;
/*
* Allocate 1 block for the journalInfoBlock. The
* journal file size is passed in hfsparams_t.
*/
hp->journalInfoBlock = nextBlock;
/*XXX What if journal is on a different device? */
blocksUsed += 1 + ((defaults->journalSize+blockSize-1) / blockSize);
nextBlock += 1 + ((defaults->journalSize+blockSize-1) / blockSize);
} else {
hp->journalInfoBlock = 0;
}
/* set up extents b-tree file */
hp->extentsFile.clumpSize = defaults->extentsClumpSize;
hp->extentsFile.logicalSize = defaults->extentsClumpSize;
hp->extentsFile.totalBlocks = defaults->extentsClumpSize / blockSize;
hp->extentsFile.extents[0].startBlock = nextBlock;
hp->extentsFile.extents[0].blockCount = hp->extentsFile.totalBlocks;
blocksUsed += hp->extentsFile.totalBlocks;
nextBlock += hp->extentsFile.totalBlocks;
/* set up attributes b-tree file */
if (defaults->attributesClumpSize) {
hp->attributesFile.clumpSize = defaults->attributesClumpSize;
hp->attributesFile.logicalSize = defaults->attributesClumpSize;
hp->attributesFile.totalBlocks = defaults->attributesClumpSize / blockSize;
hp->attributesFile.extents[0].startBlock = nextBlock;
hp->attributesFile.extents[0].blockCount = hp->attributesFile.totalBlocks;
blocksUsed += hp->attributesFile.totalBlocks;
nextBlock += hp->attributesFile.totalBlocks;
/*
* Leave some room for the Attributes B-tree to grow, if the volsize >= 2MB
*/
if (volsize >= MINVOLSIZE_WITHSPACE) {
nextBlock += 10 * (hp->attributesFile.clumpSize / blockSize);
}
}
/* set up catalog b-tree file */
hp->catalogFile.clumpSize = defaults->catalogClumpSize;
hp->catalogFile.logicalSize = defaults->catalogClumpSize;
hp->catalogFile.totalBlocks = defaults->catalogClumpSize / blockSize;
hp->catalogFile.extents[0].startBlock = nextBlock;
hp->catalogFile.extents[0].blockCount = hp->catalogFile.totalBlocks;
blocksUsed += hp->catalogFile.totalBlocks;
nextBlock += hp->catalogFile.totalBlocks;
/*
* Add some room for the catalog file to grow...
*/
nextBlock += 10 * (hp->catalogFile.clumpSize / hp->blockSize);
/*
* Add some room for the hot file band. This uses the same 5MB per GB
* as the kernel. The kernel only uses hotfiles if the volume is larger
* than 10GBytes, so do the same here.
*/
#define METADATAZONE_MINIMUM_VOLSIZE (10ULL * 1024ULL * 1024ULL * 1024ULL)
#define HOTBAND_MINIMUM_SIZE (10*1024*1024)
#define HOTBAND_MAXIMUM_SIZE (512*1024*1024)
if (volsize >= METADATAZONE_MINIMUM_VOLSIZE) {
hotFileBandSize = (UInt64) blockCount * blockSize / 1024 * 5;
if (hotFileBandSize > HOTBAND_MAXIMUM_SIZE)
hotFileBandSize = HOTBAND_MAXIMUM_SIZE;
else if (hotFileBandSize < HOTBAND_MINIMUM_SIZE)
hotFileBandSize = HOTBAND_MINIMUM_SIZE;
nextBlock += hotFileBandSize / blockSize;
}
hp->nextAllocation = nextBlock;
/* Adjust free blocks to reflect everything we have allocated. */
hp->freeBlocks -= blocksUsed;
/* Generate and write UUID for the HFS+ disk */
GenerateVolumeUUID(&newVolumeUUID);
finderInfoUUIDPtr = (VolumeUUID *)(&hp->finderInfo[24]);
finderInfoUUIDPtr->v.high = OSSwapHostToBigInt32(newVolumeUUID.v.high);
finderInfoUUIDPtr->v.low = OSSwapHostToBigInt32(newVolumeUUID.v.low);
}
/*
* InitBitmap
*
* This routine initializes the Allocation Bitmap. Allocation blocks
* that are in use have their corresponding bit set.
*
* It assumes that initially there are no gaps between allocated blocks.
*
* It also assumes the buffer is big enough to hold all the bits
* (ie its at least (alBlksUsed/8) bytes in size.
*/
static void
WriteBitmap(const DriveInfo *driveInfo, UInt32 startingSector,
UInt32 alBlksUsed, UInt8 *buffer)
{
UInt32 bytes, bits, bytesUsed;
bytes = alBlksUsed >> 3;
bits = alBlksUsed & 0x0007;
(void)memset(buffer, 0xFF, bytes);
if (bits) {
*(UInt8 *)(buffer + bytes) = (0xFF00 >> bits) & 0xFF;
++bytes;
}
bytesUsed = ROUNDUP(bytes, driveInfo->sectorSize);
if (bytesUsed > bytes)
bzero(buffer + bytes, bytesUsed - bytes);
WriteBuffer(driveInfo, startingSector, bytesUsed, buffer);
}
/*
* AllocateExtent
*
* Mark the given extent as in-use in the given bitmap buffer.
*/
static void AllocateExtent(UInt8 *buffer, UInt32 startBlock, UInt32 blockCount)
{
UInt8 *p;
/* Point to start of extent in bitmap buffer */
p = buffer + (startBlock / 8);
/* Partial byte at start of extent */
if (startBlock & 7)
{
*(p++) |= 0xFF >> (startBlock & 7);
blockCount -= 8 - (startBlock & 7);
}
/* Fill in whole bytes */
if (blockCount >= 8)
{
memset(p, 0xFF, blockCount / 8);
p += blockCount / 8;
blockCount &= 7;
}
/* Partial byte at end of extent */
if (blockCount)
{
*(p++) |= 0xFF << (8 - blockCount);
}
}
/*
* WriteExtentsFile
*
* Initializes and writes out the extents b-tree file.
*
* Byte swapping is performed in place. The buffer should not be
* accessed through direct casting once it leaves this function.
*/
static void
WriteExtentsFile(const DriveInfo *driveInfo, UInt64 startingSector,
const hfsparams_t *dp, HFSExtentDescriptor *bbextp, void *buffer,
UInt32 *bytesUsed, UInt32 *mapNodes)
{
BTNodeDescriptor *ndp;
BTHeaderRec *bthp;
UInt8 *bmp;
UInt32 nodeBitsInHeader;
UInt32 fileSize;
UInt32 nodeSize;
UInt32 temp;
SInt16 offset;
int wrapper = (dp->flags & kMakeHFSWrapper);
*mapNodes = 0;
fileSize = dp->extentsClumpSize;
nodeSize = dp->extentsNodeSize;
bzero(buffer, nodeSize);
/* FILL IN THE NODE DESCRIPTOR: */
ndp = (BTNodeDescriptor *)buffer;
ndp->kind = kBTHeaderNode;
ndp->numRecords = SWAP_BE16 (3);
offset = sizeof(BTNodeDescriptor);
SETOFFSET(buffer, nodeSize, offset, 1);
/* FILL IN THE HEADER RECORD: */
bthp = (BTHeaderRec *)((UInt8 *)buffer + offset);
// bthp->treeDepth = 0;
// bthp->rootNode = 0;
// bthp->firstLeafNode = 0;
// bthp->lastLeafNode = 0;
// bthp->leafRecords = 0;
bthp->nodeSize = SWAP_BE16 (nodeSize);
bthp->totalNodes = SWAP_BE32 (fileSize / nodeSize);
bthp->freeNodes = SWAP_BE32 (SWAP_BE32 (bthp->totalNodes) - 1); /* header */
bthp->clumpSize = SWAP_BE32 (fileSize);
if (dp->flags & kMakeStandardHFS) {
bthp->maxKeyLength = SWAP_BE16 (kHFSExtentKeyMaximumLength);
/* wrapper has a bad-block extent record */
if (wrapper) {
bthp->treeDepth = SWAP_BE16 (SWAP_BE16 (bthp->treeDepth) + 1);
bthp->leafRecords = SWAP_BE32 (SWAP_BE32 (bthp->leafRecords) + 1);
bthp->rootNode = SWAP_BE32 (1);
bthp->firstLeafNode = SWAP_BE32 (1);
bthp->lastLeafNode = SWAP_BE32 (1);
bthp->freeNodes = SWAP_BE32 (SWAP_BE32 (bthp->freeNodes) - 1);
}
} else {
bthp->attributes |= SWAP_BE32 (kBTBigKeysMask);
bthp->maxKeyLength = SWAP_BE16 (kHFSPlusExtentKeyMaximumLength);
}
offset += sizeof(BTHeaderRec);
SETOFFSET(buffer, nodeSize, offset, 2);
offset += kBTreeHeaderUserBytes;
SETOFFSET(buffer, nodeSize, offset, 3);
/* FIGURE OUT HOW MANY MAP NODES (IF ANY): */
nodeBitsInHeader = 8 * (nodeSize
- sizeof(BTNodeDescriptor)
- sizeof(BTHeaderRec)
- kBTreeHeaderUserBytes
- (4 * sizeof(SInt16)) );
if (SWAP_BE32 (bthp->totalNodes) > nodeBitsInHeader) {
UInt32 nodeBitsInMapNode;
ndp->fLink = SWAP_BE32 (SWAP_BE32 (bthp->lastLeafNode) + 1);
nodeBitsInMapNode = 8 * (nodeSize
- sizeof(BTNodeDescriptor)
- (2 * sizeof(SInt16))
- 2 );
*mapNodes = (SWAP_BE32 (bthp->totalNodes) - nodeBitsInHeader +
(nodeBitsInMapNode - 1)) / nodeBitsInMapNode;
bthp->freeNodes = SWAP_BE32 (SWAP_BE32 (bthp->freeNodes) - *mapNodes);
}
/*
* FILL IN THE MAP RECORD, MARKING NODES THAT ARE IN USE.
* Note - worst case (32MB alloc blk) will have only 18 nodes in use.
*/
bmp = ((UInt8 *)buffer + offset);
temp = SWAP_BE32 (bthp->totalNodes) - SWAP_BE32 (bthp->freeNodes);
/* Working a byte at a time is endian safe */
while (temp >= 8) { *bmp = 0xFF; temp -= 8; bmp++; }
*bmp = ~(0xFF >> temp);
offset += nodeBitsInHeader/8;
SETOFFSET(buffer, nodeSize, offset, 4);
if (wrapper) {
InitExtentsRoot(nodeSize, bbextp, (buffer + nodeSize));
}
*bytesUsed = (SWAP_BE32 (bthp->totalNodes) - SWAP_BE32 (bthp->freeNodes) - *mapNodes) * nodeSize;
WriteBuffer(driveInfo, startingSector, *bytesUsed, buffer);
}
static void
InitExtentsRoot(UInt16 btNodeSize, HFSExtentDescriptor *bbextp, void *buffer)
{
BTNodeDescriptor *ndp;
HFSExtentKey *ekp;
HFSExtentRecord *edp;
SInt16 offset;
bzero(buffer, btNodeSize);
/*
* All nodes have a node descriptor...
*/
ndp = (BTNodeDescriptor *)buffer;
ndp->kind = kBTLeafNode;
ndp->numRecords = SWAP_BE16 (1);
ndp->height = 1;
offset = sizeof(BTNodeDescriptor);
SETOFFSET(buffer, btNodeSize, offset, 1);
/*
* First and only record is bad block extents...
*/
ekp = (HFSExtentKey *)((UInt8 *) buffer + offset);
ekp->keyLength = kHFSExtentKeyMaximumLength;
// ekp->forkType = 0;
ekp->fileID = SWAP_BE32 (kHFSBadBlockFileID);
// ekp->startBlock = 0;
offset += sizeof(HFSExtentKey);
edp = (HFSExtentRecord *)((UInt8 *)buffer + offset);
edp[0]->startBlock = SWAP_BE16 (bbextp->startBlock);
edp[0]->blockCount = SWAP_BE16 (bbextp->blockCount);
offset += sizeof(HFSExtentRecord);
SETOFFSET(buffer, btNodeSize, offset, 2);
}
/*
* WriteAttributesFile
*
* Initializes and writes out the attributes b-tree file.
*
* Byte swapping is performed in place. The buffer should not be
* accessed through direct casting once it leaves this function.
*/
static void
WriteAttributesFile(const DriveInfo *driveInfo, UInt64 startingSector,
const hfsparams_t *dp, HFSExtentDescriptor *bbextp, void *buffer,
UInt32 *bytesUsed, UInt32 *mapNodes)
{
BTNodeDescriptor *ndp;
BTHeaderRec *bthp;
UInt8 *bmp;
UInt32 nodeBitsInHeader;
UInt32 fileSize;
UInt32 nodeSize;
UInt32 temp;
SInt16 offset;
*mapNodes = 0;
fileSize = dp->attributesClumpSize;
nodeSize = dp->attributesNodeSize;
bzero(buffer, nodeSize);
/* FILL IN THE NODE DESCRIPTOR: */
ndp = (BTNodeDescriptor *)buffer;
ndp->kind = kBTHeaderNode;
ndp->numRecords = SWAP_BE16 (3);
offset = sizeof(BTNodeDescriptor);
SETOFFSET(buffer, nodeSize, offset, 1);
/* FILL IN THE HEADER RECORD: */
bthp = (BTHeaderRec *)((UInt8 *)buffer + offset);
// bthp->treeDepth = 0;
// bthp->rootNode = 0;
// bthp->firstLeafNode = 0;
// bthp->lastLeafNode = 0;
// bthp->leafRecords = 0;
bthp->nodeSize = SWAP_BE16 (nodeSize);
bthp->totalNodes = SWAP_BE32 (fileSize / nodeSize);
bthp->freeNodes = SWAP_BE32 (SWAP_BE32 (bthp->totalNodes) - 1); /* header */
bthp->clumpSize = SWAP_BE32 (fileSize);
bthp->attributes |= SWAP_BE32 (kBTBigKeysMask | kBTVariableIndexKeysMask);
bthp->maxKeyLength = SWAP_BE16 (kHFSPlusAttrKeyMaximumLength);
offset += sizeof(BTHeaderRec);
SETOFFSET(buffer, nodeSize, offset, 2);
offset += kBTreeHeaderUserBytes;
SETOFFSET(buffer, nodeSize, offset, 3);
/* FIGURE OUT HOW MANY MAP NODES (IF ANY): */
nodeBitsInHeader = 8 * (nodeSize
- sizeof(BTNodeDescriptor)
- sizeof(BTHeaderRec)
- kBTreeHeaderUserBytes
- (4 * sizeof(SInt16)) );
if (SWAP_BE32 (bthp->totalNodes) > nodeBitsInHeader) {
UInt32 nodeBitsInMapNode;
ndp->fLink = SWAP_BE32 (SWAP_BE32 (bthp->lastLeafNode) + 1);
nodeBitsInMapNode = 8 * (nodeSize
- sizeof(BTNodeDescriptor)
- (2 * sizeof(SInt16))
- 2 );
*mapNodes = (SWAP_BE32 (bthp->totalNodes) - nodeBitsInHeader +
(nodeBitsInMapNode - 1)) / nodeBitsInMapNode;
bthp->freeNodes = SWAP_BE32 (SWAP_BE32 (bthp->freeNodes) - *mapNodes);
}
/*
* FILL IN THE MAP RECORD, MARKING NODES THAT ARE IN USE.
* Note - worst case (32MB alloc blk) will have only 18 nodes in use.
*/
bmp = ((UInt8 *)buffer + offset);
temp = SWAP_BE32 (bthp->totalNodes) - SWAP_BE32 (bthp->freeNodes);
/* Working a byte at a time is endian safe */
while (temp >= 8) { *bmp = 0xFF; temp -= 8; bmp++; }
*bmp = ~(0xFF >> temp);
offset += nodeBitsInHeader/8;
SETOFFSET(buffer, nodeSize, offset, 4);
*bytesUsed = (SWAP_BE32 (bthp->totalNodes) - SWAP_BE32 (bthp->freeNodes) - *mapNodes) * nodeSize;
WriteBuffer(driveInfo, startingSector, *bytesUsed, buffer);
}
#if !TARGET_OS_EMBEDDED && !LINUX
static int
get_dev_uuid(const char *disk_name, char *dev_uuid_str, int dev_uuid_len)
{
io_service_t service;
CFStringRef uuid_str;
int ret = EINVAL;
if (strncmp(disk_name, _PATH_DEV, strlen(_PATH_DEV)) == 0) {
disk_name += strlen(_PATH_DEV);
}
dev_uuid_str[0] = '\0';
service = IOServiceGetMatchingService(kIOMasterPortDefault, IOBSDNameMatching(kIOMasterPortDefault, 0, disk_name));
if (service != IO_OBJECT_NULL) {
uuid_str = IORegistryEntryCreateCFProperty(service, CFSTR(kIOMediaUUIDKey), kCFAllocatorDefault, 0);
if (uuid_str) {
if (CFStringGetFileSystemRepresentation(uuid_str, dev_uuid_str, dev_uuid_len) != 0) {
ret = 0;
}
CFRelease(uuid_str);
}
IOObjectRelease(service);
}
return ret;
}
static int
clear_journal_dev(const char *dev_name)
{
int fd;
fd = open(dev_name, O_RDWR);
if (fd < 0) {
printf("Failed to open the journal device %s (%s)\n", dev_name, strerror(errno));
return -1;
}
dowipefs(fd);
close(fd);
return 0;
}
#endif /* !TARGET_OS_EMBEDDED */
static int
WriteJournalInfo(const DriveInfo *driveInfo, UInt64 startingSector,
const hfsparams_t *dp, HFSPlusVolumeHeader *header,
void *buffer)
{
JournalInfoBlock *jibp = buffer;
memset(buffer, 0xdb, driveInfo->physSectorSize);
memset(jibp, 0, sizeof(JournalInfoBlock));
#if !TARGET_OS_EMBEDDED && !LINUX
if (dp->journalDevice) {
char uuid_str[64];
if (get_dev_uuid(dp->journalDevice, uuid_str, sizeof(uuid_str)) == 0) {
strlcpy((char *)&jibp->reserved[0], uuid_str, sizeof(jibp->reserved));
// we also need to blast out some zeros to the journal device
// in case it had a file system on it previously. that way
// it's "initialized" in the sense that the previous contents
// won't get mounted accidently. if this fails we'll bail out.
if (clear_journal_dev(dp->journalDevice) != 0) {
return -1;
}
} else {
printf("FAILED to get the device uuid for device %s\n", dp->journalDevice);
strlcpy((char *)&jibp->reserved[0], "NO-DEV-UUID", sizeof(jibp->reserved));
return -1;
}
} else {
#endif
jibp->flags = kJIJournalInFSMask;
#if !TARGET_OS_EMBEDDED && !LINUX
}
#endif
jibp->flags |= kJIJournalNeedInitMask;
jibp->offset = ((UInt64) header->journalInfoBlock + 1) * header->blockSize;
jibp->size = dp->journalSize;
jibp->flags = SWAP_BE32(jibp->flags);
jibp->offset = SWAP_BE64(jibp->offset);
jibp->size = SWAP_BE64(jibp->size);
WriteBuffer(driveInfo, startingSector, driveInfo->physSectorSize, buffer);
jibp->flags = SWAP_BE32(jibp->flags);
jibp->offset = SWAP_BE64(jibp->offset);
jibp->size = SWAP_BE64(jibp->size);
return 0;
}
/*
* WriteCatalogFile
*
* This routine initializes a Catalog B-Tree.
*
* Note: Since large volumes can have bigger b-trees they
* might need to have map nodes setup.
*/
static void
WriteCatalogFile(const DriveInfo *driveInfo, UInt64 startingSector,
const hfsparams_t *dp, HFSPlusVolumeHeader *header, void *buffer,
UInt32 *bytesUsed, UInt32 *mapNodes)
{
BTNodeDescriptor *ndp;
BTHeaderRec *bthp;
UInt8 *bmp;
UInt32 nodeBitsInHeader;
UInt32 fileSize;
UInt32 nodeSize;
UInt32 temp;
SInt16 offset;
int wrapper = (dp->flags & kMakeHFSWrapper);
*mapNodes = 0;
fileSize = dp->catalogClumpSize;
nodeSize = dp->catalogNodeSize;
bzero(buffer, nodeSize);
/* FILL IN THE NODE DESCRIPTOR: */
ndp = (BTNodeDescriptor *)buffer;
ndp->kind = kBTHeaderNode;
ndp->numRecords = SWAP_BE16 (3);
offset = sizeof(BTNodeDescriptor);
SETOFFSET(buffer, nodeSize, offset, 1);
/* FILL IN THE HEADER RECORD: */
bthp = (BTHeaderRec *)((UInt8 *)buffer + offset);
bthp->treeDepth = SWAP_BE16 (1);
bthp->rootNode = SWAP_BE32 (1);
bthp->firstLeafNode = SWAP_BE32 (1);
bthp->lastLeafNode = SWAP_BE32 (1);
bthp->leafRecords = SWAP_BE32 (dp->journaledHFS ? 6 : 2);
bthp->nodeSize = SWAP_BE16 (nodeSize);
bthp->totalNodes = SWAP_BE32 (fileSize / nodeSize);
bthp->freeNodes = SWAP_BE32 (SWAP_BE32 (bthp->totalNodes) - 2); /* header and root */
bthp->clumpSize = SWAP_BE32 (fileSize);
if (dp->flags & kMakeStandardHFS) {
bthp->maxKeyLength = SWAP_BE16 (kHFSCatalogKeyMaximumLength);
if (dp->flags & kMakeHFSWrapper) {
bthp->treeDepth = SWAP_BE16 (SWAP_BE16 (bthp->treeDepth) + 1);
bthp->leafRecords = SWAP_BE32 (SWAP_BE32 (bthp->leafRecords) + kWapperFileCount);
bthp->firstLeafNode = SWAP_BE32 (SWAP_BE32 (bthp->rootNode) + 1);
bthp->lastLeafNode = SWAP_BE32 (SWAP_BE32 (bthp->firstLeafNode) + 1);
bthp->freeNodes = SWAP_BE32 (SWAP_BE32 (bthp->freeNodes) - 2); /* tree now split with 2 leaf nodes */
}
} else /* HFS+ */ {
bthp->attributes |= SWAP_BE32 (kBTVariableIndexKeysMask + kBTBigKeysMask);
bthp->maxKeyLength = SWAP_BE16 (kHFSPlusCatalogKeyMaximumLength);
if (dp->flags & kMakeCaseSensitive)
bthp->keyCompareType = kHFSBinaryCompare;
else
bthp->keyCompareType = kHFSCaseFolding;
}
offset += sizeof(BTHeaderRec);
SETOFFSET(buffer, nodeSize, offset, 2);
offset += kBTreeHeaderUserBytes;
SETOFFSET(buffer, nodeSize, offset, 3);
/* FIGURE OUT HOW MANY MAP NODES (IF ANY): */
nodeBitsInHeader = 8 * (nodeSize
- sizeof(BTNodeDescriptor)
- sizeof(BTHeaderRec)
- kBTreeHeaderUserBytes
- (4 * sizeof(SInt16)) );
if (SWAP_BE32 (bthp->totalNodes) > nodeBitsInHeader) {
UInt32 nodeBitsInMapNode;
ndp->fLink = SWAP_BE32 (SWAP_BE32 (bthp->lastLeafNode) + 1);
nodeBitsInMapNode = 8 * (nodeSize
- sizeof(BTNodeDescriptor)
- (2 * sizeof(SInt16))
- 2 );
*mapNodes = (SWAP_BE32 (bthp->totalNodes) - nodeBitsInHeader +
(nodeBitsInMapNode - 1)) / nodeBitsInMapNode;
bthp->freeNodes = SWAP_BE32 (SWAP_BE32 (bthp->freeNodes) - *mapNodes);
}
/*
* FILL IN THE MAP RECORD, MARKING NODES THAT ARE IN USE.
* Note - worst case (32MB alloc blk) will have only 18 nodes in use.
*/
bmp = ((UInt8 *)buffer + offset);
temp = SWAP_BE32 (bthp->totalNodes) - SWAP_BE32 (bthp->freeNodes);
/* Working a byte at a time is endian safe */
while (temp >= 8) { *bmp = 0xFF; temp -= 8; bmp++; }
*bmp = ~(0xFF >> temp);
offset += nodeBitsInHeader/8;
SETOFFSET(buffer, nodeSize, offset, 4);
if ((dp->flags & kMakeStandardHFS) == 0) {
InitCatalogRoot_HFSPlus(dp, header, buffer + nodeSize);
} else if (wrapper) {
InitCatalogRoot_HFS (dp, buffer + (1 * nodeSize));
InitFirstCatalogLeaf (dp, buffer + (2 * nodeSize), TRUE);
InitSecondCatalogLeaf(dp, buffer + (3 * nodeSize));
} else /* plain HFS */ {
InitFirstCatalogLeaf(dp, buffer + nodeSize, FALSE);
}
*bytesUsed = (SWAP_BE32 (bthp->totalNodes) - SWAP_BE32 (bthp->freeNodes) - *mapNodes) * nodeSize;
WriteBuffer(driveInfo, startingSector, *bytesUsed, buffer);
}
static void
InitCatalogRoot_HFSPlus(const hfsparams_t *dp, const HFSPlusVolumeHeader *header, void * buffer)
{
BTNodeDescriptor *ndp;
HFSPlusCatalogKey *ckp;
HFSPlusCatalogKey *tkp;
HFSPlusCatalogFolder *cdp;
HFSPlusCatalogFile *cfp;
HFSPlusCatalogThread *ctp;
UInt16 nodeSize;
SInt16 offset;
size_t unicodeBytes;
#if !LINUX
UInt8 canonicalName[256];
CFStringRef cfstr;
Boolean cfOK;
#endif
int index = 0;
nodeSize = dp->catalogNodeSize;
bzero(buffer, nodeSize);
/*
* All nodes have a node descriptor...
*/
ndp = (BTNodeDescriptor *)buffer;
ndp->kind = kBTLeafNode;
ndp->height = 1;
ndp->numRecords = SWAP_BE16 (dp->journaledHFS ? 6 : 2);
offset = sizeof(BTNodeDescriptor);
SETOFFSET(buffer, nodeSize, offset, ++index);
/*
* First record is always the root directory...
*/
ckp = (HFSPlusCatalogKey *)((UInt8 *)buffer + offset);
#if LINUX
ConvertUTF8toUnicode(dp->volumeName, sizeof(ckp->nodeName.unicode), ckp->nodeName.unicode, &ckp->nodeName.length);
#else
/* Use CFString functions to get a HFSPlus Canonical name */
cfstr = CFStringCreateWithCString(kCFAllocatorDefault, (char *)dp->volumeName, kCFStringEncodingUTF8);
cfOK = _CFStringGetFileSystemRepresentation(cfstr, canonicalName, sizeof(canonicalName));
if (!cfOK || ConvertUTF8toUnicode(canonicalName, sizeof(ckp->nodeName.unicode),
ckp->nodeName.unicode, &ckp->nodeName.length)) {
/* On conversion errors "untitled" is used as a fallback. */
(void) ConvertUTF8toUnicode((UInt8 *)kDefaultVolumeNameStr,
sizeof(ckp->nodeName.unicode),
ckp->nodeName.unicode,
&ckp->nodeName.length);
warnx("invalid HFS+ name: \"%s\", using \"%s\" instead",
dp->volumeName, kDefaultVolumeNameStr);
}
CFRelease(cfstr);
#endif
ckp->nodeName.length = SWAP_BE16 (ckp->nodeName.length);
unicodeBytes = sizeof(UniChar) * SWAP_BE16 (ckp->nodeName.length);
ckp->keyLength = SWAP_BE16 (kHFSPlusCatalogKeyMinimumLength + unicodeBytes);
ckp->parentID = SWAP_BE32 (kHFSRootParentID);
offset += SWAP_BE16 (ckp->keyLength) + 2;
cdp = (HFSPlusCatalogFolder *)((UInt8 *)buffer + offset);
cdp->recordType = SWAP_BE16 (kHFSPlusFolderRecord);
/* folder count is only supported on HFSX volumes */
#if !LINUX
// FIXME
if (dp->flags & kMakeCaseSensitive) {
cdp->flags = SWAP_BE16 (kHFSHasFolderCountMask);
}
#endif
cdp->valence = SWAP_BE32 (dp->journaledHFS ? 2 : 0);
cdp->folderID = SWAP_BE32 (kHFSRootFolderID);
cdp->createDate = SWAP_BE32 (dp->createDate);
cdp->contentModDate = SWAP_BE32 (dp->createDate);
cdp->textEncoding = SWAP_BE32 (dp->encodingHint);
if (dp->flags & kUseAccessPerms) {
cdp->bsdInfo.ownerID = SWAP_BE32 (dp->owner);
cdp->bsdInfo.groupID = SWAP_BE32 (dp->group);
cdp->bsdInfo.fileMode = SWAP_BE16 (dp->mask | S_IFDIR);
}
offset += sizeof(HFSPlusCatalogFolder);
SETOFFSET(buffer, nodeSize, offset, ++index);
/*
* Second record is always the root directory thread...
*/
tkp = (HFSPlusCatalogKey *)((UInt8 *)buffer + offset);
tkp->keyLength = SWAP_BE16 (kHFSPlusCatalogKeyMinimumLength);
tkp->parentID = SWAP_BE32 (kHFSRootFolderID);
// tkp->nodeName.length = 0;
offset += SWAP_BE16 (tkp->keyLength) + 2;
ctp = (HFSPlusCatalogThread *)((UInt8 *)buffer + offset);
ctp->recordType = SWAP_BE16 (kHFSPlusFolderThreadRecord);
ctp->parentID = SWAP_BE32 (kHFSRootParentID);
bcopy(&ckp->nodeName, &ctp->nodeName, sizeof(UInt16) + unicodeBytes);
offset += (sizeof(HFSPlusCatalogThread)
- (sizeof(ctp->nodeName.unicode) - unicodeBytes) );
SETOFFSET(buffer, nodeSize, offset, ++index);
/*
* Add records for ".journal" and ".journal_info_block" files:
*/
if (dp->journaledHFS) {
struct HFSUniStr255 *nodename1, *nodename2;
size_t uBytes1, uBytes2;
/* File record #1 */
ckp = (HFSPlusCatalogKey *)((UInt8 *)buffer + offset);
(void) ConvertUTF8toUnicode((UInt8 *)HFS_JOURNAL_FILE, sizeof(ckp->nodeName.unicode),
ckp->nodeName.unicode, &ckp->nodeName.length);
ckp->nodeName.length = SWAP_BE16 (ckp->nodeName.length);
uBytes1 = sizeof(UniChar) * SWAP_BE16 (ckp->nodeName.length);
ckp->keyLength = SWAP_BE16 (kHFSPlusCatalogKeyMinimumLength + uBytes1);
ckp->parentID = SWAP_BE32 (kHFSRootFolderID);
offset += SWAP_BE16 (ckp->keyLength) + 2;
cfp = (HFSPlusCatalogFile *)((UInt8 *)buffer + offset);
cfp->recordType = SWAP_BE16 (kHFSPlusFileRecord);
cfp->flags = SWAP_BE16 (kHFSThreadExistsMask);
cfp->fileID = SWAP_BE32 (dp->nextFreeFileID);
cfp->createDate = SWAP_BE32 (dp->createDate + 1);
cfp->contentModDate = SWAP_BE32 (dp->createDate + 1);
cfp->textEncoding = 0;
cfp->bsdInfo.fileMode = SWAP_BE16 (S_IFREG);
cfp->bsdInfo.ownerFlags = (uint8_t) SWAP_BE16 (((uint16_t)UF_NODUMP));
cfp->bsdInfo.special.linkCount = SWAP_BE32(1);
cfp->userInfo.fdType = SWAP_BE32 (kJournalFileType);
cfp->userInfo.fdCreator = SWAP_BE32 (kHFSPlusCreator);
cfp->userInfo.fdFlags = SWAP_BE16 (kIsInvisible + kNameLocked);
cfp->dataFork.logicalSize = SWAP_BE64 (dp->journalSize);
cfp->dataFork.totalBlocks = SWAP_BE32 ((dp->journalSize+dp->blockSize-1) / dp->blockSize);
cfp->dataFork.extents[0].startBlock = SWAP_BE32 (header->journalInfoBlock + 1);
cfp->dataFork.extents[0].blockCount = cfp->dataFork.totalBlocks;
offset += sizeof(HFSPlusCatalogFile);
SETOFFSET(buffer, nodeSize, offset, ++index);
nodename1 = &ckp->nodeName;
/* File record #2 */
ckp = (HFSPlusCatalogKey *)((UInt8 *)buffer + offset);
(void) ConvertUTF8toUnicode((UInt8 *)HFS_JOURNAL_INFO, sizeof(ckp->nodeName.unicode),
ckp->nodeName.unicode, &ckp->nodeName.length);
ckp->nodeName.length = SWAP_BE16 (ckp->nodeName.length);
uBytes2 = sizeof(UniChar) * SWAP_BE16 (ckp->nodeName.length);
ckp->keyLength = SWAP_BE16 (kHFSPlusCatalogKeyMinimumLength + uBytes2);
ckp->parentID = SWAP_BE32 (kHFSRootFolderID);
offset += SWAP_BE16 (ckp->keyLength) + 2;
cfp = (HFSPlusCatalogFile *)((UInt8 *)buffer + offset);
cfp->recordType = SWAP_BE16 (kHFSPlusFileRecord);
cfp->flags = SWAP_BE16 (kHFSThreadExistsMask);
cfp->fileID = SWAP_BE32 (dp->nextFreeFileID + 1);
cfp->createDate = SWAP_BE32 (dp->createDate);
cfp->contentModDate = SWAP_BE32 (dp->createDate);
cfp->textEncoding = 0;
cfp->bsdInfo.fileMode = SWAP_BE16 (S_IFREG);
cfp->bsdInfo.ownerFlags = (uint8_t) SWAP_BE16 (((uint16_t)UF_NODUMP));
cfp->bsdInfo.special.linkCount = SWAP_BE32(1);
cfp->userInfo.fdType = SWAP_BE32 (kJournalFileType);
cfp->userInfo.fdCreator = SWAP_BE32 (kHFSPlusCreator);
cfp->userInfo.fdFlags = SWAP_BE16 (kIsInvisible + kNameLocked);
cfp->dataFork.logicalSize = SWAP_BE64(dp->blockSize);;
cfp->dataFork.totalBlocks = SWAP_BE32(1);
cfp->dataFork.extents[0].startBlock = SWAP_BE32 (header->journalInfoBlock);
cfp->dataFork.extents[0].blockCount = cfp->dataFork.totalBlocks;
offset += sizeof(HFSPlusCatalogFile);
SETOFFSET(buffer, nodeSize, offset, ++index);
nodename2 = &ckp->nodeName;
/* Thread record for file #1 */
tkp = (HFSPlusCatalogKey *)((UInt8 *)buffer + offset);
tkp->keyLength = SWAP_BE16 (kHFSPlusCatalogKeyMinimumLength);
tkp->parentID = SWAP_BE32 (dp->nextFreeFileID);
tkp->nodeName.length = 0;
offset += SWAP_BE16 (tkp->keyLength) + 2;
ctp = (HFSPlusCatalogThread *)((UInt8 *)buffer + offset);
ctp->recordType = SWAP_BE16 (kHFSPlusFileThreadRecord);
ctp->parentID = SWAP_BE32 (kHFSRootFolderID);
bcopy(nodename1, &ctp->nodeName, sizeof(UInt16) + uBytes1);
offset += (sizeof(HFSPlusCatalogThread)
- (sizeof(ctp->nodeName.unicode) - uBytes1) );
SETOFFSET(buffer, nodeSize, offset, ++index);
/* Thread record for file #2 */
tkp = (HFSPlusCatalogKey *)((UInt8 *)buffer + offset);
tkp->keyLength = SWAP_BE16 (kHFSPlusCatalogKeyMinimumLength);
tkp->parentID = SWAP_BE32 (dp->nextFreeFileID + 1);
tkp->nodeName.length = 0;
offset += SWAP_BE16 (tkp->keyLength) + 2;
ctp = (HFSPlusCatalogThread *)((UInt8 *)buffer + offset);
ctp->recordType = SWAP_BE16 (kHFSPlusFileThreadRecord);
ctp->parentID = SWAP_BE32 (kHFSRootFolderID);
bcopy(nodename2, &ctp->nodeName, sizeof(UInt16) + uBytes2);
offset += (sizeof(HFSPlusCatalogThread)
- (sizeof(ctp->nodeName.unicode) - uBytes2) );
SETOFFSET(buffer, nodeSize, offset, ++index);
}
}
static void
InitFirstCatalogLeaf(const hfsparams_t *dp, void * buffer, int wrapper)
{
BTNodeDescriptor *ndp;
HFSCatalogKey *ckp;
HFSCatalogKey *tkp;
HFSCatalogFolder *cdp;
HFSCatalogFile *cfp;
HFSCatalogThread *ctp;
UInt16 nodeSize;
SInt16 offset;
UInt32 timeStamp;
nodeSize = dp->catalogNodeSize;
timeStamp = UTCToLocal(dp->createDate);
bzero(buffer, nodeSize);
/*
* All nodes have a node descriptor...
*/
ndp = (BTNodeDescriptor *)buffer;
ndp->kind = kBTLeafNode;
ndp->numRecords = SWAP_BE16 (2);
ndp->height = 1;
offset = sizeof(BTNodeDescriptor);
SETOFFSET(buffer, nodeSize, offset, 1);
/*
* First record is always the root directory...
*/
ckp = (HFSCatalogKey *)((UInt8 *)buffer + offset);
ckp->nodeName[0] = strlen((char *)dp->volumeName);
bcopy(dp->volumeName, &ckp->nodeName[1], ckp->nodeName[0]);
ckp->keyLength = 1 + 4 + ((ckp->nodeName[0] + 2) & 0xFE); /* pad to word */
ckp->parentID = SWAP_BE32 (kHFSRootParentID);
offset += ckp->keyLength + 1;
cdp = (HFSCatalogFolder *)((UInt8 *)buffer + offset);
cdp->recordType = SWAP_BE16 (kHFSFolderRecord);
if (wrapper)
cdp->valence = SWAP_BE16 (SWAP_BE16 (cdp->valence) + kWapperFileCount);
cdp->folderID = SWAP_BE32 (kHFSRootFolderID);
cdp->createDate = SWAP_BE32 (timeStamp);
cdp->modifyDate = SWAP_BE32 (timeStamp);
offset += sizeof(HFSCatalogFolder);
SETOFFSET(buffer, nodeSize, offset, 2);
/*
* Second record is always the root directory thread...
*/
tkp = (HFSCatalogKey *)((UInt8 *)buffer + offset);
tkp->keyLength = kHFSCatalogKeyMinimumLength;
tkp->parentID = SWAP_BE32 (kHFSRootFolderID);
// tkp->nodeName[0] = 0;
offset += tkp->keyLength + 2;
ctp = (HFSCatalogThread *)((UInt8 *)buffer + offset);
ctp->recordType = SWAP_BE16 (kHFSFolderThreadRecord);
ctp->parentID = SWAP_BE32 (kHFSRootParentID);
bcopy(ckp->nodeName, ctp->nodeName, ckp->nodeName[0]+1);
offset += sizeof(HFSCatalogThread);
SETOFFSET(buffer, nodeSize, offset, 3);
/*
* For Wrapper volumes there are more file records...
*/
if (wrapper) {
ndp->fLink = SWAP_BE32 (3);
ndp->numRecords = SWAP_BE16 (SWAP_BE16 (ndp->numRecords) + 2);
/*
* Add "Desktop DB" file...
*/
ckp = (HFSCatalogKey *)((UInt8 *)buffer + offset);
ckp->keyLength = 1 + 4 + ((kDTDB_Chars + 2) & 0xFE); /* pad to word */
ckp->parentID = SWAP_BE32 (kHFSRootFolderID);
ckp->nodeName[0] = kDTDB_Chars;
bcopy(kDTDB_Name, &ckp->nodeName[1], kDTDB_Chars);
offset += ckp->keyLength + 1;
cfp = (HFSCatalogFile *)((UInt8 *)buffer + offset);
cfp->recordType = SWAP_BE16 (kHFSFileRecord);
cfp->userInfo.fdType = SWAP_BE32 (kDTDB_Type);
cfp->userInfo.fdCreator = SWAP_BE32 (kDTDB_Creator);
cfp->userInfo.fdFlags = SWAP_BE16 (kIsInvisible);
cfp->fileID = SWAP_BE32 (kDTDB_FileID);
cfp->createDate = SWAP_BE32 (timeStamp);
cfp->modifyDate = SWAP_BE32 (timeStamp);
cfp->dataExtents[0].startBlock = SWAP_BE16 (gDTDBFork.startBlock);
cfp->dataExtents[0].blockCount = SWAP_BE16 (gDTDBFork.blockCount);
cfp->dataPhysicalSize = SWAP_BE32 (gDTDBFork.physicalSize);
cfp->dataLogicalSize = SWAP_BE32 (gDTDBFork.logicalSize);
offset += sizeof(HFSCatalogFile);
SETOFFSET(buffer, nodeSize, offset, 4);
/*
* Add empty "Desktop DF" file...
*/
ckp = (HFSCatalogKey *)((UInt8 *)buffer + offset);
ckp->keyLength = 1 + 4 + ((kDTDF_Chars + 2) & 0xFE); /* pad to word */
ckp->parentID = SWAP_BE32 (kHFSRootFolderID);
ckp->nodeName[0] = kDTDF_Chars;
bcopy(kDTDF_Name, &ckp->nodeName[1], kDTDF_Chars);
offset += ckp->keyLength + 1;
cfp = (HFSCatalogFile *)((UInt8 *)buffer + offset);
cfp->recordType = SWAP_BE16 (kHFSFileRecord);
cfp->userInfo.fdType = SWAP_BE32 (kDTDF_Type);
cfp->userInfo.fdCreator = SWAP_BE32 (kDTDF_Creator);
cfp->userInfo.fdFlags = SWAP_BE16 (kIsInvisible);
cfp->fileID = SWAP_BE32 (kDTDF_FileID);
cfp->createDate = SWAP_BE32 (timeStamp);
cfp->modifyDate = SWAP_BE32 (timeStamp);
offset += sizeof(HFSCatalogFile);
SETOFFSET(buffer, nodeSize, offset, 5);
}
}
static void
InitSecondCatalogLeaf(const hfsparams_t *dp, void * buffer)
{
BTNodeDescriptor *ndp;
HFSCatalogKey *ckp;
HFSCatalogFile *cfp;
UInt16 nodeSize;
SInt16 offset;
UInt32 timeStamp;
nodeSize = dp->catalogNodeSize;
timeStamp = UTCToLocal(dp->createDate);
bzero(buffer, nodeSize);
/*
* All nodes have a node descriptor...
*/
ndp = (BTNodeDescriptor *)buffer;
ndp->bLink = SWAP_BE32 (2);
ndp->kind = kBTLeafNode;
ndp->numRecords = SWAP_BE16 (3);
ndp->height = 1;
offset = sizeof(BTNodeDescriptor);
SETOFFSET(buffer, nodeSize, offset, 1);
/*
* Add "Finder" file...
*/
ckp = (HFSCatalogKey *)((UInt8 *)buffer + offset);
ckp->keyLength = 1 + 4 + ((kFinder_Chars + 2) & 0xFE); /* pad to word */
ckp->parentID = SWAP_BE32 (kHFSRootFolderID);
ckp->nodeName[0] = kFinder_Chars;
bcopy(kFinder_Name, &ckp->nodeName[1], kFinder_Chars);
offset += ckp->keyLength + 1;
cfp = (HFSCatalogFile *)((UInt8 *)buffer + offset);
cfp->recordType = SWAP_BE16 (kHFSFileRecord);
cfp->userInfo.fdType = SWAP_BE32 (kFinder_Type);
cfp->userInfo.fdCreator = SWAP_BE32 (kFinder_Creator);
cfp->userInfo.fdFlags = SWAP_BE16 (kIsInvisible + kNameLocked + kHasBeenInited);
cfp->fileID = SWAP_BE32 (kFinder_FileID);
cfp->createDate = SWAP_BE32 (timeStamp);
cfp->modifyDate = SWAP_BE32 (timeStamp);
offset += sizeof(HFSCatalogFile);
SETOFFSET(buffer, nodeSize, offset, 2);
/*
* Add "ReadMe" file...
*/
ckp = (HFSCatalogKey *)((UInt8 *)buffer + offset);
ckp->keyLength = 1 + 4 + ((kReadMe_Chars + 2) & 0xFE); /* pad to word */
ckp->parentID = SWAP_BE32 (kHFSRootFolderID);
ckp->nodeName[0] = kReadMe_Chars;
bcopy(kReadMe_Name, &ckp->nodeName[1], kReadMe_Chars);
offset += ckp->keyLength + 1;
cfp = (HFSCatalogFile *)((UInt8 *)buffer + offset);
cfp->recordType = SWAP_BE16 (kHFSFileRecord);
cfp->userInfo.fdType = SWAP_BE32 (kReadMe_Type);
cfp->userInfo.fdCreator = SWAP_BE32 (kReadMe_Creator);
cfp->fileID = SWAP_BE32 (kReadMe_FileID);
cfp->createDate = SWAP_BE32 (timeStamp);
cfp->modifyDate = SWAP_BE32 (timeStamp);
cfp->dataExtents[0].startBlock = SWAP_BE16 (gReadMeFork.startBlock);
cfp->dataExtents[0].blockCount = SWAP_BE16 (gReadMeFork.blockCount);
cfp->dataPhysicalSize = SWAP_BE32 (gReadMeFork.physicalSize);
cfp->dataLogicalSize = SWAP_BE32 (gReadMeFork.logicalSize);
offset += sizeof(HFSCatalogFile);
SETOFFSET(buffer, nodeSize, offset, 3);
/*
* Add "System" file...
*/
ckp = (HFSCatalogKey *)((UInt8 *)buffer + offset);
ckp->keyLength = 1 + 4 + ((kSystem_Chars + 2) & 0xFE); /* pad to word */
ckp->parentID = SWAP_BE32 (kHFSRootFolderID);
ckp->nodeName[0] = kSystem_Chars;
bcopy(kSystem_Name, &ckp->nodeName[1], kSystem_Chars);
offset += ckp->keyLength + 1;
cfp = (HFSCatalogFile *)((UInt8 *)buffer + offset);
cfp->recordType = SWAP_BE16 (kHFSFileRecord);
cfp->userInfo.fdType = SWAP_BE32 (kSystem_Type);
cfp->userInfo.fdCreator = SWAP_BE32 (kSystem_Creator);
cfp->userInfo.fdFlags = SWAP_BE16 (kIsInvisible + kNameLocked + kHasBeenInited);
cfp->fileID = SWAP_BE32 (kSystem_FileID);
cfp->createDate = SWAP_BE32 (timeStamp);
cfp->modifyDate = SWAP_BE32 (timeStamp);
cfp->rsrcExtents[0].startBlock = SWAP_BE16 (gSystemFork.startBlock);
cfp->rsrcExtents[0].blockCount = SWAP_BE16 (gSystemFork.blockCount);
cfp->rsrcPhysicalSize = SWAP_BE32 (gSystemFork.physicalSize);
cfp->rsrcLogicalSize = SWAP_BE32 (gSystemFork.logicalSize);
offset += sizeof(HFSCatalogFile);
SETOFFSET(buffer, nodeSize, offset, 4);
}
static void
InitCatalogRoot_HFS(const hfsparams_t *dp, void * buffer)
{
BTNodeDescriptor *ndp;
HFSCatalogKey *ckp;
UInt32 *prp; /* pointer record */
UInt16 nodeSize;
SInt16 offset;
nodeSize = dp->catalogNodeSize;
bzero(buffer, nodeSize);
/*
* All nodes have a node descriptor...
*/
ndp = (BTNodeDescriptor *)buffer;
ndp->kind = kBTIndexNode;
ndp->numRecords = SWAP_BE16 (2);
ndp->height = 2;
offset = sizeof(BTNodeDescriptor);
SETOFFSET(buffer, nodeSize, offset, 1);
/*
* Add root directory index...
*/
ckp = (HFSCatalogKey *)((UInt8 *)buffer + offset);
ckp->keyLength = kHFSCatalogKeyMaximumLength;
ckp->parentID = SWAP_BE32 (kHFSRootParentID);
ckp->nodeName[0] = strlen((char *)dp->volumeName);
bcopy(dp->volumeName, &ckp->nodeName[1], ckp->nodeName[0]);
offset += ckp->keyLength + 1;
prp = (UInt32 *)((UInt8 *)buffer + offset);
*prp = SWAP_BE32 (2); /* point to first leaf node */
offset += sizeof(UInt32);
SETOFFSET(buffer, nodeSize, offset, 2);
/*
* Add finder file index...
*/
ckp = (HFSCatalogKey *)((UInt8 *)buffer + offset);
ckp->keyLength = kHFSCatalogKeyMaximumLength;
ckp->parentID = SWAP_BE32 (kHFSRootFolderID);
ckp->nodeName[0] = kFinder_Chars;
bcopy(kFinder_Name, &ckp->nodeName[1], kFinder_Chars);
offset += ckp->keyLength + 1;
prp = (UInt32 *)((UInt8 *)buffer + offset);
*prp = SWAP_BE32 (3); /* point to last leaf node */
offset += sizeof(UInt32);
SETOFFSET(buffer, nodeSize, offset, 3);
}
static void
WriteDesktopDB(const hfsparams_t *dp, const DriveInfo *driveInfo,
UInt32 startingSector, void *buffer, UInt32 *mapNodes)
{
BTNodeDescriptor *ndp;
BTHeaderRec *bthp;
UInt8 *bmp;
UInt32 nodeBitsInHeader;
UInt32 fileSize;
UInt32 nodeSize;
UInt32 temp;
SInt16 offset;
UInt8 *keyDiscP;
*mapNodes = 0;
fileSize = gDTDBFork.logicalSize;
nodeSize = kHFSNodeSize;
bzero(buffer, nodeSize);
/* FILL IN THE NODE DESCRIPTOR: */
ndp = (BTNodeDescriptor *)buffer;
ndp->kind = kBTHeaderNode;
ndp->numRecords = SWAP_BE16 (3);
offset = sizeof(BTNodeDescriptor);
SETOFFSET(buffer, nodeSize, offset, 1);
/* FILL IN THE HEADER RECORD: */
bthp = (BTHeaderRec *)((UInt8 *)buffer + offset);
// bthp->treeDepth = 0;
// bthp->rootNode = 0;
// bthp->firstLeafNode = 0;
// bthp->lastLeafNode = 0;
// bthp->leafRecords = 0;
bthp->nodeSize = SWAP_BE16 (nodeSize);
bthp->maxKeyLength = SWAP_BE16 (37);
bthp->totalNodes = SWAP_BE32 (fileSize / nodeSize);
bthp->freeNodes = SWAP_BE32 (SWAP_BE32 (bthp->totalNodes) - 1); /* header */
bthp->clumpSize = SWAP_BE32 (fileSize);
bthp->btreeType = 0xFF;
offset += sizeof(BTHeaderRec);
SETOFFSET(buffer, nodeSize, offset, 2);
keyDiscP = (UInt8 *)((UInt8 *)buffer + offset);
*keyDiscP++ = 2; /* length of descriptor */
*keyDiscP++ = KD_USEPROC; /* always uses a compare proc */
*keyDiscP++ = 1; /* just one of them */
offset += kBTreeHeaderUserBytes;
SETOFFSET(buffer, nodeSize, offset, 3);
/* FIGURE OUT HOW MANY MAP NODES (IF ANY): */
nodeBitsInHeader = 8 * (nodeSize
- sizeof(BTNodeDescriptor)
- sizeof(BTHeaderRec)
- kBTreeHeaderUserBytes
- (4 * sizeof(SInt16)) );
if (SWAP_BE32 (bthp->totalNodes) > nodeBitsInHeader) {
UInt32 nodeBitsInMapNode;
ndp->fLink = SWAP_BE32 (SWAP_BE32 (bthp->lastLeafNode) + 1);
nodeBitsInMapNode = 8 * (nodeSize
- sizeof(BTNodeDescriptor)
- (2 * sizeof(SInt16))
- 2 );
*mapNodes = (SWAP_BE32 (bthp->totalNodes) - nodeBitsInHeader +
(nodeBitsInMapNode - 1)) / nodeBitsInMapNode;
bthp->freeNodes = SWAP_BE32 (SWAP_BE32 (bthp->freeNodes) - *mapNodes);
}
/*
* FILL IN THE MAP RECORD, MARKING NODES THAT ARE IN USE.
* Note - worst case (32MB alloc blk) will have only 18 nodes in use.
*/
bmp = ((UInt8 *)buffer + offset);
temp = SWAP_BE32 (bthp->totalNodes) - SWAP_BE32 (bthp->freeNodes);
/* Working a byte at a time is endian safe */
while (temp >= 8) { *bmp = 0xFF; temp -= 8; bmp++; }
*bmp = ~(0xFF >> temp);
offset += nodeBitsInHeader/8;
SETOFFSET(buffer, nodeSize, offset, 4);
WriteBuffer(driveInfo, startingSector, kHFSNodeSize, buffer);
}
static void
WriteSystemFile(const DriveInfo *dip, UInt32 startingSector, UInt32 *filesize)
{
int fd;
ssize_t datasize, writesize;
UInt8 *buf;
struct stat stbuf;
if (stat(HFS_BOOT_DATA, &stbuf) < 0)
err(1, "stat %s", HFS_BOOT_DATA);
datasize = stbuf.st_size;
writesize = ROUNDUP(datasize, dip->sectorSize);
if (datasize > (64 * 1024))
errx(1, "hfsbootdata file too big.");
if ((buf = malloc(writesize)) == NULL)
err(1, NULL);
if ((fd = open(HFS_BOOT_DATA, O_RDONLY, 0)) < 0)
err(1, "open %s", HFS_BOOT_DATA);
if (read(fd, buf, datasize) != datasize) {
if (errno)
err(1, "read %s", HFS_BOOT_DATA);
else
errx(1, "problems reading %s", HFS_BOOT_DATA);
}
if (writesize > datasize)
bzero(buf + datasize, writesize - datasize);
WriteBuffer(dip, startingSector, writesize, buf);
close(fd);
free(buf);
*filesize = datasize;
}
static void
WriteReadMeFile(const DriveInfo *dip, UInt32 startingSector, UInt32 *filesize)
{
ssize_t datasize, writesize;
UInt8 *buf;
datasize = sizeof(hfswrap_readme);
writesize = ROUNDUP(datasize, dip->sectorSize);
if ((buf = malloc(writesize)) == NULL)
err(1, NULL);
bcopy(hfswrap_readme, buf, datasize);
if (writesize > datasize)
bzero(buf + datasize, writesize - datasize);
WriteBuffer(dip, startingSector, writesize, buf);
*filesize = datasize;
}
/*
* WriteMapNodes
*
* Initializes a B-tree map node and writes it out to disk.
*/
static void
WriteMapNodes(const DriveInfo *driveInfo, UInt64 diskStart, UInt32 firstMapNode,
UInt32 mapNodes, UInt16 btNodeSize, void *buffer)
{
UInt32 sectorsPerNode;
UInt32 mapRecordBytes;
UInt16 i;
BTNodeDescriptor *nd = (BTNodeDescriptor *)buffer;
bzero(buffer, btNodeSize);
nd->kind = kBTMapNode;
nd->numRecords = SWAP_BE16 (1);
/* note: must belong word aligned (hence the extra -2) */
mapRecordBytes = btNodeSize - sizeof(BTNodeDescriptor) - 2*sizeof(SInt16) - 2;
SETOFFSET(buffer, btNodeSize, sizeof(BTNodeDescriptor), 1);
SETOFFSET(buffer, btNodeSize, sizeof(BTNodeDescriptor) + mapRecordBytes, 2);
sectorsPerNode = btNodeSize/kBytesPerSector;
/*
* Note - worst case (32MB alloc blk) will have
* only 18 map nodes. So don't bother optimizing
* this section to do multiblock writes!
*/
for (i = 0; i < mapNodes; i++) {
if ((i + 1) < mapNodes)
nd->fLink = SWAP_BE32 (++firstMapNode); /* point to next map node */
else
nd->fLink = 0; /* this is the last map node */
WriteBuffer(driveInfo, diskStart, btNodeSize, buffer);
diskStart += sectorsPerNode;
}
}
/*
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* NOTE: IF buffer IS NULL, THIS FUNCTION WILL WRITE ZERO'S.
*
* startingSector is in terms of 512-byte sectors.
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
static void
WriteBuffer(const DriveInfo *driveInfo, UInt64 startingSector, UInt64 byteCount,
const void *buffer)
{
off_t sector;
off_t physSector = 0;
off_t byteOffsetInPhysSector;
UInt32 numBytesToIO;
UInt32 numPhysSectorsToIO;
UInt32 tempbufSizeInPhysSectors;
UInt32 tempbufSize;
UInt32 fd = driveInfo->fd;
UInt32 physSectorSize = driveInfo->physSectorSize;
void *tempbuf = NULL;
int sectorSizeRatio = driveInfo->physSectorSize / kBytesPerSector;
int status = 0; /* 0: no error; 1: alloc; 2: read; 3: write */
if (0 == byteCount) {
goto exit;
}
/*@@@@@@@@@@ buffer allocation @@@@@@@@@@*/
/* try a buffer size for optimal IO, __UP TO 4MB__. if that
fails, then try with the minimum allowed buffer size, which
is equal to physSectorSize */
tempbufSizeInPhysSectors = MIN ( (byteCount - 1 + physSectorSize) / physSectorSize,
driveInfo->physSectorsPerIO );
/* limit at 4MB */
tempbufSizeInPhysSectors = MIN ( tempbufSizeInPhysSectors, (4 * 1024 * 1024) / physSectorSize );
tempbufSize = tempbufSizeInPhysSectors * physSectorSize;
if ((tempbuf = valloc(tempbufSize)) == NULL) {
/* try allocation of smallest allowed size: one
physical sector.
NOTE: the previous valloc tempbufSize might have
already been one physical sector. we don't want to
check if that was the case, so just try again.
*/
tempbufSizeInPhysSectors = 1;
tempbufSize = physSectorSize;
if ((tempbuf = valloc(tempbufSize)) == NULL) {
status = 1;
goto exit;
}
}
/*@@@@@@@@@@ io @@@@@@@@@@*/
sector = driveInfo->sectorOffset + startingSector;
physSector = sector / sectorSizeRatio;
byteOffsetInPhysSector = (sector % sectorSizeRatio) * kBytesPerSector;
while (byteCount > 0) {
numPhysSectorsToIO = MIN ( (byteCount - 1 + physSectorSize) / physSectorSize,
tempbufSizeInPhysSectors );
numBytesToIO = MIN(byteCount, (numPhysSectorsToIO * physSectorSize) - byteOffsetInPhysSector);
/* if IO does not align with physical sector boundaries */
if ((0 != byteOffsetInPhysSector) || ((numBytesToIO % physSectorSize) != 0)) {
if (pread(fd, tempbuf, numPhysSectorsToIO * physSectorSize, physSector * physSectorSize) < 0) {
status = 2;
goto exit;
}
}
if (NULL != buffer) {
memcpy(tempbuf + byteOffsetInPhysSector, buffer, numBytesToIO);
}
else {
bzero(tempbuf + byteOffsetInPhysSector, numBytesToIO);
}
if (pwrite(fd, tempbuf, numPhysSectorsToIO * physSectorSize, physSector * physSectorSize) < 0) {
status = 3;
goto exit;
}
byteOffsetInPhysSector = 0;
byteCount -= numBytesToIO;
physSector += numPhysSectorsToIO;
if (NULL != buffer) {
buffer += numBytesToIO;
}
}
exit:
if (tempbuf) {
free(tempbuf);
tempbuf = NULL;
}
if (1 == status) {
err(1, NULL);
}
else if (2 == status) {
err(1, "read (sector %llu)", physSector);
}
else if (3 == status) {
err(1, "write (sector %llu)", physSector);
}
return;
}
static UInt32 Largest( UInt32 a, UInt32 b, UInt32 c, UInt32 d )
{
/* a := max(a,b) */
if (a < b)
a = b;
/* c := max(c,d) */
if (c < d)
c = d;
/* return max(a,c) */
if (a > c)
return a;
else
return c;
}
/*
* MarkBitInAllocationBuffer
*
* Given a buffer and allocation block, will mark off the corresponding
* bitmap bit, and return the sector number the block belongs in.
*/
static void MarkBitInAllocationBuffer( HFSPlusVolumeHeader *header,
UInt32 allocationBlock, void* sectorBuffer, UInt64 *sector )
{
UInt8 *byteP;
UInt8 mask;
UInt32 sectorsPerBlock;
UInt16 bitInSector = allocationBlock % kBitsPerSector;
UInt16 bitPosition = allocationBlock % 8;
sectorsPerBlock = header->blockSize / kBytesPerSector;
*sector = (header->allocationFile.extents[0].startBlock * sectorsPerBlock) +
(allocationBlock / kBitsPerSector);
byteP = (UInt8 *)sectorBuffer + (bitInSector >> 3);
mask = ( 0x80 >> bitPosition );
*byteP |= mask;
}
/*
* UTCToLocal - convert from Mac OS GMT time to Mac OS local time
*/
static UInt32 UTCToLocal(UInt32 utcTime)
{
UInt32 localTime = utcTime;
struct timezone timeZone;
struct timeval timeVal;
if (localTime != 0) {
/* HFS volumes need timezone info to convert local to GMT */
(void)gettimeofday( &timeVal, &timeZone );
localTime -= (timeZone.tz_minuteswest * 60);
if (timeZone.tz_dsttime)
localTime += 3600;
}
return (localTime);
}
static UInt32
DivideAndRoundUp(UInt32 numerator, UInt32 denominator)
{
UInt32 quotient;
quotient = numerator / denominator;
if (quotient * denominator != numerator)
quotient++;
return quotient;
}
#if !LINUX
#define __kCFUserEncodingFileName ("/.CFUserTextEncoding")
static UInt32
GetDefaultEncoding()
{
struct passwd *passwdp;
if ((passwdp = getpwuid(0))) { // root account
char buffer[MAXPATHLEN + 1];
int fd;
strlcpy(buffer, passwdp->pw_dir, sizeof(buffer));
strlcat(buffer, __kCFUserEncodingFileName, sizeof(buffer));
if ((fd = open(buffer, O_RDONLY, 0)) > 0) {
size_t readSize;
readSize = read(fd, buffer, MAXPATHLEN);
buffer[(readSize < 0 ? 0 : readSize)] = '\0';
close(fd);
return strtol(buffer, NULL, 0);
}
}
return 0;
}
#endif
static int
ConvertUTF8toUnicode(const UInt8* source, size_t bufsize, UniChar* unibuf,
UInt16 *charcount)
{
UInt8 byte;
UniChar* target;
UniChar* targetEnd;
*charcount = 0;
target = unibuf;
targetEnd = (UniChar *)((UInt8 *)unibuf + bufsize);
while ((byte = *source++)) {
/* check for single-byte ascii */
if (byte < 128) {
if (byte == ':') /* ':' is mapped to '/' */
byte = '/';
*target++ = SWAP_BE16 (byte);
} else {
UniChar ch;
UInt8 seq = (byte >> 4);
switch (seq) {
case 0xc: /* double-byte sequence (1100 and 1101) */
case 0xd:
ch = (byte & 0x1F) << 6; /* get 5 bits */
if (((byte = *source++) >> 6) != 2)
return (EINVAL);
break;
case 0xe: /* triple-byte sequence (1110) */
ch = (byte & 0x0F) << 6; /* get 4 bits */
if (((byte = *source++) >> 6) != 2)
return (EINVAL);
ch += (byte & 0x3F); ch <<= 6; /* get 6 bits */
if (((byte = *source++) >> 6) != 2)
return (EINVAL);
break;
default:
return (EINVAL); /* malformed sequence */
}
ch += (byte & 0x3F); /* get last 6 bits */
if (target >= targetEnd)
return (ENOBUFS);
*target++ = SWAP_BE16 (ch);
}
}
*charcount = target - unibuf;
return (0);
}
/*
* Derive the encoding hint for the given name.
*/
static int
getencodinghint(unsigned char *name)
{
#if LINUX
return(0);
#else
int mib[3];
size_t buflen = sizeof(int);
struct vfsconf vfc;
int hint = 0;
if (getvfsbyname("hfs", &vfc) < 0)
goto error;
mib[0] = CTL_VFS;
mib[1] = vfc.vfc_typenum;
mib[2] = HFS_ENCODINGHINT;
if (sysctl(mib, 3, &hint, &buflen, name, strlen((char *)name) + 1) < 0)
goto error;
return (hint);
error:
hint = GetDefaultEncoding();
return (0);
#endif
}
/* Generate Volume UUID - similar to code existing in hfs_util */
void GenerateVolumeUUID(VolumeUUID *newVolumeID) {
SHA_CTX context;
char randomInputBuffer[26];
unsigned char digest[20];
time_t now;
clock_t uptime;
size_t datalen;
double sysloadavg[3];
#if !LINUX
int sysdata;
int mib[2];
char sysctlstring[128];
struct vmtotal sysvmtotal;
#endif
do {
/* Initialize the SHA-1 context for processing: */
SHA1_Init(&context);
/* Now process successive bits of "random" input to seed the process: */
/* The current system's uptime: */
uptime = clock();
SHA1_Update(&context, &uptime, sizeof(uptime));
/* The kernel's boot time: */
#if !LINUX
mib[0] = CTL_KERN;
mib[1] = KERN_BOOTTIME;
datalen = sizeof(sysdata);
sysctl(mib, 2, &sysdata, &datalen, NULL, 0);
SHA1_Update(&context, &sysdata, datalen);
#endif
/* The system's host id: */
#if !LINUX
mib[0] = CTL_KERN;
mib[1] = KERN_HOSTID;
datalen = sizeof(sysdata);
sysctl(mib, 2, &sysdata, &datalen, NULL, 0);
SHA1_Update(&context, &sysdata, datalen);
#endif
/* The system's host name: */
#if !LINUX
mib[0] = CTL_KERN;
mib[1] = KERN_HOSTNAME;
datalen = sizeof(sysctlstring);
sysctl(mib, 2, sysctlstring, &datalen, NULL, 0);
SHA1_Update(&context, sysctlstring, datalen);
#endif
/* The running kernel's OS release string: */
#if !LINUX
mib[0] = CTL_KERN;
mib[1] = KERN_OSRELEASE;
datalen = sizeof(sysctlstring);
sysctl(mib, 2, sysctlstring, &datalen, NULL, 0);
SHA1_Update(&context, sysctlstring, datalen);
#endif
/* The running kernel's version string: */
#if !LINUX
mib[0] = CTL_KERN;
mib[1] = KERN_VERSION;
datalen = sizeof(sysctlstring);
sysctl(mib, 2, sysctlstring, &datalen, NULL, 0);
SHA1_Update(&context, sysctlstring, datalen);
#endif
/* The system's load average: */
datalen = sizeof(sysloadavg);
getloadavg(sysloadavg, 3);
SHA1_Update(&context, &sysloadavg, datalen);
/* The system's VM statistics: */
#if !LINUX
mib[0] = CTL_VM;
mib[1] = VM_METER;
datalen = sizeof(sysvmtotal);
sysctl(mib, 2, &sysvmtotal, &datalen, NULL, 0);
SHA1_Update(&context, &sysvmtotal, datalen);
#endif
/* The current GMT (26 ASCII characters): */
time(&now);
strncpy(randomInputBuffer, asctime(gmtime(&now)), 26); /* "Mon Mar 27 13:46:26 2000" */
SHA1_Update(&context, randomInputBuffer, 26);
/* Pad the accumulated input and extract the final digest hash: */
SHA1_Final(digest, &context);
memcpy(newVolumeID, digest, sizeof(*newVolumeID));
} while ((newVolumeID->v.high == 0) || (newVolumeID->v.low == 0));
}
|