-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathandroid_utils.c
1764 lines (1499 loc) · 40.6 KB
/
android_utils.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) 2007-2008 The Android Open Source Project
**
** This software is licensed under the terms of the GNU General Public
** License version 2, as published by the Free Software Foundation, and
** may be copied, distributed, and modified under those terms.
**
** 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.
*/
#include "android_utils.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#ifdef _WIN32
#include <process.h>
#include <shlobj.h>
#include <tlhelp32.h>
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <limits.h>
#include <winbase.h>
#else
#include <unistd.h>
#include <sys/stat.h>
#include <time.h>
#include <signal.h>
#endif
#include "android.h"
#include "android_debug.h"
#define D(...) VERBOSE_PRINT(init,__VA_ARGS__)
/** PATH HANDLING ROUTINES
**
** path_parent() can be used to return the n-level parent of a given directory
** this understands . and .. when encountered in the input path
**/
static __inline__ int
ispathsep(int c)
{
#ifdef _WIN32
return (c == '/' || c == '\\');
#else
return (c == '/');
#endif
}
char* path_parent( const char* path, int levels )
{
const char* end = path + strlen(path);
char* result;
while (levels > 0) {
const char* base;
/* trim any trailing path separator */
while (end > path && ispathsep(end[-1]))
end--;
base = end;
while (base > path && !ispathsep(base[-1]))
base--;
if (base <= path) /* we can't go that far */
return NULL;
if (end == base+1 && base[0] == '.')
goto Next;
if (end == base+2 && base[0] == '.' && base[1] == '.') {
levels += 1;
goto Next;
}
levels -= 1;
Next:
end = base - 1;
}
result = malloc( end-path+1 );
if (result != NULL) {
memcpy( result, path, end-path );
result[end-path] = 0;
}
return result;
}
/** MISC FILE AND DIRECTORY HANDLING
**/
int
path_exists( const char* path )
{
int ret;
CHECKED(ret, access(path, F_OK));
return (ret == 0) || (errno != ENOENT);
}
/* checks that a path points to a regular file */
int
path_is_regular( const char* path )
{
int ret;
struct stat st;
CHECKED(ret, stat(path, &st));
if (ret < 0)
return 0;
return S_ISREG(st.st_mode);
}
/* checks that a path points to a directory */
int
path_is_dir( const char* path )
{
int ret;
struct stat st;
CHECKED(ret, stat(path, &st));
if (ret < 0)
return 0;
return S_ISDIR(st.st_mode);
}
/* checks that one can read/write a given (regular) file */
int
path_can_read( const char* path )
{
int ret;
CHECKED(ret, access(path, R_OK));
return (ret == 0);
}
int
path_can_write( const char* path )
{
int ret;
CHECKED(ret, access(path, R_OK));
return (ret == 0);
}
/* try to make a directory. returns 0 on success, -1 on failure
* (error code in errno) */
int
path_mkdir( const char* path, int mode )
{
#ifdef _WIN32
(void)mode;
return _mkdir(path);
#else
int ret;
CHECKED(ret, mkdir(path, mode));
return ret;
#endif
}
static int
path_mkdir_recursive( char* path, unsigned len, int mode )
{
char old_c;
int ret;
unsigned len2;
/* get rid of trailing separators */
while (len > 0 && ispathsep(path[len-1]))
len -= 1;
if (len == 0) {
errno = ENOENT;
return -1;
}
/* check that the parent exists, 'len2' is the length of
* the parent part of the path */
len2 = len-1;
while (len2 > 0 && !ispathsep(path[len2-1]))
len2 -= 1;
if (len2 > 0) {
old_c = path[len2];
path[len2] = 0;
ret = 0;
if ( !path_exists(path) ) {
/* the parent doesn't exist, so try to create it */
ret = path_mkdir_recursive( path, len2, mode );
}
path[len2] = old_c;
if (ret < 0)
return ret;
}
/* at this point, we now the parent exists */
old_c = path[len];
path[len] = 0;
ret = path_mkdir( path, mode );
path[len] = old_c;
return ret;
}
/* ensure that a given directory exists, create it if not,
0 on success, -1 on failure (error code in errno) */
int
path_mkdir_if_needed( const char* path, int mode )
{
int ret = 0;
if (!path_exists(path)) {
ret = path_mkdir(path, mode);
if (ret < 0 && errno == ENOENT) {
char temp[MAX_PATH];
unsigned len = (unsigned)strlen(path);
if (len > sizeof(temp)-1) {
errno = EINVAL;
return -1;
}
memcpy( temp, path, len );
temp[len] = 0;
return path_mkdir_recursive(temp, len, mode);
}
}
return ret;
}
/* return the size of a given file in '*psize'. returns 0 on
* success, -1 on failure (error code in errno) */
int
path_get_size( const char* path, uint64_t *psize )
{
#ifdef _WIN32
/* avoid _stat64 which is only defined in MSVCRT.DLL, not CRTDLL.DLL */
/* do not use OpenFile() because it has strange search behaviour that could */
/* result in getting the size of a different file */
LARGE_INTEGER size;
HANDLE file = CreateFile( /* lpFilename */ path,
/* dwDesiredAccess */ GENERIC_READ,
/* dwSharedMode */ FILE_SHARE_READ|FILE_SHARE_WRITE,
/* lpSecurityAttributes */ NULL,
/* dwCreationDisposition */ OPEN_EXISTING,
/* dwFlagsAndAttributes */ 0,
/* hTemplateFile */ NULL );
if (file == INVALID_HANDLE_VALUE) {
/* ok, just to play fair */
errno = ENOENT;
return -1;
}
if (!GetFileSizeEx(file, &size)) {
/* maybe we tried to get the size of a pipe or something like that ? */
*psize = 0;
}
else {
*psize = (uint64_t) size.QuadPart;
}
CloseHandle(file);
return 0;
#else
int ret;
struct stat st;
CHECKED(ret, stat(path, &st));
if (ret == 0) {
*psize = (uint64_t) st.st_size;
}
return ret;
#endif
}
/** USEFUL STRING BUFFER FUNCTIONS
**/
char*
vbufprint( char* buffer,
char* buffer_end,
const char* fmt,
va_list args )
{
int len = vsnprintf( buffer, buffer_end - buffer, fmt, args );
if (len < 0 || buffer+len >= buffer_end) {
if (buffer < buffer_end)
buffer_end[-1] = 0;
return buffer_end;
}
return buffer + len;
}
char*
bufprint(char* buffer, char* end, const char* fmt, ... )
{
va_list args;
char* result;
va_start(args, fmt);
result = vbufprint(buffer, end, fmt, args);
va_end(args);
return result;
}
/** USEFUL DIRECTORY SUPPORT
**
** bufprint_app_dir() returns the directory where the emulator binary is located
**
** get_android_home() returns a user-specific directory where the emulator will
** store its writable data (e.g. config files, profiles, etc...).
** on Unix, this is $HOME/.android, on Windows, this is something like
** "%USERPROFILE%/Local Settings/AppData/Android" on XP, and something different
** on Vista.
**
** both functions return a string that must be freed by the caller
**/
#ifdef __linux__
char*
bufprint_app_dir(char* buff, char* end)
{
char path[1024];
int len;
char* x;
len = readlink("/proc/self/exe", path, sizeof(path));
if (len <= 0 || len >= (int)sizeof(path)) goto Fail;
path[len] = 0;
x = strrchr(path, '/');
if (x == 0) goto Fail;
*x = 0;
return bufprint(buff, end, "%s", path);
Fail:
fprintf(stderr,"cannot locate application directory\n");
exit(1);
return end;
}
#elif defined(__APPLE__)
/* the following hack is needed in order to build with XCode 3.1
* don't ask me why, but it seems that there were changes in the
* GCC compiler that we don't have in our pre-compiled version
*/
#ifndef __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__
#define __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ MAC_OS_X_VERSION_10_4
#endif
#import <Carbon/Carbon.h>
#include <unistd.h>
char*
bufprint_app_dir(char* buff, char* end)
{
ProcessSerialNumber psn;
CFDictionaryRef dict;
CFStringRef value;
char s[PATH_MAX];
char* x;
GetCurrentProcess(&psn);
dict = ProcessInformationCopyDictionary(&psn, 0xffffffff);
value = (CFStringRef)CFDictionaryGetValue(dict,
CFSTR("CFBundleExecutable"));
CFStringGetCString(value, s, PATH_MAX - 1, kCFStringEncodingUTF8);
x = strrchr(s, '/');
if (x == 0) goto fail;
*x = 0;
return bufprint(buff, end, "%s", s);
fail:
fprintf(stderr,"cannot locate application directory\n");
exit(1);
return end;
}
#elif defined _WIN32
char*
bufprint_app_dir(char* buff, char* end)
{
char appDir[MAX_PATH];
char* sep;
GetModuleFileName( 0, appDir, sizeof(appDir)-1 );
sep = strrchr( appDir, '\\' );
if (sep)
*sep = 0;
return bufprint(buff, end, "%s", appDir);
}
#else
char*
bufprint_app_dir(char* buff, char* end)
{
return bufprint(buff, end, ".");
}
#endif
#ifdef _WIN32
#define _ANDROID_PATH "Android"
#else
#define _ANDROID_PATH ".android"
#endif
char*
bufprint_config_path(char* buff, char* end)
{
#ifdef _WIN32
char path[MAX_PATH];
SHGetFolderPath( NULL, CSIDL_LOCAL_APPDATA|CSIDL_FLAG_CREATE,
NULL, 0, path);
return bufprint(buff, end, "%s\\%s\\%s", path, _ANDROID_PATH, ANDROID_SDK_VERSION);
#else
const char* home = getenv("HOME");
if (home == NULL)
home = "/tmp";
return bufprint(buff, end, "%s/%s/%s", home, _ANDROID_PATH, ANDROID_SDK_VERSION);
#endif
}
char*
bufprint_config_file(char* buff, char* end, const char* suffix)
{
char* p;
p = bufprint_config_path(buff, end);
p = bufprint(p, end, PATH_SEP "%s", suffix);
return p;
}
char*
bufprint_temp_dir(char* buff, char* end)
{
#ifdef _WIN32
char path[MAX_PATH];
DWORD retval;
retval = GetTempPath( sizeof(path), path );
if (retval > sizeof(path) || retval == 0) {
D( "can't locate TEMP directory" );
pstrcpy(path, sizeof(path), "C:\\Temp");
}
strncat( path, "\\AndroidEmulator", sizeof(path)-1 );
_mkdir(path);
return bufprint(buff, end, "%s", path);
#else
const char* tmppath = "/tmp/android";
mkdir(tmppath, 0744);
return bufprint(buff, end, "%s", tmppath );
#endif
}
char*
bufprint_temp_file(char* buff, char* end, const char* suffix)
{
char* p;
p = bufprint_temp_dir(buff, end);
p = bufprint(p, end, PATH_SEP "%s", suffix);
return p;
}
/** FILE LOCKS SUPPORT
**
** a FileLock is useful to prevent several emulator instances from using the same
** writable file (e.g. the userdata.img disk images).
**
** create a FileLock object with filelock_create(), ithis function should return NULL
** only if thee file doesn't exist, or if you don't have enough memory.
*
* then call filelock_lock() to try to acquire a lock for the corresponding file.
** returns 0 on success, or -1 in case of error, which means that another program
** is using the file or that the directory containing the file is read-only.
**
** all file locks are automatically released and destroyed when the program exits.
** the filelock_lock() function can also detect stale file locks that can linger
** when the emulator crashes unexpectedly, and will happily clean them for you
**
** here's how it works, three files are used:
** file - the data file accessed by the emulator
** lock - a lock file (file + '.lock')
** temp - a temporary file make unique with mkstemp
**
** when locking:
** create 'temp' and store our pid in it
** attemp to link 'lock' to 'temp'
** if the link succeeds, we obtain the lock
** unlink 'temp'
**
** when unlocking:
** unlink 'lock'
**
**
** on Windows, 'lock' is a directory name. locking is equivalent to
** creating it...
**
**/
struct FileLock
{
const char* file;
const char* lock;
char* temp;
int locked;
FileLock* next;
};
#define LOCK_NAME ".lock"
#define TEMP_NAME ".tmp-XXXXXX"
#ifdef _WIN32
#define PIDFILE_NAME "pid"
#endif
/* returns 0 on success, -1 on failure */
int
filelock_lock( FileLock* lock )
{
int ret;
#ifdef _WIN32
int pidfile_fd = -1;
ret = _mkdir( lock->lock );
if (ret < 0) {
if (errno == ENOENT) {
D( "could not access directory '%s', check path elements", lock->lock );
return -1;
} else if (errno != EEXIST) {
D( "_mkdir(%s): %s", lock->lock, strerror(errno) );
return -1;
}
/* if we get here, it's because the .lock directory already exists */
/* check to see if there is a pid file in it */
D("directory '%s' already exist, waiting a bit to ensure that no other emulator instance is starting", lock->lock );
{
int _sleep = 200;
int tries;
for ( tries = 4; tries > 0; tries-- )
{
pidfile_fd = open( lock->temp, O_RDONLY );
if (pidfile_fd >= 0)
break;
Sleep( _sleep );
_sleep *= 2;
}
}
if (pidfile_fd < 0) {
D( "no pid file in '%s', assuming stale directory", lock->lock );
}
else
{
/* read the pidfile, and check wether the corresponding process is still running */
char buf[16];
int len, lockpid;
HANDLE processSnapshot;
PROCESSENTRY32 pe32;
int is_locked = 0;
len = read( pidfile_fd, buf, sizeof(buf)-1 );
if (len < 0) {
D( "could not read pid file '%s'", lock->temp );
close( pidfile_fd );
return -1;
}
buf[len] = 0;
lockpid = atoi(buf);
/* PID 0 is the IDLE process, and 0 is returned in case of invalid input */
if (lockpid == 0)
lockpid = -1;
close( pidfile_fd );
pe32.dwSize = sizeof( PROCESSENTRY32 );
processSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if ( processSnapshot == INVALID_HANDLE_VALUE ) {
D( "could not retrieve the list of currently active processes\n" );
is_locked = 1;
}
else if ( !Process32First( processSnapshot, &pe32 ) )
{
D( "could not retrieve first process id\n" );
CloseHandle( processSnapshot );
is_locked = 1;
}
else
{
do {
if (pe32.th32ProcessID == lockpid) {
is_locked = 1;
break;
}
} while (Process32Next( processSnapshot, &pe32 ) );
CloseHandle( processSnapshot );
}
if (is_locked) {
D( "the file '%s' is locked by process ID %d\n", lock->file, lockpid );
return -1;
}
}
}
/* write our PID into the pid file */
pidfile_fd = open( lock->temp, O_WRONLY | O_CREAT | O_TRUNC );
if (pidfile_fd < 0) {
if (errno == EACCES) {
if ( unlink_file( lock->temp ) < 0 ) {
D( "could not remove '%s': %s\n", lock->temp, strerror(errno) );
return -1;
}
pidfile_fd = open( lock->temp, O_WRONLY | O_CREAT | O_TRUNC );
}
if (pidfile_fd < 0) {
D( "could not create '%s': %s\n", lock->temp, strerror(errno) );
return -1;
}
}
{
char buf[16];
sprintf( buf, "%ld", GetCurrentProcessId() );
ret = write( pidfile_fd, buf, strlen(buf) );
close(pidfile_fd);
if (ret < 0) {
D( "could not write PID to '%s'\n", lock->temp );
return -1;
}
}
lock->locked = 1;
return 0;
#else
int temp_fd = -1;
int lock_fd = -1;
int rc, tries, _sleep;
FILE* f = NULL;
char pid[8];
struct stat st_temp;
strcpy( lock->temp, lock->file );
strcat( lock->temp, TEMP_NAME );
temp_fd = mkstemp( lock->temp );
if (temp_fd < 0) {
D("cannot create locking temp file '%s'", lock->temp );
goto Fail;
}
sprintf( pid, "%d", getpid() );
ret = write( temp_fd, pid, strlen(pid)+1 );
if (ret < 0) {
D( "cannot write to locking temp file '%s'", lock->temp);
goto Fail;
}
close( temp_fd );
temp_fd = -1;
CHECKED(rc, lstat( lock->temp, &st_temp ));
if (rc < 0) {
D( "can't properly stat our locking temp file '%s'", lock->temp );
goto Fail;
}
/* now attempt to link the temp file to the lock file */
_sleep = 0;
for ( tries = 4; tries > 0; tries-- )
{
struct stat st_lock;
int rc;
if (_sleep > 0) {
if (_sleep > 2000000) {
D( "cannot acquire lock file '%s'", lock->lock );
goto Fail;
}
usleep( _sleep );
}
_sleep += 200000;
/* the return value of link() is buggy on NFS */
CHECKED(rc, link( lock->temp, lock->lock ));
CHECKED(rc, lstat( lock->lock, &st_lock ));
if (rc == 0 &&
st_temp.st_rdev == st_lock.st_rdev &&
st_temp.st_ino == st_lock.st_ino )
{
/* SUCCESS */
lock->locked = 1;
CHECKED(rc, unlink( lock->temp ));
return 0;
}
/* if we get there, it means that the link() call failed */
/* check the lockfile to see if it is stale */
if (rc == 0) {
char buf[16];
time_t now;
int lockpid = 0;
int lockfd;
int stale = 2; /* means don't know */
struct stat st;
CHECKED(rc, time( &now));
st.st_mtime = now - 120;
CHECKED(lockfd, open( lock->lock,O_RDONLY ));
if ( lockfd >= 0 ) {
int len;
CHECKED(len, read( lockfd, buf, sizeof(buf)-1 ));
buf[len] = 0;
lockpid = atoi(buf);
CHECKED(rc, fstat( lockfd, &st ));
if (rc == 0)
now = st.st_atime;
CHECKED(rc, close(lockfd));
}
/* if there is a PID, check that it is still alive */
if (lockpid > 0) {
CHECKED(rc, kill( lockpid, 0 ));
if (rc == 0 || errno == EPERM) {
stale = 0;
} else if (rc < 0 && errno == ESRCH) {
stale = 1;
}
}
if (stale == 2) {
/* no pid, stale if the file is older than 1 minute */
stale = (now >= st.st_mtime + 60);
}
if (stale) {
D( "removing stale lockfile '%s'", lock->lock );
CHECKED(rc, unlink( lock->lock ));
_sleep = 0;
tries++;
}
}
}
D("file '%s' is already in use by another process", lock->file );
Fail:
if (f)
fclose(f);
if (temp_fd >= 0) {
close(temp_fd);
}
if (lock_fd >= 0) {
close(lock_fd);
}
unlink( lock->lock );
unlink( lock->temp );
return -1;
#endif
}
void
filelock_unlock( FileLock* lock )
{
#ifdef _WIN32
unlink_file( (char*)lock->temp );
rmdir( (char*)lock->lock );
lock->locked = 0;
#else
unlink( (char*)lock->lock );
lock->locked = 0;
#endif
}
/* used to cleanup all locks at emulator exit */
static FileLock* _all_filelocks;
static void
filelock_atexit( void )
{
FileLock* lock;
for (lock = _all_filelocks; lock != NULL; lock = lock->next)
{
if (lock->locked)
filelock_unlock( lock );
}
}
/* create a file lock */
FileLock*
filelock_create( const char* file )
{
int file_len = strlen(file);
int lock_len = file_len + sizeof(LOCK_NAME);
#ifdef _WIN32
int temp_len = lock_len + 1 + sizeof(PIDFILE_NAME);
#else
int temp_len = file_len + sizeof(TEMP_NAME);
#endif
int total_len = sizeof(FileLock) + file_len + lock_len + temp_len + 3;
FileLock* lock = malloc(total_len);
if (lock == NULL)
goto Exit;
lock->file = (const char*)(lock + 1);
memcpy( (char*)lock->file, file, file_len+1 );
lock->lock = lock->file + file_len + 1;
memcpy( (char*)lock->lock, file, file_len+1 );
strcat( (char*)lock->lock, LOCK_NAME );
lock->temp = (char*)lock->lock + lock_len + 1;
#ifdef _WIN32
sprintf( (char*)lock->temp, "%s\\" PIDFILE_NAME, lock->lock );
#else
lock->temp[0] = 0;
#endif
lock->locked = 0;
lock->next = _all_filelocks;
_all_filelocks = lock;
if (lock->next == NULL)
atexit( filelock_atexit );
Exit:
return lock;
}
/** TEMP FILE SUPPORT
**
** simple interface to create an empty temporary file on the system.
**
** create the file with tempfile_create(), which returns a reference to a TempFile
** object, or NULL if your system is so weird it doesn't have a temporary directory.
**
** you can then call tempfile_path() to retrieve the TempFile's real path to open
** it. the returned path is owned by the TempFile object and should not be freed.
**
** all temporary files are destroyed when the program quits, unless you explicitely
** close them before that with tempfile_close()
**/
struct TempFile
{
const char* name;
TempFile* next;
};
static void tempfile_atexit();
static TempFile* _all_tempfiles;
TempFile*
tempfile_create( void )
{
TempFile* tempfile;
const char* tempname = NULL;
#ifdef _WIN32
char temp_namebuff[MAX_PATH];
char temp_dir[MAX_PATH];
char *p = temp_dir, *end = p + sizeof(temp_dir);
UINT retval;
p = bufprint_temp_dir( p, end );
if (p >= end) {
D( "TEMP directory path is too long" );
return NULL;
}
retval = GetTempFileName(temp_dir, "TMP", 0, temp_namebuff);
if (retval == 0) {
D( "can't create temporary file in '%s'", temp_dir );
return NULL;
}
tempname = temp_namebuff;
#else
#define TEMPLATE "/tmp/.android-emulator-XXXXXX"
int tempfd = -1;
char template[512];
char *p = template, *end = p + sizeof(template);
p = bufprint_temp_file( p, end, "emulator-XXXXXX" );
if (p >= end) {
D( "Xcannot create temporary file in /tmp/android !!" );
return NULL;
}
D( "template: %s", template );
tempfd = mkstemp( template );
if (tempfd < 0) {
D("cannot create temporary file in /tmp/android !!");
return NULL;
}
close(tempfd);
tempname = template;
#endif
tempfile = malloc( sizeof(*tempfile) + strlen(tempname) + 1 );
tempfile->name = (char*)(tempfile + 1);
strcpy( (char*)tempfile->name, tempname );
tempfile->next = _all_tempfiles;
_all_tempfiles = tempfile;
if ( !tempfile->next ) {
atexit( tempfile_atexit );
}
return tempfile;
}
const char*
tempfile_path(TempFile* temp)
{
return temp ? temp->name : NULL;
}
void
tempfile_close(TempFile* tempfile)
{
#ifdef _WIN32
DeleteFile(tempfile->name);
#else
unlink(tempfile->name);
#endif
}
/** TEMP FILE CLEANUP
**
**/
/* we don't expect to use many temporary files */
#define MAX_ATEXIT_FDS 16
typedef struct {
int count;
int fds[ MAX_ATEXIT_FDS ];
} AtExitFds;
static void
atexit_fds_add( AtExitFds* t, int fd )
{
if (t->count < MAX_ATEXIT_FDS)
t->fds[t->count++] = fd;
else {
dwarning("%s: over %d calls. Program exit may not cleanup all temporary files",
__FUNCTION__, MAX_ATEXIT_FDS);
}
}
static void
atexit_fds_del( AtExitFds* t, int fd )
{
int nn;
for (nn = 0; nn < t->count; nn++)
if (t->fds[nn] == fd) {
/* move the last element to the current position */
t->count -= 1;
t->fds[nn] = t->fds[t->count];
break;
}
}
static void
atexit_fds_close_all( AtExitFds* t )
{
int nn;
for (nn = 0; nn < t->count; nn++)
close(t->fds[nn]);
}
static AtExitFds _atexit_fds[1];
void
atexit_close_fd(int fd)
{
if (fd >= 0)