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
|
/*********************************************************
* Copyright (C) 1998 VMware, Inc. All rights reserved.
*
* This program 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 version 2.1 and no later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*
*********************************************************/
/*
* util.c --
*
* misc util functions
*/
#undef WIN32_LEAN_AND_MEAN
#if defined(__linux__) && !defined(VMX86_TOOLS)
#define _GNU_SOURCE
#endif
#include "vm_ctype.h"
#include "safetime.h"
#if defined(_WIN32)
# include <winsock2.h> // also includes windows.h
# include <io.h>
# include <process.h>
# include "coreDump.h"
#endif
#include <fcntl.h>
#include <stdlib.h>
#include <limits.h>
#include <stddef.h>
#include <stdarg.h>
#include <errno.h>
#include <ctype.h>
#if !defined(_WIN32) && !defined(N_PLAT_NLM)
# include <unistd.h>
# include <pwd.h>
# include <dlfcn.h>
#endif
#if defined(__linux__) && !defined(VMX86_TOOLS)
# include <link.h>
#endif
#include "vmware.h"
#include "msg.h"
#include "util.h"
#include "str.h"
/* For HARD_EXPIRE --hpreg */
#include "vm_version.h"
#include "su.h"
#include "posix.h"
#include "file.h"
#include "util_shared.h"
#include "escape.h"
#include "base64.h"
#include "unicode.h"
#include "posix.h"
#ifndef O_BINARY
#define O_BINARY 0
#endif
/*
* Win32 doesn't have an iovec type, so do this here to avoid messy games in
* the header files. --Jeremy.
*/
struct UtilVector {
void *base;
int len;
};
#if defined(_WIN32)
#include "win32util.h"
static int UtilTokenHasGroup(HANDLE token, SID *group);
#endif
#ifdef VM_X86_64
# if defined(__GNUC__) && (!defined(USING_AUTOCONF) || defined(HAVE_UNWIND_H))
# define UTIL_BACKTRACE_USE_UNWIND
# endif
#endif
#ifdef UTIL_BACKTRACE_USE_UNWIND
#include <unwind.h>
#define MAX_SKIPPED_FRAMES 10
struct UtilBacktraceFromPointerData {
uintptr_t basePtr;
Util_OutputFunc outFunc;
void *outFuncData;
unsigned int frameNr;
unsigned int skippedFrames;
};
struct UtilBacktraceToBufferData {
uintptr_t basePtr;
uintptr_t *buffer;
size_t len;
};
#endif /* UTIL_BACKTRACE_USE_UNWIND */
#if !defined(_WIN32) && !defined(N_PLAT_NLM)
static Unicode GetHomeDirectory(ConstUnicode name);
static Unicode GetLoginName(int uid);
#endif
static Bool IsAlphaOrNum(char ch);
/*
*----------------------------------------------------------------------
*
* Util_Init --
*
* Opportunity to sanity check things
*
* Results:
* Bool - TRUE (this should never fail)
*
* Side effects:
* None
*
*----------------------------------------------------------------------
*/
Bool
Util_Init(void)
{
#ifdef VMX86_DEVEL
/*
* Sanity check Str_Snprintf so that we're never thrown off guard
* by a change in the underlying libraries that Str_Snprintf doesn't
* catch and wrap properly.
*/
{
char buf[2] = { 'x', 'x' };
int rv;
rv = Str_Snprintf(buf, sizeof(buf), "a");
ASSERT(rv == 1);
ASSERT(!strcmp(buf, "a"));
rv = Str_Snprintf(buf, sizeof(buf), "ab");
ASSERT(rv == -1);
ASSERT(!strcmp(buf, "a"));
}
#endif
return TRUE;
}
/*
*----------------------------------------------------------------------
*
* Util_Checksum32 --
*
* Checksums a uint32 aligned block by progressive XOR. Basically parity
* checking of each bit position.
*
*----------------------------------------------------------------------
*/
uint32
Util_Checksum32(const uint32 *buf, int len)
{
uint32 checksum = 0;
int i;
ASSERT((len % 4) == 0);
for (i = 0; i < len; i+=4) checksum ^= *(buf++);
return checksum;
}
/*
*----------------------------------------------------------------------
*
* Util_Checksum --
*
* Checksums a block by progressive XOR. Basically parity
* checking of each bit position.
*
*----------------------------------------------------------------------
*/
uint32
Util_Checksum(const uint8 *buf, int len)
{
uint32 checksum;
int remainder, shift;
remainder = len % 4;
len -= remainder;
checksum = Util_Checksum32((uint32 *)buf, len);
buf += len;
shift = 0;
while (remainder--) {
/*
* Note: this is little endian.
*/
checksum ^= (*buf++ << shift);
shift += 8;
}
return checksum;
}
/*
*----------------------------------------------------------------------
*
* Util_Checksumv --
*
* Checksums an iovector by progressive XOR. Basically parity checking of
* each bit position.
*
*----------------------------------------------------------------------
*/
uint32
Util_Checksumv(void *iov, // IN
int numEntries) // IN
{
uint32 checksum = 0;
struct UtilVector *vector = (struct UtilVector *) iov;
uint32 partialChecksum;
int bytesSoFar = 0;
int rotate;
while (numEntries-- > 0) {
partialChecksum = Util_Checksum(vector->base, vector->len);
rotate = (bytesSoFar & 3) * 8;
checksum ^= ((partialChecksum << rotate) |
(partialChecksum >> (32 - rotate)));
bytesSoFar += vector->len;
vector++;
}
return checksum;
}
/*
*-----------------------------------------------------------------------------
*
* UtilLogWrapper --
*
* Adapts the Log function to meet the interface required by backtracing
* functions by adding an ignored void* argument.
*
* NOTE: This function needs to be static on linux (and any other
* platform appLoader might be ported to). See bug 403780.
*
* Results:
* Same effect as Log(fmt, ...)
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
static void
UtilLogWrapper(void *ignored, // IN:
const char *fmt, // IN:
...) // IN:
{
uint32 len;
va_list ap;
char thisLine[UTIL_BACKTRACE_LINE_LEN];
va_start(ap, fmt);
len = Str_Vsnprintf(thisLine, UTIL_BACKTRACE_LINE_LEN - 2, fmt, ap);
va_end(ap);
if (len >= UTIL_BACKTRACE_LINE_LEN - 2) {
len = UTIL_BACKTRACE_LINE_LEN - 3;
}
if (thisLine[len - 1] != '\n') {
thisLine[len] = '\n';
thisLine[len + 1] = '\0';
}
Log("%s", thisLine);
}
#ifdef UTIL_BACKTRACE_USE_UNWIND
/*
*-----------------------------------------------------------------------------
*
* UtilBacktraceToBufferCallback --
*
* Callback from _Unwind_Backtrace to add one entry to the backtrace
* buffer.
*
* Results:
* _URC_NO_REASON : Please continue with backtrace.
* _URC_END_OF_STACK : Abort backtrace, we run out of space (*).
*
* (*) Caller does not care. Anything else than NO_REASON is fatal
* and forces _Unwind_Backtrace to report PHASE1 error.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
static _Unwind_Reason_Code
UtilBacktraceToBufferCallback(struct _Unwind_Context *ctx, // IN: Unwind context
void *cbData) // IN/OUT: Our data
{
struct UtilBacktraceToBufferData *data = cbData;
uintptr_t cfa = _Unwind_GetCFA(ctx);
/*
* Stack grows down. So if we are below basePtr, do nothing...
*/
if (cfa >= data->basePtr) {
if (data->len) {
*data->buffer++ = _Unwind_GetIP(ctx);
data->len--;
} else {
return _URC_END_OF_STACK;
}
}
return _URC_NO_REASON;
}
/*
*-----------------------------------------------------------------------------
*
* UtilBacktraceFromPointerCallback --
*
* Callback from _Unwind_Backtrace to print one backtrace entry
* to the backtrace output.
*
* Results:
* _URC_NO_REASON : Please continue with backtrace.
* _URC_END_OF_STACK : Abort backtrace.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
static _Unwind_Reason_Code
UtilBacktraceFromPointerCallback(struct _Unwind_Context *ctx, // IN: Unwind context
void *cbData) // IN/OUT: Our status
{
struct UtilBacktraceFromPointerData *data = cbData;
uintptr_t cfa = _Unwind_GetCFA(ctx);
/*
* Stack grows down. So if we are below basePtr, do nothing...
*/
if (cfa >= data->basePtr && data->frameNr < 500) {
#ifndef VM_X86_64
# error You should not build this on 32bit - there is no eh_frame there.
#endif
/* bump basePtr for glibc unwind bug, see [302237] */
data->basePtr = cfa + 8;
/* Do output without leading '0x' to save some horizontal space... */
data->outFunc(data->outFuncData,
"Backtrace[%u] %016lx rip=%016lx rbx=%016lx rbp=%016lx "
"r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
data->frameNr, cfa, _Unwind_GetIP(ctx),
_Unwind_GetGR(ctx, 3), _Unwind_GetGR(ctx, 6),
_Unwind_GetGR(ctx, 12), _Unwind_GetGR(ctx, 13),
_Unwind_GetGR(ctx, 14), _Unwind_GetGR(ctx, 15));
data->frameNr++;
return _URC_NO_REASON;
} else if (data->skippedFrames < MAX_SKIPPED_FRAMES && !data->frameNr) {
/*
* Skip over the frames before the specified starting point of the
* backtrace.
*/
data->skippedFrames++;
return _URC_NO_REASON;
}
return _URC_END_OF_STACK;
}
#if !defined(_WIN32) && !defined(N_PLAT_NLM) && !defined(VMX86_TOOLS)
/*
*-----------------------------------------------------------------------------
*
* UtilSymbolBacktraceFromPointerCallback --
*
* Callback from _Unwind_Backtrace to print one backtrace entry
* to the backtrace output. This version includes symbol information,
* if available.
*
* Results:
* _URC_NO_REASON : Please continue with backtrace.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
static _Unwind_Reason_Code
UtilSymbolBacktraceFromPointerCallback(struct _Unwind_Context *ctx, // IN: Unwind context
void *cbData) // IN/OUT: Our status
{
struct UtilBacktraceFromPointerData *data = cbData;
uintptr_t cfa = _Unwind_GetCFA(ctx);
/*
* Stack grows down. So if we are below basePtr, do nothing...
*/
if (cfa >= data->basePtr && data->frameNr < 500) {
#ifndef VM_X86_64
# error You should not build this on 32bit - there is no eh_frame there.
#endif
void *enclFuncAddr;
Dl_info dli;
/* bump basePtr for glibc unwind bug, see [302237] */
data->basePtr = cfa + 8;
#ifdef __linux__
enclFuncAddr = _Unwind_FindEnclosingFunction((void *)_Unwind_GetIP(ctx));
#else
enclFuncAddr = NULL;
#endif
if (dladdr(enclFuncAddr, &dli) ||
dladdr((void *)_Unwind_GetIP(ctx), &dli)) {
data->outFunc(data->outFuncData,
"SymBacktrace[%u] %016lx rip=%016lx in function %s "
"in object %s loaded at %016lx\n",
data->frameNr, cfa, _Unwind_GetIP(ctx),
dli.dli_sname, dli.dli_fname, dli.dli_fbase);
} else {
data->outFunc(data->outFuncData,
"SymBacktrace[%u] %016lx rip=%016lx \n",
data->frameNr, cfa, _Unwind_GetIP(ctx));
}
data->frameNr++;
return _URC_NO_REASON;
} else if (data->skippedFrames < MAX_SKIPPED_FRAMES && !data->frameNr) {
/*
* Skip over the frames before the specified starting point of the
* backtrace.
*/
data->skippedFrames++;
return _URC_NO_REASON;
}
return _URC_END_OF_STACK;
}
#endif
#endif
/*
*----------------------------------------------------------------------
*
* Util_BacktraceFromPointer --
*
* log the stack backtrace given a frame pointer
*
* Results:
*
* void
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
void
Util_BacktraceFromPointer(uintptr_t *basePtr)
{
Util_BacktraceFromPointerWithFunc(basePtr, UtilLogWrapper, NULL);
}
/*
*-----------------------------------------------------------------------------
*
* Util_BacktraceFromPointerWithFunc --
*
* Output a backtrace from the given frame porinter, using
* "outputFunc" as the logging function. For each line of the backtrace,
* this will call "outputFunc(outputFuncData, fmt, ...)"
*
* Results:
* None.
*
* Side effects:
* Calls outFunc repeatedly.
*
*-----------------------------------------------------------------------------
*/
void
Util_BacktraceFromPointerWithFunc(uintptr_t *basePtr,
Util_OutputFunc outFunc,
void *outFuncData)
{
#if defined(UTIL_BACKTRACE_USE_UNWIND)
struct UtilBacktraceFromPointerData data;
data.basePtr = (uintptr_t)basePtr;
data.outFunc = outFunc;
data.outFuncData = outFuncData;
data.frameNr = 0;
data.skippedFrames = 0;
_Unwind_Backtrace(UtilBacktraceFromPointerCallback, &data);
#if !defined(_WIN32) && !defined(N_PLAT_NLM) && !defined(VMX86_TOOLS)
/*
* We do a separate pass here that includes symbols in order to
* make sure the base backtrace that does not call dladdr() etc.
* is safely produced.
*/
data.basePtr = (uintptr_t)basePtr;
data.outFunc = outFunc;
data.outFuncData = outFuncData;
data.frameNr = 0;
data.skippedFrames = 0;
_Unwind_Backtrace(UtilSymbolBacktraceFromPointerCallback, &data);
#endif
#elif !defined(VM_X86_64)
uintptr_t *x = basePtr;
int i;
#if !defined(_WIN32) && !defined(N_PLAT_NLM) && !defined(VMX86_TOOLS)
Dl_info dli;
#endif
for (i = 0; i < 256; i++) {
if (x < basePtr ||
(uintptr_t) x - (uintptr_t) basePtr > 0x8000) {
break;
}
outFunc(outFuncData, "Backtrace[%d] %#08x eip %#08x \n", i, x[0], x[1]);
x = (uintptr_t *) x[0];
}
#if !defined(_WIN32) && !defined(N_PLAT_NLM) && !defined(VMX86_TOOLS)
/*
* We do a separate pass here that includes symbols in order to
* make sure the base backtrace that does not call dladdr() etc.
* is safely produced.
*/
x = basePtr;
for (i = 0; i < 256; i++) {
if (x < basePtr ||
(uintptr_t) x - (uintptr_t) basePtr > 0x8000) {
break;
}
if (dladdr((uintptr_t *)x[1], &dli)) {
outFunc(outFuncData, "SymBacktrace[%d] %#08x eip %#08x in function %s "
"in object %s loaded at %#08x\n",
i, x[0], x[1], dli.dli_sname, dli.dli_fname,
dli.dli_fbase);
} else {
outFunc(outFuncData, "SymBacktrace[%d] %#08x eip %#08x \n", i, x[0], x[1]);
}
x = (uintptr_t *) x[0];
}
#endif
#endif
}
/*
*-----------------------------------------------------------------------------
*
* Util_BacktraceToBuffer --
*
* Output a backtrace from the given frame pointer to supplied buffer.
*
* Results:
* None.
*
* Side effects:
* See above.
*
*-----------------------------------------------------------------------------
*/
void
Util_BacktraceToBuffer(uintptr_t *basePtr,
uintptr_t *buffer,
int len)
{
#if defined(UTIL_BACKTRACE_USE_UNWIND)
struct UtilBacktraceToBufferData data;
data.basePtr = (uintptr_t)basePtr;
data.buffer = buffer;
data.len = len;
_Unwind_Backtrace(UtilBacktraceToBufferCallback, &data);
#elif !defined(VM_X86_64)
uintptr_t *x = basePtr;
int i;
for (i = 0; i < 256 && i < len; i++) {
if (x < basePtr ||
(uintptr_t) x - (uintptr_t) basePtr > 0x8000) {
break;
}
buffer[i] = x[1];
x = (uintptr_t *) x[0];
}
#endif
}
/*
*----------------------------------------------------------------------
*
* Util_Data2Buffer --
*
* Format binary data for printing
*
* Results:
* TRUE if all data fits into buffer, FALSE otherwise.
*
* Side effects:
* None
*
*----------------------------------------------------------------------
*/
Bool
Util_Data2Buffer(char *buf, // OUT
size_t bufSize, // IN
const void *data0, // IN
size_t dataSize) // IN
{
size_t n;
/* At least 1 byte (for NUL) must be available. */
if (!bufSize) {
return FALSE;
}
bufSize = bufSize / 3;
n = MIN(dataSize, bufSize);
if (n != 0) {
const uint8 *data = data0;
while (n > 0) {
static const char digits[] = "0123456789ABCDEF";
*buf++ = digits[*data >> 4];
*buf++ = digits[*data & 0xF];
*buf++ = ' ';
data++;
n--;
}
buf--;
}
*buf = 0;
return dataSize <= bufSize;
}
/*
*----------------------------------------------------------------------
*
* Util_Backtrace --
*
* log the stack backtrace for a particular bug number
*
* Results:
*
* void
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
void
Util_Backtrace(int bugNr) // IN
{
Util_BacktraceWithFunc(bugNr, UtilLogWrapper, NULL);
}
/*
*-----------------------------------------------------------------------------
*
* Util_BacktraceWithFunc --
*
* Outputs the stack backtrace for the bug "bugNr," using the
* log function "outFunc" as described in the comment for
* Util_BacktraceFromPointerWithFunc.
*
* Results:
* None.
*
* Side effects:
* Calls outFunc several times.
*
*-----------------------------------------------------------------------------
*/
void
Util_BacktraceWithFunc(int bugNr, Util_OutputFunc outFunc, void *outFuncData)
{
#if !defined(_WIN32)
uintptr_t *x = (uintptr_t *) &bugNr;
#endif
if (bugNr == 0) {
outFunc(outFuncData, "Backtrace:\n");
} else {
outFunc(outFuncData, "Backtrace for bugNr=%d\n",bugNr);
}
#if defined(_WIN32)
CoreDump_Backtrace(outFunc, outFuncData);
#else
Util_BacktraceFromPointerWithFunc(&x[-2], outFunc, outFuncData);
#endif
}
#if !defined(_WIN32) && !defined(N_PLAT_NLM)
/*
*----------------------------------------------------------------------
*
* UtilDoTildeSubst --
*
* Given a string following a tilde, this routine returns the
* corresponding home directory.
*
* Results:
* The result is a pointer to a static string containing the home
* directory in native format. The returned string is a newly
* allocated string which may/must be freed by the caller
*
* Side effects:
* Information may be left in resultPtr.
*
* Credit: derived from J.K.Ousterhout's Tcl
*----------------------------------------------------------------------
*/
static Unicode
UtilDoTildeSubst(Unicode user) // IN - name of user
{
Unicode str = NULL;
if (*user == '\0') {
str = Unicode_Duplicate(Posix_Getenv("HOME"));
if (str == NULL) {
Log("Could not expand environment variable HOME.\n");
}
} else {
str = GetHomeDirectory(user);
if (str == NULL) {
Log("Could not get information for user '%s'.\n", user);
}
}
return str;
}
#endif
#ifndef N_PLAT_NLM
/*
*----------------------------------------------------------------------
*
* Util_ExpandString --
*
* converts the strings by expanding "~", "~user" and environment
* variables
*
* Results:
*
* Return a newly allocated string. The caller is responsible
* for deallocating it.
*
* Return NULL in case of error.
*
* Side effects:
* memory allocation
*
* Bugs:
* the handling of enviroment variable references is very
* simplistic: there can be only one in a pathname segment
* and it must appear last in the string
*
*----------------------------------------------------------------------
*/
#define UTIL_MAX_PATH_CHUNKS 100
Unicode
Util_ExpandString(ConstUnicode fileName) // IN file path to expand
{
Unicode copy = NULL;
Unicode result = NULL;
int nchunk = 0;
char *chunks[UTIL_MAX_PATH_CHUNKS];
int chunkSize[UTIL_MAX_PATH_CHUNKS];
Bool freeChunk[UTIL_MAX_PATH_CHUNKS];
char *cp;
int i;
ASSERT(fileName);
copy = Unicode_Duplicate(fileName);
/*
* quick exit
*/
if (!Unicode_StartsWith(fileName, "~") &&
Unicode_Find(fileName, "$") == UNICODE_INDEX_NOT_FOUND) {
return copy;
}
/*
* XXX Because the rest part of code depends pretty heavily from character
* pointer operations we want to leave it as-is and don't want to re-work
* it with using unicode library. However it's acceptable only until our
* Unicode type is utf-8 and until code below works correctly with utf-8.
*/
/*
* Break string into nice chunks for separate expansion.
*
* The rule for terminating a ~ expansion is historical. -- edward
*/
nchunk = 0;
for (cp = copy; *cp;) {
size_t len;
if (*cp == '$') {
char *p;
for (p = cp + 1; IsAlphaOrNum(*p) || *p == '_'; p++) {
}
len = p - cp;
#if !defined(_WIN32)
} else if (cp == copy && *cp == '~') {
len = strcspn(cp, DIRSEPS);
#endif
} else {
len = strcspn(cp, "$");
}
if (nchunk >= UTIL_MAX_PATH_CHUNKS) {
Msg_Append(MSGID(util.expandStringTooManyChunks)
"Filename \"%s\" has too many chunks.\n",
UTF8(fileName));
goto out;
}
chunks[nchunk] = cp;
chunkSize[nchunk] = len;
freeChunk[nchunk] = FALSE;
nchunk++;
cp += len;
}
/*
* Expand leanding ~
*/
#if !defined(_WIN32)
if (chunks[0][0] == '~') {
char save = (cp = chunks[0])[chunkSize[0]];
cp[chunkSize[0]] = 0;
ASSERT(!freeChunk[0]);
chunks[0] = UtilDoTildeSubst(chunks[0] + 1);
cp[chunkSize[0]] = save;
if (chunks[0] == NULL) {
/* It could not be expanded, therefore leave as original. */
chunks[0] = cp;
} else {
/* It was expanded, so adjust the chunks. */
chunkSize[0] = strlen(chunks[0]);
freeChunk[0] = TRUE;
}
}
#endif
/*
* Expand $
*/
for (i = 0; i < nchunk; i++) {
char save;
Unicode expand = NULL;
char buf[100];
#if defined(_WIN32)
utf16_t bufW[100];
#endif
cp = chunks[i];
if (*cp != '$' || chunkSize[i] == 1) {
/*
* Skip if the chuck has only the $ character.
* $ will be kept as a part of the pathname.
*/
continue;
}
save = cp[chunkSize[i]];
cp[chunkSize[i]] = 0;
/*
* $PID and $USER are interpreted specially.
* Others are just getenv().
*/
expand = Unicode_Duplicate(Posix_Getenv(cp + 1));
if (expand != NULL) {
} else if (strcasecmp(cp + 1, "PID") == 0) {
Str_Snprintf(buf, sizeof buf, "%"FMTPID, getpid());
expand = Util_SafeStrdup(buf);
} else if (strcasecmp(cp + 1, "USER") == 0) {
#if !defined(_WIN32)
int uid = getuid();
expand = GetLoginName(uid);
#else
DWORD n = ARRAYSIZE(bufW);
if (GetUserNameW(bufW, &n)) {
expand = Unicode_AllocWithUTF16(bufW);
}
#endif
if (expand == NULL) {
expand = Unicode_Duplicate("unknown");
}
} else {
Warning("Environment variable '%s' not defined in '%s'.\n",
cp + 1, fileName);
#if !defined(_WIN32)
/*
* Strip off the env variable string from the pathname.
*/
expand = Unicode_Duplicate("");
#else // _WIN32
/*
* The problem is we have really no way to distinguish the caller's
* intention is a dollar sign ($) is used as a part of the pathname
* or as an environment variable.
*
* If the token does not expand to an environment variable,
* then assume it is a part of the pathname. Do not strip it
* off like it is done in linux host (see above)
*
* XXX We should also consider using %variable% convention instead
* of $variable for Windows platform.
*/
Str_Strcpy(buf, cp, 100);
expand = Unicode_AllocWithUTF8(buf);
#endif
}
cp[chunkSize[i]] = save;
ASSERT(expand != NULL);
ASSERT(!freeChunk[i]);
chunks[i] = expand;
if (chunks[i] == NULL) {
Msg_Append(MSGID(util.ExpandStringNoMemForChunk)
"Cannot allocate memory to expand \"%s\" in \"%s\".\n",
expand, UTF8(fileName));
goto out;
}
chunkSize[i] = strlen(expand);
freeChunk[i] = TRUE;
}
/*
* Put all the chunks back together.
*/
{
int size = 1; // 1 for the terminating null
for (i = 0; i < nchunk; i++) {
size += chunkSize[i];
}
result = malloc(size);
}
if (result == NULL) {
Msg_Append(MSGID(util.expandStringNoMemForResult)
"Cannot allocate memory for the expansion of \"%s\".\n",
UTF8(fileName));
goto out;
}
cp = result;
for (i = 0; i < nchunk; i++) {
memcpy(cp, chunks[i], chunkSize[i]);
cp += chunkSize[i];
}
*cp = 0;
out:
/*
* Clean up and return.
*/
for (i = 0; i < nchunk; i++) {
if (freeChunk[i]) {
free(chunks[i]);
}
}
free(copy);
return result;
}
#endif /* !defined(N_PLAT_NLM) */
/* XXX This should go in a separate utilPosix.c file --hpreg */
#if !defined(_WIN32) && !defined(N_PLAT_NLM)
/*
*----------------------------------------------------------------------
*
* Util_MakeSureDirExists --
*
* Make sure a directory exists
*
* Results:
* TRUE on success
* FALSE on failure
*
* Side effects:
* None
*
*----------------------------------------------------------------------
*/
Bool
Util_MakeSureDirExistsAndAccessible(char const *path, // IN
unsigned int mode) // IN
{
char *epath;
struct stat statbuf;
epath = Util_ExpandString(path);
if (epath == NULL) {
return FALSE;
}
if (Posix_Stat(epath, &statbuf) == 0) {
if (! S_ISDIR(statbuf.st_mode)) {
Msg_Append(MSGID(util.msde.notDir)
"The path \"%s\" exists, but it is not a directory.\n",
epath);
free(epath);
return FALSE;
}
} else {
if (Posix_Mkdir(epath, mode) != 0) {
Msg_Append(MSGID(util.msde.mkdir)
"Cannot create directory \"%s\": %s.\n",
epath, Msg_ErrString());
free(epath);
return FALSE;
}
}
if (FileIO_Access(epath, FILEIO_ACCESS_READ | FILEIO_ACCESS_WRITE | FILEIO_ACCESS_EXEC | FILEIO_ACCESS_EXISTS) ==
FILEIO_ERROR) {
Msg_Append(MSGID(util.msde.noAccess)
"Directory \"%s\" is not accessible: %s.\n",
epath, Msg_ErrString());
free(epath);
return FALSE;
}
free(epath);
return TRUE;
}
#endif
/*
*----------------------------------------------------------------------
*
* Util_ExitProcessAbruptly
*
* On Win32, terminate the process and all of its threads, without
* calling any of the DLL termination handlers.
* On Linux, call exit().
*
* Results:
* None
*
* Side effects:
* None
*
*----------------------------------------------------------------------
*/
void
Util_ExitProcessAbruptly(int code) // IN
{
#if defined(_WIN32)
TerminateProcess(GetCurrentProcess(),code);
#else
exit(code);
#endif
}
/*
*----------------------------------------------------------------------
*
* Util_ExitThread --
*
* Terminate the running thread.
*
* Results:
* None
*
* Side effects:
* None
*
*----------------------------------------------------------------------
*/
void
Util_ExitThread(int code) // IN
{
#if defined(_WIN32)
ExitThread(code);
#else
exit(code);
#endif
}
/*
*----------------------------------------------------------------------
*
* Util_CompareDotted --
*
* Compares two version numbers encoded as dotted strings.
*
* Results:
* 0 if equal, -1 if s1 is less than s2, else 1.
*
* Side effects:
* None
*
*----------------------------------------------------------------------
*/
int
Util_CompareDotted(const char *s1, const char *s2)
{
int i, x[5], y[5];
for (i = 0; i < 5; i++) {
x[i] = 0;
y[i] = 0;
}
if (sscanf(s1, "%d.%d.%d.%d.%d", &x[0], &x[1], &x[2], &x[3], &x[4]) < 1) {
x[0] = 1;
}
if (sscanf(s2, "%d.%d.%d.%d.%d", &y[0], &y[1], &y[2], &y[3], &y[4]) < 1) {
y[0] = 1;
}
for (i = 0; i < 5; i++) {
if (x[i] < y[i]) {
return -1;
}
if (x[i] > y[i]) {
return 1;
}
}
return 0;
}
#if defined(_WIN32)
/*
*-----------------------------------------------------------------------------
*
* UtilTokenHasGroup --
*
* Determine if the specified token has a particular group
*
* Results:
* 1 if yes
* 0 if no
* <0 on error
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
static int
UtilTokenHasGroup(HANDLE token,
SID *group)
{
/*
* The code is from
* http://support.microsoft.com/support/kb/articles/Q118/6/26.ASP
* (HOWTO: Determine Whether a Thread Is Running in User Context of Local
* Administrator Account), modified as follows:
*
* . Removed the exception stuff
*
* . Fixed the token handle leak
*
* . Used DuplicateToken() which does just what we need instead of
* ImpersonateSelf()/RevertToSelf() which does more, and which I believe
* will not work if we are already impersonating ourselves
*
* . Allocated the SD on the stack
*
* . Got rid of the hardcoded DWORD in the computation of the ACL size
*
* . Used malloc()/free() instead of Local*()
*
* . Added comments
*
* --hpreg
*/
/*
* Make up private access rights --hpreg
*/
#define Util_HasAdminPriv_Read (1 << 0)
#define Util_HasAdminPriv_Write (1 << 1)
int ret;
HANDLE iToken;
SECURITY_DESCRIPTOR sd;
DWORD aclLen;
ACL *acl;
GENERIC_MAPPING gm;
PRIVILEGE_SET ps;
DWORD psLen;
DWORD granted;
BOOL status;
iToken = INVALID_HANDLE_VALUE;
acl = NULL;
/*
* Duplicate the token, because AccessCheck() requires an impersonation
* token --hpreg
*/
if (DuplicateToken(token, SecurityImpersonation, &iToken) == 0) {
ret = -3;
goto end;
}
/*
* Construct a Security Descriptor with a Discretionary Access Control List
* that contains an Access Control Entry for the administrator group's
* Security IDentifier --hpreg
*/
if (InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION) == 0) {
ret = -5;
goto end;
}
/*
* This magic formula comes from the documentation for
* InitializeAcl() --hpreg
*/
aclLen = sizeof(ACL)
+ ( sizeof(ACCESS_ALLOWED_ACE)
- sizeof(((ACCESS_ALLOWED_ACE *)0)->SidStart)
+ GetLengthSid(group));
acl = malloc(aclLen);
if (acl == NULL) {
ret = -6;
goto end;
}
if (InitializeAcl(acl, aclLen, ACL_REVISION) == 0) {
ret = -7;
goto end;
}
if (AddAccessAllowedAce(acl, ACL_REVISION,
Util_HasAdminPriv_Read | Util_HasAdminPriv_Write, group) == 0) {
ret = -8;
goto end;
}
if (SetSecurityDescriptorDacl(&sd, TRUE, acl, FALSE) == 0) {
ret = -9;
goto end;
}
/*
* Set the owner and group of the SD, because AccessCheck() requires
* it --hpreg
*/
if (SetSecurityDescriptorGroup(&sd, group, FALSE) == 0) {
ret = -10;
goto end;
}
if (SetSecurityDescriptorOwner(&sd, group, FALSE) == 0) {
ret = -11;
goto end;
}
/*
* Finally, check if the SD grants access to the calling thread --hpreg
*/
gm.GenericRead = Util_HasAdminPriv_Read;
gm.GenericWrite = Util_HasAdminPriv_Write;
gm.GenericExecute = 0;
gm.GenericAll = Util_HasAdminPriv_Read | Util_HasAdminPriv_Write;
psLen = sizeof(ps);
if (AccessCheck(&sd, iToken, Util_HasAdminPriv_Read, &gm, &ps, &psLen,
&granted, &status) == 0) {
ret = -12;
goto end;
}
ret = status ? 1 : 0;
end:
if (iToken != INVALID_HANDLE_VALUE) {
if (CloseHandle(iToken) == 0 && ret >= 0) {
ret = -14;
}
}
free(acl);
return ret;
#undef Util_HasAdminPriv_Read
#undef Util_HasAdminPriv_Write
}
/*
*-----------------------------------------------------------------------------
*
* Util_TokenHasAdminPriv --
*
* Determine if the specified token has administrator privileges
*
* Results:
* 1 if yes
* 0 if no
* <0 on error
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
int
Util_TokenHasAdminPriv(HANDLE token)
{
SID_IDENTIFIER_AUTHORITY sidIdentAuth = SECURITY_NT_AUTHORITY;
SID *adminGrp = NULL;
int ret;
/*
* Build the Security IDentifier of the administrator group --hpreg
*/
if (AllocateAndInitializeSid(&sidIdentAuth, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
&adminGrp) == 0) {
ret = -4;
goto end;
}
ret = UtilTokenHasGroup(token, adminGrp);
end:
if (adminGrp) {
FreeSid(adminGrp);
}
return ret;
}
/*
*-----------------------------------------------------------------------------
*
* Util_TokenHasInteractPriv --
*
* Determine if the specified token is logged in interactively.
* -- local logons and Remote Desktops logons
*
* Results:
* 1 if yes
* 0 if no
* <0 on error
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
int
Util_TokenHasInteractPriv(HANDLE token)
{
SID_IDENTIFIER_AUTHORITY sidIdentAuth = SECURITY_NT_AUTHORITY;
SID *interactiveGrp = NULL;
int ret;
/*
* Build the Security IDentifier of the administrator group --hpreg
*/
if (AllocateAndInitializeSid(&sidIdentAuth, 1, SECURITY_INTERACTIVE_RID,
0, 0, 0, 0, 0, 0, 0,
&interactiveGrp) == 0) {
ret = -4;
goto end;
}
ret = UtilTokenHasGroup(token, interactiveGrp);
end:
if (interactiveGrp) {
FreeSid(interactiveGrp);
}
return ret;
}
#endif
/*
*-----------------------------------------------------------------------------
*
* Util_HasAdminPriv --
*
* Determine if the calling code has administrator privileges --hpreg
*
* Results:
* 1 if yes
* 0 if no
* <0 on error
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
int
Util_HasAdminPriv(void)
{
#if defined(_WIN32)
HANDLE token = INVALID_HANDLE_VALUE;
int ret = -1;
/*
* Retrieve the access token of the calling thread --hpreg
*
* On some machines OpenThreadToken with openAsSelf set to FALSE fails.
* Empirically, it seems that, in the security context of another user
* (even when the impersonation token is at SecurityImpersonation level)
* it is not able to obtain the thread token with TOKEN_DUPLICATE access.
* Calling OpenThreadToken to open as self is more reliable and does not
* seem to hurt. -- vui
*/
if (OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE, TRUE,
&token) == 0) {
if (GetLastError() != ERROR_NO_TOKEN) {
ret = -1;
goto end;
}
if (OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE,
&token) == 0) {
ret = -2;
goto end;
}
}
ret = Util_TokenHasAdminPriv(token);
end:
if (token != INVALID_HANDLE_VALUE) {
if (CloseHandle(token) == 0 && ret >= 0) {
ret = -13;
}
}
return ret;
#else
return Id_IsSuperUser() ? 1 : 0;
#endif
}
#if !defined(N_PLAT_NLM)
/*
*-----------------------------------------------------------------------------
*
* Util_DeriveFileName --
*
* This function is admittedly weird. The basic idea is that we
* have a path to a dictionary file, and we need to make a path to
* a another file that's named in a similar way to that dictionary
* file (e.g., only difference is extension, or filename and
* extension).
*
* This function returns a pointer to the result
*
* Results:
* Pointer to string (on success, caller should free string),
* otherwise NULL.
*
* Side effects:
* Allocates memory to be freed by caller.
*
*-----------------------------------------------------------------------------
*/
char *
Util_DeriveFileName(const char *source, // IN: path to dict file (incl filename)
const char *name, // IN: what to replace filename with (optional)
const char *ext) // IN: what to replace extension with (optional)
{
char *returnResult = NULL;
char *path = NULL;
char *base = NULL;
if (source == NULL || (name == NULL && ext == NULL)) {
Warning("invalid use of function\n");
return NULL;
}
File_GetPathName(source, &path, &base);
/* If replacing name and extension */
if (name != NULL) {
free(base);
/*
* If the "name" we have to append is a relative path (i.e., not an
* absolute path), then we need to concatenate the "name" to the
* path of "source". If the path of "source" doesn't exist or is
* just ".", then we don't need to bother with concatenating results
* together.
*/
if (!Util_IsAbsolutePath(name) && strlen(path) > 0 &&
strcmp(path, ".") != 0) {
if (ext == NULL) {
returnResult = Str_Asprintf(NULL, "%s%s%s",
path, DIRSEPS, name);
} else {
returnResult = Str_Asprintf(NULL, "%s%s%s.%s",
path, DIRSEPS, name, ext);
}
} else {
/*
* Path is non-existent or is just the current directory (or the
* result from the dictionary is an absolute path), so we
* just need to use the filename (using the DIRSEPS method above
* for a non-existent path might result in something undesireable
* like "\foobar.vmdk")
*/
if (ext == NULL) {
returnResult = Str_Asprintf(NULL, "%s", name);
} else {
returnResult = Str_Asprintf(NULL, "%s.%s", name, ext);
}
}
free(path);
return returnResult;
}
/* replacing only the file extension */
/* strip off the existing file extension, if present */
{
char *p = Str_Strrchr(base, '.');
if (p != NULL) {
*p = '\0';
}
}
/* Combine disk path with parent path */
if (strlen(path) > 0 && strcmp(path, ".") != 0) {
returnResult = Str_Asprintf(NULL, "%s%s%s.%s",
path, DIRSEPS, base, ext);
} else {
/*
* Path is non-existent or is just the current directory, so we
* just need to use the filename (using the DIRSEPS method might
* result in something undesireable like "\foobar.vmdk")
*/
returnResult = Str_Asprintf(NULL, "%s.%s", base, ext);
}
free(path);
free(base);
return returnResult;
}
/*
*-----------------------------------------------------------------------------
*
* Util_CombineStrings --
*
* Takes a vector of strings, and combines them into one string,
* where each string is separated by a 0 (zero) byte.
*
* The 0 bytes are then escaped out, and the result is returned.
*
* Results:
*
* A NULL terminated string
*
* Side effects:
*
* The result string is allocated
*
*-----------------------------------------------------------------------------
*/
char *
Util_CombineStrings(char **sources, // IN
int count) // IN
{
size_t size = 0;
int index = 0;
char *combinedString = NULL;
char *cursor = NULL;
char *escapedString = NULL;
int bytesToEsc[256];
ASSERT(sources != NULL);
memset(bytesToEsc, 0, sizeof bytesToEsc);
bytesToEsc[0] = 1;
bytesToEsc['#'] = 1;
for (index = 0; index < count; index++) {
/*
* Count the size of each string + the delimeter
*/
size += strlen(sources[index]) + 1;
}
combinedString = Util_SafeMalloc(size);
cursor = combinedString;
for (index = 0; index < count; index++) {
memcpy(cursor, sources[index], strlen(sources[index]));
cursor += strlen(sources[index]);
cursor[0] = '\0';
cursor++;
}
escapedString = Escape_Do('#', bytesToEsc, combinedString, size, NULL);
free(combinedString);
return escapedString;
}
/*
*-----------------------------------------------------------------------------
*
* Util_SeparateStrings --
*
* Takes as input the result of a call to Util_CombineStrings, and
* separates the strings back onto a vector of strings.
*
* Results:
*
* A vector of strings, the count will also reflect the number of
* entries in the vector
*
* Side effects:
*
* The vector is allocated, and each string in the vector must be
* freed by the caller
*
*-----------------------------------------------------------------------------
*/
char **
Util_SeparateStrings(char *source, // IN
int *count) // OUT
{
char *data = NULL;
size_t dataSize = 0;
int index = 0;
char *cursor = NULL;
char *endCursor = NULL;
char **stringVector = NULL;
ASSERT(count != NULL);
*count = 0;
data = Escape_Undo('#', source, strlen(source), &dataSize);
ASSERT(data != NULL);
endCursor = data + dataSize;
ASSERT(endCursor[0] == '\0');
cursor = data;
while (cursor < endCursor) {
(*count)++;
cursor += strlen(cursor) + 1;
}
stringVector = Util_SafeMalloc(sizeof(char *) * (*count));
cursor = data;
for (index = 0; index < (*count); index++) {
stringVector[index] = Util_SafeStrdup(cursor);
cursor += strlen(cursor) + 1;
}
free(data);
return stringVector;
}
#endif /* !defined(N_PLAT_NLM) */
#if defined (__linux__) && !defined(VMX86_TOOLS)
/*
*-----------------------------------------------------------------------------
*
* UtilPrintLoadedObjectsCallback --
*
* Callback from dl_iterate_phdr to add info for a single
* loaded object to the log.
*
* Results:
* 0: continue iterating/success
* non-zero: stop iterating/error
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
static int
UtilPrintLoadedObjectsCallback(struct dl_phdr_info *info, //IN
size_t size, //IN
void *data) //IN
{
/* Blank name means things like stack, which we don't care about */
if (strcmp(info->dlpi_name, "")) {
Log("Object %s loaded at %p\n", info->dlpi_name,
(void *)info->dlpi_addr);
}
return 0;
}
/*
*----------------------------------------------------------------------
*
* Util_PrintLoadedObjects --
*
* Print the list of loaded objects to the log. Useful in
* parsing backtraces with ASLR.
*
* Results:
*
* void
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
void
Util_PrintLoadedObjects(void *addr_inside_exec)
{
Dl_info dli;
Log("Printing loaded objects\n");
if (dladdr(addr_inside_exec, &dli)) {
Log("Object %s loaded at %p\n", dli.dli_fname,
(void *)dli.dli_fbase);
}
dl_iterate_phdr(UtilPrintLoadedObjectsCallback, NULL);
Log("End printing loaded objects\n");
}
#endif
#if !defined(_WIN32) && !defined(N_PLAT_NLM)
/*
*-----------------------------------------------------------------------------
*
* GetHomeDirectory --
*
* Unicode wrapper for posix getpwnam call for working directory.
*
* Results:
* Returns initial working directory or NULL if it fails.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
static Unicode
GetHomeDirectory(ConstUnicode name) // IN: user name
{
char *tmpname = NULL;
struct passwd *pw;
Unicode ret = NULL;
tmpname = Unicode_GetAllocBytes(name, STRING_ENCODING_DEFAULT);
pw = getpwnam(tmpname);
free(tmpname);
if (!pw || (pw && !pw->pw_dir)) {
endpwent();
return NULL;
}
ret = Unicode_Alloc(pw->pw_dir, STRING_ENCODING_DEFAULT);
endpwent();
return ret;
}
/*
*-----------------------------------------------------------------------------
*
* GetLoginName --
*
* Unicode wrapper for posix getpwnam call for working directory.
*
* Results:
* Returns user's login name or NULL if it fails.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
static Unicode
GetLoginName(int uid) //IN: user id
{
struct passwd *pw = NULL;
pw = getpwuid(uid);
if (!pw || (pw && !pw->pw_name)) {
return NULL;
}
return Unicode_Alloc(pw->pw_name, STRING_ENCODING_DEFAULT);
}
#endif
/*
*-----------------------------------------------------------------------------
*
* IsAlphaOrNum --
*
* Checks if character is a numeric digit or a letter of the
* english alphabet.
*
* Results:
* Returns TRUE if character is a digit or a letter, FALSE otherwise.
*
* Side effects:
* None.
*
*-----------------------------------------------------------------------------
*/
static Bool
IsAlphaOrNum(char ch) //IN
{
if ((ch >= '0' && ch <= '9') ||
(ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z')) {
return TRUE;
} else {
return FALSE;
}
}
|