- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCFPlatform.c
1195 lines (1010 loc) · 40.4 KB
/
CFPlatform.c
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
/*
* Copyright (c) 2008-2012 Brent Fulgham <bfulgham@gmail.org>. All rights reserved.
* Copyright (c) 2009 Grant Erickson <gerickson@nuovations.com>. All rights reserved.
*
* This source code is a modified version of the CoreFoundation sources released by Apple Inc. under
* the terms of the APSL version 2.0 (see below).
*
* For information about changes from the original Apple source release can be found by reviewing the
* source control system for the project at https://sourceforge.net/svn/?group_id=246198.
*
* The original license information is as follows:
*
* Copyright (c) 2012 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/* CFPlatform.c
Copyright (c) 1999-2011, Apple Inc. All rights reserved.
Responsibility: Tony Parker
*/
#include<CoreFoundation/CoreFoundation_Prefix.h>
#include"CFInternal.h"
#include<CoreFoundation/CFPriv.h>
#include<fcntl.h>
#ifDEPLOYMENT_TARGET_MACOSX||DEPLOYMENT_TARGET_EMBEDDED
#include<stdlib.h>
#include<sys/stat.h>
#include<string.h>
#include<unistd.h>
#include<pwd.h>
#include<crt_externs.h>
#include<mach-o/dyld.h>
#elifDEPLOYMENT_TARGET_LINUX||DEPLOYMENT_TARGET_FREEBSD
#include<pwd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#endif
#ifDEPLOYMENT_TARGET_WINDOWS
#include<shellapi.h>
#include<shlobj.h>
#include<WinIoCtl.h>
#definegetcwd _NS_getcwd
#definestrdup _strdup
#endif
#ifDEPLOYMENT_TARGET_MACOSX||DEPLOYMENT_TARGET_EMBEDDED||DEPLOYMENT_TARGET_WINDOWS_SYNC
#definekCFPlatformInterfaceStringEncoding kCFStringEncodingUTF8
#else
#definekCFPlatformInterfaceStringEncoding CFStringGetSystemEncoding()
#endif
staticCFStringRef_CFUserName(void);
#ifDEPLOYMENT_TARGET_MACOSX||DEPLOYMENT_TARGET_EMBEDDED
// CoreGraphics and LaunchServices are only projects (1 Dec 2006) that use these
char**_CFArgv(void) { return*_NSGetArgv(); }
int_CFArgc(void) { return*_NSGetArgc(); }
#endif
__private_extern__Boolean_CFGetCurrentDirectory(char*path, intmaxlen) {
returngetcwd(path, maxlen) !=NULL;
}
#ifSUPPORT_CFM
staticBoolean__CFIsCFM= false;
// If called super early, we just return false
__private_extern__Boolean_CFIsCFM(void) {
return__CFIsCFM;
}
#endif
#ifDEPLOYMENT_TARGET_WINDOWS
#definePATH_SEP '\\'
#else
#definePATH_SEP '/'
#endif
#ifDEPLOYMENT_TARGET_WINDOWS
// Returns the path to the CF DLL, which we can then use to find resources like char sets
boolbDllPathCached= false;
__private_extern__constwchar_t*_CFDLLPath(void) {
staticwchar_tcachedPath[MAX_PATH+1];
if (!bDllPathCached) {
#ifdef_DEBUG
// might be nice to get this from the project file at some point
wchar_t*DLLFileName=L"CFLite_debug.dll"; //L"CoreFoundation_debug.dll";
#else
wchar_t*DLLFileName=L"CFLite.dll"; //L"CoreFoundation.dll";
#endif
HMODULEourModule=GetModuleHandleW(DLLFileName);
CFAssert(ourModule, __kCFLogAssertion, "GetModuleHandle failed");
DWORDwResult=GetModuleFileNameW(ourModule, cachedPath, MAX_PATH+1);
CFAssert1(wResult>0, __kCFLogAssertion, "GetModuleFileName failed: %d", GetLastError());
CFAssert1(wResult<MAX_PATH+1, __kCFLogAssertion, "GetModuleFileName result truncated: %s", cachedPath);
// strip off last component, the DLL name
CFIndexidx;
for (idx=wResult-1; idx; idx--) {
if ('\\'==cachedPath[idx]) {
cachedPath[idx] ='\0';
break;
}
}
bDllPathCached= true;
}
returncachedPath;
}
#endif
staticconstchar*__CFProcessPath=NULL;
staticconstchar*__CFprogname=NULL;
constchar**_CFGetProgname(void) {
if (!__CFprogname)
_CFProcessPath(); // sets up __CFprogname as a side-effect
return&__CFprogname;
}
constchar**_CFGetProcessPath(void) {
if (!__CFProcessPath)
_CFProcessPath(); // sets up __CFProcessPath as a side-effect
return&__CFProcessPath;
}
#ifDEPLOYMENT_TARGET_WINDOWS
constchar*_CFProcessPath(void) {
if (__CFProcessPath) return__CFProcessPath;
wchar_tbuf[CFMaxPathSize] = {0};
DWORDrlen=GetModuleFileNameW(NULL, buf, sizeof(buf) / sizeof(buf[0]));
if (0<rlen) {
charasciiBuf[CFMaxPathSize] = {0};
intres=WideCharToMultiByte(CP_UTF8, 0, buf, rlen, asciiBuf, sizeof(asciiBuf) / sizeof(asciiBuf[0]), NULL, NULL);
if (0<res) {
__CFProcessPath=strdup(asciiBuf);
__CFprogname=strrchr(__CFProcessPath, PATH_SEP);
__CFprogname= (__CFprogname ? __CFprogname+1 : __CFProcessPath);
}
}
if (!__CFProcessPath) {
__CFProcessPath="";
__CFprogname=__CFProcessPath;
}
return__CFProcessPath;
}
#endif
#ifDEPLOYMENT_TARGET_MACOSX||DEPLOYMENT_TARGET_EMBEDDED
constchar*_CFProcessPath(void) {
if (__CFProcessPath) return__CFProcessPath;
#ifDEPLOYMENT_TARGET_MACOSX
if (!issetugid()) {
constchar*path= (char*)__CFgetenv("CFProcessPath");
if (path) {
__CFProcessPath=strdup(path);
__CFprogname=strrchr(__CFProcessPath, PATH_SEP);
__CFprogname= (__CFprogname ? __CFprogname+1 : __CFProcessPath);
return__CFProcessPath;
}
}
#endif
uint32_tsize=CFMaxPathSize;
charbuffer[size];
if (0==_NSGetExecutablePath(buffer, &size)) {
#ifSUPPORT_CFM
size_tlen=strlen(buffer);
if (12 <= len&&0==strcmp("LaunchCFMApp", buffer+len-12)) {
structstatexec, lcfm;
constchar*launchcfm="/System/Library/Frameworks/Carbon.framework/Versions/Current/Support/LaunchCFMApp";
if (0==stat(launchcfm, &lcfm) &&0==stat(buffer, &exec) && (lcfm.st_dev==exec.st_dev) && (lcfm.st_ino==exec.st_ino)) {
// Executable is LaunchCFMApp, take special action
__CFIsCFM= true;
if ((*_NSGetArgv())[1] &&'/'==*((*_NSGetArgv())[1])) {
strlcpy(buffer, (*_NSGetArgv())[1], sizeof(buffer));
}
}
}
#endif
__CFProcessPath=strdup(buffer);
__CFprogname=strrchr(__CFProcessPath, PATH_SEP);
__CFprogname= (__CFprogname ? __CFprogname+1 : __CFProcessPath);
}
if (!__CFProcessPath) {
__CFProcessPath="";
__CFprogname=__CFProcessPath;
}
return__CFProcessPath;
}
#endif
#ifDEPLOYMENT_TARGET_LINUX
#include<unistd.h>
constchar*_CFProcessPath(void) {
if (__CFProcessPath) return__CFProcessPath;
charbuf[CFMaxPathSize+1];
ssize_tres=readlink("/proc/self/exe", buf, CFMaxPathSize);
if (res>0) {
// null terminate, readlink does not
buf[res] =0;
__CFProcessPath=strdup(buf);
__CFprogname=strrchr(__CFProcessPath, PATH_SEP);
__CFprogname= (__CFprogname ? __CFprogname+1 : __CFProcessPath);
} else {
__CFProcessPath="";
__CFprogname=__CFProcessPath;
}
return__CFProcessPath;
}
#endif
__private_extern__CFStringRef_CFProcessNameString(void) {
staticCFStringRef__CFProcessNameString=NULL;
if (!__CFProcessNameString) {
constchar*processName=*_CFGetProgname();
if (!processName) processName="";
CFStringRefnewStr=CFStringCreateWithCString(kCFAllocatorSystemDefault, processName, kCFPlatformInterfaceStringEncoding);
if (!OSAtomicCompareAndSwapPtrBarrier(NULL, (void*) newStr, (void*volatile*)&__CFProcessNameString)) {
CFRelease(newStr); // someone else made the assignment, so just release the extra string.
}
}
return__CFProcessNameString;
}
staticCFStringRef__CFUserName=NULL;
staticCFSpinLock_t__CFPlatformCacheLock=CFSpinLockInit;
#ifDEPLOYMENT_TARGET_MACOSX||DEPLOYMENT_TARGET_EMBEDDED|| defined(__svr4__) || defined(__hpux__) ||DEPLOYMENT_TARGET_LINUX||DEPLOYMENT_TARGET_FREEBSD
#include<pwd.h>
staticCFURLRef__CFHomeDirectory=NULL;
staticuint32_t__CFEUID=-1;
staticuint32_t__CFUID=-1;
staticCFURLRef_CFCopyHomeDirURLForUser(structpasswd*upwd) { // __CFPlatformCacheLock must be locked on entry and will be on exit
CFURLRefhome=NULL;
if (!__CFIsCurrentProcessTainted()) {
constchar*path=__CFgetenv("CFFIXED_USER_HOME");
if (path) {
home=CFURLCreateFromFileSystemRepresentation(kCFAllocatorSystemDefault, (uint8_t*)path, strlen(path), true);
}
}
if (!home) {
if (upwd&&upwd->pw_dir) {
home=CFURLCreateFromFileSystemRepresentation(kCFAllocatorSystemDefault, (uint8_t*)upwd->pw_dir, strlen(upwd->pw_dir), true);
}
}
returnhome;
}
staticvoid_CFUpdateUserInfo(void) { // __CFPlatformCacheLock must be locked on entry and will be on exit
structpasswd*upwd;
__CFEUID=geteuid();
__CFUID=getuid();
if (__CFHomeDirectory) CFRelease(__CFHomeDirectory);
__CFHomeDirectory=NULL;
if (__CFUserName) CFRelease(__CFUserName);
__CFUserName=NULL;
upwd=getpwuid(__CFEUID ? __CFEUID : __CFUID);
__CFHomeDirectory=_CFCopyHomeDirURLForUser(upwd);
if (!__CFHomeDirectory) {
constchar*cpath=__CFgetenv("HOME");
if (cpath) {
__CFHomeDirectory=CFURLCreateFromFileSystemRepresentation(kCFAllocatorSystemDefault, (uint8_t*)cpath, strlen(cpath), true);
}
}
// This implies that UserManager stores directory info in CString
// rather than FileSystemRep. Perhaps this is wrong & we should
// expect NeXTSTEP encodings. A great test of our localized system would
// be to have a user "O-umlat z e r". XXX
if (upwd&&upwd->pw_name) {
__CFUserName=CFStringCreateWithCString(kCFAllocatorSystemDefault, upwd->pw_name, kCFPlatformInterfaceStringEncoding);
} else {
constchar*cuser=__CFgetenv("USER");
if (cuser)
__CFUserName=CFStringCreateWithCString(kCFAllocatorSystemDefault, cuser, kCFPlatformInterfaceStringEncoding);
}
}
#endif
staticCFURLRef_CFCreateHomeDirectoryURLForUser(CFStringRefuName) { // __CFPlatformCacheLock must be locked on entry and will be on exit
#ifDEPLOYMENT_TARGET_MACOSX||DEPLOYMENT_TARGET_EMBEDDED|| defined(__svr4__) || defined(__hpux__) ||DEPLOYMENT_TARGET_LINUX||DEPLOYMENT_TARGET_FREEBSD
if (!uName) {
if (geteuid() !=__CFEUID||getuid() !=__CFUID|| !__CFHomeDirectory)
_CFUpdateUserInfo();
if (__CFHomeDirectory) CFRetain(__CFHomeDirectory);
return__CFHomeDirectory;
} else {
structpasswd*upwd=NULL;
charbuf[128], *user;
SInt32len=CFStringGetLength(uName), size=CFStringGetMaximumSizeForEncoding(len, kCFPlatformInterfaceStringEncoding);
CFIndexusedSize;
if (size<127) {
user=buf;
} else {
user= (char*)CFAllocatorAllocate(kCFAllocatorSystemDefault, size+1, 0);
if (__CFOASafe) __CFSetLastAllocationEventName(user, "CFUtilities (temp)");
}
if (CFStringGetBytes(uName, CFRangeMake(0, len), kCFPlatformInterfaceStringEncoding, 0, true, (uint8_t*)user, size, &usedSize) ==len) {
user[usedSize] ='\0';
upwd=getpwnam(user);
}
if (buf!=user) {
CFAllocatorDeallocate(kCFAllocatorSystemDefault, user);
}
return_CFCopyHomeDirURLForUser(upwd);
}
#elifDEPLOYMENT_TARGET_WINDOWS
// This code can only get the directory for the current user
if (uName&& !CFEqual(uName, _CFUserName())) {
CFLog(kCFLogLevelError, CFSTR("CFCopyHomeDirectoryURLForUser(): Unable to get home directory for other user"));
returnNULL;
}
CFURLRefretVal=NULL;
CFIndexlen=0;
CFStringRefstr=NULL;
UniCharpathChars[MAX_PATH];
if (S_OK==SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, (wchar_t*)pathChars)) {
len= (CFIndex)wcslen((wchar_t*)pathChars);
str=CFStringCreateWithCharacters(kCFAllocatorSystemDefault, pathChars, len);
retVal=CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, str, kCFURLWindowsPathStyle, true);
CFRelease(str);
}
if (!retVal) {
// Fall back to environment variable, but this will not be unicode compatible
constchar*cpath=__CFgetenv("HOMEPATH");
constchar*cdrive=__CFgetenv("HOMEDRIVE");
if (cdrive&&cpath) {
charfullPath[CFMaxPathSize];
strlcpy(fullPath, cdrive, sizeof(fullPath));
strlcat(fullPath, cpath, sizeof(fullPath));
str=CFStringCreateWithCString(kCFAllocatorSystemDefault, fullPath, kCFPlatformInterfaceStringEncoding);
retVal=CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, str, kCFURLWindowsPathStyle, true);
CFRelease(str);
}
}
if (!retVal) {
// Last resort: We have to get "some" directory location, so fall-back to the processes current directory.
UniCharcurrDir[MAX_PATH];
DWORDdwChars=GetCurrentDirectoryW(MAX_PATH+1, (wchar_t*)currDir);
if (dwChars>0) {
len= (CFIndex)wcslen((wchar_t*)currDir);
str=CFStringCreateWithCharacters(kCFAllocatorDefault, currDir, len);
retVal=CFURLCreateWithFileSystemPath(NULL, str, kCFURLWindowsPathStyle, true);
CFRelease(str);
}
}
// We could do more here (as in KB Article Q101507). If that article is to be believed, we should only run into this case on Win95, or through user error.
CFStringReftestPath=CFURLCopyFileSystemPath(retVal, kCFURLWindowsPathStyle);
if (CFStringGetLength(testPath) ==0) {
CFRelease(retVal);
retVal=NULL;
}
if (testPath) CFRelease(testPath);
returnretVal;
#else
#error Dont know how to compute users home directories on this platform
#endif
}
staticCFStringRef_CFUserName(void) { // __CFPlatformCacheLock must be locked on entry and will be on exit
#ifDEPLOYMENT_TARGET_MACOSX||DEPLOYMENT_TARGET_EMBEDDED||DEPLOYMENT_TARGET_LINUX||DEPLOYMENT_TARGET_FREEBSD
if (geteuid() !=__CFEUID||getuid() !=__CFUID)
_CFUpdateUserInfo();
#elifDEPLOYMENT_TARGET_WINDOWS
if (!__CFUserName) {
wchar_tusername[1040];
DWORDsize=1040;
username[0] =0;
if (GetUserNameW(username, &size)) {
// discount the extra NULL by decrementing the size
__CFUserName=CFStringCreateWithCharacters(kCFAllocatorSystemDefault, (constUniChar*)username, size-1);
} else {
constchar*cname=__CFgetenv("USERNAME");
if (cname)
__CFUserName=CFStringCreateWithCString(kCFAllocatorSystemDefault, cname, kCFPlatformInterfaceStringEncoding);
}
}
#else
#error Dont know how to compute user name on this platform
#endif
if (!__CFUserName)
__CFUserName= (CFStringRef)CFRetain(CFSTR(""));
return__CFUserName;
}
#defineCFMaxHostNameLength 256
#defineCFMaxHostNameSize (CFMaxHostNameLength+1)
__private_extern__CFStringRef_CFStringCreateHostName(void) {
charmyName[CFMaxHostNameSize];
// return @"" instead of nil a la CFUserName() and Ali Ozer
if (0!=gethostname(myName, CFMaxHostNameSize)) myName[0] ='\0';
returnCFStringCreateWithCString(kCFAllocatorSystemDefault, myName, kCFPlatformInterfaceStringEncoding);
}
/* These are sanitized versions of the above functions. We might want to eliminate the above ones someday.
These can return NULL.
*/
CF_EXPORTCFStringRefCFGetUserName(void) {
CFStringRefresult=NULL;
__CFSpinLock(&__CFPlatformCacheLock);
result=CFStringCreateCopy(kCFAllocatorSystemDefault, _CFUserName());
__CFSpinUnlock(&__CFPlatformCacheLock);
returnresult;
}
CF_EXPORTCFStringRefCFCopyUserName(void) {
CFStringRefresult=NULL;
__CFSpinLock(&__CFPlatformCacheLock);
result=CFStringCreateCopy(kCFAllocatorSystemDefault, _CFUserName());
__CFSpinUnlock(&__CFPlatformCacheLock);
returnresult;
}
CF_EXPORTCFURLRefCFCopyHomeDirectoryURLForUser(CFStringRefuName) {
CFURLRefresult=NULL;
__CFSpinLock(&__CFPlatformCacheLock);
result=_CFCreateHomeDirectoryURLForUser(uName);
__CFSpinUnlock(&__CFPlatformCacheLock);
returnresult;
}
#undef CFMaxHostNameLength
#undef CFMaxHostNameSize
#ifDEPLOYMENT_TARGET_WINDOWS
CF_INLINECFIndexstrlen_UniChar(constUniChar*p) {
CFIndexresult=0;
while ((*p++) !=0)
++result;
returnresult;
}
//#include <shfolder.h>
/*
* _CFCreateApplicationRepositoryPath returns the path to the application's
* repository in a CFMutableStringRef. The path returned will be:
* <nFolder_path>\Apple Computer\<bundle_name>\
* or if the bundle name cannot be obtained:
* <nFolder_path>\Apple Computer\
* where nFolder_path is obtained by calling SHGetFolderPath with nFolder
* (for example, with CSIDL_APPDATA or CSIDL_LOCAL_APPDATA).
*
* The CFMutableStringRef result must be released by the caller.
*
* If anything fails along the way, the result will be NULL.
*/
CF_EXPORTCFMutableStringRef_CFCreateApplicationRepositoryPath(CFAllocatorRefalloc, intnFolder) {
CFMutableStringRefresult=NULL;
UniCharszPath[MAX_PATH];
// get the current path to the data repository: CSIDL_APPDATA (roaming) or CSIDL_LOCAL_APPDATA (nonroaming)
if (S_OK==SHGetFolderPathW(NULL, nFolder, NULL, 0, (wchar_t*) szPath)) {
CFStringRefdirectoryPath;
// make it a CFString
directoryPath=CFStringCreateWithCharacters(alloc, szPath, strlen_UniChar(szPath));
if (directoryPath) {
CFBundleRefbundle;
CFStringRefbundleName;
CFStringRefcompletePath;
// attempt to get the bundle name
bundle=CFBundleGetMainBundle();
if (bundle) {
bundleName= (CFStringRef)CFBundleGetValueForInfoDictionaryKey(bundle, kCFBundleNameKey);
}
else {
bundleName=NULL;
}
if (bundleName) {
// the path will be "<directoryPath>\Apple Computer\<bundleName>\" if there is a bundle name
completePath=CFStringCreateWithFormat(alloc, NULL, CFSTR("%@\\Apple Computer\\%@\\"), directoryPath, bundleName);
}
else {
// or "<directoryPath>\Apple Computer\" if there is no bundle name.
completePath=CFStringCreateWithFormat(alloc, NULL, CFSTR("%@\\Apple Computer\\"), directoryPath);
}
CFRelease(directoryPath);
// make a mutable copy to return
if (completePath) {
result=CFStringCreateMutableCopy(alloc, 0, completePath);
CFRelease(completePath);
}
}
}
return ( result );
}
#endif
#pragma mark -
#pragma mark Thread Functions
#ifDEPLOYMENT_TARGET_WINDOWS
// This code from here:
// http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
constDWORDMS_VC_EXCEPTION=0x406D1388;
#pragma pack(push,8)
typedefstructtagTHREADNAME_INFO
{
DWORDdwType; // Must be 0x1000.
LPCSTRszName; // Pointer to name (in user addr space).
DWORDdwThreadID; // Thread ID (-1=caller thread).
DWORDdwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
CF_EXPORTvoid_NS_pthread_setname_np(constchar*name) {
THREADNAME_INFOinfo;
info.dwType=0x1000;
info.szName=name;
info.dwThreadID=GetCurrentThreadId();
info.dwFlags=0;
__try
{
RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
}
staticpthread_t__initialPthread= { NULL, 0 };
CF_EXPORTint_NS_pthread_main_np() {
pthread_tme=pthread_self();
if (NULL==__initialPthread.p) {
__initialPthread.p=me.p;
__initialPthread.x=me.x;
}
return (pthread_equal(__initialPthread, me));
}
#endif
#pragma mark -
#pragma mark Thread Local Data
// If slot >= CF_TSD_MAX_SLOTS, the SPI functions will crash at NULL + slot address.
// If thread data has been torn down, these functions should crash on CF_TSD_BAD_PTR + slot address.
#defineCF_TSD_MAX_SLOTS 70
#ifDEPLOYMENT_TARGET_MACOSX||DEPLOYMENT_TARGET_EMBEDDED
#defineCF_TSD_KEY 55
#endif
// Windows and Linux, not sure how many times the destructor could get called; CF_TSD_MAX_DESTRUCTOR_CALLS could be 1
#defineCF_TSD_BAD_PTR ((void *)0x1000)
typedefvoid (*tsdDestructor)(void*);
// Data structure to hold TSD data, cleanup functions for each
typedefstruct__CFTSDTable {
uint32_tdestructorCount;
uintptr_tdata[CF_TSD_MAX_SLOTS];
tsdDestructordestructors[CF_TSD_MAX_SLOTS];
} __CFTSDTable;
staticvoid__CFTSDFinalize(void*arg);
#ifDEPLOYMENT_TARGET_WINDOWS
staticDWORD__CFTSDIndexKey=0xFFFFFFFF;
// Called from CFRuntime's startup code, on Windows only
__private_extern__void__CFTSDWindowsInitialize() {
__CFTSDIndexKey=TlsAlloc();
}
// Called from CFRuntime's cleanup code, on Windows only
__private_extern__void__CFTSDWindowsCleanup() {
TlsFree(__CFTSDIndexKey);
}
// Called for each thread as it exits, on Windows only
__private_extern__void__CFFinalizeWindowsThreadData() {
// Normally, this should call the finalizer several times to emulate the behavior of pthreads on Windows. However, a few bugs keep us from doing this:
// <rdar://problem/8989063> REGRESSION(CF-610-CF-611): Crash closing Safari in BonjourDB destructor (Windows)
// <rdar://problem/9326814> SyncUIHandler crashes after conflict is resolved and we do SyncNow
// and a bug in dispatch keeps us from using pthreadsWin32 directly, because it does not deal with the case of a dispatch_async happening during process exit (it attempts to create a thread, but that is illegal on Win32 and causes a hang).
// So instead we just finalize once, which is the behavior pre-Airwolf anyway
__CFTSDFinalize(TlsGetValue(__CFTSDIndexKey));
}
#endif
#ifDEPLOYMENT_TARGET_LINUX
staticpthread_key_t__CFTSDIndexKey;
// Called from CFRuntime's startup code, on Linux only
__private_extern__void__CFTSDLinuxInitialize() {
(void)pthread_key_create(&__CFTSDIndexKey, __CFTSDFinalize);
}
#endif
staticvoid__CFTSDSetSpecific(void*arg) {
#ifDEPLOYMENT_TARGET_MACOSX||DEPLOYMENT_TARGET_EMBEDDED
pthread_setspecific(CF_TSD_KEY, arg);
#elifDEPLOYMENT_TARGET_LINUX
pthread_setspecific(__CFTSDIndexKey, arg);
#elifDEPLOYMENT_TARGET_WINDOWS
TlsSetValue(__CFTSDIndexKey, arg);
#endif
}
staticvoid*__CFTSDGetSpecific() {
#ifDEPLOYMENT_TARGET_MACOSX||DEPLOYMENT_TARGET_EMBEDDED
returnpthread_getspecific(CF_TSD_KEY);
#elifDEPLOYMENT_TARGET_LINUX
returnpthread_getspecific(__CFTSDIndexKey);
#elifDEPLOYMENT_TARGET_WINDOWS
returnTlsGetValue(__CFTSDIndexKey);
#endif
}
staticvoid__CFTSDFinalize(void*arg) {
// Set our TSD so we're called again by pthreads. It will call the destructor 5 times as long as a value is set in the thread specific data. We handle each case below.
__CFTSDSetSpecific(arg);
if (!arg||arg==CF_TSD_BAD_PTR) {
// We've already been destroyed. The call above set the bad pointer again. Now we just return.
return;
}
__CFTSDTable*table= (__CFTSDTable*)arg;
table->destructorCount++;
// On 1st, 2nd, 3rd, 4th calls, invoke destructor
// Note that invocation of the destructor may cause a value to be set again in the per-thread data slots. The destructor count and destructors are preserved.
// This logic is basically the same as what pthreads does. We just skip the 'created' flag.
#ifCOCOA_ARR0
uintptr_tpool=_CFAutoreleasePoolPush();
#endif
for (int32_ti=0; i<CF_TSD_MAX_SLOTS; i++) {
if (table->data[i] &&table->destructors[i]) {
uintptr_told=table->data[i];
table->data[i] = (uintptr_t)NULL;
table->destructors[i]((void*)(old));
}
}
#ifCOCOA_ARR0
_CFAutoreleasePoolPop(pool);
#endif
if (table->destructorCount==PTHREAD_DESTRUCTOR_ITERATIONS-1) { // On 4th call, destroy our data
free(table);
// Now if the destructor is called again we will take the shortcut at the beginning of this function.
__CFTSDSetSpecific(CF_TSD_BAD_PTR);
return;
}
}
#ifDEPLOYMENT_TARGET_MACOSX||DEPLOYMENT_TARGET_EMBEDDED
externintpthread_key_init_np(int, void (*)(void*));
#endif
// Get or initialize a thread local storage. It is created on demand.
static__CFTSDTable*__CFTSDGetTable() {
__CFTSDTable*table= (__CFTSDTable*)__CFTSDGetSpecific();
// Make sure we're not setting data again after destruction.
if (table==CF_TSD_BAD_PTR) {
returnNULL;
}
// Create table on demand
if (!table) {
// This memory is freed in the finalize function
table= (__CFTSDTable*)calloc(1, sizeof(__CFTSDTable));
// Windows and Linux have created the table already, we need to initialize it here for other platforms. On Windows, the cleanup function is called by DllMain when a thread exits. On Linux the destructor is set at init time.
#ifDEPLOYMENT_TARGET_MACOSX||DEPLOYMENT_TARGET_EMBEDDED
pthread_key_init_np(CF_TSD_KEY, __CFTSDFinalize);
#endif
__CFTSDSetSpecific(table);
}
returntable;
}
// For the use of CF and Foundation only
CF_EXPORTvoid*_CFGetTSD(uint32_tslot) {
if (slot>CF_TSD_MAX_SLOTS) {
_CFLogSimple(kCFLogLevelError, "Error: TSD slot %d out of range (get)", slot);
HALT;
}
__CFTSDTable*table=__CFTSDGetTable();
if (!table) {
// Someone is getting TSD during thread destruction. The table is gone, so we can't get any data anymore.
_CFLogSimple(kCFLogLevelWarning, "Warning: TSD slot %d retrieved but the thread data has already been torn down.", slot);
returnNULL;
}
uintptr_t*slots= (uintptr_t*)(table->data);
return (void*)slots[slot];
}
// For the use of CF and Foundation only
CF_EXPORTvoid*_CFSetTSD(uint32_tslot, void*newVal, tsdDestructordestructor) {
if (slot>CF_TSD_MAX_SLOTS) {
_CFLogSimple(kCFLogLevelError, "Error: TSD slot %d out of range (set)", slot);
HALT;
}
__CFTSDTable*table=__CFTSDGetTable();
if (!table) {
// Someone is setting TSD during thread destruction. The table is gone, so we can't get any data anymore.
_CFLogSimple(kCFLogLevelWarning, "Warning: TSD slot %d set but the thread data has already been torn down.", slot);
returnNULL;
}
void*oldVal= (void*)table->data[slot];
table->data[slot] = (uintptr_t)newVal;
table->destructors[slot] =destructor;
returnoldVal;
}
#pragma mark -
#pragma mark Windows Wide to UTF8 and UTF8 to Wide
#ifDEPLOYMENT_TARGET_WINDOWS
/* On Windows, we want to use UTF-16LE for path names to get full unicode support. Internally, however, everything remains in UTF-8 representation. These helper functions stand between CF and the Microsoft CRT to ensure that we are using the right representation on both sides. */
#include<sys/stat.h>
#include<share.h>
// Creates a buffer of wchar_t to hold a UTF16LE version of the UTF8 str passed in. Caller must free the buffer when done. If resultLen is non-NULL, it is filled out with the number of characters in the string.
staticwchar_t*createWideFileSystemRepresentation(constchar*str, CFIndex*resultLen) {
// Get the real length of the string in UTF16 characters
CFStringRefcfStr=CFStringCreateWithCString(kCFAllocatorSystemDefault, str, kCFStringEncodingUTF8);
CFIndexstrLen=CFStringGetLength(cfStr);
// Allocate a wide buffer to hold the converted string, including space for a NULL terminator
wchar_t*wideBuf= (wchar_t*)malloc((strLen+1) *sizeof(wchar_t));
// Copy the string into the buffer and terminate
CFStringGetCharacters(cfStr, CFRangeMake(0, strLen), (UniChar*)wideBuf);
wideBuf[strLen] =0;
CFRelease(cfStr);
if (resultLen) *resultLen=strLen;
returnwideBuf;
}
// Copies a UTF16 buffer into a supplied UTF8 buffer.
staticvoidcopyToNarrowFileSystemRepresentation(constwchar_t*wide, CFIndexdstBufSize, char*dstbuf) {
// Get the real length of the wide string in UTF8 characters
CFStringRefcfStr=CFStringCreateWithCharacters(kCFAllocatorSystemDefault, (constUniChar*)wide, (CFIndex)wcslen(wide));
CFIndexstrLen=CFStringGetLength(cfStr);
CFIndexbytesUsed;
// Copy the wide string into the buffer and terminate
CFStringGetBytes(cfStr, CFRangeMake(0, strLen), kCFStringEncodingUTF8, 0, false, (uint8_t*)dstbuf, dstBufSize, &bytesUsed);
dstbuf[bytesUsed] =0;
CFRelease(cfStr);
}
CF_EXPORTint_NS_stat(constchar*name, struct_stat*st) {
wchar_t*wide=createWideFileSystemRepresentation(name, NULL);
intres=_wstat(wide, st);
free(wide);
returnres;
}
CF_EXPORTint_NS_mkdir(constchar*name) {
wchar_t*wide=createWideFileSystemRepresentation(name, NULL);
intres=_wmkdir(wide);
free(wide);
returnres;
}
CF_EXPORTint_NS_rmdir(constchar*name) {
wchar_t*wide=createWideFileSystemRepresentation(name, NULL);
intres=_wrmdir(wide);
free(wide);
returnres;
}
CF_EXPORTint_NS_chmod(constchar*name, intmode) {
wchar_t*wide=createWideFileSystemRepresentation(name, NULL);
// Convert mode
intnewMode=0;
if (mode | 0400) newMode |= _S_IREAD;
if (mode | 0200) newMode |= _S_IWRITE;
if (mode | 0100) newMode |= _S_IEXEC;
intres=_wchmod(wide, newMode);
free(wide);
returnres;
}
CF_EXPORTint_NS_unlink(constchar*name) {
wchar_t*wide=createWideFileSystemRepresentation(name, NULL);
intres=_wunlink(wide);
free(wide);
returnres;
}
// Warning: this doesn't support dstbuf as null even though 'getcwd' does
CF_EXPORTchar*_NS_getcwd(char*dstbuf, size_tsize) {
if (!dstbuf) {
CFLog(kCFLogLevelWarning, CFSTR("CFPlatform: getcwd called with null buffer"));
return0;
}
wchar_t*buf=_wgetcwd(NULL, 0);
if (!buf) {
returnNULL;
}
// Convert result to UTF8
copyToNarrowFileSystemRepresentation(buf, (CFIndex)size, dstbuf);
free(buf);
returndstbuf;
}
CF_EXPORTchar*_NS_getenv(constchar*name) {
// todo: wide getenv
// We have to be careful what happens here, because getenv is called during cf initialization, and things like cfstring may not be working yet
returngetenv(name);
}
CF_EXPORTint_NS_rename(constchar*oldName, constchar*newName) {
wchar_t*oldWide=createWideFileSystemRepresentation(oldName, NULL);
wchar_t*newWide=createWideFileSystemRepresentation(newName, NULL);
// _wrename on Windows does not behave exactly as rename() on Mac OS -- if the file exists, the Windows one will fail whereas the Mac OS version will replace
// To simulate the Mac OS behavior, we use the Win32 API then fill out errno if something goes wrong
BOOLwinRes=MoveFileExW(oldWide, newWide, MOVEFILE_REPLACE_EXISTING);
DWORDerror=GetLastError();
if (!winRes) {
switch (error) {
caseERROR_SUCCESS:
errno=0;
break;
caseERROR_FILE_NOT_FOUND:
caseERROR_PATH_NOT_FOUND:
caseERROR_OPEN_FAILED:
errno=ENOENT;
break;
caseERROR_ACCESS_DENIED:
errno=EACCES;
break;
default:
errno=error;
}
}
free(oldWide);
free(newWide);
return (winRes ? 0 : -1);
}
CF_EXPORTint_NS_open(constchar*name, intoflag, intpmode) {
wchar_t*wide=createWideFileSystemRepresentation(name, NULL);
intfd;
_wsopen_s(&fd, wide, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE);
free(wide);
returnfd;
}
CF_EXPORTint_NS_chdir(constchar*name) {
wchar_t*wide=createWideFileSystemRepresentation(name, NULL);
intres=_wchdir(wide);
free(wide);
returnres;
}
CF_EXPORTint_NS_access(constchar*name, intamode) {
// execute is always true
if (amode==1) return0;
wchar_t*wide=createWideFileSystemRepresentation(name, NULL);
// we only care about the read-only (04) and write-only (02) bits, so mask octal 06
intres=_waccess(wide, amode&06);
free(wide);
returnres;
}
// This is a bit different than the standard 'mkstemp', because the size parameter is needed so we know the size of the UTF8 buffer
// Also, we don't avoid the race between creating a temporary file name and opening it on Windows like we do on Mac
CF_EXPORTint_NS_mkstemp(char*name, intbufSize) {
CFIndexnameLen;
wchar_t*wide=createWideFileSystemRepresentation(name, &nameLen);
// First check to see if the directory that this new temporary file will be created in exists. If not, set errno to ENOTDIR. This mimics the behavior of mkstemp on MacOS more closely.
// Look for the last '\' in the path
wchar_t*lastSlash=wcsrchr(wide, '\\');
if (!lastSlash) {
free(wide);
return-1;
}
// Set the last slash to NULL temporarily and use it for _wstat
*lastSlash=0;
struct_statdirInfo;
intres=_wstat(wide, &dirInfo);
if (res<0) {
if (errno==ENOENT) {
errno=ENOTDIR;
}
free(wide);
return-1;
}
// Restore the last slash
*lastSlash='\\';
errno_terr=_wmktemp_s(wide, nameLen+1);
if (err!=0) {
free(wide);
return0;
}
intfd;
_wsopen_s(&fd, wide, _O_RDWR | _O_CREAT | CF_OPENFLGS, _SH_DENYNO, _S_IREAD | _S_IWRITE);
// Convert the wide name back into the UTF8 buffer the caller supplied
copyToNarrowFileSystemRepresentation(wide, bufSize, name);
free(wide);
returnfd;
}
#endif
#ifDEPLOYMENT_TARGET_WINDOWS
// Utilities to convert from a volume name to a drive letter
Boolean_isAFloppy(chardriveLetter)
{
HANDLEh;
TCHARtsz[8];
Booleanretval= false;
intiDrive;
if (driveLetter >= 'a'&&driveLetter <= 'z') {
driveLetter=driveLetter-'a'+'A';
}
if ((driveLetter<'A') || (driveLetter>'Z')) {
// invalid driveLetter; I guess it's not a floppy...
return false;
}
iDrive=driveLetter-'A'+1;
// On Windows NT, use the technique described in the Knowledge Base article Q115828 and in the "FLOPPY" SDK sample.
wsprintf(tsz, TEXT("\\\\.\\%c:"), TEXT('@') +iDrive);
h=CreateFile(tsz, 0, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (h!=INVALID_HANDLE_VALUE)
{