File: app_start.cpp

package info (click to toggle)
boinc 7.14.2%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 111,132 kB
  • sloc: cpp: 163,589; php: 113,173; ansic: 49,284; pascal: 35,620; xml: 17,864; java: 13,521; python: 6,551; sh: 4,082; perl: 1,843; makefile: 1,796; objc: 1,543; sql: 959; csh: 126; lisp: 47
file content (1396 lines) | stat: -rw-r--r-- 42,637 bytes parent folder | download
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
// This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2008 University of California
//
// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with BOINC.  If not, see <http://www.gnu.org/licenses/>.

// initialization and starting of applications

#include "cpp.h"

#ifdef _WIN32
#include "boinc_win.h"
#include "win_util.h"
#define unlink   _unlink
#ifdef _MSC_VER
#define snprintf _snprintf
#define strdup   _strdup
#define getcwd   _getcwd
#endif
#else
#include "config.h"
#if HAVE_SCHED_SETSCHEDULER && defined (__linux__)
#include <sched.h>
#endif
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#if HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#if HAVE_SYS_IPC_H
#include <sys/ipc.h>
#endif
#if HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#include <unistd.h>
#include <cerrno>
#include <sys/stat.h>
#include <string>
#endif

#ifdef __EMX__
#include <process.h>
#endif

#if (defined (__APPLE__) && (defined(__i386__) || defined(__x86_64__)))
#include <mach-o/loader.h>
#include <mach-o/fat.h>
#include <mach/machine.h>
#include <libkern/OSByteOrder.h>
#endif

#if(!defined (_WIN32) && !defined (__EMX__))
#include <fcntl.h>
#endif

#include <vector>

using std::vector;
using std::string;

#include "base64.h"
#include "error_numbers.h"
#include "filesys.h"
#include "shmem.h"
#include "str_replace.h"
#include "str_util.h"
#include "util.h"

#include "async_file.h"
#include "client_msgs.h"
#include "client_state.h"
#include "file_names.h"
#include "result.h"
#include "sandbox.h"

#ifdef _WIN32
#include "run_app_windows.h"
#endif

#include "cs_proxy.h"

#include "app.h"


#ifdef _WIN32
// Dynamically link to these functions at runtime;
// otherwise BOINC cannot run on Win98

// CreateEnvironmentBlock
typedef BOOL (WINAPI *tCEB)(LPVOID *lpEnvironment, HANDLE hToken, BOOL bInherit);
// DestroyEnvironmentBlock
typedef BOOL (WINAPI *tDEB)(LPVOID lpEnvironment);

#endif

// print each string in an array
//
#ifndef _WIN32
static void debug_print_argv(char** argv) {
    msg_printf(0, MSG_INFO, "[task] Arguments:");
    for (int i=0; argv[i]; i++) {
        msg_printf(0, MSG_INFO, "[task]    argv[%d]: %s\n", i, argv[i]);
    }
}
#endif

// For apps that use coprocessors, append "--device x" to the command line.
// NOTE: this is deprecated.  Use app_init_data instead.
//
static void coproc_cmdline(
    int rsc_type, RESULT* rp, double ninstances, char* cmdline, int cmdline_len
) {
    char buf[256];
    COPROC* coproc = &coprocs.coprocs[rsc_type];
    for (int j=0; j<ninstances; j++) {
        int k = rp->coproc_indices[j];
        // sanity check
        //
        if (k < 0 || k >= coproc->count) {
            msg_printf(0, MSG_INTERNAL_ERROR,
                "coproc_cmdline: coproc index %d out of range", k
            );
            k = 0;
        }
        sprintf(buf, " --device %d", coproc->device_nums[k]);
        strlcat(cmdline, buf, cmdline_len);
    }
}

// Make a unique key for client/app shared memory segment.
// Windows: also create and attach to the segment.
//
int ACTIVE_TASK::get_shmem_seg_name() {
#ifdef _WIN32
    int i;
    char seg_name[256];

    bool try_global = (sandbox_account_service_token != NULL);
    for (i=0; i<1024; i++) {
        sprintf(seg_name, "%sboinc_%d", SHM_PREFIX, i);
        shm_handle = create_shmem(
            seg_name, sizeof(SHARED_MEM), (void**)&app_client_shm.shm,
            try_global
        );
        if (shm_handle) break;
    }
    if (!shm_handle) return ERR_SHMGET;
    sprintf(shmem_seg_name, "boinc_%d", i);
#else
    char init_data_path[MAXPATHLEN];
#ifndef __EMX__
    // shmem_seg_name is not used with mmap() shared memory
    if (app_version->api_version_at_least(6, 0)) {
        shmem_seg_name = -1;
        return 0;
    }
#endif
    sprintf(init_data_path, "%s/%s", slot_dir, INIT_DATA_FILE);

    // ftok() only works if there's a file at the given location
    //
    if (!boinc_file_exists(init_data_path)) {
        FILE* f = boinc_fopen(init_data_path, "w");
        if (f) {
            fclose(f);
        } else {
            msg_printf(wup->project, MSG_INTERNAL_ERROR,
                "error: can't open file for shmem seg name"
            );
        }
    }
    shmem_seg_name = ftok(init_data_path, 1);
    if (shmem_seg_name == -1) {
        msg_printf(wup->project, MSG_INTERNAL_ERROR,
            "error: can't open file for shmem seg name: %d", errno
        );
        perror("ftok");
        return ERR_SHMEM_NAME;
    }
#endif
    return 0;
}

void ACTIVE_TASK::init_app_init_data(APP_INIT_DATA& aid) {
    PROJECT* project = wup->project;
    aid.major_version = BOINC_MAJOR_VERSION;
    aid.minor_version = BOINC_MINOR_VERSION;
    aid.release = BOINC_RELEASE;
    aid.app_version = app_version->version_num;
    safe_strcpy(aid.app_name, wup->app->name);
    safe_strcpy(aid.symstore, project->symstore);
    safe_strcpy(aid.acct_mgr_url, gstate.acct_mgr_info.master_url);
    if (project->project_specific_prefs.length()) {
        aid.project_preferences = strdup(
            project->project_specific_prefs.c_str()
        );
    }
    aid.userid = project->userid;
    aid.teamid = project->teamid;
    aid.hostid = project->hostid;
    safe_strcpy(aid.user_name, project->user_name);
    safe_strcpy(aid.team_name, project->team_name);
    safe_strcpy(aid.project_dir, project->project_dir_absolute());
    relative_to_absolute("", aid.boinc_dir);
    safe_strcpy(aid.authenticator, project->authenticator);
    aid.slot = slot;
#ifdef _WIN32
    aid.client_pid = GetCurrentProcessId();
#else
    aid.client_pid = getpid();
#endif
    safe_strcpy(aid.wu_name, wup->name);
    safe_strcpy(aid.result_name, result->name);
    aid.user_total_credit = project->user_total_credit;
    aid.user_expavg_credit = project->user_expavg_credit;
    aid.host_total_credit = project->host_total_credit;
    aid.host_expavg_credit = project->host_expavg_credit;
    double rrs = gstate.runnable_resource_share(RSC_TYPE_CPU);
    if (rrs) {
        aid.resource_share_fraction = project->resource_share/rrs;
    } else {
        aid.resource_share_fraction = 1;
    }
    aid.host_info = gstate.host_info;
    aid.proxy_info = working_proxy_info;
    aid.global_prefs = gstate.global_prefs;
    aid.starting_elapsed_time = checkpoint_elapsed_time;
    aid.using_sandbox = g_use_sandbox;
    aid.vm_extensions_disabled = gstate.host_info.p_vm_extensions_disabled;
    aid.rsc_fpops_est = wup->rsc_fpops_est;
    aid.rsc_fpops_bound = wup->rsc_fpops_bound;
    aid.rsc_memory_bound = wup->rsc_memory_bound;
    aid.rsc_disk_bound = wup->rsc_disk_bound;
    aid.computation_deadline = result->computation_deadline();
    int rt = app_version->gpu_usage.rsc_type;
    if (rt) {
        COPROC& cp = coprocs.coprocs[rt];
        if (coproc_type_name_to_num(cp.type) >= 0) {
            // Standardized vendor name ("NVIDIA", "ATI" or "intel_gpu")
            safe_strcpy(aid.gpu_type, cp.type);
        } else {
            // For other vendors, use vendor name as returned by OpenCL
            safe_strcpy(aid.gpu_type, cp.opencl_prop.vendor);
        }
        int k = result->coproc_indices[0];
        if (k<0 || k>=cp.count) {
            msg_printf(0, MSG_INTERNAL_ERROR,
                "init_app_init_data(): coproc index %d out of range", k
            );
            k = 0;
        }
        aid.gpu_device_num = cp.device_nums[k];
        aid.gpu_opencl_dev_index = cp.opencl_device_indexes[k];
        aid.gpu_usage = app_version->gpu_usage.usage;
    } else {
        safe_strcpy(aid.gpu_type, "");
        aid.gpu_device_num = -1;
        aid.gpu_opencl_dev_index = -1;
        aid.gpu_usage = 0;
    }
    aid.ncpus = app_version->avg_ncpus;
    aid.vbox_window = cc_config.vbox_window;
    aid.checkpoint_period = gstate.global_prefs.disk_interval;
    aid.fraction_done_start = 0;
    aid.fraction_done_end = 1;
#ifdef _WIN32
    safe_strcpy(aid.shmem_seg_name, shmem_seg_name);
#else
    aid.shmem_seg_name = shmem_seg_name;
#endif
    aid.wu_cpu_time = checkpoint_cpu_time;
    APP_VERSION* avp = app_version;
    for (unsigned int i=0; i<avp->app_files.size(); i++) {
        FILE_REF& fref = avp->app_files[i];
        aid.app_files.push_back(string(fref.file_name));
    }
}

// write the app init file.
// This is done before starting or restarting the app,
// and when project prefs have changed during app execution
//
int ACTIVE_TASK::write_app_init_file(APP_INIT_DATA& aid) {
    FILE *f;
    char init_data_path[MAXPATHLEN];

#if 0
    msg_printf(wup->project, MSG_INFO,
        "writing app_init.xml for %s; slot %d rt %s gpu_device_num %d", result->name, slot, aid.gpu_type, aid.gpu_device_num
    );
#endif

    sprintf(init_data_path, "%s/%s", slot_dir, INIT_DATA_FILE);

    // delete the file using the switcher (Unix)
    // in case it's owned by another user and we don't have write access
    //
    delete_project_owned_file(init_data_path, false);
    f = boinc_fopen(init_data_path, "w");
    if (!f) {
        msg_printf(wup->project, MSG_INTERNAL_ERROR,
            "Failed to open init file %s",
            init_data_path
        );
        return ERR_FOPEN;
    }

    int retval = write_init_data_file(f, aid);
    fclose(f);
    return retval;
}

// Given a logical name of the form D1/D2/.../Dn/F,
// create the directories D1 ... Dn in the slot dir
//
static int create_dirs_for_logical_name(
    const char* name, const char* slot_dir
) {
    char buf[1024];
    char dir_path[MAXPATHLEN];
    int retval;

    safe_strcpy(buf, name);
    safe_strcpy(dir_path, slot_dir);
    char* p = buf;
    while (1) {
        char* q = strstr(p, "/");
        if (!q) break;
        *q = 0;
        safe_strcat(dir_path, "/");
        safe_strcat(dir_path, p);
        retval = boinc_mkdir(dir_path);
        if (retval) return retval;
        p = q+1;
    }
    return 0;
}

static void prepend_prefix(APP_VERSION* avp, char* in, char* out, int len) {
    if (strlen(avp->file_prefix)) {
        snprintf(out, len, "%s/%s", avp->file_prefix, in);
    } else {
        strlcpy(out, in, len);
    }
}

// an input/output file must be copied if either
// - the FILE_REFERENCE says so or
// - the APP_VERSION has a non-empty file_prefix
//
bool ACTIVE_TASK::must_copy_file(FILE_REF& fref, bool is_io_file) {
    if (fref.copy_file) return true;
    if (is_io_file && strlen(app_version->file_prefix)) return true;
    return false;
}

// set up a file reference, given a slot dir and project dir.
// This means:
// 1) copy the file to slot dir, if reference is by copy
// 2) else make a soft link
//
int ACTIVE_TASK::setup_file(
    FILE_INFO* fip, FILE_REF& fref, char* file_path, bool input, bool is_io_file
) {
    char link_path[MAXPATHLEN], rel_file_path[MAXPATHLEN], open_name[256];
    int retval;
    PROJECT* project = result->project;

    if (log_flags.slot_debug) {
        msg_printf(wup->project, MSG_INFO,
            "setup_file: %s (%s)", file_path, input?"input":"output"
        );
    }

    if (strlen(fref.open_name)) {
        if (is_io_file) {
            prepend_prefix(
                app_version, fref.open_name, open_name, sizeof(open_name)
            );
        } else {
            safe_strcpy(open_name, fref.open_name);
        }
        retval = create_dirs_for_logical_name(open_name, slot_dir);
        if (retval) return retval;
        snprintf(link_path, sizeof(link_path), "%s/%s", slot_dir, open_name);
    } else {
        snprintf(link_path, sizeof(link_path), "%s/%s", slot_dir, fip->name);
    }

    snprintf(rel_file_path, sizeof(rel_file_path), "../../%s", file_path );

    if (boinc_file_exists(link_path)) {
        return 0;
    }

    if (must_copy_file(fref, is_io_file)) {
        if (input) {
            // the file may be there already (async copy case)
            //
            if (boinc_file_exists(link_path)) {
                return 0;
            }
            if (fip->nbytes > ASYNC_FILE_THRESHOLD) {
                ASYNC_COPY* ac = new ASYNC_COPY;
                retval = ac->init(this, fip, file_path, link_path);
                if (retval) return retval;
                return ERR_IN_PROGRESS;
            } else {
                retval = boinc_copy(file_path, link_path);
                if (retval) {
                    msg_printf(project, MSG_INTERNAL_ERROR,
                        "Can't copy %s to %s: %s", file_path, link_path,
                        boincerror(retval)
                    );
                    return retval;
                }
                retval = fip->set_permissions(link_path);
                if (retval) return retval;
            }
        }
        return 0;
    }

#ifdef _WIN32
    retval = make_soft_link(project, link_path, rel_file_path);
    if (retval) return retval;
#else
    if (project->use_symlinks) {
        retval = symlink(rel_file_path, link_path);
    } else {
        retval = make_soft_link(project, link_path, rel_file_path);
    }
    if (retval) return retval;
#endif
    if (g_use_sandbox) set_to_project_group(link_path);
    return 0;
}

int ACTIVE_TASK::link_user_files() {
    PROJECT* project = wup->project;
    unsigned int i;
    FILE_REF fref;
    FILE_INFO* fip;
    char file_path[MAXPATHLEN];

    for (i=0; i<project->user_files.size(); i++) {
        fref = project->user_files[i];
        fip = fref.file_info;
        if (fip->status != FILE_PRESENT) continue;
        get_pathname(fip, file_path, sizeof(file_path));
        setup_file(fip, fref, file_path, true, false);
    }
    return 0;
}

int ACTIVE_TASK::copy_output_files() {
    char slotfile[256], projfile[256], open_name[256];
    unsigned int i;
    for (i=0; i<result->output_files.size(); i++) {
        FILE_REF& fref = result->output_files[i];
        if (!must_copy_file(fref, true)) continue;
        FILE_INFO* fip = fref.file_info;
        prepend_prefix(
            app_version, fref.open_name, open_name, sizeof(open_name)
        );
        snprintf(slotfile, sizeof(slotfile), "%s/%s", slot_dir, open_name);
        get_pathname(fip, projfile, sizeof(projfile));
        int retval = boinc_rename(slotfile, projfile);
        // the rename fails if the output file isn't there.
        //
        if (retval) {
            if (retval == ERR_FILE_MISSING) {
                if (log_flags.slot_debug) {
                    msg_printf(wup->project, MSG_INFO,
                        "[slot] output file %s missing, not copying", slotfile
                    );
                }
            } else {
                msg_printf(wup->project, MSG_INTERNAL_ERROR,
                    "Can't rename output file %s to %s: %s",
                    slotfile, projfile, boincerror(retval)
                );
            }
        } else {
            if (log_flags.slot_debug) {
                msg_printf(wup->project, MSG_INFO,
                    "[slot] renamed %s to %s", slotfile, projfile
                );
            }
        }
    }
    return 0;
}

static int get_priority(bool is_high_priority) {
    int p = is_high_priority?cc_config.process_priority_special:cc_config.process_priority;
#ifdef _WIN32
    switch (p) {
    case 0: return IDLE_PRIORITY_CLASS;
    case 1: return BELOW_NORMAL_PRIORITY_CLASS;
    case 2: return NORMAL_PRIORITY_CLASS;
    case 3: return ABOVE_NORMAL_PRIORITY_CLASS;
    case 4: return HIGH_PRIORITY_CLASS;
    case 5: return REALTIME_PRIORITY_CLASS;
    }
    return is_high_priority ? BELOW_NORMAL_PRIORITY_CLASS : IDLE_PRIORITY_CLASS;
#else
    switch (p) {
    case 0: return PROCESS_IDLE_PRIORITY;
    case 1: return PROCESS_MEDIUM_PRIORITY;
    case 2: return PROCESS_NORMAL_PRIORITY;
    case 3: return PROCESS_ABOVE_NORMAL_PRIORITY;
    case 4: return PROCESS_HIGH_PRIORITY;
    case 5: return PROCESS_REALTIME_PRIORITY;
    }
    return is_high_priority ? PROCESS_MEDIUM_PRIORITY : PROCESS_IDLE_PRIORITY;
#endif
}

// Start a task in a slot directory.
// This includes setting up soft links,
// passing preferences, and starting the process
//
// Current dir is top-level BOINC dir
//
// postcondition:
// If any error occurs
//   ACTIVE_TASK::task_state is PROCESS_COULDNT_START
//   report_result_error() is called
// else
//   ACTIVE_TASK::task_state is PROCESS_EXECUTING
//
// If "test" is set, we're doing the API test; just run "test_app".
//
int ACTIVE_TASK::start(bool test) {
    char exec_name[256], file_path[MAXPATHLEN], buf[MAXPATHLEN], exec_path[MAXPATHLEN];
    char cmdline[80000];    // 64KB plus some extra
    unsigned int i;
    FILE_REF fref;
    FILE_INFO* fip;
    int retval;
    APP_INIT_DATA aid;
#ifdef _WIN32
    bool success = false;
    LPVOID environment_block=NULL;
#endif

    if (async_copy) {
        if (log_flags.task_debug) {
            msg_printf(wup->project, MSG_INFO,
                "[task_debug] ACTIVE_TASK::start(): async file copy already in progress"
            );
        }
        return 0;
    }

    // run it at above idle priority if it
    // - uses coprocs
    // - uses less than one CPU
    // - is a wrapper
    //
    bool high_priority = false;
    if (app_version->rsc_type()) high_priority = true;
    if (app_version->avg_ncpus < 1) high_priority = true;
    if (app_version->is_wrapper) high_priority = true;

    if (wup->project->verify_files_on_app_start) {
        fip=0;
        retval = gstate.input_files_available(result, true, &fip);
        if (retval) {
            if (fip) {
                snprintf(
                    buf, sizeof(buf),
                    "Input file %s missing or invalid: %s",
                    fip->name, boincerror(retval)
                );
            } else {
                safe_strcpy(buf, "Input file missing or invalid");
            }
            goto error;
        }
    }

    current_cpu_time = checkpoint_cpu_time;
    elapsed_time = checkpoint_elapsed_time;

    graphics_request_queue.init(result->name);        // reset message queues
    process_control_queue.init(result->name);

    bytes_sent_episode = 0;
    bytes_received_episode = 0;

    if (!app_client_shm.shm) {
        retval = get_shmem_seg_name();
        if (retval) {
            snprintf(buf, sizeof(buf),
                "Can't get shared memory segment name: %s",
                boincerror(retval)
            );
            goto error;
        }
    }

    // this must go AFTER creating shmem name,
    // since the shmem name is part of the file
    //
    init_app_init_data(aid);
    retval = write_app_init_file(aid);
    if (retval) {
        snprintf(buf, sizeof(buf), "Can't write init file: %s", boincerror(retval));
        goto error;
    }

    // set up applications files
    //
    if (test) {
        safe_strcpy(exec_name, "test_app");
        safe_strcpy(exec_path, "test_app");
    } else {
        safe_strcpy(exec_name, "");
    }
    for (i=0; i<app_version->app_files.size(); i++) {
        fref = app_version->app_files[i];
        fip = fref.file_info;
        get_pathname(fip, file_path, sizeof(file_path));
        if (fref.main_program) {
            if (is_image_file(fip->name)) {
                snprintf(buf, sizeof(buf), "Main program %s is an image file", fip->name);
                retval = ERR_NO_SIGNATURE;
                goto error;
            }
            if (!fip->executable && !wup->project->anonymous_platform) {
                snprintf(buf, sizeof(buf), "Main program %s is not executable", fip->name);
                retval = ERR_NO_SIGNATURE;
                goto error;
            }
            safe_strcpy(exec_name, fip->name);
            safe_strcpy(exec_path, file_path);
        }
        retval = setup_file(fip, fref, file_path, true, false);
        if (retval == ERR_IN_PROGRESS) {
            set_task_state(PROCESS_COPY_PENDING, "start");
            return 0;
        } else if (retval) {
            safe_strcpy(buf, "Can't link app version file");
            goto error;
        }
    }
    if (!strlen(exec_name)) {
        safe_strcpy(buf, "No main program specified");
        retval = ERR_NOT_FOUND;
        goto error;
    }

    // set up input, output files
    //
    for (i=0; i<wup->input_files.size(); i++) {
        fref = wup->input_files[i];
        fip = fref.file_info;
        get_pathname(fref.file_info, file_path, sizeof(file_path));
        retval = setup_file(fip, fref, file_path, true, true);
        if (retval == ERR_IN_PROGRESS) {
            set_task_state(PROCESS_COPY_PENDING, "start");
            return 0;
        } else if (retval) {
            safe_strcpy(buf, "Can't link input file");
            goto error;
        }
    }
    for (i=0; i<result->output_files.size(); i++) {
        fref = result->output_files[i];
        if (must_copy_file(fref, true)) continue;
        fip = fref.file_info;
        get_pathname(fref.file_info, file_path, sizeof(file_path));
        retval = setup_file(fip, fref, file_path, false, true);
        if (retval) {
            safe_strcpy(buf, "Can't link output file");
            goto error;
        }
    }

    link_user_files();
        // don't check retval here

    // remove temporary exit file from last run
    //
    snprintf(file_path, sizeof(file_path), "%s/%s", slot_dir, TEMPORARY_EXIT_FILE);
    delete_project_owned_file(file_path, true);

    if (cc_config.exit_before_start) {
        msg_printf(0, MSG_INFO, "about to start a job; exiting");
        exit(0);
    }

#ifdef _WIN32
    PROCESS_INFORMATION process_info;
    STARTUPINFO startup_info;
    char slotdirpath[MAXPATHLEN];
    char error_msg[1024];
    char error_msg2[1024];
    DWORD last_error = 0;
    
    memset(&process_info, 0, sizeof(process_info));
    memset(&startup_info, 0, sizeof(startup_info));
    startup_info.cb = sizeof(startup_info);

    // suppress 2-sec rotating hourglass cursor on startup
    //
    startup_info.dwFlags = STARTF_FORCEOFFFEEDBACK;

    app_client_shm.reset_msgs();

    if (cc_config.run_apps_manually) {
        // fill in client's PID so we won't think app has exited
        //
        pid = GetCurrentProcessId();
        process_handle = GetCurrentProcess();
        set_task_state(PROCESS_EXECUTING, "start");
        return 0;
    }

    snprintf(cmdline, sizeof(cmdline),
        "%s %s %s",
        exec_path, wup->command_line.c_str(), app_version->cmdline
    );
    if (!app_version->api_version_at_least(7, 5)) {
        int rt = app_version->gpu_usage.rsc_type;
        if (rt) {
            coproc_cmdline(rt, result, app_version->gpu_usage.usage, cmdline, sizeof(cmdline));
        }
    }

    relative_to_absolute(slot_dir, slotdirpath);
    int prio_mask;
    if (cc_config.no_priority_change) {
        prio_mask = 0;
    } else {
        prio_mask = get_priority(high_priority);
    }

    for (i=0; i<5; i++) {
        last_error = 0;
        if (sandbox_account_service_token != NULL) {

            if (!CreateEnvironmentBlock(&environment_block, sandbox_account_service_token, FALSE)) {
                if (log_flags.task) {
                    windows_format_error_string(GetLastError(), error_msg, sizeof(error_msg));
                    msg_printf(wup->project, MSG_INFO,
                        "Process environment block creation failed: %s", error_msg
                    );
                }
            }

            if (CreateProcessAsUser(
                sandbox_account_service_token,
                exec_path,
                cmdline,
                NULL,
                NULL,
                FALSE,
                CREATE_NEW_PROCESS_GROUP|CREATE_NO_WINDOW|prio_mask|CREATE_UNICODE_ENVIRONMENT,
                environment_block,
                slotdirpath,
                &startup_info,
                &process_info
            )) {
                success = true;
                break;
            } else {
                last_error = GetLastError();
                windows_format_error_string(last_error, error_msg, sizeof(error_msg));
                msg_printf(wup->project, MSG_INTERNAL_ERROR,
                    "Process creation failed: %s - error code %d (0x%x)",
                    error_msg, last_error, last_error
                );
            }

            if (!DestroyEnvironmentBlock(environment_block)) {
                if (log_flags.task) {
                    windows_format_error_string(GetLastError(), error_msg, sizeof(error_msg2));
                    msg_printf(wup->project, MSG_INFO,
                        "Process environment block cleanup failed: %s",
                        error_msg2
                    );
                }
            }

        } else {
            if (CreateProcess(
                exec_path,
                cmdline,
                NULL,
                NULL,
                FALSE,
                CREATE_NEW_PROCESS_GROUP|CREATE_NO_WINDOW|prio_mask,
                NULL,
                slotdirpath,
                &startup_info,
                &process_info
            )) {
                success = true;
                break;
            } else {
                last_error = GetLastError();
                windows_format_error_string(last_error, error_msg, sizeof(error_msg));
                msg_printf(wup->project, MSG_INTERNAL_ERROR,
                    "Process creation failed: %s - error code %d (0x%x)",
                    error_msg, last_error, last_error
                );
            }
        }
        boinc_sleep(drand());
    }

    if (!success) {
        snprintf(buf, sizeof(buf), "CreateProcess() failed - %s", error_msg);

        if (last_error == ERROR_NOT_ENOUGH_MEMORY) {
            // if CreateProcess() failed because system is low on memory,
            // treat this like a temporary exit;
            // retry in 10 min, and give up after 100 times
            //
            bool will_restart;
            handle_temporary_exit(will_restart, 600, "not enough memory", false);
            if (will_restart) return 0;
        }
        retval = ERR_EXEC;
        goto error;
    }
    pid = process_info.dwProcessId;
    process_handle = process_info.hProcess;
    CloseHandle(process_info.hThread);  // thread handle is not used
#elif defined(__EMX__)

    char* argv[100];
    char current_dir[_MAX_PATH];

    // Set up client/app shared memory seg if needed
    //
    if (!app_client_shm.shm) {
        retval = create_shmem(
            shmem_seg_name, sizeof(SHARED_MEM), (void**)&app_client_shm.shm
        );
        if (retval) {
            return retval;
        }
    }
    app_client_shm.reset_msgs();

    // save current dir
    getcwd(current_dir, sizeof(current_dir));

    // chdir() into the slot directory
    //
    retval = chdir(slot_dir);
    if (retval) {
        sprintf(buf, "Can't change directory to %s: %s", slot_dir, boincerror(retval));
        goto error;
    }

    // hook up stderr to a specially-named file
    //
    //freopen(STDERR_FILE, "a", stderr);

    argv[0] = exec_name;
    safe_strcpy(cmdline, wup->command_line.c_str());
    if (strlen(result->cmdline)) {
        safe_strcat(cmdline, " ");
        safe_strcat(cmdline, result->cmdline);
    }
    parse_command_line(cmdline, argv+1);
    if (log_flags.task_debug) {
        debug_print_argv(argv);
    }
    snprintf(buf, sizeof(buf), "../../%s", exec_path );
    pid = spawnv(P_NOWAIT, buf, argv);
    if (pid == -1) {
        snprintf(buf, sizeof(buf), "Process creation failed: %s\n", boincerror(retval));
        chdir(current_dir);
        retval = ERR_EXEC;
        goto error;
    }

    // restore current dir
    chdir(current_dir);

    if (log_flags.task_debug) {
        msg_printf(wup->project, MSG_INFO,
            "[task] ACTIVE_TASK::start(): forked process: pid %d\n", pid
        );
    }

    if (!cc_config.no_priority_change) {
        int priority = get_priority(high_priority);
        if (setpriority(PRIO_PROCESS, pid, priority)) {
            perror("setpriority");
        }
    }

#else
    // Unix/Linux/Mac case

    char* argv[100];
    char current_dir[1024];

    if (getcwd(current_dir, sizeof(current_dir)) == NULL) {
        snprintf(buf, sizeof(buf), "Can't get cwd");
        goto error;
    }

    snprintf(cmdline, sizeof(cmdline),
        "%s %s",
        wup->command_line.c_str(), app_version->cmdline
    );

    if (!app_version->api_version_at_least(7, 5)) {
        int rt = app_version->gpu_usage.rsc_type;
        if (rt) {
            coproc_cmdline(rt, result, app_version->gpu_usage.usage, cmdline, sizeof(cmdline));
        }
    }

    // Set up client/app shared memory seg if needed
    //
    if (!app_client_shm.shm) {
#ifdef ANDROID
        if (true) {
#else
        if (app_version->api_version_at_least(6, 0)) {
#endif
            // Use mmap() shared memory
            snprintf(buf, sizeof(buf), "%s/%s", slot_dir, MMAPPED_FILE_NAME);
            if (g_use_sandbox) {
                if (!boinc_file_exists(buf)) {
                    int fd = open(buf, O_RDWR | O_CREAT, 0660);
                    if (fd >= 0) {
                        close (fd);
                        if (g_use_sandbox) set_to_project_group(buf);
                    }
                }
            }
            retval = create_shmem_mmap(
                buf, sizeof(SHARED_MEM), (void**)&app_client_shm.shm
            );
            if (retval) {
                msg_printf(wup->project, MSG_INTERNAL_ERROR,
                    "ACTIVE_TASK::start(): can't create memory-mapped file: %s",
                    boincerror(retval)
                );
                return retval;
            }
        } else {
            // Use shmget() shared memory
            retval = create_shmem(
                shmem_seg_name, sizeof(SHARED_MEM), gstate.boinc_project_gid,
                (void**)&app_client_shm.shm
            );

            if (retval) {
                needs_shmem = true;
                destroy_shmem(shmem_seg_name);
                return retval;
            }
        }
        needs_shmem = false;
    }
    app_client_shm.reset_msgs();

#if (defined (__APPLE__) && (defined(__i386__) || defined(__x86_64__)))
    // PowerPC apps emulated on i386 Macs crash if running graphics
    powerpc_emulated_on_i386 = ! is_native_i386_app(exec_path);
#endif
    if (cc_config.run_apps_manually) {
        pid = getpid();     // use the client's PID
        set_task_state(PROCESS_EXECUTING, "start");
        return 0;
    }
    pid = fork();
    if (pid == -1) {
        snprintf(buf, sizeof(buf), "fork() failed: %s", strerror(errno));
        retval = ERR_FORK;
        goto error;
    }
    if (pid == 0) {
        // from here on we're running in a new process.
        // If an error happens,
        // exit nonzero so that the client knows there was a problem.

        // don't pass stdout to the app
        //
        int fd = open("/dev/null", O_RDWR);
        dup2(fd, STDOUT_FILENO);
        close(fd);

        // prepend to library path:
        // - the project dir (../../projects/X)
        // - the slot dir (.)
        // - the BOINC dir (../..)
        // (Mac) /usr/local/cuda/lib/
        // We use relative paths in case higher-level dirs
        // are not readable to the account under which app runs
        //
        char libpath[8192];
        char newlibs[256];
        snprintf(newlibs, sizeof(newlibs), "../../%s:.:../..", wup->project->project_dir());
#ifdef __APPLE__
        safe_strcat(newlibs, ":/usr/local/cuda/lib/");
#endif
        char* p = getenv("LD_LIBRARY_PATH");
        if (p) {
            snprintf(libpath, sizeof(libpath), "%s:%s", newlibs, p);
        } else {
            safe_strcpy(libpath, newlibs);
        }
        setenv("LD_LIBRARY_PATH", libpath, 1);

        // On the Mac, do the same for DYLD_LIBRARY_PATH
        //
#ifdef __APPLE__
        p = getenv("DYLD_LIBRARY_PATH");
        if (p) {
            snprintf(libpath, sizeof(libpath), "%s:%s", newlibs, p);
        } else {
            safe_strcpy(libpath, newlibs);
        }
        setenv("DYLD_LIBRARY_PATH", libpath, 1);
#endif

        retval = chdir(slot_dir);
        if (retval) {
            perror("chdir");
            fflush(NULL);
            _exit(errno);
        }

#if 0
        // set stack size limit to the max.
        // Some BOINC apps have reported problems with exceeding
        // small stack limits (e.g. 8 MB)
        // and it seems like the best thing to raise it as high as possible
        //
        struct rlimit rlim;
#define MIN_STACK_LIMIT 64000000
        getrlimit(RLIMIT_STACK, &rlim);
        if (rlim.rlim_cur != RLIM_INFINITY && rlim.rlim_cur <= MIN_STACK_LIMIT) {
            if (rlim.rlim_max == RLIM_INFINITY || rlim.rlim_max > MIN_STACK_LIMIT) {
                rlim.rlim_cur = MIN_STACK_LIMIT;
            } else {
                rlim.rlim_cur = rlim.rlim_max;
            }
            setrlimit(RLIMIT_STACK, &rlim);
        }
#endif

        // hook up stderr to a specially-named file
        //
        (void) freopen(STDERR_FILE, "a", stderr);

        // lower our priority if needed
        //
        if (!cc_config.no_priority_change) {
#if HAVE_SETPRIORITY
            int priority = get_priority(high_priority);
            if (setpriority(PRIO_PROCESS, 0, priority)) {
                perror("setpriority");
            }
#endif
#ifdef ANDROID
            // Android has its own notion of background scheduling
            if (!high_priority) {
                FILE* f = fopen("/dev/cpuctl/apps/bg_non_interactive/tasks", "w");
                if (!f) {
                    msg_printf(NULL, MSG_INFO, "Can't open /dev/cpuctl/apps/bg_non_interactive/tasks");
                } else {
                    fprintf(f, "%d", getpid());
                    fclose(f);
                }
            }
#endif
#if HAVE_SCHED_SETSCHEDULER && defined(SCHED_BATCH) && defined (__linux__)
            if (!high_priority) {
                struct sched_param sp;
                sp.sched_priority = 0;
                if (sched_setscheduler(0, SCHED_BATCH, &sp)) {
                    perror("sched_setscheduler");
                }
            }
#endif
        }

        // Run the application program.
        // If using account-based sandboxing, use a helper app
        // to do this, to set the right user ID
        //
        if (test) {
            strcpy(buf, exec_path);
        } else {
            snprintf(buf, sizeof(buf), "../../%s", exec_path);
        }
        if (g_use_sandbox) {
            char switcher_path[MAXPATHLEN];
            snprintf(switcher_path, sizeof(switcher_path), 
                "../../%s/%s",
                SWITCHER_DIR, SWITCHER_FILE_NAME
            );
            argv[0] = const_cast<char*>(SWITCHER_FILE_NAME);
            argv[1] = buf;
            argv[2] = exec_name;
            parse_command_line(cmdline, argv+3);
            if (log_flags.task_debug) {
                debug_print_argv(argv);
            }
            // Files written by projects have user boinc_project
            // and group boinc_project,
            // so they must be world-readable so BOINC CLient can read them
            //
            umask(2);
            retval = execv(switcher_path, argv);
        } else {
            argv[0] = buf;
            parse_command_line(cmdline, argv+1);
            retval = execv(buf, argv);
        }
        fprintf(stderr,
            "Process creation (%s) failed: %s, errno=%d\n",
            buf, boincerror(retval), errno
        );
        perror("execv");
        fflush(NULL);
        _exit(errno);
    }

    // parent process (client) continues here
    //
    if (log_flags.task_debug) {
        msg_printf(wup->project, MSG_INFO,
            "[task] ACTIVE_TASK::start(): forked process: pid %d\n", pid
        );
    }

#endif
    set_task_state(PROCESS_EXECUTING, "start");
    return 0;

    // go here on error; "buf" contains error message, "retval" is nonzero
    //
error:
    if (test) {
        return retval;
    }

    // if something failed, it's possible that the executable was munged.
    // Verify it to trigger another download.
    //
    gstate.input_files_available(result, true);
    char err_msg[4096];
    snprintf(err_msg, sizeof(err_msg), "couldn't start app: %s", buf);
    gstate.report_result_error(*result, err_msg);
    if (log_flags.task_debug) {
        msg_printf(wup->project, MSG_INFO,
            "[task] couldn't start app: %s", buf
        );
    }
    set_task_state(PROCESS_COULDNT_START, "start");
    return retval;
}

// Resume the task if it was previously running; otherwise start it
// Postcondition: "state" is set correctly
//
int ACTIVE_TASK::resume_or_start(bool first_time) {
    const char* str = "??";
    int retval;

    switch (task_state()) {
    case PROCESS_UNINITIALIZED:
        str = (first_time)?"Starting":"Restarting";
        retval = start();
        if ((retval == ERR_SHMGET) || (retval == ERR_SHMAT)) {
            return retval;
        }
        if (retval) {
            set_task_state(PROCESS_COULDNT_START, "resume_or_start1");
            return retval;
        }
        break;
    case PROCESS_SUSPENDED:
        retval = unsuspend();
        if (retval) {
            msg_printf(wup->project, MSG_INTERNAL_ERROR,
                "Couldn't resume task %s", result->name
            );
            set_task_state(PROCESS_COULDNT_START, "resume_or_start2");
            return retval;
        }
        str = "Resuming";
        break;
    default:
        msg_printf(result->project, MSG_INTERNAL_ERROR,
            "Unexpected state %d for task %s", task_state(), result->name
        );
        return 0;
    }
    if (log_flags.task && first_time) {
        msg_printf(result->project, MSG_INFO,
            "Starting task %s", result->name
        );
    }
    if (log_flags.cpu_sched) {
        char buf[256];
        safe_strcpy(buf, "");
        if (strlen(app_version->plan_class)) {
            snprintf(buf, sizeof(buf), " (%s)", app_version->plan_class);
        }
        msg_printf(result->project, MSG_INFO,
            "[cpu_sched] %s task %s using %s version %d%s in slot %d",
            str,
            result->name,
            app_version->app->name,
            app_version->version_num,
            buf,
            slot
        );
    }
    return 0;
}

#if (defined (__APPLE__) && (defined(__i386__) || defined(__x86_64__)))

union headeru {
    fat_header fat;
    mach_header mach;
};

// Read the mach-o headers to determine the architectures
// supported by executable file.
// Returns 1 if application can run natively on i386 / x86_64 Macs,
// else returns 0.
//
int ACTIVE_TASK::is_native_i386_app(char* exec_path) {
    FILE *f;
    int retval = 0;
    
    headeru myHeader;
    fat_arch fatHeader;
    
    uint32_t n, i, len;
    uint32_t theMagic;
    integer_t theType;
    
    f = boinc_fopen(exec_path, "rb");
    if (!f) {
        return retval;          // Should never happen
    }
    
    myHeader.fat.magic = 0;
    myHeader.fat.nfat_arch = 0;
    
    fread(&myHeader, 1, sizeof(fat_header), f);
    theMagic = myHeader.mach.magic;
    switch (theMagic) {
    case MH_CIGAM:
    case MH_MAGIC:
    case MH_MAGIC_64:
    case MH_CIGAM_64:
       theType = myHeader.mach.cputype;
        if ((theMagic == MH_CIGAM) || (theMagic == MH_CIGAM_64)) {
            theType = OSSwapInt32(theType);
        }
        if ((theType == CPU_TYPE_I386) || (theType == CPU_TYPE_X86_64)) {
            retval = 1;        // Single-architecture i386or x86_64 file
        }
        break;
    case FAT_MAGIC:
    case FAT_CIGAM:
        n = myHeader.fat.nfat_arch;
        if (theMagic == FAT_CIGAM) {
            n = OSSwapInt32(myHeader.fat.nfat_arch);
        }
           // Multiple architecture (fat) file
        for (i=0; i<n; i++) {
            len = fread(&fatHeader, 1, sizeof(fat_arch), f);
            if (len < sizeof(fat_arch)) {
                break;          // Should never happen
            }
            theType = fatHeader.cputype;
            if (theMagic == FAT_CIGAM) {
                theType = OSSwapInt32(theType);
            }
            if ((theType == CPU_TYPE_I386) || (theType == CPU_TYPE_X86_64)) {
                retval = 1;
                break;
            }
        }
        break;
    default:
        break;
    }

    fclose (f);
    return retval;
}
#endif

// The following runs "test_app" and sends it various messages.
// Used for testing the runtime system.
//
void run_test_app() {
    WORKUNIT wu;
    PROJECT project;
    APP app;
    APP_VERSION av;
    ACTIVE_TASK at;
    ACTIVE_TASK_SET ats;
    RESULT result;
    int retval;

    char buf[256];
    getcwd(buf, sizeof(buf));   // so we can see where we're running

    gstate.run_test_app = true;

    wu.project = &project;
    wu.app = &app;
    wu.command_line = string("--critical_section");

    safe_strcpy(app.name, "test app");
    av.init();
    av.avg_ncpus = 1;

    safe_strcpy(result.name, "test result");
    result.avp = &av;
    result.wup = &wu;
    result.project = &project;
    result.app = &app;

    at.result = &result;
    at.wup = &wu;
    at.app_version = &av;
    at.max_elapsed_time = 1e6;
    at.max_disk_usage = 1e14;
    at.max_mem_usage = 1e14;
    safe_strcpy(at.slot_dir, ".");

#if 1
    // test file copy
    //
    ASYNC_COPY* ac = new ASYNC_COPY;
    FILE_INFO fi;
    retval = ac->init(&at, &fi, "big_file", "./big_file_copy");
    if (retval) {
        exit(1);
    }
    while (1) {
        do_async_file_op();
        if (at.async_copy == NULL) {
            break;
        }
    }
    fprintf(stderr, "done\n");
    exit(0);
#endif
    ats.active_tasks.push_back(&at);

    unlink("boinc_finish_called");
    unlink("boinc_lockfile");
    unlink("boinc_temporary_exit");
    unlink("stderr.txt");
    retval = at.start(true);
    if (retval) {
        fprintf(stderr, "start() failed: %s\n", boincerror(retval));
    }
    while (1) {
        gstate.now = dtime();
        at.preempt(REMOVE_NEVER);
        ats.poll();
        boinc_sleep(.1);
        at.unsuspend();
        ats.poll();
        boinc_sleep(.2);
        //at.request_reread_prefs();
    }
}