Source

Coin / src / tidbits.cpp

Full commit
   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
/**************************************************************************\
 * Copyright (c) Kongsberg Oil & Gas Technologies AS
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * 
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of the copyright holder nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\**************************************************************************/

/*
  This file containes various miniscule code fragments that don't really
  belong anywhere in Coin, but which is included to make it easier to keep
  Coin portable.
*/

/*! \file tidbits.h */
#include <Inventor/C/tidbits.h>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */

#include <assert.h>
#include <errno.h>
#include <math.h> /* isinf(), isnan(), finite() */
#include <float.h> /* _fpclass(), _isnan(), _finite() */
#include <locale.h>
#include <string.h> /* strncasecmp() */
#include <stdio.h>
#include <stdlib.h> /* atio() */
#include <ctype.h> /* tolower() */
#include <stdlib.h> /* atexit(), putenv(), qsort(), atof() */
#ifdef HAVE_WINDOWS_H
#include <windows.h> /* GetEnvironmentVariable() */
#endif /* HAVE_WINDOWS_H */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef HAVE_IO_H
#include <io.h> /* defines open() on MSVC++ 5.0 */
#endif /* HAVE_IO_H */
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#ifdef HAVE_IEEEFP_H
#include <ieeefp.h>
#endif /* HAVE_IEEEFP_H */

#ifdef HAVE_DIRECT_H
#include <direct.h> /* _getcwd() */
#endif /* HAVE_DIRECT_H */

#include <Inventor/C/base/string.h>
#include <Inventor/C/base/list.h>
#include <Inventor/C/errors/debugerror.h>

#include "tidbitsp.h"
#include "coindefs.h"

/**************************************************************************/

/* FIXME: we should grab some BSD/PD-style licensed code to provide a
   replacement for the (v)snprintf functions. This would provide a
   fail-safe option on obscure platforms.

   Here is handegar's list of possible candidates (note that many of
   these can probably be ruled out due to the license restrictions --
   we need to be able to find code with a liberal enough license that
   we can re-license it under the Coin PEL and the GPL, which
   probably effectively limits us to code in the PD, or possibly under
   BSD- or MIT-style licenses:

   1) The BSDs:

      - http://www.openbsd.org/cgi-bin/cvsweb/src/lib/libc/stdio/
      - http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libc/stdio/
      - http://cvsweb.netbsd.org/cgi-bin/cvsweb.cgi/basesrc/lib/libc/stdio/


   2) A portable snprintf under either GNU (L?)GPL or the "Frontier
      Artistic Lisence" (wahtever that is):

      - http://www.ijs.si/software/snprintf/


   3) TRIO (seems to be under an "MIT-like" license):

      - http://daniel.haxx.se/trio/


   4) Samba (under GNU GPL?):

      - http://samba.org/cgi-bin/cvsweb/samba/source/lib/snprintf.c


   5) Apache:

      - http://www.apache.org


   6) Caol�n McNamara's (GNU GPL?):

      - http://www.csn.ul.ie/~caolan/publink/snprintf-1.1.tar.gz


   7) Castaglia (GNU GPL?):

      - http://www.castaglia.org/proftpd/doc/devel-guide/src/lib/vsnprintf.c.html


   8) Gnome (GNU (L?)GPL? -- looks very similar to the Samba
      implementation):

      - http://cvs.gnome.org/lxr/

   20021128 mortene.

   UPDATE 20021206 mortene: it looks like integrating any of these
   would be quite some effort, to get the build / configure stuff
   correct, to slim down the code of the chosen implementation, etc
   etc. I think our first step should perhaps be to let configure bail
   out if no "native" snprintf() is found on the system, with a good
   error message, a fallback, and a notice about mailing us info on
   the platform in question. Just so we avoid spending much time
   solving a problem which is really not there on any platform Coin is
   being used.
 */

#ifdef __cplusplus
extern "C" {
#endif

/* ********************************************************************** */

#ifdef COIN_THREADSAFE
#include <Inventor/C/threads/mutex.h>
#include "threads/mutexp.h"
static cc_mutex * atexit_list_monitor = NULL;
#endif /* COIN_THREADSAFE */


static int COIN_DEBUG_EXTRA = -1;
static int COIN_DEBUG_NORMALIZE = -1;

/* ********************************************************************** */

/* Called from SoDB::init() exactly once, a call which is guaranteed
   free from race conditions. */
void
coin_init_tidbits(void)
{
  const char * env;
#ifdef COIN_THREADSAFE
  atexit_list_monitor = cc_mutex_construct();
#endif /* COIN_THREADSAFE */

  env  = coin_getenv("COIN_DEBUG_EXTRA");
  if (env && atoi(env) == 1) {
    COIN_DEBUG_EXTRA = 1;
  }
  else {
    COIN_DEBUG_EXTRA = 0;
  }
  env = coin_getenv("COIN_DEBUG_NORMALIZE");
  if (env && atoi(env) == 1) {
    COIN_DEBUG_NORMALIZE = 1;
  }
  else {
    COIN_DEBUG_NORMALIZE = 0;
  }
}

/* ********************************************************************** */

/*
  coin_vsnprintf() wrapper. Returns -1 if resultant string will be
  longer than n.
*/

typedef int func_vsnprintf(char *, size_t, const char *, va_list);

static int
coin_common_vsnprintf(func_vsnprintf * func,
                      char * dst, size_t n,
                      const char * fmtstr, va_list args)
{
  int length;
  static int debug = -1;

  if (debug == -1) {
    const char * env = coin_getenv("COIN_DEBUG_NPRINTF");
    debug = (env && (atoi(env) > 0)) ? 1 : 0;
  }

  /* Note: subtract one from n as the buffer size, because libDCE on
     HP-UX has a vsnprintf() implementation which will otherwise
     overwrite the array with one byte (it doesn't count the trailing
     \0, as e.g. GNU libc does, and like a C99-conforming
     implementation would). */
  assert(n > 1);
  n -= 1;

  /* Can not use cc_debugerror_* interface(), as that could cause an
     infinite recursion. */
  if (debug) { printf("dst==%p, n==%zu, fmtstr=='%s'\n", dst, n, fmtstr); }

#ifdef HAVE_VA_COPY_MACRO
  /* The C99 va_copy() is available, so use that to help us "rewind"
     the va_list between invocations. */
  {
    va_list argscopy;
    va_copy(argscopy, args);
    length = (*func)(dst, n, fmtstr, argscopy);
    va_end(argscopy);
  }
#else /* !HAVE_VA_COPY_MACRO */
  /* No va_copy() available, so we just assume the system's
     vsnprintf() to "rewind" the va_list after use. This assumption is
     "sanity checked" from within SoDB::init(). */
  length = (*func)(dst, n, fmtstr, args);
#endif /* !HAVE_VA_COPY_MACRO */

  if (debug) { printf("==> length==%d\n", length); }

  //POTENTIAL_ROTTING_DOCUMENTATION
  /* Not all vsnprintf() implementations returns -1 upon failure (this
     is what vsnprintf() from GNU libc is documented to do).

     At least with GNU libc 2.1.1, vsnprintf() does _not_ return -1
     (as documented in the snprintf(3) man-page) when we can't fit the
     constructed string within the given buffer, but rather the number
     of characters needed, excluding the terminating \0. The latter is
     also the behavior specified by C99.

     IRIX 6.5 vsnprintf() just returns the number of characters until
     clipped, i.e. input argument n minus one.

     For the C run-times that comes with MSVC++ 5.0 and MSVC++ 6.0,
     _vsnprintf() is specified to return -1 on overruns. (To match
     C99, one would expect Microsoft to change this, though. Perhaps
     done for MSVC++ v7?)


     For reference, here's a simple test example which checks the
     behavior of snprintf() / vsnprintf(), when trying to fit 26
     characters plus a terminating \0 into a 20-character buffer:

     -----8<----------- [snip] ---------------8<----------- [snip] ---------
     #include <stdio.h>

     int
     main(void)
     {
       char buffer[20] = "";
       const int ret =
         snprintf(buffer, sizeof(buffer), "%s",
                  "abcdefghijklmnopqrstuvwxyz");
       (void)printf("snprintf()==%d\n", ret);
       (void)printf("buffer=\"%s\"\n", buffer);
       return 0;
     }
     -----8<----------- [snip] ---------------8<----------- [snip] ---------
  */

  if (length >= (((int)n) - 1)) { length = -1; }

  return length;
}

#ifdef HAVE_VSNPRINTF

int
coin_vsnprintf(char * dst, unsigned int n, const char * fmtstr, va_list args)
{
  return coin_common_vsnprintf(vsnprintf, dst, (size_t)n, fmtstr, args);
}

#elif defined HAVE__VSNPRINTF

int
coin_vsnprintf(char * dst, unsigned int n, const char * fmtstr, va_list args)
{
  return coin_common_vsnprintf(_vsnprintf, dst, (size_t)n, fmtstr, args);
}

#else /* neither vsnprintf() nor _vsnprintf() available, roll our own */

/*
  This is a butt-ugly hack to emulate the vsnprintf() extension
  available on some systems, without having to reimplement all the
  code needed to parse printf-format strings.

  vsnprintf() is necessary to use for copying a formatstring with a
  variable number of arguments into a char buffer without the
  possibility of overflows.

  Note that there's one exception to the similarity in functionality
  with "native" vsnprintf() implementations: the target buffer might
  not contain _any_ characters from the formatstr upon a -1 return
  value.

  All external functions and macros in this code should be conforming
  to ANSI C3.159-1989 / ISO 9899 or POSIX (or both), as far as I can
  see.

  Compile with something like this (example is under GCC and Linux),
  to generate a stand-alone program testing the function:
    gcc -Wall -DENABLE_TESTCODE=1 -DHAVE_UNISTD_H=1 -DHAVE_VSNPRINTF=1 \
        -o snprintf snprintf.c

  19991221 mortene. Thanks to larsa for the idea.

  20040203 larsa: Finally solved a strange problem of having files
  popping up in the root directory (on windows computers, and on the
  current drive) with names like "s3n4" and "s25o" etc. with just a
  few characters of text in them.  It turned out to be this fallback
  that created them, and I had forgotten to use the SIM_AC_CHECK_NPRINTF
  macro in the configure script.  The fallback is in other words not
  entirely "safe", since it pollutes the filesystem on windows computers.
*/

/*
  FIXME: could perhaps grab a decent snprintf() implementation (with a
  liberal enough license for our use) from one of the BSD-Unixen?
  Investigate.  20010821 mortene.
 */

/* First a helper function to find a valid file pointer which is
   pointing at nothing (for a number of different definitions of
   "nothing"..). */
static FILE *
nullfileptr(void)
{
  static FILE * nullfp = NULL;

  if (!nullfp) {
    struct stat sbuf;
    const char unixdevnull[] = "/dev/null";
    int nullfd = -1;

    if ((stat(unixdevnull, &sbuf) == 0) && (sbuf.st_mode & S_IFCHR))
      nullfd = open(unixdevnull, O_WRONLY);

    if (nullfd == -1) {
      const char * tmpname = tmpnam(NULL);

      if (tmpname) {
        nullfd = open(tmpname, O_CREAT|O_WRONLY);
        (void)remove(tmpname);
      }
    }

    if (nullfd != -1) nullfp = fdopen(nullfd, "w");
    if (!nullfp) nullfp = stderr; /* :^} (as a last resort.) 19991221 mortene. */
  }

  return nullfp;
}

int
coin_vsnprintf(char * dst, unsigned int n, const char * fmtstr, va_list args)
{
  int len;

#ifdef HAVE_VA_COPY_MACRO

  /* The C99 va_copy() is available, so use that to help us "rewind"
     the va_list between invocations. */
  {
    va_list argscopy;

    va_copy(argscopy, args);
    len = vfprintf(nullfileptr(), fmtstr, argscopy);
    va_end(argscopy);

    if (((unsigned int) len + 1) > n) return -1;

    va_copy(argscopy, args);
    (void)vsprintf(dst, fmtstr, argscopy);
    va_end(argscopy);
  }

#else /* !HAVE_VA_COPY_MACRO */

  /* No va_copy() available, so we just assume the system's vfprintf()
     to "rewind" the va_list after use. This assumption is "sanity
     checked" from within SoDB::init(). */
  len = vfprintf(nullfileptr(), fmtstr, args);
  if (((unsigned int) len + 1) > n) return -1;
  (void)vsprintf(dst, fmtstr, args);

#endif /* !HAVE_VA_COPY_MACRO */

  return len;
}
#endif /* coin_vsnprintf() */


/**************************************************************************/
/*
  coin_snprintf() wrapper. Returns -1 if resultant string will be
  longer than n.
*/

int
coin_snprintf(char * dst, unsigned int n, const char * fmtstr, ...)
{
  int len;
  va_list argptr;
  va_start(argptr, fmtstr);
  len = coin_vsnprintf(dst, n, fmtstr, argptr);
  va_end(argptr);
  return len;
}


/**************************************************************************/

/*** Singlelinked list for the environment variables. *********************/

/*
  FIXME: should implement a generic (macro-based) singlelinked list
  abstraction in C (the following code could be a good starting
  point). Then axe this code. Then move the various listhandling stuff
  in the Coin library from the SbList<> template to the C-based one to
  aid any future transition to pure C. 20010821 mortene.

  UPDATE: SbList isn't really a linked list, but in fact a growable
  array -- so the code below can not be used as a replacement. Still,
  we should have a generic linked list class. 20011220 mortene.
*/

#ifdef HAVE_GETENVIRONMENTVARIABLE
static struct envvar_data * envlist_head = NULL;
static struct envvar_data * envlist_tail = NULL;

struct envvar_data {
  char * name;
  char * val;
  struct envvar_data * next;
};

static void
envlist_cleanup(void)
{
  struct envvar_data * ptr = envlist_head;
  while (ptr != NULL) {
    struct envvar_data * tmp = ptr;
    free(ptr->name);
    free(ptr->val);
    ptr = ptr->next;
    free(tmp);
  }
  envlist_head = NULL;
  envlist_tail = NULL;
}

static void
envlist_append(struct envvar_data * item)
{
  item->next = NULL;
  if (envlist_head == NULL) {
    envlist_head = item;
    envlist_tail = item;
    coin_atexit_func("envlist_cleanup", envlist_cleanup, CC_ATEXIT_ENVIRONMENT);
  }
  else {
    envlist_tail->next = item;
    envlist_tail = item;
  }
}

#endif /* HAVE_GETENVIRONMENTVARIABLE */


/**************************************************************************/

/* FIXME: should getenv/setenv/unsetenv be made mt-safe by locking access
 * to the envlist linked list under Win32?  20030205 larsa */

/*
  When working with MSWindows applications using Coin as a DLL,
  setenv() / getenv() will not work as expected, as the application
  and the DLL has different instances of the C library with different
  datastructures on different heaps. That's why we need this
  abstraction around the C-libs getenv() vs the Win32 API
  GetEnvironmentVariable() function.

  Note: do not deallocate the returned string -- they are supposed to
  be permanently available to all callers. Deallocating the resources
  is the responsibility of the application exit cleanup code (i.e. the
  internal library cleanup code -- application programmers won't need
  to care about it).
*/
const char *
coin_getenv(const char * envname)
{
  /* FIXME: with recent version(s) of Cygwin, it seems the Win32
     GetEnvironmentVariable() is no longer working properly, if Coin
     has been built with the Cygwin-port of GCC. We've had one bug
     report to this effect, plus handegar had to fix wrapmsvc.cpp,
     which exhibited the exact same problem.

     Not 100% sure how to fix it, but perhaps always preferring to use
     getenv() over GetEnvironmentVariable() would be sufficient? Or
     would that just exhibit the opposite problem when building Coin
     with MSVC?

     20060314 mortene. */

  /* Important note: this code is identical to the getenv() code in
     So@Gui@/.../common/SoAny.cpp.in. If you do bugfixes or whatever,
     keep them in sync! */
  /* FIXME: this code from tidbits should be moved under
     Coin/src/share/, so the actual source code is shared instead of
     having to copy it around. 20060314 mortene. */
#ifdef HAVE_GETENVIRONMENTVARIABLE
  int neededsize;
  neededsize = GetEnvironmentVariable(envname, NULL, 0);
  /* neededsize includes the \0-terminating character */
  if (neededsize >= 1) {
    int resultsize;
    struct envvar_data * envptr;
    char * valbuf = (char *) malloc(neededsize);
    if (valbuf == NULL) {
      /* Augh. Could we handle this any better? */
      /* If we already bookkeep a buffer for this variable, we /could/ try
         to reuse it (much work for a non-100% solution).  20030205 larsa */
      return NULL;
    }
    resultsize = GetEnvironmentVariable(envname, valbuf, neededsize);
    if (resultsize != (neededsize - 1)) {
      /* Augh. Could we handle this any better? */
      /* How about looping to top and trying again (in case the reason is mt
         and envval being changed in the background, or maybe just asserting?
         20030205 larsa */
      free(valbuf);
      return NULL;
    }

    /*
      The GetEnvironmentVariable() signature forces us to allocate the space
      for the value string on the outside of the call, as opposed to the UNIX
      getenv() function.  We therefore have to do bookkeeping and maintain
      this linked list of allocated buffers that should be cleaned up on exit
      (atexit()).  We don't keep it for lookup of values - we actually can't
      use the valus as value caches in case they have been changed from other
      parts of the application.  We only keep them so we can free them later.
    */

    /* Try to find bookkeeped envvar buffer among those registered earlier. */
    envptr = envlist_head;
    while ((envptr != NULL) && (strcmp(envptr->name, envname) != 0))
      envptr = envptr->next;

    /* We can avoid this if-else by always freeing the envvar_data for the
       variable upfront, but it's a tad less efficient. */
    if (envptr != NULL) {
      /* We are already bookkeeping a buffer for this variable.
       * => free previous value buffer and bookkeep the new one instead */
      free(envptr->val);
      envptr->val = valbuf;
    }
    else {
      /* We aren't bookkeeping a buffer for this one yet. */
      envptr = (struct envvar_data *) malloc(sizeof(struct envvar_data));
      if (envptr == NULL) {
        /* Augh. Could we handle this any better? */
        /* We can alternatively ignore the bookkeeping and leak the buffer
           - 20030205 larsa */
        free(valbuf);
        return NULL;
      }
      envptr->name = strdup(envname);
      if (envptr->name == NULL) {
        /* Augh. Could we handle this any better? */
        /* We can alternatively ignore the bookkeeping and leak the buffer
           - 20030205 larsa */
        free(envptr);
        free(valbuf);
        return NULL;
      }
      envptr->val = valbuf;
      envlist_append(envptr);
    }
    return envptr->val;
  }
  return NULL;
#else /* !HAVE_GETENVIRONMENTVARIABLE */
  return getenv(envname);
#endif /* !HAVE_GETENVIRONMENTVARIABLE */
}

SbBool
coin_setenv(const char * name, const char * value, int overwrite)
{
#ifdef HAVE_GETENVIRONMENTVARIABLE
/*
  The value is changed by the application, so we no longer need to
  guarantee old buffers' existence to the outside world.  We therefore
  free buffers we are bookkeeping here.  This code can be disabled
  without any consequence though.
*/
  struct envvar_data * envptr, * prevptr;
  envptr = envlist_head;
  prevptr = NULL;
  while ((envptr != NULL) && (strcmp(envptr->name, name) != 0)) {
    prevptr = envptr;
    envptr = envptr->next;
  }
  if (envptr) {
    /* unlink node */
    if (prevptr) prevptr->next = envptr->next;
    else envlist_head = envptr->next;
    if (envlist_tail == envptr) envlist_tail = prevptr;
    /* free node */
    free(envptr->name);
    free(envptr->val);
    free(envptr);
  }

  /* FIXME: This is from Win32s 1.3 Bug List - how should we handle it?
  and what's with the typo in the function name?  20030205 larsa
  ====================================================================
  SetEnvironmentVariables() does not handle an empty string, an equal
  sign (=), or foreign lowercase characters in the variable name.
  */

  if (overwrite || (GetEnvironmentVariable(name, NULL, 0) == 0))
    return SetEnvironmentVariable(name, value) ? TRUE : FALSE;
  else
    return TRUE;
#else /* !HAVE_GETENVIRONMENTVARIABLE */
  return (setenv(name,value,overwrite) == 0);
#endif /* !HAVE_GETENVIRONMENTVARIABLE */
}

void
coin_unsetenv(const char * name)
{
#ifdef HAVE_GETENVIRONMENTVARIABLE
/*
  The value is removed by the application, so we no longer need to
  guarantee old buffers' existence to the outside world.  We therefore
  free buffers we are bookkeeping here.  This code can be disabled
  without any consequence though.
*/
  struct envvar_data * envptr, * prevptr;
  envptr = envlist_head;
  prevptr = NULL;
  while ((envptr != NULL) && (strcmp(envptr->name, name) != 0)) {
    prevptr = envptr;
    envptr = envptr->next;
  }
  if (envptr) {
    /* unlink node */
    if (prevptr) prevptr->next = envptr->next;
    else envlist_head = envptr->next;
    if (envlist_tail == envptr) envlist_tail = prevptr;
    /* free node */
    free(envptr->name);
    free(envptr->val);
    free(envptr);
  }
  SetEnvironmentVariable(name, NULL);
#else /* !HAVE_GETENVIRONMENTVARIABLE */
  unsetenv(name);
#endif /* !HAVE_GETENVIRONMENTVARIABLE */
}

/**************************************************************************/

/*
  strncasecmp() is not available on all platforms (it's neither ISO C
  nor POSIX). At least MSVC doesn't have it.
 */
int
coin_strncasecmp(const char * s1, const char * s2, int len)
{
#ifdef HAVE_STRNCASECMP

  return strncasecmp(s1, s2, len);

#else /* !HAVE_STRNCASECMP */

  assert(s1 && s2);
  while (len > 0) {
    int c1 = tolower(*s1);
    int c2 = tolower(*s2);
    if (c1 < c2) { return -1; }
    if (c1 > c2) { return +1; }
    if (c1=='\0' && c2=='\0') { return 0; } /* in case len is too large */
    len--; s1++; s2++;
  }
  return 0;

#endif /* !HAVE_STRNCASECMP */
}

/**************************************************************************/

#define COIN_BSWAP_8(x)  ((x) & 0xff)
#define COIN_BSWAP_16(x) ((COIN_BSWAP_8(x)  << 8)  | COIN_BSWAP_8((x)  >> 8))
#define COIN_BSWAP_32(x) ((COIN_BSWAP_16(x) << 16) | COIN_BSWAP_16((x) >> 16))
#define COIN_BSWAP_64(x) ((COIN_BSWAP_32(x) << 32) | COIN_BSWAP_32((x) >> 32))

static int coin_endianness = COIN_HOST_IS_UNKNOWNENDIAN;

int
coin_host_get_endianness(void)
{
  union temptype {
    uint32_t value;
    uint8_t  bytes[4];
  } temp;

  if (coin_endianness != COIN_HOST_IS_UNKNOWNENDIAN) {
    return coin_endianness;
  }

  temp.bytes[0] = 0x00;
  temp.bytes[1] = 0x01;
  temp.bytes[2] = 0x02;
  temp.bytes[3] = 0x03;
  switch (temp.value) {
    case 0x03020100: return coin_endianness = COIN_HOST_IS_LITTLEENDIAN;
    case 0x00010203: return coin_endianness = COIN_HOST_IS_BIGENDIAN;
    /* might be more variations here for some obscure CPU architectures */
  }
  assert(0 && "system has unknown endianness");
  return COIN_HOST_IS_UNKNOWNENDIAN; /* maybe just as well exit()? */
}

uint16_t
coin_hton_uint16(uint16_t value)
{
  switch (coin_host_get_endianness()) {
  case COIN_HOST_IS_BIGENDIAN:
    /* value = value */
    break;
  case COIN_HOST_IS_LITTLEENDIAN:
    value = COIN_BSWAP_16(value);
    break;
  default:
    assert(0 && "system has unknown endianness");
  }
  return value;
}

uint16_t
coin_ntoh_uint16(uint16_t value)
{
  return coin_hton_uint16(value);
}

uint32_t
coin_hton_uint32(uint32_t value)
{
  switch (coin_host_get_endianness()) {
  case COIN_HOST_IS_BIGENDIAN:
    /* big-endian is the same order as network order */
    break;
  case COIN_HOST_IS_LITTLEENDIAN:
    value = COIN_BSWAP_32(value);
    break;
  default:
    assert(0 && "system has unknown endianness");
  }
  return value;
}

uint32_t
coin_ntoh_uint32(uint32_t value)
{
  return coin_hton_uint32(value);
}

uint64_t
coin_hton_uint64(uint64_t value)
{
  switch (coin_host_get_endianness()) {
  case COIN_HOST_IS_BIGENDIAN:
    /* big-endian is the same order as network order */
    break;
  case COIN_HOST_IS_LITTLEENDIAN:
    value = COIN_BSWAP_64(value);
    break;
  default:
    assert(0 && "system has unknown endianness");
  }
  return value;
}

uint64_t
coin_ntoh_uint64(uint64_t value)
{
  return coin_hton_uint64(value);
}

void
coin_hton_float_bytes(float value, char * result)
{
  union {
    float f32;
    uint32_t u32;
  } val;

  assert(sizeof(float) == sizeof(uint32_t));
  val.f32 = value;
  val.u32 = coin_hton_uint32(val.u32);
  memcpy(result, &val.u32, sizeof(uint32_t));
}

float
coin_ntoh_float_bytes(const char * value)
{
  union {
    float f32;
    uint32_t u32;
  } val;

  assert(sizeof(float) == sizeof(uint32_t));
  memcpy(&val.u32, value, sizeof(uint32_t));
  val.u32 = coin_ntoh_uint32(val.u32);
  return val.f32;
}

void
coin_hton_double_bytes(double value, char * result)
{
  union {
    double d64;
    uint64_t u64;
  } val;

  assert(sizeof(double) == sizeof(uint64_t));
  val.d64 = value;
  val.u64 = coin_hton_uint64(val.u64);
  memcpy(result, &val.u64, sizeof(uint64_t));
}

double
coin_ntoh_double_bytes(const char * value)
{
  union {
    float d64;
    uint64_t u64;
  } val;

  assert(sizeof(double) == sizeof(uint64_t));
  memcpy(&val.u64, value, sizeof(uint64_t));
  val.u64 = coin_ntoh_uint64(val.u64);
  return val.d64;
}

/**************************************************************************/

/*
  isascii() is neither ANSI C nor POSIX, but a BSD extension and SVID
  extension.
 */
SbBool
coin_isascii(const int c)
{
  return (c >= 0x00) && (c < 0x80);
}

/* We provide our own version of the isspace() method, as we don't
   really want it to be locale-dependent (which is known to have
   caused trouble for us with some specific German characters under
   MSWindows, at least). */
SbBool
coin_isspace(const char c)
{
  /* This is what isspace() does under the POSIX and C locales,
     according to the GNU libc man page. */
  return (c==' ') || (c=='\n') || (c=='\t') ||
         (c=='\r') || (c=='\f') || (c=='\v');
}

/**************************************************************************/

/* Quick check to see if an integer value is equal to 2^n, for any
   n=[0, ...]. */
SbBool
coin_is_power_of_two(uint32_t x)
{
  return (x != 0) && ((x & (x - 1)) == 0);
}

/*
  Returns nearest upward number for x that is a power of two.

  Note that if "x" is already a power of two, we will still return the
  *next* number that is a power of two, and not x itself.
 */
uint32_t
coin_next_power_of_two(uint32_t x)
{
  assert((x < (uint32_t)(1 << 31)) && "overflow");

  x |= (x >> 1);
  x |= (x >> 2);
  x |= (x >> 4);
  x |= (x >> 8);
  x |= (x >> 16);
  /* This will make it work with 64-bit numbers: */
  /* x |= (x >> 32); */

  return x + 1;
}

/*
  Returns nearest upward number for x that is a power of two, or x
  itself if it is already a power of two.

  ("geq" is short for "Greater or EQual".)
 */
uint32_t
coin_geq_power_of_two(uint32_t x)
{
  if (coin_is_power_of_two(x)) return x;
  return coin_next_power_of_two(x);
}

/*
  Calculate the view volume jitter vector when doing multipass
  antialiasing rendering.
*/
void
coin_viewvolume_jitter(int numpasses, int curpass, const int * vpsize, float * jitter)
{
  /* jitter values from OpenGL Programming Guide */
  static float jitter2[] = {
    0.25f, 0.77f,
    0.75f, 0.25f
  };
  static float jitter3[] = {
    0.5033922635f, 0.8317967229f,
    0.7806016275f, 0.2504380877f,
    0.2261828938f, 0.4131553612f
  };
  static float jitter4[] = {
    0.375f, 0.25f,
    0.125f, 0.75f,
    0.875f, 0.25f,
    0.625f, 0.75f
  };
  static float jitter5[] = {
    0.5f, 0.5f,
    0.3f, 0.1f,
    0.7f, 0.9f,
    0.9f, 0.3f,
    0.1f, 0.7f
  };
  static float jitter6[] = {
    0.4646464646f, 0.4646464646f,
    0.1313131313f, 0.7979797979f,
    0.5353535353f, 0.8686868686f,
    0.8686868686f, 0.5353535353f,
    0.7979797979f, 0.1313131313f,
    0.2020202020f, 0.2020202020f
  };
  static float jitter8[] = {
    0.5625f, 0.4375f,
    0.0625f, 0.9375f,
    0.3125f, 0.6875f,
    0.6875f, 0.8125f,
    0.8125f, 0.1875f,
    0.9375f, 0.5625f,
    0.4375f, 0.0625f,
    0.1875f, 0.3125f
  };
  static float jitter9[] = {
    0.5f, 0.5f,
    0.1666666666f, 0.9444444444f,
    0.5f, 0.1666666666f,
    0.5f, 0.8333333333f,
    0.1666666666f, 0.2777777777f,
    0.8333333333f, 0.3888888888f,
    0.1666666666f, 0.6111111111f,
    0.8333333333f, 0.7222222222f,
    0.8333333333f, 0.0555555555f
  };
  static float jitter12[] = {
    0.4166666666f, 0.625f,
    0.9166666666f, 0.875f,
    0.25f, 0.375f,
    0.4166666666f, 0.125f,
    0.75f, 0.125f,
    0.0833333333f, 0.125f,
    0.75f, 0.625f,
    0.25f, 0.875f,
    0.5833333333f, 0.375f,
    0.9166666666f, 0.375f,
    0.0833333333f, 0.625f,
    0.583333333f, 0.875f
  };
  static float jitter16[] = {
    0.375f, 0.4375f,
    0.625f, 0.0625f,
    0.875f, 0.1875f,
    0.125f, 0.0625f,
    0.375f, 0.6875f,
    0.875f, 0.4375f,
    0.625f, 0.5625f,
    0.375f, 0.9375f,
    0.625f, 0.3125f,
    0.125f, 0.5625f,
    0.125f, 0.8125f,
    0.375f, 0.1875f,
    0.875f, 0.9375f,
    0.875f, 0.6875f,
    0.125f, 0.3125f,
    0.625f, 0.8125f
  };

  static float * jittertab[] = {
    jitter2,
    jitter3,
    jitter4,
    jitter5,
    jitter6,
    jitter8,
    jitter8,
    jitter9,
    jitter12,
    jitter12,
    jitter12,
    jitter16,
    jitter16,
    jitter16,
    jitter16
  };

  float * jittab;

  /* FIXME: support more rendering passes by generating jitter tables
   * using some clever algorithm. pederb, 2001-02-21 */
  if (numpasses > 16) numpasses = 16;
  if (curpass >= numpasses) curpass = numpasses - 1;

  jittab = jittertab[numpasses-2];

  if (numpasses < 2) {
    jitter[0] = 0.0f;
    jitter[1] = 0.0f;
    jitter[2] = 0.0f;
  }
  else {
    jitter[0] = (jittab[curpass*2] - 0.5f) * 2.0f / ((float)vpsize[0]);
    jitter[1] = (jittab[curpass*2+1] - 0.5f) * 2.0f / ((float)vpsize[1]);
    jitter[2] = 0.0f;
  }
}


/**************************************************************************/

void free_std_fds(void);

typedef void(*atexit_func_type)(void);

static cc_list * atexit_list = NULL;
static SbBool isexiting = FALSE;

typedef struct {
  char * name;
  coin_atexit_f * func;
  int32_t priority;
  uint32_t cnt;
} tb_atexit_data;

static int
atexit_qsort_cb(const void * q0, const void * q1)
{
  tb_atexit_data * p0, * p1;

  p0 = *((tb_atexit_data**) q0);
  p1 = *((tb_atexit_data**) q1);

  /* sort list on ascending priorities, so that high priority
     callbacks are called first  */
  if (p0->priority < p1->priority) return -1;
  if (p0->priority > p1->priority) return 1;

  /* when priority is equal, use LIFO */
  if (p0->cnt < p1->cnt) return -1;
  return 1;
}

/*
   Calls all atexit functions. Invoked from SoDB::finish().
*/
void
coin_atexit_cleanup(void)
{
  int i, n;
  tb_atexit_data * data;
  const char * debugstr;
  SbBool debug = FALSE;

  if (!atexit_list) return;

  isexiting = TRUE;

  /* delete mutex here to make sure this is done before the threading subsystem is shut down */
#ifdef COIN_THREADSAFE
  cc_mutex_destruct(atexit_list_monitor);
  atexit_list_monitor = NULL;
#endif /* COIN_THREADSAFE */

  debugstr = coin_getenv("COIN_DEBUG_CLEANUP");
  debug = debugstr && (atoi(debugstr) > 0);

  n = cc_list_get_length(atexit_list);
  qsort(cc_list_get_array(atexit_list), n, sizeof(void*), atexit_qsort_cb);

  for (i = n-1; i >= 0; i--) {
    data = (tb_atexit_data*) cc_list_get(atexit_list, i);
    if (debug) {
      /* Can't use cc_debugerror_postinfo() here, since this will
          allocate static data that need to be cleaned up, resulting
          in a call to coin_atexit() while we are already exiting...
      */
      fprintf(stdout, "coin_atexit_cleanup: invoking %s()\n", data->name);
    }
    data->func();
    free(data->name);
    free((void*)data);
  }

  /* Close stdin/stdout/stderr if any of them have been opened */
  free_std_fds();

  cc_list_destruct(atexit_list);
  atexit_list = NULL;
  isexiting = FALSE;

  if (debug) {
    fprintf(stdout, "coin_atexit_cleanup: fini\n");
  }
}

/*
  This replacement for the C library's atexit() function is used for
  two reasons: first, we want to control the internal order of when
  clean-up callbacks are invoked (as can be done by setting the
  priority argument accordingly), second, we want to be able to do a
  controlled clean-up in advance of the C library's shutdown, to make
  sure that we get cleaned up before any DLLs we are using are thrown
  out of the process.

  Callbacks with higher priority will be called first. On equal
  priority callbacks will be made last-in-first-out ("LIFO").

  For this function a higher number is a higher priority.  An atexit
  function with priority 2 will trigger before an atexit function with
  priority 1.

  Functions passed to this method should be cast to the apropriate
  method signature (coin_atexit_f), so the OSF1/cxx compiler can
  accept a C++ function as it's input argument. (Problem reported by
  Guy Barrand.)
*/

void
coin_atexit_func(const char * name, coin_atexit_f * f, coin_atexit_priorities priority)
{
#ifdef COIN_THREADSAFE
  /* This function being not mt-safe seemed to be the only cause of
     problems when constructing SoNode-derived classes in parallel
     threads. So for that extra bit of undocumented, unofficial,
     under-the-table mt-safety, this should take care of it. */

  /*
    Need this test, since the thread system calls coin_atexit
    before tidbits is initialized.
  */
  if (atexit_list_monitor) {
    cc_mutex_lock(atexit_list_monitor);
  }
#endif /* COIN_THREADSAFE */

  assert(!isexiting && "tried to attach an atexit function while exiting");

  if (atexit_list == NULL) {
    atexit_list = cc_list_construct();
    /* The atexit() registration was disabled, since it has proved
       dangerous to let the C library trigger the callbacks.

       There is for instance the known problem with deallocating
       resources from a DLL we're using (like OpenAL), as the DLL
       could already have been "offloaded" or simply cleaned up /
       cleaned out when our callback triggers.

       We therefore now force cleanup at exit to be done explicitly
       from application code by invoking the SoDB::finish() method,
       which then invokes the coin_atexit_cleanup() method.

       Note that this scheme is not to be considered a temporary
       workaround -- application-exit clean-up should be done
       explicitly by invoking SoDB::finish().

       mortene.
    */
    /* (void)atexit(coin_atexit_cleanup); */
  }

  {
    tb_atexit_data * data;

    data = (tb_atexit_data*) malloc(sizeof(tb_atexit_data));
    data->name = strdup(name);
    data->func = f;
    data->priority = priority;
    data->cnt = cc_list_get_length(atexit_list);

    cc_list_append(atexit_list, data);
  }

#ifdef COIN_THREADSAFE
  if (atexit_list_monitor) {
    cc_mutex_unlock(atexit_list_monitor);
  }
#endif /* COIN_THREADSAFE */
}

/*
  Public version of the coin_atexit function which always sets the
  priority such that external clean-up functions are run \e first.

  (Which is of course important because they may have dependencies
  into Coin functionality.)

  Note that the registered atexit functions will only be called when
  SoDB::finish() is invoked from the application code.
 */
void
cc_coin_atexit(coin_atexit_f * f)
{
  coin_atexit(f, CC_ATEXIT_EXTERNAL);
}

/*!
  Internal function used for cleaning up static data. Do not use
  from appliction code.
*/
void
cc_coin_atexit_static_internal(coin_atexit_f * fp)
{
  coin_atexit(fp, CC_ATEXIT_STATIC_DATA);
}

/*
  Returns \c TRUE if we are currently iterating over the functions
  registered with coin_atexit(), otherwise \c FALSE.
 */
SbBool
coin_is_exiting(void)
{
  return isexiting;
}

/**************************************************************************/

/*
  It is not possible to "pass" C library data from the application
  to a MSWin .DLL, so this is necessary to get hold of the stderr
  FILE*.  Just using fprintf(stderr, ...) or fprintf(stdout, ...)
  directly will result in a crash when Coin has been compiled as a
  .DLL.
*/

/* These constants are fixed according to POSIX */
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
#define STDERR_FILENO 2
#endif

/*
  FIXME: if Coin does an fclose() on one of these, what happens when the
  cached variable is used later on?  We should make sure Coin doesn't
  fclose() one of these...  Or we should open a new FILE pointer each time
  it is called?  Would it be safe to check if the FILE * is closed and
  then open a new one?  20030217 larsa
*/

static FILE * coin_stdin = NULL;
static FILE * coin_stdout = NULL;
static FILE * coin_stderr = NULL;
static int coin_dup_stdin = -1;
static int coin_dup_stdout = -1;
static int coin_dup_stderr = -1;

void
free_std_fds(void)
{
  /* Close stdin/stdout/stderr */
  if (coin_stdin) {
    assert(coin_dup_stdin != -1);
    fclose(coin_stdin);
    coin_stdin = NULL;
    dup2(coin_dup_stdin, STDIN_FILENO);
    close(coin_dup_stdin);
    coin_dup_stdin = -1;
  }
  if (coin_stdout) {
    assert(coin_dup_stdout != -1);
    fclose(coin_stdout);
    coin_stdout = NULL;
    dup2(coin_dup_stdout, STDOUT_FILENO);
    close(coin_dup_stdout);
    coin_dup_stdout = -1;
  }
  if (coin_stderr) {
    assert(coin_dup_stderr != -1);
    fclose(coin_stderr);
    coin_stderr = NULL;
    dup2(coin_dup_stderr, STDERR_FILENO);
    close(coin_dup_stderr);
    coin_dup_stderr = -1;
  }
}

FILE *
coin_get_stdin(void)
{
  if ( ! coin_stdin ){
    coin_dup_stdin = dup(STDIN_FILENO);
    coin_stdin = fdopen(STDIN_FILENO, "r");
  }
  return coin_stdin;
}

FILE *
coin_get_stdout(void)
{
  if ( ! coin_stdout ){
    coin_dup_stdout = dup(STDOUT_FILENO);
    coin_stdout = fdopen(STDOUT_FILENO, "w");
  }
  return coin_stdout;
}

FILE *
coin_get_stderr(void)
{
  if ( ! coin_stderr ){
    coin_dup_stderr = dup(STDERR_FILENO);
    coin_stderr = fdopen(STDERR_FILENO, "w");
  }
  return coin_stderr;
}

/**************************************************************************/

SbBool
coin_locale_set_portable(cc_string * storeold)
{
  const char * loc;

  const char * deflocale = setlocale(LC_NUMERIC, NULL);
  if (strcmp(deflocale, "C") == 0) { return FALSE; }

  /* Must copy deflocale string, as it will be changed on the next
     invocation of setlocale(). */
  cc_string_construct(storeold);
  cc_string_set_text(storeold, deflocale);

  loc = setlocale(LC_NUMERIC, "C");
  assert(loc != NULL && "could not set locale to supposed portable C locale");
  return TRUE;
}

void
coin_locale_reset(cc_string * storedold)
{
  const char * l = setlocale(LC_NUMERIC, cc_string_get_text(storedold));
  assert(l != NULL && "could not reset locale");
  cc_string_clean(storedold);
}

double
coin_atof(const char * ptr)
{
  /* Avoid trying to read decimal point as ",", and reading with
     thousands separator, as defined for some locales, influencing the
     atof() call. */

  double v;
  cc_string storedlocale;
  SbBool changed = coin_locale_set_portable(&storedlocale);
  v = atof(ptr);
  if (changed) { coin_locale_reset(&storedlocale); }
  return v;
}

/**************************************************************************/

/* helper function for ascii85 handling */
static int
coin_encode_ascii85(const unsigned char * in, unsigned char * out)
{
  uint32_t data =
    ((uint32_t)(in[0])<<24) |
    ((uint32_t)(in[1])<<16) |
    ((uint32_t)(in[2])<< 8) |
    ((uint32_t)(in[3]));

  if (data == 0) {
    out[0] = 'z';
    return 1;
  }
  out[4] = (unsigned char) (data%85 + '!');
  data /= 85;
  out[3] = (unsigned char) (data%85 + '!');
  data /= 85;
  out[2] = (unsigned char) (data%85 + '!');
  data /= 85;
  out[1] = (unsigned char) (data%85 + '!');
  data /= 85;
  out[0] = (unsigned char) (data%85 + '!');
  return 5;
}

void
coin_output_ascii85(FILE * fp,
                    const unsigned char val,
                    unsigned char * tuple,
                    unsigned char * linebuf,
                    int * tuplecnt, int * linecnt,
                    const int rowlen,
                    const SbBool flush)
{
  int i;
  if (flush) {
    /* fill up tuple */
    for (i = *tuplecnt; i < 4; i++) tuple[i] = 0;
  }
  else {
    tuple[(*tuplecnt)++] = val;
  }
  if (flush || *tuplecnt == 4) {
    if (*tuplecnt) {
      int add = coin_encode_ascii85(tuple, linebuf + *linecnt);
      if (flush) {
        if (add == 1) {
          for (i = 0; i < 5; i++) linebuf[*linecnt + i] = '!';
        }
        *linecnt += *tuplecnt + 1;
      }
      else *linecnt += add;
      *tuplecnt = 0;
    }
    if (*linecnt >= rowlen) {
      unsigned char store = linebuf[rowlen];
      linebuf[rowlen] = 0;
      fprintf(fp, "%s\n", linebuf);
      linebuf[rowlen] = store;
      for (i = rowlen; i < *linecnt; i++) {
        linebuf[i-rowlen] = linebuf[i];
      }
      *linecnt -= rowlen;
    }
    if (flush && *linecnt) {
      linebuf[*linecnt] = 0;
      fprintf(fp, "%s\n", linebuf);
    }
  }
}

void
coin_flush_ascii85(FILE * fp,
                   unsigned char * tuple,
                   unsigned char * linebuf,
                   int * tuplecnt, int * linecnt,
                   const int rowlen)
{
  coin_output_ascii85(fp, 0, tuple, linebuf, tuplecnt, linecnt, rowlen, TRUE);
}

/**************************************************************************/

SbBool
coin_parse_versionstring(const char * versionstr,
                         int * major,
                         int * minor,
                         int * patch)
{
  char buffer[256];
  char * dotptr;

  *major = 0;
  if (minor) *minor = 0;
  if (patch) *patch = 0;
  if (versionstr == NULL) return FALSE;

  (void)strncpy(buffer, versionstr, 255);
  buffer[255] = '\0'; /* strncpy() will not null-terminate if strlen > 255 */
  dotptr = strchr(buffer, '.');
  if (dotptr) {
    char * spaceptr;
    char * start = buffer;
    *dotptr = '\0';
    *major = atoi(start);
    if (minor == NULL) return TRUE;
    start = ++dotptr;

    dotptr = strchr(start, '.');
    spaceptr = strchr(start, ' ');
    if (!dotptr && spaceptr) dotptr = spaceptr;
    if (dotptr && spaceptr && spaceptr < dotptr) dotptr = spaceptr;
    if (dotptr) {
      int terminate = *dotptr == ' ';
      *dotptr = '\0';
      *minor = atoi(start);
      if (patch == NULL) return TRUE;
      if (!terminate) {
        start = ++dotptr;
        dotptr = strchr(start, ' ');
        if (dotptr) *dotptr = '\0';
        *patch = atoi(start);
      }
    }
    else {
      *minor = atoi(start);
    }
  }
  else {
    cc_debugerror_post("coin_parse_versionstring",
                       "Invalid versionstring: \"%s\"\n", versionstr);
    return FALSE;
  }
  return TRUE;
}

/* Wrapper to use either _getcwd() (Win32) or getcwd() (POSIX.1) */
static char *
getcwd_wrapper(char * buf, size_t size)
{
#ifdef HAVE__GETCWD
  return _getcwd(buf, (int)size);
#elif defined(HAVE_GETCWD)
  return getcwd(buf, size);
#else /* HAVE_GETCWD */
  /* FIXME: abort compilation? pederb, 2003-08-18 */
  return NULL;
#endif /* ! HAVE_GETCWD */
}

/**************************************************************************/

/* Stores the name of the current working directory in the \a str
   argument.

   Returns TRUE if current working directory could be found, FALSE if
   not. If FALSE is returned, an error message will be stored in \a
   str.

   \a str must have been initialized before being passed to this
   function.

   The rationale behind this wrapper around the POSIX.1 getcwd()
   function is to abstract away the extra operations necessary to
   handle that the input buffer is guaranteed to be large enough.
*/
SbBool
coin_getcwd(cc_string * str)
{
  char buf[256], * dynbuf = NULL;
  size_t bufsize = sizeof(buf);
  char * cwd = getcwd_wrapper(buf, bufsize);

  while ((cwd == NULL) && (errno == ERANGE)) {
    bufsize *= 2;
    if (dynbuf != NULL) { free(dynbuf); }
    dynbuf = (char *)malloc(bufsize);
    cwd = getcwd_wrapper(dynbuf, bufsize);
  }
  if (cwd == NULL) { cc_string_set_text(str, strerror(errno)); }
  else { cc_string_set_text(str, cwd); }

  if (dynbuf != NULL) { free(dynbuf); }
  return cwd ? TRUE : FALSE;
}

/**************************************************************************/

/* Returns -1 if value equals negative infinity, +1 if it is equal to
   positive infinity, or 0 if the number is not infinite.

   Note that on some systems, this method will always return 0
   (i.e. false positives).
*/
int
coin_isinf(double value)
{
#ifdef HAVE_ISINF
  return isinf(value);
#elif defined(HAVE_FPCLASS)
  if (fpclass(value) == FP_NINF) { return -1; }
  if (fpclass(value) == FP_PINF) { return +1; }
  return 0;
#elif defined(HAVE__FPCLASS)
  if (_fpclass(value) == _FPCLASS_NINF) { return -1; }
  if (_fpclass(value) == _FPCLASS_PINF) { return +1; }
  return 0;
#else
  /* FIXME: it might be possible to investigate the fp bits and decide
     in a portable manner whether or not they represent an infinite. A
     groups.google.com search turned up inconclusive. 20030919
     mortene. */
  return 0;
#endif
}

/* Returns 0 if the bitpattern of the \a value argument is not a valid
   floating point number, otherwise returns non-zero.

   Note that on some systems, this method will always return 0
   (i.e. false positives).
*/
int
coin_isnan(double value)
{
#ifdef HAVE_ISNAN
  return isnan(value);
#elif defined(HAVE__ISNAN)
  return _isnan(value);
#elif defined(HAVE_FPCLASS)
  if (fpclass(value) == FP_SNAN) { return 1; }
  if (fpclass(value) == FP_QNAN) { return 1; }
  return 0;
#elif defined(HAVE__FPCLASS)
  if (_fpclass(value) == _FPCLASS_SNAN) { return 1; }
  if (_fpclass(value) == _FPCLASS_QNAN) { return 1; }
  return 0;
#else
  /* FIXME: it might be possible to investigate the fp bits and decide
     in a portable manner whether or not they represent a NaN. A
     groups.google.com search turned up inconclusive. 20030919
     mortene. */
  return 0;
#endif
}

/* Returns 0 if the bitpattern of the \a value argument is not a valid
   floating point number, or an infinite number, otherwise returns
   non-zero.

   Note that on some systems, this method will always return 1
   (i.e. false positives).
*/
int
coin_finite(double value)
{
#ifdef HAVE_FINITE
  return finite(value);
#elif defined(HAVE__FINITE)
  return _finite(value);
#else
  return !coin_isinf(value) && !coin_isnan(value);
#endif
}

/**************************************************************************/

/* table containing the next prime number for all power of twos from
   2^1 to 2^32 (the 2^32 prime is obviously less than 2^32 though) */
static const unsigned long coin_prime_table[32] = {
  2,
  5,
  11,
  17,
  37,
  67,
  131,
  257,
  521,
  1031,
  2053,
  4099,
  8209,
  16411,
  32771,
  65537,
  131101,
  262147,
  524309,
  1048583,
  2097169,
  4194319,
  8388617,
  16777259,
  33554467,
  67108879,
  134217757,
  268435459,
  536870923,
  1073741827,
  2147483659U,
  4294967291U /* 2^32 = 4294967296 */
};

unsigned long
coin_geq_prime_number(unsigned long num)
{
  int i;
  for (i = 0; i < 32; i++) {
    if (coin_prime_table[i] >= num) {
      return coin_prime_table[i];
    }
  }
  /* just return num if we can't find a bigger prime number */
  return num;
}

/**************************************************************************/

int
coin_runtime_os(void)
{
  /*
   * FIXME: this implementation should be replaced by something that
   * does a runtime check. kyrah suggested using sysctl() or uname()
   * (both part of the C runtime library) which sounds like a good
   * idea. pederb, 20051101
   *
   */
#if defined(__APPLE__)
  return COIN_OS_X;
#elif defined(HAVE_WIN32_API)
  return COIN_MSWINDOWS;
#else
  return COIN_UNIX;
#endif
}

/**************************************************************************/

/*
 * Will return TRUE if extra debugging information is enabled. These
 * are typically debugging messages extra for Coin and not found in
 * SGI Inventor. Also, these debugging message will not necessarily
 * mean that anything is wrong, but they can be useful for debugging
 * anyway.
 */
int
coin_debug_extra(void)
{
#if COIN_DEBUG
  return COIN_DEBUG_EXTRA;
#else /* COIN_DEBUG */
  return 0;
#endif /* !COIN_DEBUG */
}

/*
 * Will return TRUE if SbVec*::normalize() debugging is enabled.
 * This can be enabled using the COIN_DEBUG_NORMALIZE environment
 * variable.
 */
int
coin_debug_normalize(void)
{
#if COIN_DEBUG
  return COIN_DEBUG_NORMALIZE;
#else /* COIN_DEBUG */
  return 0;
#endif /* !COIN_DEBUG */
}


/*!
  Used for debugging caching.
*/
int
coin_debug_caching_level(void)
{
#if COIN_DEBUG
  static int COIN_DEBUG_CACHING = -1;
  if (COIN_DEBUG_CACHING < 0) {
    const char * env = coin_getenv("COIN_DEBUG_CACHING");
    if (env) COIN_DEBUG_CACHING = atoi(env);
    else COIN_DEBUG_CACHING = 0;
  }
  return COIN_DEBUG_CACHING;
#else /* debug */
  return 0;
#endif /* !debug */
}

/**************************************************************************/

#ifdef __cplusplus
} /* extern "C" */
#endif