File: vbox_common.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 (1482 lines) | stat: -rw-r--r-- 44,523 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
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
// This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2010-2012 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/>.

#ifdef _WIN32
#include "boinc_win.h"
#include "win_util.h"

#if defined(_MSC_VER)
#define getcwd      _getcwd
#define stricmp     _stricmp
#endif

#else
#include <algorithm>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <unistd.h>
#endif

using std::string;

#include "diagnostics.h"
#include "filesys.h"
#include "parse.h"
#include "str_util.h"
#include "str_replace.h"
#include "base64.h"
#include "md5_file.h"
#include "util.h"
#include "error_numbers.h"
#include "procinfo.h"
#include "network.h"
#include "boinc_api.h"
#include "floppyio.h"
#include "vboxlogging.h"
#include "vboxwrapper.h"
#include "vbox_common.h"


bool is_boinc_client_version_newer(APP_INIT_DATA& aid, int maj, int min, int rel) {
    if (maj < aid.major_version) return true;
    if (maj > aid.major_version) return false;
    if (min < aid.minor_version) return true;
    if (min > aid.minor_version) return false;
    if (rel < aid.release) return true;
    return false;
}

// t1 > t2
static bool is_timestamp_newer(VBOX_TIMESTAMP& t1, VBOX_TIMESTAMP& t2) {
    if (t1.hours > t2.hours) return true;
    if (t1.hours < t2.hours) return false;
    if (t1.minutes > t2.minutes) return true;
    if (t1.minutes < t2.minutes) return false;
    if (t1.seconds > t2.seconds) return true;
    if (t1.seconds < t2.seconds) return false;
    if (t1.milliseconds > t2.milliseconds) return true;
    return false;
}


VBOX_BASE::VBOX_BASE() : VBOX_JOB() {
    VBOX_JOB::clear();
    virtualbox_home_directory.clear();
    virtualbox_scratch_directory.clear();
    virtualbox_install_directory.clear();
    virtualbox_guest_additions.clear();
    virtualbox_version_raw.clear();
    virtualbox_version_display.clear();
    pFloppy = NULL;
    vm_log.clear();
    vm_log_timestamp.hours = 0;
    vm_log_timestamp.minutes = 0;
    vm_log_timestamp.seconds = 0;
    vm_log_timestamp.milliseconds = 0;
    vm_master_name.clear();
    vm_master_description.clear();
    vm_name.clear();
    vm_cpu_count.clear();
    image_filename.clear();
    iso_image_filename.clear();
    cache_disk_filename.clear();
    floppy_image_filename.clear();
    current_cpu_time = 0.0;
    suspended = false;
    network_suspended = false;
    online = false;
    saving = false;
    restoring = false;
    crashed = false;
    started_successfully = false;
    register_only = false;
    rd_host_port = 0;
    headless = true;
    vm_pid = 0;
    vboxsvc_pid = 0;

#ifdef _WIN32
    vm_pid_handle = 0;
    vboxsvc_pid_handle = 0;
#endif
}

VBOX_BASE::~VBOX_BASE() {
    if (pFloppy) {
        delete pFloppy;
        pFloppy = NULL;
    }

#ifdef _WIN32
    if (vm_pid_handle) {
        CloseHandle(vm_pid_handle);
        vm_pid_handle = NULL;
    }
    if (vboxsvc_pid_handle) {
        CloseHandle(vboxsvc_pid_handle);
        vboxsvc_pid_handle = NULL;
    }
#endif
}

int VBOX_BASE::run(bool do_restore_snapshot) {
    int retval;

    retval = is_registered();
    if (ERR_TIMEOUT == retval) {
        vboxlog_msg("Error: Timeout");

        return VBOXWRAPPER_ERR_RECOVERABLE;

    } else if (ERR_NOT_FOUND == retval) {

        if (is_vm_machine_configuration_available()) {
            retval = register_vm();
          
            if (retval){

                vboxlog_msg("Could not register");
                return retval;
            }
        } else {
            if (is_disk_image_registered()) {
                // Handle the case where a previous instance of the same projects VM
                // was already initialized for the current slot directory but aborted
                // while the task was suspended and unloaded from memory.
                retval = deregister_stale_vm();
              
                if (retval){

                    vboxlog_msg("Could not deregister stale VM");
                    return retval;
                }
            }
            retval = create_vm();

            if (retval){

                vboxlog_msg("Could not create VM");
                return retval;
            }
        }
    }

    // The user has requested that we exit after registering the VM, so return an
    // error to stop further processing.
    if (register_only) return ERR_FOPEN;

    // If we are restarting an already registered VM, then the vm_name variable
    // will be empty right now, so populate it with the master name so all of the
    // various other functions will work.
    vm_name = vm_master_name;

    // Check to see if the VM is already in a running state, if so, poweroff.
    poll2(false);
    if (online) {
        vboxlog_msg("VM was running");
        retval = poweroff();

        if (retval){

            vboxlog_msg("Could not stop running VM");
            return ERR_NOT_EXITED;
        }
    }

    // If our last checkpoint time is greater than 0, restore from the previously
    // saved snapshot
    if (do_restore_snapshot) {
        retval = restore_snapshot();

        if (retval){

            vboxlog_msg("Could not restore from snapshot");
            return retval;
        }
    }

    // Has BOINC signaled that we should quit?
    // Try to prevent starting the VM in an environment where we might be terminated any
    // second.  This can happen if BOINC has been told to shutdown or the volunteer has
    // told BOINC to switch to a different project.
    //
    if (boinc_status.no_heartbeat || boinc_status.quit_request) {
        return VBOXWRAPPER_ERR_RECOVERABLE;
    }

    // Start the VM
    retval = start();

    if (retval){

        vboxlog_msg("Could not start ");
        return retval;
    }

    return 0;
}

void VBOX_BASE::cleanup() {
    poweroff();
    deregister_vm(true);

    // Give time enough for external processes to finish the cleanup process
    boinc_sleep(5.0);
}

void VBOX_BASE::dump_hypervisor_logs(bool include_error_logs) {
    string local_system_log;
    string local_vm_log;
    string local_startup_log;
    string local_trace_log;
    unsigned long vm_exit_code = 0;

    get_system_log(local_system_log);
    get_vm_log(local_vm_log);
    get_trace_log(local_trace_log);
    get_startup_log(local_startup_log);
    get_vm_exit_code(vm_exit_code);

    if (include_error_logs) {
        dump_screenshot();
        fprintf(
                stderr,
                "\n"
                "    Hypervisor System Log:\n\n"
                "%s\n"
                "    VM Execution Log:\n\n"
                "%s\n"
                "    VM Startup Log:\n\n"
                "%s\n"
                "    VM Trace Log:\n\n"
                "%s",
                local_system_log.c_str(),
                local_vm_log.c_str(),
                local_startup_log.c_str(),
                local_trace_log.c_str()
               );
    }

    if (vm_exit_code) {
        fprintf(
                stderr,
                "\n"
                "    VM Exit Code: %d (0x%x)\n\n",
                (unsigned int)vm_exit_code,
                (unsigned int)vm_exit_code
               );
    }
}

void VBOX_BASE::report_clean(bool unrecoverable_error, bool skip_cleanup, bool do_dump_hypervisor_logs,
        int retval, std::string error_reason,
        int vm_pid, int temp_delay, std::string temp_reason,
        double current_cpu_time,
        double last_checkpoint_cpu_time,
        double fraction_done,
        double bytes_sent,
        double bytes_received) {


    if (unrecoverable_error) {

        // Attempt to cleanup the VM and exit.
        if (!skip_cleanup) {
            cleanup();
        }

        if (error_reason.size()) {
            vboxlog_msg("\n%s", error_reason.c_str());
        }

        if (do_dump_hypervisor_logs) {
            dump_hypervisor_logs(true);
        }

        boinc_finish(retval);
    }
    else {

        // if the VM is already running notify BOINC about the process ID so it can
        // clean up the environment.  We should be safe to run after that.
        //
        if (vm_pid) {
            retval = boinc_report_app_status_aux(
                    current_cpu_time,
                    last_checkpoint_cpu_time,
                    fraction_done,
                    vm_pid,
                    bytes_sent,
                    bytes_received
                    );
        }

        // Give the BOINC API time to report the pid to BOINC.
        //
        boinc_sleep(5.0);

        if (error_reason.size()) {
            vboxlog_msg("\n%s", error_reason.c_str());
        }

        if (do_dump_hypervisor_logs) {
            dump_hypervisor_logs(true);
        }

        // Exit and let BOINC clean up the rest.
        //
        boinc_temporary_exit(temp_delay, temp_reason.c_str());
    }
}

string VBOX_BASE::get_error(int num){

    const char* args[] = {"   BOINC will be notified that it needs to clean up the environment.\n \
        This is a temporary problem and so this job will be rescheduled for another time.\n",

          "   NOTE: VM was already running.\n \
              BOINC will be notified that it needs to clean up the environment.\n \
              This might be a temporary problem and so this job will be rescheduled for another time.\n",

          "   NOTE: VirtualBox has reported an improperly configured virtual machine. It was configured to require\n \
              hardware acceleration for virtual machines, but your processor does not support the required feature.\n \
              Please report this issue to the project so that it can be addresssed.\n \
              Error Code: ERR_CPU_VM_EXTENSIONS_DISABLED\n",

          "   VboxSvc crashed while attempting to restore the current snapshot.  This is a critical\n \
              operation and this job cannot be recovered.\n",

          "   NOTE: VM session lock error encountered.\n \
              BOINC will be notified that it needs to clean up the environment.\n \
              This might be a temporary problem and so this job will be rescheduled for another time.\n",

          "   NOTE: BOINC has detected that your computer's processor supports hardware acceleration for\n \
              virtual machines but the hypervisor failed to successfully launch with this feature enabled.\n \
              This means that the hardware acceleration feature has been disabled in the computer's BIOS.\n \
              Please enable this feature in your computer's BIOS.\n \
              Intel calls it 'VT-x'\n \
              AMD calls it 'AMD-V'\n \
              More information can be found here: https://en.wikipedia.org/wiki/X86_virtualization\n \
              Error Code: ERR_CPU_VM_EXTENSIONS_DISABLED\n",

          "   NOTE: VirtualBox hypervisor reports that another hypervisor has locked the hardware acceleration\n \
              for virtual machines feature in exclusive mode.\n",

          "   NOTE: VirtualBox has failed to allocate enough memory to start the configured virtual machine.\n \
              This might be a temporary problem and so this job will be rescheduled for another time.\n",

          "   NOTE: VM failed to enter an online state within the timeout period.\n \
              This might be a temporary problem and so this job will be rescheduled for another time.\n",

          "VM environment needed to be cleaned up.",

          "Foreign VM Hypervisor locked hardware acceleration features.",

          "VM Hypervisor was unable to allocate enough memory to start VM.",

          "VM Hypervisor failed to enter an online state in a timely fashion."
    };

    std::vector<std::string> v(args, args + 13);
    return v[num];
}

string VBOX_BASE::read_vm_log(){

    string line;
    size_t line_pos;
    size_t line_end;
    size_t line_start;
    string msg;
    static string state = "poweredoff";
    string virtualbox_vm_log;
    virtualbox_vm_log = vm_master_name + "/Logs/VBox.log";

    string console = "Console: Machine state changed to \'";

    std::ifstream  src(virtualbox_vm_log.c_str(), std::ios::binary);

    if ((src.is_open()) && (src.seekg(log_pointer)))
    {

        while (std::getline(src, line))
        {
            line_start = line.find(console);
            if (line_start != string::npos) {

                line_start += console.size();

                line_end = line.find("\'", line_start);

                msg = line.substr(line_start, line_end - line_start);

                sanitize_format(msg);

                state = msg;

		std::transform(state.begin(), state.end(), state.begin(), ::tolower);
            }

            line_pos = line.find("Guest Log:");
            if (line_pos != string::npos) {

                msg = line.substr(line_pos, line.size() - line_pos);

                sanitize_format(msg);
                sanitize_output(msg);

                vboxlog_msg(msg.c_str());

            }
            log_pointer = src.tellg();
        }

        return state;
    }
    else return "Error in parsing the log file";
}


// Dump any new guest log messages which are generated by applications running within
// the guest VM.
void VBOX_BASE::dump_vmguestlog_entries() {
    string local_vm_log;
    string line;
    size_t line_pos;
    VBOX_TIMESTAMP current_timestamp;
    string msg;
    string virtualbox_vm_log;
    virtualbox_vm_log = vm_master_name + "/Logs/VBox.log";
    int check;

    if (boinc_file_exists(virtualbox_vm_log.c_str())) {

        std::ifstream  src(virtualbox_vm_log.c_str(), std::ios::in);
        while (std::getline(src, line))
        {
            line_pos = line.find("Guest Log:");
            if (line_pos != string::npos) {
                check = sscanf(
                        line.c_str(),
                        "%d:%d:%d.%d",
                        &current_timestamp.hours, &current_timestamp.minutes,
                        &current_timestamp.seconds, &current_timestamp.milliseconds
                        );

                if (is_timestamp_newer(current_timestamp, vm_log_timestamp) && check == 4) {
                    vm_log_timestamp = current_timestamp;
                    msg = line.substr(line_pos, line.size() - line_pos);

                    sanitize_format(msg);

                    vboxlog_msg(msg.c_str());
                }
            }
        }
    }
}

int VBOX_BASE::dump_screenshot() {
    int    retval;
    char   screenshot_md5[33];
    double nbytes;
    char*  buf = NULL;
    size_t n;
    FILE*  f = NULL;
    string screenshot_encoded;
    string virtual_machine_slot_directory;
    string screenshot_location;

    get_slot_directory(virtual_machine_slot_directory);

    screenshot_location = virtual_machine_slot_directory;
    screenshot_location += "/";
    screenshot_location += SCREENSHOT_FILENAME;

    if (boinc_file_exists(screenshot_location.c_str())) {

        // Compute MD5 hash for raw file
        retval = md5_file(screenshot_location.c_str(), screenshot_md5, nbytes, false);
        if (retval) return retval;

        buf = (char*)malloc((size_t)nbytes);
        if (!buf) {
            vboxlog_msg("Failed to allocate buffer for screenshot image dump.");
            return ERR_MALLOC;
        }
        f = fopen(screenshot_location.c_str(), "rb");
        if (!f) {
            vboxlog_msg("Failed to open screenshot image file. (%s)", screenshot_location.c_str());
            free(buf);
            return ERR_FOPEN;
        }

        n = fread(buf, 1, (size_t)nbytes, f);
        if (n != nbytes) {
            vboxlog_msg("Failed to read screenshot image file into buffer.");
        }

        screenshot_encoded = r_base64_encode(buf, n);

        fclose(f);
        free(buf);

        fprintf(
                stderr,
                "\n"
                "Screen Shot Information (Base64 Encoded PNG):\n"
                "MD5 Signature: %s\n"
                "Data: %s\n"
                "\n",
                screenshot_md5,
                screenshot_encoded.c_str()
               );
    }

    return 0;
}

bool VBOX_BASE::is_vm_machine_configuration_available() {
    string virtual_machine_slot_directory;
    string vm_machine_configuration_file;

    get_slot_directory(virtual_machine_slot_directory);

    vm_machine_configuration_file = virtual_machine_slot_directory + "/" + vm_master_name + "/" + vm_master_name + ".vbox";
    if (boinc_file_exists(vm_machine_configuration_file.c_str())) {
        return true;
    }
    return false;
}


// Updates for VirtualBox errors dealing with CPU exceleration can be found here:
// https://www.virtualbox.org/browser/vbox/trunk/src/VBox/VMM/VMMR3/HM.cpp#L599
//

bool VBOX_BASE::is_logged_failure_vm_extensions_disabled() {
    if (vm_log.find("VERR_VMX_MSR_LOCKED_OR_DISABLED") != string::npos) return true;
    if (vm_log.find("VERR_SVM_DISABLED") != string::npos) return true;

    // VirtualBox 4.3.x or better
    if (vm_log.find("VERR_VMX_MSR_VMXON_DISABLED") != string::npos) return true;
    if (vm_log.find("VERR_VMX_MSR_SMX_VMXON_DISABLED") != string::npos) return true;

    // VirtualBox 5.x or better
    if (vm_log.find("VERR_VMX_MSR_VMX_DISABLED") != string::npos) return true;
    if (vm_log.find("VERR_VMX_MSR_ALL_VMX_DISABLED") != string::npos) return true;
    if (vm_log.find("VERR_VMX_MSR_LOCKING_FAILED") != string::npos) return true;

    return false;
}

bool VBOX_BASE::is_logged_failure_vm_extensions_in_use() {
    if (vm_log.find("VERR_VMX_IN_VMX_ROOT_MODE") != string::npos) return true;
    if (vm_log.find("VERR_SVM_IN_USE") != string::npos) return true;
    return false;
}

bool VBOX_BASE::is_logged_failure_vm_extensions_not_supported() {
    if (vm_log.find("VERR_VMX_NO_VMX") != string::npos) return true;
    if (vm_log.find("VERR_SVM_NO_SVM") != string::npos) return true;
    return false;
}

//
//
//

bool VBOX_BASE::is_logged_failure_vm_powerup() {
    if (vm_log.find("Power up failed (vrc=VINF_SUCCESS, rc=E_FAIL (0X80004005))") != string::npos) return true;
    return false;
}

bool VBOX_BASE::is_logged_failure_host_out_of_memory() {
    if (vm_log.find("VERR_EM_NO_MEMORY") != string::npos) return true;
    if (vm_log.find("VERR_NO_MEMORY") != string::npos) return true;
    return false;
}

bool VBOX_BASE::is_logged_failure_guest_job_out_of_memory() {
    if (vm_log.find("EXIT_OUT_OF_MEMORY") != string::npos) return true;
    return false;
}

bool VBOX_BASE::is_virtualbox_version_newer(int maj, int min, int rel) {
    int vbox_major = 0, vbox_minor = 0, vbox_release = 0;
    if (3 == sscanf(virtualbox_version_raw.c_str(), "%d.%d.%d", &vbox_major, &vbox_minor, &vbox_release)) {
        if (maj < vbox_major) return true;
        if (maj > vbox_major) return false;
        if (min < vbox_minor) return true;
        if (min > vbox_minor) return false;
        if (rel < vbox_release) return true;
    }
    return false;
}

int VBOX_BASE::get_scratch_directory(string& dir) {
    APP_INIT_DATA aid;
    boinc_get_init_data_p(&aid);

    dir = aid.project_dir + std::string("/scratch");

    if (!dir.empty()) {
        return 1;
    }
    return 0;
}

// Returns the current directory in which the executable resides.
//
int VBOX_BASE::get_slot_directory(string& dir) {
    char slot_dir[256];

    getcwd(slot_dir, sizeof(slot_dir));
    dir = slot_dir;

    if (!dir.empty()) {
        return 1;
    }
    return 0;
}

int VBOX_BASE::get_system_log(string& log, bool tail_only, unsigned int buffer_size) {
    string virtualbox_system_log;
    string::iterator iter;
    int retval = BOINC_SUCCESS;

    // Locate and read log file
    virtualbox_system_log = virtualbox_home_directory + "/VBoxSVC.log";

    if (boinc_file_exists(virtualbox_system_log.c_str())) {
        if (tail_only) {
            // Keep only the last 8k if it is larger than that.
            read_file_string(virtualbox_system_log.c_str(), log, buffer_size, true);
        } else {
            read_file_string(virtualbox_system_log.c_str(), log);
        }

        sanitize_output(log);

        if (tail_only) {
            if (log.size() >= (buffer_size - 115)) {
                // Look for the next whole line of text.
                iter = log.begin();
                while (iter != log.end()) {
                    if (*iter == '\n') {
                        log.erase(iter);
                        break;
                    }
                    iter = log.erase(iter);
                }
            }
        }
    }

    return retval;
}

int VBOX_BASE::get_vm_log(string& log, bool tail_only, unsigned int buffer_size) {
    string virtualbox_vm_log;
    string::iterator iter;
    int retval = BOINC_SUCCESS;

    // Locate and read log file
    virtualbox_vm_log = vm_master_name + "/Logs/VBox.log";

    if (boinc_file_exists(virtualbox_vm_log.c_str())) {
        if (tail_only) {
            // Keep only the last 8k if it is larger than that.
            read_file_string(virtualbox_vm_log.c_str(), log, buffer_size, true);
        } else {
            read_file_string(virtualbox_vm_log.c_str(), log);
        }

        sanitize_output(log);

        if (tail_only) {
            if (log.size() >= (buffer_size - 115)) {
                // Look for the next whole line of text.
                iter = log.begin();
                while (iter != log.end()) {
                    if (*iter == '\n') {
                        log.erase(iter);
                        break;
                    }
                    iter = log.erase(iter);
                }
            }
        }

    }

    return retval;
}

int VBOX_BASE::get_trace_log(string& log, bool tail_only, unsigned int buffer_size) {
    string vm_trace_log;
    string::iterator iter;
    int retval = BOINC_SUCCESS;

    // Locate and read log file
    vm_trace_log = TRACELOG_FILENAME;

    if (boinc_file_exists(vm_trace_log.c_str())) {
        if (tail_only) {
            // Keep only the last 8k if it is larger than that.
            read_file_string(vm_trace_log.c_str(), log, buffer_size, true);
        } else {
            read_file_string(vm_trace_log.c_str(), log);
        }

        sanitize_output(log);

        if (tail_only) {
            if (log.size() >= (buffer_size - 115)) {
                // Look for the next whole line of text.
                iter = log.begin();
                while (iter != log.end()) {
                    if (*iter == '\n') {
                        log.erase(iter);
                        break;
                    }
                    iter = log.erase(iter);
                }
            }
        }

    } else {
        retval = ERR_NOT_FOUND;
    }

    return retval;
}

int VBOX_BASE::get_startup_log(string& log, bool tail_only, unsigned int buffer_size) {
    string virtualbox_startup_log;
    string::iterator iter;
    int retval = BOINC_SUCCESS;

    // Locate and read log file
    virtualbox_startup_log = vm_master_name + "/Logs/VBoxStartup.log";

    if (boinc_file_exists(virtualbox_startup_log.c_str())) {
        if (tail_only) {
            // Keep only the last 8k if it is larger than that.
            read_file_string(virtualbox_startup_log.c_str(), log, buffer_size, true);
        } else {
            read_file_string(virtualbox_startup_log.c_str(), log);
        }

        sanitize_output(log);

        if (tail_only) {
            if (log.size() >= (buffer_size - 115)) {
                // Look for the next whole line of text.
                iter = log.begin();
                while (iter != log.end()) {
                    if (*iter == '\n') {
                        log.erase(iter);
                        break;
                    }
                    iter = log.erase(iter);
                }
            }
        }

    }

    return retval;
}

int VBOX_BASE::read_floppy(std::string& data) {
    if (enable_floppyio && pFloppy) {
        data = pFloppy->receive();
        return 0;
    }
    return 1;
}

int VBOX_BASE::write_floppy(std::string& data) {
    if (enable_floppyio && pFloppy) {
        pFloppy->send(data);
        return 0;
    }
    return 1;
}

void VBOX_BASE::sanitize_format(std::string& output) {
    // Check for special characters used by printf and render them harmless
    string::iterator iter = output.begin();
    while (iter != output.end()) {
        if (*iter == '%') {
            // If we find '%', insert an additional '%' so that the we end up with
            // "%%" in its place.  This with cause printf() type functions to print
            // % within the formatted output.
            //
            iter = output.insert(iter+1, '%');
            ++iter;
        } else {
            ++iter;
        }
    }
}

#ifdef _WIN32
void VBOX_BASE::sanitize_output(std::string& output) {
    // Remove \r from the log spew
    string::iterator iter = output.begin();
    while (iter != output.end()) {
        if (*iter == '\r') {
            iter = output.erase(iter);
        } else {
            ++iter;
        }
    }
}
#else
void VBOX_BASE::sanitize_output(std::string& ) {}
#endif

// Launch VboxSVC.exe before going any further. if we don't, it'll be launched by
// svchost.exe with its environment block which will not contain the reference
// to VBOX_USER_HOME which is required for running in the BOINC account-based
// sandbox on Windows.
int VBOX_BASE::launch_vboxsvc() {
    APP_INIT_DATA aid;
    PROC_MAP pm;
    PROCINFO p;
    string command;
    int retval = ERR_EXEC;

#ifdef _WIN32
    char buf[256];
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    int pidVboxSvc = 0;
    HANDLE hVboxSvc = NULL;

    memset(&si, 0, sizeof(si));
    memset(&pi, 0, sizeof(pi));

    boinc_get_init_data_p(&aid);

    if (aid.using_sandbox) {

        if (!vboxsvc_pid_handle || !process_exists(vboxsvc_pid_handle)) {

            if (vboxsvc_pid_handle) CloseHandle(vboxsvc_pid_handle);

            procinfo_setup(pm);
            for (PROC_MAP::iterator i = pm.begin(); i != pm.end(); ++i) {
                p = i->second;

                // We are only looking for vboxsvc
                if (0 != stricmp(p.command, "vboxsvc.exe")) continue;

                // Store process id for later use
                pidVboxSvc = p.id;

                // Is this the vboxsvc for the current user?
                // Non-service install it would be the current username
                // Service install it would be boinc_project
                hVboxSvc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, p.id);
                if (hVboxSvc) break;
            }

            if (pidVboxSvc && hVboxSvc) {
                vboxlog_msg("Status Report: Detected vboxsvc.exe. (PID = '%d')", pidVboxSvc);
                vboxsvc_pid = pidVboxSvc;
                vboxsvc_pid_handle = hVboxSvc;
                retval = BOINC_SUCCESS;

            } else {

                si.cb = sizeof(STARTUPINFO);
                si.dwFlags |= STARTF_FORCEOFFFEEDBACK | STARTF_USESHOWWINDOW;
                si.wShowWindow = SW_HIDE;

                command = "\"VBoxSVC.exe\" --logrotate 1";

                CreateProcess(
                        NULL,
                        (LPTSTR)command.c_str(),
                        NULL,
                        NULL,
                        TRUE,
                        CREATE_NO_WINDOW,
                        NULL,
                        (LPTSTR)virtualbox_home_directory.c_str(),
                        &si,
                        &pi
                        );

                if (pi.hThread) CloseHandle(pi.hThread);
                if (pi.hProcess) {
                    vboxlog_msg("Status Report: Launching vboxsvc.exe. (PID = '%d')", pi.dwProcessId);
                    vboxsvc_pid = pi.dwProcessId;
                    vboxsvc_pid_handle = pi.hProcess;
                    retval = BOINC_SUCCESS;
                } else {
                    vboxlog_msg("Status Report: Launching vboxsvc.exe failed!.");
                    vboxlog_msg("        Error: %s", windows_format_error_string(GetLastError(), buf, sizeof(buf)));
#ifdef _DEBUG
                    vboxlog_msg("Vbox Version: '%s'", virtualbox_version_raw.c_str());
                    vboxlog_msg("Vbox Install Directory: '%s'", virtualbox_install_directory.c_str());
                    vboxlog_msg("Vbox Home Directory: '%s'", virtualbox_home_directory.c_str());
#endif
                }

                string s = string("");
                vbm_trace(command, s, retval);
            }
        }
    }
#endif

    return retval;
}

// Launch the VM.
int VBOX_BASE::launch_vboxvm() {
    char cmdline[1024];
    char* argv[5];
    int argc;
    std::string output;
    int retval = ERR_EXEC;

    // Construct the command line parameters
    //
    if (headless) {
        argv[0] = const_cast<char*>("VboxHeadless.exe");
    } else {
        argv[0] = const_cast<char*>("VirtualBox.exe");
    }
    argv[1] = const_cast<char*>("--startvm");
    argv[2] = const_cast<char*>(vm_name.c_str());
    if (headless) {
        argv[3] = const_cast<char*>("--vrde config");
    } else {
        argv[3] = const_cast<char*>("--no-startvm-errormsgbox");
    }
    argv[4] = NULL;
    argc = 4;

    strcpy(cmdline, "");
    for (int i=0; i<argc; i++) {
        strcat(cmdline, argv[i]);
        if (i<argc-1) {
            strcat(cmdline, " ");
        }
    }

#ifdef _WIN32
    char buf[256];
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    SECURITY_ATTRIBUTES sa;
    SECURITY_DESCRIPTOR sd;
    HANDLE hReadPipe = NULL, hWritePipe = NULL;
    void* pBuf = NULL;
    DWORD dwCount = 0;
    unsigned long ulExitCode = 0;
    unsigned long ulExitTimeout = 0;

    memset(&si, 0, sizeof(si));
    memset(&pi, 0, sizeof(pi));
    memset(&sa, 0, sizeof(sa));
    memset(&sd, 0, sizeof(sd));

    InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
    SetSecurityDescriptorDacl(&sd, true, NULL, false);

    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = &sd;

    if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, NULL)) {
        vboxlog_msg("CreatePipe failed! (%d).", GetLastError());
        goto CLEANUP;
    }
    SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0);

    si.cb = sizeof(STARTUPINFO);
    si.dwFlags |= STARTF_FORCEOFFFEEDBACK | STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    si.wShowWindow = SW_HIDE;
    si.hStdOutput = hWritePipe;
    si.hStdError = hWritePipe;
    si.hStdInput = NULL;

    // Execute command
    if (!CreateProcess(

                NULL, 
                cmdline,
                NULL,
                NULL,
                TRUE,
                CREATE_NO_WINDOW,
                NULL,
                NULL,
                &si,
                &pi

                )) {

        vboxlog_msg(
                "Status Report: Launching virtualbox.exe/vboxheadless.exe failed!."
                );
        vboxlog_msg(
                "        Error: %s (%d)",
                windows_format_error_string(GetLastError(), buf, sizeof(buf)),
                GetLastError()
                );
        goto CLEANUP;
    }

    while(1) {
        GetExitCodeProcess(pi.hProcess, &ulExitCode);

        // Copy stdout/stderr to output buffer, handle in the loop so that we can
        // copy the pipe as it is populated and prevent the child process from blocking
        // in case the output is bigger than pipe buffer.
        PeekNamedPipe(hReadPipe, NULL, NULL, NULL, &dwCount, NULL);
        if (dwCount) {
            pBuf = malloc(dwCount+1);
            memset(pBuf, 0, dwCount+1);

            if (ReadFile(hReadPipe, pBuf, dwCount, &dwCount, NULL)) {
                output += (char*)pBuf;
            }

            free(pBuf);
        }

        if ((ulExitCode != STILL_ACTIVE) || (ulExitTimeout >= 1000)) break;

        Sleep(250);
        ulExitTimeout += 250;
    }

    if (ulExitCode != STILL_ACTIVE) {
        sanitize_output(output);
        vboxlog_msg(
                "Status Report: Virtualbox.exe/Vboxheadless.exe exited prematurely!."
                );
        vboxlog_msg(
                "    Exit Code: %d",
                ulExitCode
                );
        vboxlog_msg(
                "       Output: %s",
                output.c_str()
                );
    }

    if (pi.hProcess && (ulExitCode == STILL_ACTIVE)) {
        vm_pid = pi.dwProcessId;
        vm_pid_handle = pi.hProcess;
        retval = BOINC_SUCCESS;
    }

CLEANUP:
    if (pi.hThread) CloseHandle(pi.hThread);
    if (hReadPipe) CloseHandle(hReadPipe);
    if (hWritePipe) CloseHandle(hWritePipe);

#else
    int pid = fork();
    if (-1 == pid) {
        vboxlog_msg(
                "Status Report: Launching virtualbox/vboxheadless failed!."
                );
        vboxlog_msg(
                "        Error: %s (%d)",
                strerror(errno),
                errno
                );
        retval = ERR_FORK;
    } else if (0 == pid) {
        if (-1 == execv(argv[0], argv)) {
            _exit(errno);
        }
    } else {
        vm_pid = pid;
        retval = BOINC_SUCCESS;
    }
#endif

    string cmd_line = cmdline;
    vbm_trace(cmd_line, output, retval);

    return retval;
}

// If there are errors we can recover from, process them here.
//
int VBOX_BASE::vbm_popen(string& command, string& output, const char* item, bool log_error, bool retry_failures, unsigned int timeout, bool log_trace) {
    int retval = 0;
    int retry_count = 0;
    double sleep_interval = 1.0;
    string retry_notes;

    // Initialize command line
    command = "VBoxManage -q " + command;

    do {
        retval = vbm_popen_raw(command, output , timeout);
        sanitize_output(command);
        sanitize_output(output);

        if (log_trace) {
            vbm_trace(command, output, retval);
        }

        if (retval) {

            // VirtualBox designed the concept of sessions to prevent multiple applications using
            // the VirtualBox COM API (virtualbox.exe, vboxmanage.exe) from modifying the same VM
            // at the same time.
            //
            // The problem here is that vboxwrapper uses vboxmanage.exe to modify and control the
            // VM.  Vboxmanage.exe can only maintain the session lock for as long as it takes it
            // to run.  So that means 99% of the time that a VM is running under BOINC technology
            // it is running without a session lock.
            //
            // If a volunteer opens another VirtualBox management application and goes poking around
            // that application can aquire the session lock and not give it up for some time.
            //
            // If we detect that condition retry the desired command.
            //
            // Experiments performed by jujube suggest changing the sleep interval to an exponential
            // style backoff would increase our chances of success in situations where the previous
            // lock is held by a previous instance of vboxmanage whos instance data hasn't been
            // cleaned up within vboxsvc yet.
            //
            // Error Code: VBOX_E_INVALID_OBJECT_STATE (0x80bb0007)
            //
            if (VBOX_E_INVALID_OBJECT_STATE == (unsigned int)retval) {
                if (retry_notes.find("Another VirtualBox management") == string::npos) {
                    retry_notes += "Another VirtualBox management application has locked the session for\n";
                    retry_notes += "this VM. BOINC cannot properly monitor this VM\n";
                    retry_notes += "and so this job will be aborted.\n\n";
                }
                if (retry_count) {
                    sleep_interval *= 2;
                }
            }

            // VboxManage has to be able to communicate with vboxsvc in order to actually issue a
            // command.  In cases where we detect CO_E_SERVER_EXEC_FAILURE, we should just automatically
            // try the command again.  Vboxmanage wasn't even able to issue the desired command
            // anyway.
            //
            // Experiments performed by jujube suggest changing the sleep interval to an exponential
            // style backoff would increase our chances of success.
            //
            // Error Code: CO_E_SERVER_EXEC_FAILURE (0x80080005)
            //
            if (CO_E_SERVER_EXEC_FAILURE == (unsigned int)retval) {
                if (retry_notes.find("Unable to communicate with VirtualBox") == string::npos) {
                    retry_notes += "Unable to communicate with VirtualBox.  VirtualBox may need to\n";
                    retry_notes += "be reinstalled.\n\n";
                }
                if (retry_count) {
                    sleep_interval *= 2;
                }
            }

            // Retry?

            if (!retry_failures && 
                    (VBOX_E_INVALID_OBJECT_STATE != (unsigned int)retval) && 
                    (CO_E_SERVER_EXEC_FAILURE != (unsigned int)retval)
               ) {
                break;
            }

            // Timeout?
            if (retry_count >= 5) break;

            retry_count++;
            boinc_sleep(sleep_interval);
        }
    }
    while (retval);

    // Add all relivent notes to the output string and log errors
    //
    if (retval && log_error) {
        if (!retry_notes.empty()) {
            output += "\nNotes:\n\n" + retry_notes;
        }
        vboxlog_msg(
                "Error in %s for VM: %d\nCommand:\n%s\nOutput:\n%s",
                item,
                retval,
                command.c_str(),
                output.c_str()
                );
    }

    return retval;
}

// Execute the vbox manage application and copy the output to the buffer.
//
int VBOX_BASE::vbm_popen_raw(
        string& command, string& output ,
#ifdef _WIN32
        unsigned int timeout
#else
        unsigned int
#endif
        ) {
    size_t errcode_start;
    size_t errcode_end;
    string errcode;
    int retval = BOINC_SUCCESS;

    // Reset output buffer
    output.clear();

#ifdef _WIN32

    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    SECURITY_ATTRIBUTES sa;
    SECURITY_DESCRIPTOR sd;
    HANDLE hReadPipe = NULL, hWritePipe = NULL;
    void* pBuf = NULL;
    DWORD dwCount = 0;
    unsigned long ulExitCode = 0;
    unsigned long ulExitTimeout = 0;

    memset(&si, 0, sizeof(si));
    memset(&pi, 0, sizeof(pi));
    memset(&sa, 0, sizeof(sa));
    memset(&sd, 0, sizeof(sd));

    InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
    SetSecurityDescriptorDacl(&sd, true, NULL, false);

    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = &sd;

    if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, NULL)) {
        vboxlog_msg("CreatePipe failed! (%d).", GetLastError());
        goto CLEANUP;
    }
    SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0);

    si.cb = sizeof(STARTUPINFO);
    si.dwFlags |= STARTF_FORCEOFFFEEDBACK | STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    si.wShowWindow = SW_HIDE;
    si.hStdOutput = hWritePipe;
    si.hStdError = hWritePipe;
    si.hStdInput = NULL;

    // Execute command
    if (!CreateProcess(

                NULL, 

                (LPTSTR)command.c_str(),
                NULL,
                NULL,
                TRUE,
                CREATE_NO_WINDOW,
                NULL,
                NULL,
                &si,
                &pi
                )) {

        vboxlog_msg("CreateProcess failed! (%d).", GetLastError());
        goto CLEANUP;
    }

    // Wait until process has completed
    while(1) {
        if (timeout == 0) {
            WaitForSingleObject(pi.hProcess, INFINITE);
        }

        GetExitCodeProcess(pi.hProcess, &ulExitCode);

        // Copy stdout/stderr to output buffer, handle in the loop so that we can
        // copy the pipe as it is populated and prevent the child process from blocking
        // in case the output is bigger than pipe buffer.
        PeekNamedPipe(hReadPipe, NULL, NULL, NULL, &dwCount, NULL);
        if (dwCount) {
            pBuf = malloc(dwCount+1);
            memset(pBuf, 0, dwCount+1);

            if (ReadFile(hReadPipe, pBuf, dwCount, &dwCount, NULL)) {
                output += (char*)pBuf;
            }

            free(pBuf);
        }

        if (ulExitCode != STILL_ACTIVE) break;

        // Timeout?
        if (ulExitTimeout >= (timeout * 1000)) {
            if (!TerminateProcess(pi.hProcess, EXIT_FAILURE)) {
                vboxlog_msg("TerminateProcess failed! (%d).", GetLastError());
            }
            ulExitCode = 0;
            retval = ERR_TIMEOUT;
            Sleep(1000);
        }

        Sleep(250);
        ulExitTimeout += 250;
    }

CLEANUP:
    if (pi.hThread) CloseHandle(pi.hThread);
    if (pi.hProcess) CloseHandle(pi.hProcess);
    if (hReadPipe) CloseHandle(hReadPipe);
    if (hWritePipe) CloseHandle(hWritePipe);

    if ((ulExitCode != 0) || (!pi.hProcess)) {

        // Determine the real error code by parsing the output
        errcode_start = output.find("(0x");
        if (errcode_start != string::npos) {
            errcode_start += 1;
            errcode_end = output.find(")", errcode_start);
            errcode = output.substr(errcode_start, errcode_end - errcode_start);

            sscanf(errcode.c_str(), "%x", &retval);
        }

        // If something couldn't be found, just return ERR_FOPEN
        if (!retval) retval = ERR_FOPEN;

    }

#else

    char buf[256];
    FILE* fp;

    // redirect stderr to stdout for the child process so we can trap it with popen.
    string modified_command = command + " 2>&1";

    // Execute command
    fp = popen(modified_command.c_str(), "r");
    if (fp == NULL) {
        vboxlog_msg("vbm_popen popen failed! (%d).", errno);
        retval = ERR_FOPEN;
    } else {
        // Copy output to buffer
        while (fgets(buf, 256, fp)) {
            output += buf;
        }

        // Close stream
        pclose(fp);

        // Determine the real error code by parsing the output
        errcode_start = output.find("(0x");
        if (errcode_start != string::npos) {
            errcode_start += 1;
            errcode_end = output.find(")", errcode_start);
            errcode = output.substr(errcode_start, errcode_end - errcode_start);

            sscanf(errcode.c_str(), "%x", &retval);
        }
    }

#endif

    // Is this a RPC_S_SERVER_UNAVAILABLE returned by vboxmanage?
    if (output.find("RPC_S_SERVER_UNAVAILABLE") != string::npos) {
        retval = RPC_S_SERVER_UNAVAILABLE;
    }

    return retval;
}

void VBOX_BASE::vbm_replay(std::string& command) {
    FILE* f = fopen(REPLAYLOG_FILENAME, "a");
    if (f) {
        fprintf(f, "%s\n", command.c_str());
        fclose(f);
    }
}

void VBOX_BASE::vbm_trace(std::string& command, std::string& output, int retval) {
    char buf[256];
    int pid;
    struct tm tm;

    vbm_replay(command);

    time_t x = time(0);
#ifdef _WIN32
    pid = GetCurrentProcessId();
    localtime_s(&tm, &x);
#else
    pid = getpid();
    localtime_r(&x, &tm);
#endif

    strftime(buf, sizeof(buf)-1, "%Y-%m-%d %H:%M:%S", &tm);

    FILE* f = fopen(TRACELOG_FILENAME, "a");
    if (f) {
        fprintf(
                f,
                "%s (%d): ",
                buf,
                pid
               );
        fprintf(
                f,
                "\nCommand: %s\nExit Code: %d\nOutput:\n%s\n",
                command.c_str(),
                retval,
                output.c_str()
               );
        fclose(f);
    }
}

VBOX_VM::VBOX_VM() {
}

VBOX_VM::~VBOX_VM() {
}