summaryrefslogtreecommitdiff
path: root/libs/pbd/msvc/msvc_pbd.cc
blob: 68596e3463ab4c8b20fbb24e9e9cf263def2bc35 (plain)
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
/*
    Copyright (C) 2009 John Emmas

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

#ifdef COMPILER_MSVC

#include <WTypes.h>

extern "C" WINBASEAPI BOOL WINAPI
CreateHardLinkA( LPCSTR lpFileName,
				 LPCSTR lpExistingFileName,
				 LPSECURITY_ATTRIBUTES lpSecurityAttributes ); // Needs kernel32.lib on anything higher than Win2K

#include <algorithm>
#include <string>
#include <io.h>
#include <math.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <pbd/error.h>
#include <ardourext/misc.h>
#include <ardourext/pthread.h> // Should ensure that we include the right
                               // version - but we'll check anyway, later

#include <glibmm.h>

#define DELTA_EPOCH_IN_MICROSECS  11644473600000000Ui64

struct timezone
{
	int  tz_minuteswest; /* minutes W of Greenwich */
	int  tz_dsttime;     /* type of dst correction */
};

LIBPBD_API int PBD_APICALLTYPE
gettimeofday(struct timeval *__restrict tv, __timezone_ptr_t tz) // Does this need to be exported ?
{
FILETIME ft;
unsigned __int64 tmpres = 0;
static int tzflag = 0;

	if (NULL != tv)
	{
		GetSystemTimeAsFileTime(&ft);

		tmpres |= ft.dwHighDateTime;
		tmpres <<= 32;
		tmpres |= ft.dwLowDateTime;

		/*converting file time to unix epoch*/
		tmpres /= 10;  /*convert into microseconds*/
		tmpres -= DELTA_EPOCH_IN_MICROSECS;
		tv->tv_sec = (long)(tmpres / 1000000UL);
		tv->tv_usec = (long)(tmpres % 1000000UL);
	}

	if (NULL != tz)
	{
		struct timezone *ptz = static_cast<struct timezone*> (tz);
		if (!tzflag)
		{
			_tzset();
			tzflag++;
		}
		if (ptz)
		{
			ptz->tz_minuteswest = _timezone / 60;
			ptz->tz_dsttime = _daylight;
		}
	}

	return 0;
}

// Define the default comparison operators for Windows (ptw32) 'pthread_t' (not used
// by Ardour AFAIK but would be needed if an array of 'pthread_t' had to be sorted).
#ifndef PTHREAD_H   // Defined by PTW32 (Linux and other versions define _PTHREAD_H)
#error "An incompatible version of 'pthread.h' is #included. Use only the Windows (ptw32) version!"
#else
LIBPBD_API bool operator>  (const pthread_t& lhs, const pthread_t& rhs)
{
	return (std::greater<void*>()(lhs.p, rhs.p));
}

LIBPBD_API bool operator<  (const pthread_t& lhs, const pthread_t& rhs)
{
	return (std::less<void*>()(lhs.p, rhs.p));
}

LIBPBD_API bool operator!= (const pthread_t& lhs, const pthread_t& rhs)
{
	return (std::not_equal_to<void*>()(lhs.p, rhs.p));
}

LIBPBD_API bool operator== (const pthread_t& lhs, const pthread_t& rhs)
{
	return (!(lhs != rhs));
}
#endif

// Functions supplied (later) to std::transform
//***************************************************************
//
//	invert_backslash()
//
// Examines a supplied ASCII character and (if the character is
// a backslash) converts it to a forward slash,
//
//	Returns:
//
//    The supplied character (converted, if it was a backslash)
//
char invert_backslash(char character)
{
	if ('\\' == character)
		character = '/';

	return (character);
}

//***************************************************************
//
//	invert_forwardslash()
//
// Examines a supplied ASCII character and (if the character is
// a forward slash) converts it to a backslash,
//
//	Returns:
//
//    The supplied character (converted, if it was a fwd slash)
//
char invert_forwardslash(char character)
{
	if ('/' == character)
		character = '\\';

	return (character);
}


//***************************************************************
//
//	pread()
//
// Emulates pread() using _lseek()/_read()/_lseek().
//
//	Returns:
//
//    On Success: The number of bytes read from the file
//    On Failure: -1
//
LIBPBD_API ssize_t PBD_APICALLTYPE
pread(int handle, void *buf, size_t nbytes, off_t offset)
{
int old_errno;
ssize_t ret;

	off_t old_offset = _tell(handle);

	if (0 > old_offset)
		ret = (-1);
	else
	{
		_lseek(handle, offset, SEEK_SET);
		ret = _read(handle, buf, nbytes);

		old_errno = errno;
		_lseek(handle, old_offset, SEEK_SET);
		errno = old_errno;
	}

	return (ret);
}


//***************************************************************
//
//	pwrite()
//
// Emulates pwrite() using _lseek()/_write()/_lseek().
//
//	Returns:
//
//    On Success: The number of bytes written to the file
//    On Failure: -1
//
LIBPBD_API ssize_t PBD_APICALLTYPE
pwrite(int handle, const void *buf, size_t nbytes, off_t offset)
{
int old_errno;
ssize_t ret;

	off_t old_offset = _lseek(handle, offset, SEEK_SET);

	if (0 > old_offset)
		ret = (-1);
	else
	{
		ret = _write(handle, buf, nbytes);

		old_errno = errno;
		_lseek(handle, old_offset, SEEK_SET);
		errno = old_errno;
	}

	return (ret);
}

//***************************************************************
//
//	roundf()
//
// Emulates roundf() using floorf().
//
//	Returns:
//
//    On Success: The largest integer that is less than or
//                equal to 'x'.
//    On Failure: None
//
LIBPBD_API float PBD_APICALLTYPE
roundf(float x)
{
	return (floorf(x));
}

//***************************************************************
//
//	round()
//
// Emulates round() using floor().
//
//	Returns:
//
//    On Success: The largest integer that is less than or
//                equal to 'x'.
//    On Failure: None
//
LIBPBD_API double PBD_APICALLTYPE
round(double x)
{
	return (floor(x));
}

//***************************************************************
//
//	trunc()
//
// Emulates trunc() using floor() and ceil().
//
//	Returns:
//
//    On Success: The largest integer whose magnitude is less
//                than or equal to 'x' (regardless of sign).
//    On Failure: None
//
LIBPBD_API double PBD_APICALLTYPE
trunc(double x)
{
	if (x < 0)
		return (ceil(x));

	return (floor(x));
}

#if defined(_MSC_VER) && (_MSC_VER < 1800)
//***************************************************************
//
//	expm1()
//
// Emulates C99 expm1() using exp().
//
//	Returns:
//
//    On Success: (('e' raised to the power of 'x') - 1)
//                (e.g. expm1(1) == 1.7182818).
//    On Failure: None, except that calling exp(x) should generate
//                an appropriate error for us (such as INF etc).
//
LIBPBD_API double PBD_APICALLTYPE
expm1(double x)
{
	return (exp(x) - (double)1.0);
}

//***************************************************************
//
//	log1p()
//
// Emulates C99 log1p() using log().
//
//	Returns:
//
//    On Success: The natural logarithm of (1 + x)
//                (e.g. log1p(1) == 0.69314718).
//    On Failure: None, except that calling log(x) should generate
//                an appropriate error for us (such as ERANGE etc).
//
LIBPBD_API double PBD_APICALLTYPE
log1p(double x)
{
	return (log(x + (double)1.0));
}
#endif

#if defined(_MSC_VER) && (_MSC_VER < 1900)
//***************************************************************
//
//	log2()
//
// Emulates C99 log2() using log().
//
//	Returns:
//
//    On Success: The binary (base-2) logarithm of 'x'
//                (e.g. log2(1024) == 10).
//    On Failure: None, except that calling log(x) should generate
//                an appropriate error for us (such as ERANGE etc).
//
LIBPBD_API double PBD_APICALLTYPE
log2(double x)
{
	return (log(x) / log((double)2.0));
}
#endif

namespace PBD {

//***************************************************************
//
//	TestForMinimumSpecOS()
//
// Tests the user's OS to see if it is Win2K or later (could be
// expanded quite easily to accommodate other OS's)
//
//	Returns:
//
//    On Success: TRUE (if the user's OS matches the minimum spec)
//    On Failure: FALSE otherwise
//
LIBPBD_API bool PBD_APICALLTYPE
TestForMinimumSpecOS(char *revision /* currently ignored */)
{
bool bRet = true;
#ifdef PLATFORM_WINDOWS
	bRet = false;
	HINSTANCE hKernelDll = (HINSTANCE)dlopen("kernel32.dll", RTLD_NOW);

	if (hKernelDll)
	{
		// 'CreateHardLink()' is only available from Win2K onwards.
		if (NULL != dlsym(hKernelDll, "CreateHardLinkA"))
			bRet = true;

		dlclose(hKernelDll);
	}
#endif
	// Other OS's could be accommodated here

	return (bRet);
}


//***************************************************************
//
//	realpath()
//
// Emulates POSIX realpath() using Win32 _fullpath().
//
//	Returns:
//
//    On Success: A pointer to the resolved (absolute) path
//    On Failure: NULL
//
LIBPBD_API char* PBD_APICALLTYPE
realpath (const char *original_path, char resolved_path[_MAX_PATH+1])
{
char *pRet = NULL;
bool bIsSymLink = 0; // We'll probably need to test the incoming path
                     // to find out if it points to a Windows shortcut
                     // (or a hard link) and set this appropriately.
	if (bIsSymLink)
	{
		// At the moment I'm not sure if Windows '_fullpath()' is directly
		// equivalent to POSIX 'realpath()' - in as much as the latter will
		// resolve the supplied path if it happens to point to a symbolic
		// link ('_fullpath()' probably DOESN'T do this but I'm not really
		// sure if Ardour needs such functionality anyway). Therefore we'll
		// possibly need to add that functionality here at a later date.
	}
	else
	{
		char temp[(MAX_PATH+1)*6]; // Allow for maximum length of a path in UTF8 characters

		// POSIX 'realpath()' requires that the buffer size is at
		// least PATH_MAX+1, so assume that the user knew this !!
		pRet = _fullpath(temp, Glib::locale_from_utf8(original_path).c_str(), _MAX_PATH);
		if (NULL != pRet)
			strcpy(resolved_path, Glib::locale_to_utf8(temp).c_str());
	}

	return (pRet);
}


//***************************************************************
//
//	opendir()
//
// Creates a pointer to a DIR structure, appropriately filled in
// and ready to begin a directory search iteration.
//
//	Returns:
//
//    On Success: Pointer to a (heap based) DIR structure
//    On Failure: NULL
//
LIBPBD_API DIR* PBD_APICALLTYPE
opendir (const char *szPath)
{
wchar_t wpath[PATH_MAX+1];
unsigned int rc;
DIR *pDir = 0;

	errno = 0;

	if (!szPath)
		errno = EFAULT;

	if ((!errno) && ('\0' == szPath[0]))
		errno = ENOTDIR;

	// Determine if the given path really is a directory

	if (!errno)
		if (0 == MultiByteToWideChar (CP_UTF8, 0, (LPCSTR)szPath, -1, (LPWSTR)wpath, sizeof(wpath)))
			errno = EFAULT;

	if ((!errno) && ((rc = GetFileAttributesW(wpath)) == -1))
		errno = ENOENT;

	if ((!errno) && (!(rc & FILE_ATTRIBUTE_DIRECTORY)))
		// Error. Entry exists but not a directory. */
		errno = ENOTDIR;

	if (!errno)
	{
		// Allocate enough memory to store DIR structure, plus
		// the complete directory path originally supplied.
		pDir = (DIR *)malloc(sizeof(DIR) + strlen(szPath) + strlen("\\") + strlen ("*"));

		if (!pDir)
		{
			// Error - out of memory
			errno = ENOMEM;
		}
	}

	if (!errno)
	{
		// Create the search expression
		strcpy(pDir->dd_name, szPath);

		// Add a backslash if the path doesn't already end with one
		if (pDir->dd_name[0] != '\0' &&
			pDir->dd_name[strlen(pDir->dd_name) - 1] != '/' &&
			pDir->dd_name[strlen(pDir->dd_name) - 1] != '\\')
		{
			strcat (pDir->dd_name, "\\");
		}

		// Add the search pattern
		strcat(pDir->dd_name, "*");

		// Initialize handle to -1 so that a premature closedir()
		// doesn't try to call _findclose() on it.
		pDir->dd_handle = (-1);

		// Initialize the status
		pDir->dd_stat = 0;

		// Initialize the dirent structure. 'ino' and 'reclen' are invalid under Win32
		// and 'name' simply points at the appropriate part of the findfirst_t struct.
		pDir->dd_dir.d_ino = 0;
		pDir->dd_dir.d_reclen = 0;
		pDir->dd_dir.d_namlen = 0;
		strcpy(pDir->dd_dir.d_name, pDir->dd_dta.name);

		return (pDir);  // Succeeded
	}

	if (pDir)
		free (pDir);
	return (DIR *) 0; // Failed
}


//***************************************************************
//
//	readdir()
//
// Return a pointer to a dirent struct, filled with information
// about the next entry in the directory.
//
//	Returns:
//
//    On Success: A pointer to the supplied DIR's 'dirent' struct
//    On Failure: NULL
//
LIBPBD_API struct dirent* PBD_APICALLTYPE
readdir (DIR* pDir)
{
int old_errno = 0;
errno = 0;

	// Check for valid DIR struct
	if (!pDir)
		errno = EFAULT;

	if ((strcmp(pDir->dd_dir.d_name, pDir->dd_dta.name)) && (!errno))
		// The structure does not seem to be set up correctly
		errno = EINVAL;
	else
	{
		if (pDir->dd_stat < 0)
		{
			// We have already returned all files in this directory
			// (or the structure has an invalid dd_stat).
			return (struct dirent *)0;
		}
		else if (pDir->dd_stat == 0)
		{
			// We haven't started the search yet.
			// Start the search
			pDir->dd_handle = _findfirst (Glib::locale_from_utf8(pDir->dd_name).c_str(), &(pDir->dd_dta));

			if (pDir->dd_handle == -1)
				// The directory is empty
				pDir->dd_stat = -1;
			else
				pDir->dd_stat = 1;
		}
		else
		{
			// Do not return ENOENT on last file in directory
			old_errno = errno;

			// Get the next search entry
			if (_findnext (pDir->dd_handle, &(pDir->dd_dta)))
			{
				// We are off the end or otherwise error
				errno = old_errno;
				_findclose (pDir->dd_handle);
				pDir->dd_handle = -1;
				pDir->dd_stat = -1;
			}
			else
				// Update to indicate the correct status number
				pDir->dd_stat++;
		}

		if (pDir->dd_stat > 0)
		{
			// We successfully got an entry. Details about the file are
			// already appropriately filled in except for the length of
			// file name.
			strcpy(pDir->dd_dir.d_name, pDir->dd_dta.name);
			pDir->dd_dir.d_namlen = strlen (pDir->dd_dir.d_name);
			return (&pDir->dd_dir); // Succeeded
		}
	}

	return (struct dirent *) 0; // Failed
}


//***************************************************************
//
//	closedir()
//
// Frees the resources allocated by opendir().
//
//	Returns:
//
//    On Success: 0
//    On Failure: -1
//
LIBPBD_API int PBD_APICALLTYPE
closedir (DIR *pDir)
{
int rc = 0;

	errno = 0;

	if (!pDir)
		errno = EFAULT;
	else
	{
		if ((-1) != pDir->dd_handle)
			rc = _findclose (pDir->dd_handle);

		// Free the DIR structure
		free (pDir);

		return rc; // Succeeded
	}

	return (-1); // Failed
}

//***************************************************************
//
//	mkstemp()
//
// Emulates Linux mkstemp() using Win32 _mktemp() and _open() etc.
//
//	Returns:
//
//    On Success: A file descriptor for the opened file.
//    On Failure: (-1)
//
LIBPBD_API int PBD_APICALLTYPE
mkstemp (char *template_name)
{
int ret = (-1);
char *szFileName;
char szTempPath[PATH_MAX+100]; // Just ensure we have plenty of buffer space

	if (NULL != (szFileName = _mktemp(template_name)))
	{
		if (0 != ::GetTempPathA(sizeof(szTempPath), szTempPath))
		{
			strcat(szTempPath, szFileName);
			ret = _open(szTempPath, (_O_CREAT|_O_BINARY|_O_TEMPORARY|_O_RDWR|_O_TRUNC), _S_IWRITE);
		}
	}

	return (ret);
}


//***************************************************************
//
//	ntfs_link()
//
// Emulates Linux link() using Win32 CreateHardLink()(NTFS only).
//
//	Returns:
//
//    On Success: Non-zero.
//    On Failure: Zero (call 'GetLastError()' to retrieve info)
//
LIBPBD_API int PBD_APICALLTYPE
ntfs_link (const char *existing_filepath, const char *link_filepath)
{
int ret = 1; // 'ERROR_INVALID_FUNCTION'
bool bValidPath = false;

	// Make sure we've been sent a valid input string
	if (existing_filepath && link_filepath)
	{
		std::string strRoot = existing_filepath;

		if ((1 < strRoot.length()) && ('\\' == existing_filepath[0]) && ('\\' == existing_filepath[1]))
		{
			int slashcnt = 0;

			// We've been sent a network path. Convert backslashes to forward slashes temporarily.
			std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);

			// Now, if there are less than four slashes, add a fourth one or abort
			std::string::iterator iter = strRoot.begin();
			while ((slashcnt < 4) && (iter != strRoot.end()))
			{
				if ('/' == (*iter))
					slashcnt++;

				++iter;
			}

			if (slashcnt > 2)
			{
				// If only 3 slashes were counted, add a trailing slash
				if (slashcnt == 3)
					strRoot += '/';

				// Now find the position of the fourth slash
				iter = strRoot.begin();
				int charcnt = 0;
				for (slashcnt=0; slashcnt<4;)
				{
					charcnt++;

					if ('/' == (*iter))
						slashcnt++;

					if (++iter == strRoot.end())
						break;
				}

				strRoot.resize(charcnt);
				bValidPath = true;
			}
		}
		else
		{
			// Assume a standard Windows style path
			if (1 < strRoot.length() && (':' == existing_filepath[1]))
			{
				// Convert backslashes to forward slashes temporarily.
				std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);

				if (2 == strRoot.length())
					strRoot += '/';

				if ('/' == strRoot[2])
				{
					strRoot.resize(3);
					bValidPath = true;
				}
			}
		}

		if (bValidPath)
		{
			char szFileSystemType[_MAX_PATH+1];

			// Restore the original backslashes
			std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_forwardslash);

			// Windows only supports hard links for the NTFS filing
			// system, so let's make sure that's what we're using!!
			if (::GetVolumeInformationA(strRoot.c_str(), NULL, 0, NULL, NULL, NULL, szFileSystemType, _MAX_PATH+1))
			{
				std::string strRootFileSystemType = szFileSystemType;
				std::transform(strRootFileSystemType.begin(), strRootFileSystemType.end(), strRootFileSystemType.begin(), ::toupper);
#if (_WIN32_WINNT >= 0x0500)
				if (0 == strRootFileSystemType.compare("NTFS"))
				{
					if (TestForMinimumSpecOS()) // Hard links were only available from Win2K onwards
						if (0 == CreateHardLinkA(link_filepath, existing_filepath, NULL))
						{	// Note that the above API call cannot create a link to a directory, so
							// should we also be checking that the supplied path was actually a file?
							ret = GetLastError();
						}
						else
							SetLastError(ret = 0); // 'NO_ERROR'
				}
				else
				{
					ret = 4300; // 'ERROR_INVALID_MEDIA'
				}
#endif
			}
		}
		else
			ret = 123; // 'ERROR_INVALID_NAME'
	}
	else
		ret = 161; // 'ERROR_BAD_PATHNAME'

	if (ret)
	{
		SetLastError(ret);
		return (-1);
	}
	else
		return (0);
}


//***************************************************************
//
//	ntfs_unlink()
//
// Emulates Linux unlink() using Win32 DeleteFile()(NTFS only).
//
//	Returns:
//
//    On Success: Non-zero.
//    On Failure: Zero (call 'GetLastError()' to retrieve info)
//
LIBPBD_API int PBD_APICALLTYPE
ntfs_unlink (const char *link_filepath)
{
int ret = 1; // 'ERROR_INVALID_FUNCTION'
bool bValidPath = false;

	// Make sure we've been sent a valid input string
	if (link_filepath)
	{
		std::string strRoot = link_filepath;

		if ((1 < strRoot.length()) && ('\\' == link_filepath[0]) && ('\\' == link_filepath[1]))
		{
			int slashcnt = 0;

			// We've been sent a network path. Convert backslashes to forward slashes temporarily.
			std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);

			// Now, if there are less than four slashes, add a fourth one or abort
			std::string::iterator iter = strRoot.begin();
			while ((slashcnt < 4) && (iter != strRoot.end()))
			{
				if ('/' == (*iter))
					slashcnt++;

				++iter;
			}

			if (slashcnt > 2)
			{
				// If only 3 slashes were counted, add a trailing slash
				if (slashcnt == 3)
					strRoot += '/';

				// Now find the position of the fourth slash
				iter = strRoot.begin();
				int charcnt = 0;
				for (slashcnt=0; slashcnt<4;)
				{
					charcnt++;

					if ('/' == (*iter))
						slashcnt++;

					if (++iter == strRoot.end())
						break;
				}

				strRoot.resize(charcnt);
				bValidPath = true;
			}
		}
		else
		{
			// Assume a standard Windows style path
			if (1 < strRoot.length() && (':' == link_filepath[1]))
			{
				// Convert backslashes to forward slashes temporarily.
				std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);

				if (2 == strRoot.length())
					strRoot += '/';

				if ('/' == strRoot[2])
				{
					strRoot.resize(3);
					bValidPath = true;
				}
			}
		}

		if (bValidPath)
		{
			char szFileSystemType[_MAX_PATH+1];

			// Restore the original backslashes
			std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_forwardslash);

			// Windows only supports hard links for the NTFS filing
			// system, so let's make sure that's what we're using!!
			if (::GetVolumeInformationA(strRoot.c_str(), NULL, 0, NULL, NULL, NULL, szFileSystemType, _MAX_PATH+1))
			{
				std::string strRootFileSystemType = szFileSystemType;
				std::transform(strRootFileSystemType.begin(), strRootFileSystemType.end(), strRootFileSystemType.begin(), ::toupper);
#if (_WIN32_WINNT >= 0x0500)
				if (0 == strRootFileSystemType.compare("NTFS"))
					if (TestForMinimumSpecOS()) // Hard links were only available from Win2K onwards
						if (0 == DeleteFileA(link_filepath))
							ret = GetLastError();
						else
							ret = 0; // 'NO_ERROR'
#endif
			}
		}
		else
			ret = 123; // 'ERROR_INVALID_NAME'
	}
	else
		ret = 161; // 'ERROR_BAD_PATHNAME'

	if (ret)
	{
		SetLastError(ret);
		return (-1);
	}
	else
		return (0);
}

}  // namespace PBD


//***************************************************************
//
//	dlopen()
//
// Emulates POSIX dlopen() using Win32 LoadLibrary().
//
//	Returns:
//
//    On Success: A handle to the opened DLL
//    On Failure: NULL
//
LIBPBD_API void* PBD_APICALLTYPE
dlopen (const char *file_name, int mode)
{
	// Note that 'mode' is ignored in Win32
	return(::LoadLibraryA(Glib::locale_from_utf8(file_name).c_str()));
}


//***************************************************************
//
//	dlclose()
//
// Emulates POSIX dlclose() using Win32 FreeLibrary().
//
//	Returns:
//
//    On Success: A non-zero number
//    On Failure: 0
//
LIBPBD_API int PBD_APICALLTYPE
dlclose (void *handle)
{
	return (::FreeLibrary((HMODULE)handle));
}


//***************************************************************
//
//	dlsym()
//
// Emulates POSIX dlsym() using Win32 GetProcAddress().
//
//	Returns:
//
//    On Success: A pointer to the found function or symbol
//    On Failure: NULL
//
LIBPBD_API void* PBD_APICALLTYPE
dlsym (void *handle, const char *symbol_name)
{
	// First test for RTLD_DEFAULT and RTLD_NEXT
	if ((handle == 0/*RTLD_DEFAULT*/) || (handle == ((void *) -1L)/*RTLD_NEXT*/))
	{
		return 0; // Not yet supported for Win32
	}
	else
		return (::GetProcAddress((HMODULE)handle, symbol_name));
}

#define LOCAL_ERROR_BUF_SIZE 1024
static char szLastWinError[LOCAL_ERROR_BUF_SIZE];
//***************************************************************
//
//	dlerror()
//
// Emulates POSIX dlerror() using Win32 GetLastError().
//
//	Returns:
//
//    On Success: The translated message corresponding to the
//                last error
//    On Failure: NULL (if the last error was ERROR_SUCCESS)
//
LIBPBD_API char* PBD_APICALLTYPE
dlerror ()
{
	DWORD dwLastErrorId = GetLastError();
	if (ERROR_SUCCESS == dwLastErrorId)
		return 0;
	else
	{
		if (0 == FormatMessage(
					FORMAT_MESSAGE_FROM_SYSTEM,
					NULL,
					dwLastErrorId,
					0,
					szLastWinError,
					LOCAL_ERROR_BUF_SIZE,
					0))
		{
			sprintf(szLastWinError, "Could not decipher the previous error message");
		}

		// POSIX dlerror() seems to reset the
		// error system, so emulate that here
		SetLastError(ERROR_SUCCESS);
	}

	return(szLastWinError);
}

#endif  // COMPILER_MSVC