summaryrefslogtreecommitdiff
path: root/src/pal/src/debug/debug.cpp
blob: fa8aa3848ff5e51d51892802ecd7756562f57a3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
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
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. 
//

/*++



Module Name:

    debug.c

Abstract:

    Implementation of Win32 debugging API functions.

Revision History:



--*/

#ifndef BIT64
#undef _LARGEFILE64_SOURCE
#undef _FILE_OFFSET_BITS
#endif

#include "pal/thread.hpp"
#include "pal/procobj.hpp"
#include "pal/file.hpp"

#include "pal/palinternal.h"
#include "pal/dbgmsg.h"
#include "pal/process.h"
#include "pal/context.h"
#include "pal/debug.h"
#include "pal/misc.h"
#include "pal/malloc.hpp"
#include "pal/module.h"
#include "pal/stackstring.hpp"
#include "pal/virtual.h"

#include <signal.h>
#include <unistd.h>
#if HAVE_PROCFS_CTL
#include <unistd.h>
#elif HAVE_TTRACE // HAVE_PROCFS_CTL
#include <sys/ttrace.h>
#else // HAVE_TTRACE
#include <sys/ptrace.h>
#endif  // HAVE_PROCFS_CTL
#if HAVE_VM_READ
#include <mach/mach.h>
#endif  // HAVE_VM_READ
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

#if HAVE_PROCFS_H
#include <procfs.h>
#endif // HAVE_PROCFS_H

#if HAVE_MACH_EXCEPTIONS
#include "../exception/machexception.h"
#endif // HAVE_MACH_EXCEPTIONS

using namespace CorUnix;

SET_DEFAULT_DEBUG_CHANNEL(DEBUG);

extern "C" void DBG_DebugBreak_End();

#if HAVE_PROCFS_CTL
#define CTL_ATTACH      "attach"
#define CTL_DETACH      "detach"
#define CTL_WAIT        "wait"
#endif   // HAVE_PROCFS_CTL

/* ------------------- Constant definitions ----------------------------------*/

#if !HAVE_VM_READ && !HAVE_PROCFS_CTL
const BOOL DBG_ATTACH       = TRUE;
const BOOL DBG_DETACH       = FALSE;
#endif
static const char PAL_OUTPUTDEBUGSTRING[]    = "PAL_OUTPUTDEBUGSTRING";

#ifdef _DEBUG
#define ENABLE_RUN_ON_DEBUG_BREAK 1
#endif // _DEBUG

#ifdef ENABLE_RUN_ON_DEBUG_BREAK
static const char PAL_RUN_ON_DEBUG_BREAK[]   = "PAL_RUN_ON_DEBUG_BREAK";
#endif // ENABLE_RUN_ON_DEBUG_BREAK

/* ------------------- Static function prototypes ----------------------------*/

#if !HAVE_VM_READ && !HAVE_PROCFS_CTL && !HAVE_TTRACE
static int
DBGWriteProcMem_Int(DWORD processId, int *addr, int data);
static int
DBGWriteProcMem_IntWithMask(DWORD processId, int *addr, int data,
                            unsigned int mask);
#endif  // !HAVE_VM_READ && !HAVE_PROCFS_CTL && !HAVE_TTRACE

#if !HAVE_VM_READ && !HAVE_PROCFS_CTL

static BOOL 
DBGAttachProcess(CPalThread *pThread, HANDLE hProcess, DWORD dwProcessId);

static BOOL
DBGDetachProcess(CPalThread *pThread, HANDLE hProcess, DWORD dwProcessId);

static int
DBGSetProcessAttached(CPalThread *pThread, HANDLE hProcess, BOOL bAttach);

#endif // !HAVE_VM_READ && !HAVE_PROCFS_CTL

extern "C" {

/*++
Function:
  FlushInstructionCache

The FlushInstructionCache function flushes the instruction cache for
the specified process.

Remarks

This is a no-op for x86 architectures where the instruction and data
caches are coherent in hardware. For non-X86 architectures, this call
usually maps to a kernel API to flush the D-caches on all processors.

--*/
BOOL
PALAPI
FlushInstructionCache(
        IN HANDLE hProcess,
        IN LPCVOID lpBaseAddress,
        IN SIZE_T dwSize)
{
    BOOL Ret;

    PERF_ENTRY(FlushInstructionCache);
    ENTRY("FlushInstructionCache (hProcess=%p, lpBaseAddress=%p dwSize=%d)\
          \n", hProcess, lpBaseAddress, dwSize);

    if (lpBaseAddress != NULL)
    {
        Ret = DBG_FlushInstructionCache(lpBaseAddress, dwSize);
    }
    else
    {
        Ret = TRUE;
    }

    LOGEXIT("FlushInstructionCache returns BOOL %d\n", Ret);
    PERF_EXIT(FlushInstructionCache);
    return Ret;
}


/*++
Function:
  OutputDebugStringA

See MSDN doc.
--*/
VOID
PALAPI
OutputDebugStringA(
        IN LPCSTR lpOutputString)
{
    PERF_ENTRY(OutputDebugStringA);
    ENTRY("OutputDebugStringA (lpOutputString=%p (%s))\n",
          lpOutputString?lpOutputString:"NULL",
          lpOutputString?lpOutputString:"NULL");
    
    /* as we don't support debug events, we are going to output the debug string
      to stderr instead of generating OUT_DEBUG_STRING_EVENT */
    if ( (lpOutputString != NULL) && 
         (NULL != MiscGetenv(PAL_OUTPUTDEBUGSTRING)))
    {
        fprintf(stderr, "%s", lpOutputString);
    }
        
    LOGEXIT("OutputDebugStringA returns\n");
    PERF_EXIT(OutputDebugStringA);
}

/*++
Function:
  OutputDebugStringW

See MSDN doc.
--*/
VOID
PALAPI
OutputDebugStringW(
        IN LPCWSTR lpOutputString)
{
    CHAR *lpOutputStringA;
    int strLen;

    PERF_ENTRY(OutputDebugStringW);
    ENTRY("OutputDebugStringW (lpOutputString=%p (%S))\n",
          lpOutputString ? lpOutputString: W16_NULLSTRING,
          lpOutputString ? lpOutputString: W16_NULLSTRING);
    
    if (lpOutputString == NULL) 
    {
        OutputDebugStringA("");
        goto EXIT;
    }

    if ((strLen = WideCharToMultiByte(CP_ACP, 0, lpOutputString, -1, NULL, 0, 
                                      NULL, NULL)) 
        == 0)
    {
        ASSERT("failed to get wide chars length\n");
        SetLastError(ERROR_INTERNAL_ERROR);
        goto EXIT;
    }

    /* strLen includes the null terminator */
    if ((lpOutputStringA = (LPSTR) InternalMalloc((strLen * sizeof(CHAR)))) == NULL)
    {
        ERROR("Insufficient memory available !\n");
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        goto EXIT;
    }

    if(! WideCharToMultiByte(CP_ACP, 0, lpOutputString, -1, 
                             lpOutputStringA, strLen, NULL, NULL)) 
    {
        ASSERT("failed to convert wide chars to multibytes\n");
        SetLastError(ERROR_INTERNAL_ERROR);
        InternalFree(lpOutputStringA);
        goto EXIT;
    }
    
    OutputDebugStringA(lpOutputStringA);
    InternalFree(lpOutputStringA);

EXIT:
    LOGEXIT("OutputDebugStringW returns\n");
    PERF_EXIT(OutputDebugStringW);
}

#ifdef ENABLE_RUN_ON_DEBUG_BREAK
/*
   When DebugBreak() is called, if PAL_RUN_ON_DEBUG_BREAK is set,
   DebugBreak() will execute whatever command is in there.

   PAL_RUN_ON_DEBUG_BREAK must be no longer than 255 characters.

   This command string inherits the current process's environment,
   with two additions:
      PAL_EXE_PID  - the process ID of the current process
      PAL_EXE_NAME - the name of the executable of the current process

   When DebugBreak() runs this string, it periodically polls the child process
   and blocks until it finishes. If you use this mechanism to start a
   debugger, you can break this poll loop by setting the "spin" variable in
   run_debug_command()'s frame to 0, and then the parent process can
   continue.

   suggested values for PAL_RUN_ON_DEBUG_BREAK:
     to halt the process for later inspection:
       'echo stopping $PAL_EXE_PID; kill -STOP $PAL_EXE_PID; sleep 10'

     to print out the stack trace:
       'pstack $PAL_EXE_PID'

     to invoke the gdb debugger on the process:
       'set -x; gdb $PAL_EXE_NAME $PAL_EXE_PID'

     to invoke the ddd debugger on the process (requires X11):
       'set -x; ddd $PAL_EXE_NAME $PAL_EXE_PID'
*/

static
int
run_debug_command (const char *command)
{
    int pid;
    Volatile<int> spin = 1;

    if (!command) {
        return 1;
    }

    printf("Spawning command: %s\n", command);
    
    pid = fork();
    if (pid == -1) {
        return -1;
    }
    if (pid == 0) {
        const char *argv[4] = { "sh", "-c", command, 0 };
        execv("/bin/sh", (char **)argv);
        exit(127);
    }

    /* We continue either when the spawned process has stopped, or when
       an attached debugger sets spin to 0 */
    while (spin != 0) {
        int status = 0;
        int ret = waitpid(pid, &status, WNOHANG);
        if (ret == 0) {
            int i;
            /* I tried to use sleep for this, and that works everywhere except
               FreeBSD. The problem on FreeBSD is that if the process gets a
               signal while blocked in sleep(), gdb is confused by the stack */
            for (i = 0; i < 1000000; i++)
                ;
        }
        else if (ret == -1) {
            if (errno != EINTR) {
                return -1;
            }
        }
        else if (WIFEXITED(status)) {
            return WEXITSTATUS(status);
        }
        else {
            fprintf (stderr, "unexpected return from waitpid\n");
            return -1;
        }
    };
    return 0;
}
#endif // ENABLE_RUN_ON_DEBUG_BREAK

#define PID_TEXT "PAL_EXE_PID="
#define EXE_TEXT "PAL_EXE_NAME="

static
int
DebugBreakCommand()
{
#ifdef ENABLE_RUN_ON_DEBUG_BREAK
    extern MODSTRUCT exe_module;
    const char *command_string = getenv (PAL_RUN_ON_DEBUG_BREAK);
    if (command_string) {
        char pid_buf[sizeof (PID_TEXT) + 32];
        PathCharString exe_bufString;
        int libNameLength = 10;
        if (exe_module.lib_name != NULL)
        {
            libNameLength = PAL_wcslen(exe_module.lib_name);
        }
        
        SIZE_T dwexe_buf = strlen(EXE_TEXT) + libNameLength + 1;
        CHAR * exe_buf = exe_bufString.OpenStringBuffer(dwexe_buf);
        
        if (NULL == exe_buf)
        {
            goto FAILED;
        }

        if (snprintf (pid_buf, sizeof (pid_buf), PID_TEXT "%d", getpid()) <= 0) {
            goto FAILED;
        }
        if (snprintf (exe_buf, sizeof (CHAR) * (dwexe_buf + 1), EXE_TEXT "%ls", (wchar_t *)exe_module.lib_name) <= 0) {
            goto FAILED;
        }

        exe_bufString.CloseBuffer(dwexe_buf);
        /* strictly speaking, we might want to only set these environment
           variables in the child process, but if we do that we can't check
           for errors. putenv/setenv can fail when out of memory */

        if (!MiscPutenv (pid_buf, FALSE) || !MiscPutenv (exe_buf, FALSE)) {
            goto FAILED;
        }
        if (run_debug_command (command_string)) {
            goto FAILED;
        }
        return 1;
    }
    return 0;
FAILED:
    fprintf (stderr, "Failed to execute command: '%s'\n", command_string);
    return -1;
#else // ENABLE_RUN_ON_DEBUG_BREAK
    return 0;
#endif // ENABLE_RUN_ON_DEBUG_BREAK
}

/*++
Function:
  DebugBreak

See MSDN doc.
--*/
VOID
PALAPI
DebugBreak(
       VOID)
{
    PERF_ENTRY(DebugBreak);
    ENTRY("DebugBreak()\n");

    if (DebugBreakCommand() <= 0) {
        // either didn't do anything, or failed
        TRACE("Calling DBG_DebugBreak\n");
        DBG_DebugBreak();
    }
    
    LOGEXIT("DebugBreak returns\n");
    PERF_EXIT(DebugBreak);
}

/*++
Function:
  IsInDebugBreak(addr)

  Returns true if the address is in DBG_DebugBreak.

--*/
BOOL
IsInDebugBreak(void *addr)
{
    return (addr >= (void *)DBG_DebugBreak) && (addr <= (void *)DBG_DebugBreak_End);
}

/*++
Function:
  GetThreadContext

See MSDN doc.
--*/
BOOL
PALAPI
GetThreadContext(
           IN HANDLE hThread,
           IN OUT LPCONTEXT lpContext)
{
    PAL_ERROR palError;
    CPalThread *pThread;
    CPalThread *pTargetThread;
    IPalObject *pobjThread = NULL;
    BOOL ret = FALSE;
    
    PERF_ENTRY(GetThreadContext);
    ENTRY("GetThreadContext (hThread=%p, lpContext=%p)\n",hThread,lpContext);

    pThread = InternalGetCurrentThread();

    palError = InternalGetThreadDataFromHandle(
        pThread,
        hThread,
        0, // THREAD_GET_CONTEXT
        &pTargetThread,
        &pobjThread
        );

    if (NO_ERROR == palError)
    {
        if (!pTargetThread->IsDummy())
        {
            ret = CONTEXT_GetThreadContext(
                GetCurrentProcessId(),
                pTargetThread->GetPThreadSelf(),
                lpContext
                );
        }
        else
        {
            ASSERT("Dummy thread handle passed to GetThreadContext\n");
            pThread->SetLastError(ERROR_INVALID_HANDLE);
        }
    }
    else
    {
        pThread->SetLastError(palError);
    }

    if (NULL != pobjThread)
    {
        pobjThread->ReleaseReference(pThread);
    }
    
    LOGEXIT("GetThreadContext returns ret:%d\n", ret);
    PERF_EXIT(GetThreadContext);
    return ret;
}

/*++
Function:
  SetThreadContext

See MSDN doc.
--*/
BOOL
PALAPI
SetThreadContext(
           IN HANDLE hThread,
           IN CONST CONTEXT *lpContext)
{
    PAL_ERROR palError;
    CPalThread *pThread;
    CPalThread *pTargetThread;
    IPalObject *pobjThread = NULL;
    BOOL ret = FALSE;
    
    PERF_ENTRY(SetThreadContext);
    ENTRY("SetThreadContext (hThread=%p, lpContext=%p)\n",hThread,lpContext);

    pThread = InternalGetCurrentThread();

    palError = InternalGetThreadDataFromHandle(
        pThread,
        hThread,
        0, // THREAD_SET_CONTEXT
        &pTargetThread,
        &pobjThread
        );

    if (NO_ERROR == palError)
    {
        if (!pTargetThread->IsDummy())
        {
            ret = CONTEXT_SetThreadContext(
                GetCurrentProcessId(),
                pTargetThread->GetPThreadSelf(),
                lpContext
                );
        }
        else
        {
            ASSERT("Dummy thread handle passed to SetThreadContext\n");
            pThread->SetLastError(ERROR_INVALID_HANDLE);
        }
    }
    else
    {
        pThread->SetLastError(palError);
    }

    if (NULL != pobjThread)
    {
        pobjThread->ReleaseReference(pThread);
    }
        
    return ret;
}

/*++
Function:
  ReadProcessMemory

See MSDN doc.
--*/
BOOL
PALAPI
ReadProcessMemory(
           IN HANDLE hProcess,
           IN LPCVOID lpBaseAddress,
           IN LPVOID lpBuffer,
           IN SIZE_T nSize,
           OUT SIZE_T * lpNumberOfBytesRead
           )
{
    CPalThread *pThread;
    DWORD processId;
    Volatile<BOOL> ret = FALSE;
    Volatile<SIZE_T> numberOfBytesRead = 0;
#if HAVE_VM_READ
    kern_return_t result;
    vm_map_t task;
    LONG_PTR bytesToRead;
#elif HAVE_PROCFS_CTL
    int fd;
    char memPath[64];
    off_t offset;
#elif !HAVE_TTRACE
    SIZE_T nbInts;
    int* ptrInt;
    int* lpTmpBuffer;
#endif
#if !HAVE_PROCFS_CTL && !HAVE_TTRACE
    int* lpBaseAddressAligned;
    SIZE_T offset;
#endif  // !HAVE_PROCFS_CTL && !HAVE_TTRACE

    PERF_ENTRY(ReadProcessMemory);
    ENTRY("ReadProcessMemory (hProcess=%p,lpBaseAddress=%p, lpBuffer=%p, "
          "nSize=%u, lpNumberOfBytesRead=%p)\n",hProcess,lpBaseAddress,
          lpBuffer, (unsigned int)nSize, lpNumberOfBytesRead);

    pThread = InternalGetCurrentThread();
    
    if (!(processId = PROCGetProcessIDFromHandle(hProcess)))
    {
        ERROR("Invalid process handler hProcess:%p.",hProcess);
        SetLastError(ERROR_INVALID_HANDLE);        
        goto EXIT;
    }
    
    // Check if the read request is for the current process. 
    // We don't need ptrace in that case.
    if (GetCurrentProcessId() == processId) 
    {
        TRACE("We are in the same process, so ptrace is not needed\n");
        
        struct Param
        {
            LPCVOID lpBaseAddress;
            LPVOID lpBuffer;
            SIZE_T nSize;
            SIZE_T numberOfBytesRead;
            BOOL ret;
        } param;
        param.lpBaseAddress = lpBaseAddress;
        param.lpBuffer = lpBuffer;
        param.nSize = nSize;
        param.numberOfBytesRead = numberOfBytesRead;
        param.ret = ret;

        PAL_TRY(Param *, pParam, &param)
        {
            SIZE_T i;
            
            // Seg fault in memcpy can't be caught
            // so we simulate the memcpy here

            for (i = 0; i<pParam->nSize; i++)
            {
                *((char*)(pParam->lpBuffer)+i) = *((char*)(pParam->lpBaseAddress)+i);
            }

            pParam->numberOfBytesRead = pParam->nSize;
            pParam->ret = TRUE;
        }
        PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
        {
            SetLastError(ERROR_ACCESS_DENIED);
        }
        PAL_ENDTRY

        numberOfBytesRead = param.numberOfBytesRead;
        ret = param.ret;
        goto EXIT;        
    }

#if HAVE_VM_READ
    result = task_for_pid(mach_task_self(), processId, &task);
    if (result != KERN_SUCCESS)
    {
        ERROR("No Mach task for pid %d: %d\n", processId, ret.Load());
        SetLastError(ERROR_INVALID_HANDLE);
        goto EXIT;
    }
    // vm_read_overwrite usually requires that the address be page-aligned
    // and the size be a multiple of the page size.  We can't differentiate
    // between the cases in which that's required and those in which it
    // isn't, so we do it all the time.
    lpBaseAddressAligned = (int*)((SIZE_T) lpBaseAddress & ~VIRTUAL_PAGE_MASK);
    offset = ((SIZE_T) lpBaseAddress & VIRTUAL_PAGE_MASK);
    char *data;
    data = (char*)alloca(VIRTUAL_PAGE_SIZE);
    while (nSize > 0)
    {
        vm_size_t bytesRead;
        
        bytesToRead = VIRTUAL_PAGE_SIZE - offset;
        if (bytesToRead > (LONG_PTR)nSize)
        {
            bytesToRead = nSize;
        }
        bytesRead = VIRTUAL_PAGE_SIZE;
        result = vm_read_overwrite(task, (vm_address_t) lpBaseAddressAligned,
                                   VIRTUAL_PAGE_SIZE, (vm_address_t) data, &bytesRead);
        if (result != KERN_SUCCESS || bytesRead != VIRTUAL_PAGE_SIZE)
        {
            ERROR("vm_read_overwrite failed for %d bytes from %p in %d: %d\n",
                  VIRTUAL_PAGE_SIZE, (char *) lpBaseAddressAligned, task, result);
            if (result <= KERN_RETURN_MAX)
            {
                SetLastError(ERROR_INVALID_ACCESS);
            }
            else
            {
                SetLastError(ERROR_INTERNAL_ERROR);
            }
            goto EXIT;
        }
        memcpy((LPSTR)lpBuffer + numberOfBytesRead, data + offset, bytesToRead);
        numberOfBytesRead.Store(numberOfBytesRead.Load() + bytesToRead);
        lpBaseAddressAligned = (int*)((char*)lpBaseAddressAligned + VIRTUAL_PAGE_SIZE);
        nSize -= bytesToRead;
        offset = 0;
    }
    ret = TRUE;
#else   // HAVE_VM_READ
#if HAVE_PROCFS_CTL
    snprintf(memPath, sizeof(memPath), "/proc/%u/%s", processId, PROCFS_MEM_NAME);
    fd = InternalOpen(memPath, O_RDONLY);
    if (fd == -1)
    {
        ERROR("Failed to open %s\n", memPath);
        SetLastError(ERROR_INVALID_ACCESS);
        goto PROCFSCLEANUP;
    }

    //
    // off_t may be greater in size than void*, so first cast to
    // an unsigned type to ensure that no sign extension takes place
    //

    offset = (off_t) (UINT_PTR) lpBaseAddress;

    if (lseek(fd, offset, SEEK_SET) == -1)
    {
        ERROR("Failed to seek to base address\n");
        SetLastError(ERROR_INVALID_ACCESS);
        goto PROCFSCLEANUP;
    }
    
    numberOfBytesRead = read(fd, lpBuffer, nSize);
    ret = TRUE;

#else   // HAVE_PROCFS_CTL
    // Attach the process before calling ttrace/ptrace otherwise it fails.
    if (DBGAttachProcess(pThread, hProcess, processId))
    {
#if HAVE_TTRACE
        if (ttrace(TT_PROC_RDDATA, processId, 0, (__uint64_t)lpBaseAddress, (__uint64_t)nSize, (__uint64_t)lpBuffer) == -1)
        {
            if (errno == EFAULT) 
            {
                ERROR("ttrace(TT_PROC_RDDATA, pid:%d, 0, addr:%p, data:%d, addr2:%d) failed"
                      " errno=%d (%s)\n", processId, lpBaseAddress, (int)nSize, lpBuffer,
                      errno, strerror(errno));
                
                SetLastError(ERROR_ACCESS_DENIED);
            }
            else
            {
                ASSERT("ttrace(TT_PROC_RDDATA, pid:%d, 0, addr:%p, data:%d, addr2:%d) failed"
                      " errno=%d (%s)\n", processId, lpBaseAddress, (int)nSize, lpBuffer,
                      errno, strerror(errno));
                SetLastError(ERROR_INTERNAL_ERROR);
            }

            goto CLEANUP1;
        }

        numberOfBytesRead = nSize;
        ret = TRUE;
        
#else   // HAVE_TTRACE

        offset = (SIZE_T)lpBaseAddress % sizeof(int);
        lpBaseAddressAligned =  (int*)((char*)lpBaseAddress - offset);
        nbInts = (nSize + offset)/sizeof(int) + 
                 ((nSize + offset)%sizeof(int) ? 1:0);
        
        /* before transferring any data to lpBuffer we should make sure that all 
           data is accessible for read. so we need to use a temp buffer for that.*/
        if (!(lpTmpBuffer = (int*)InternalMalloc((nbInts * sizeof(int)))))
        {
            ERROR("Insufficient memory available !\n");
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            goto CLEANUP1;
        }
        
        for (ptrInt = lpTmpBuffer; nbInts; ptrInt++,
            lpBaseAddressAligned++, nbInts--)
        {
            errno = 0;
            *ptrInt =
                PAL_PTRACE(PAL_PT_READ_D, processId, lpBaseAddressAligned, 0);
            if (*ptrInt == -1 && errno) 
            {
                if (errno == EFAULT) 
                {
                    ERROR("ptrace(PT_READ_D, pid:%d, addr:%p, data:0) failed"
                          " errno=%d (%s)\n", processId, lpBaseAddressAligned,
                          errno, strerror(errno));
                    
                    SetLastError(ptrInt == lpTmpBuffer ? ERROR_ACCESS_DENIED : 
                                                         ERROR_PARTIAL_COPY);
                }
                else
                {
                    ASSERT("ptrace(PT_READ_D, pid:%d, addr:%p, data:0) failed"
                          " errno=%d (%s)\n", processId, lpBaseAddressAligned,
                          errno, strerror(errno));
                    SetLastError(ERROR_INTERNAL_ERROR);
                }
                
                goto CLEANUP2;
            }
        }
        
        /* transfer data from temp buffer to lpBuffer */
        memcpy( (char *)lpBuffer, ((char*)lpTmpBuffer) + offset, nSize);
        numberOfBytesRead = nSize;
        ret = TRUE;
#endif // HAVE_TTRACE        
    }
    else
    {
        /* Failed to attach processId */
        goto EXIT;    
    }
#endif  // HAVE_PROCFS_CTL

#if HAVE_PROCFS_CTL
PROCFSCLEANUP:
    if (fd != -1)
    {
        close(fd);
    }    
#elif !HAVE_TTRACE
CLEANUP2:
    if (lpTmpBuffer) 
    {
        InternalFree(lpTmpBuffer);
    }
#endif  // !HAVE_TTRACE

#if !HAVE_PROCFS_CTL
CLEANUP1:
    if (!DBGDetachProcess(pThread, hProcess, processId))
    {
        /* Failed to detach processId */
        ret = FALSE;
    }
#endif  // HAVE_PROCFS_CTL
#endif  // HAVE_VM_READ

EXIT:
    if (lpNumberOfBytesRead)
    {
        *lpNumberOfBytesRead = numberOfBytesRead;
    }
    LOGEXIT("ReadProcessMemory returns BOOL %d\n", ret.Load());
    PERF_EXIT(ReadProcessMemory);
    return ret;
}

/*++
Function:
  WriteProcessMemory

See MSDN doc.
--*/
BOOL
PALAPI
WriteProcessMemory(
           IN HANDLE hProcess,
           IN LPVOID lpBaseAddress,
           IN LPCVOID lpBuffer,
           IN SIZE_T nSize,
           OUT SIZE_T * lpNumberOfBytesWritten
           )

{
    CPalThread *pThread;
    DWORD processId;
    Volatile<BOOL> ret = FALSE;
    Volatile<SIZE_T> numberOfBytesWritten = 0;
#if HAVE_VM_READ
    kern_return_t result;
    vm_map_t task;
#elif HAVE_PROCFS_CTL
    int fd;
    char memPath[64];
    LONG_PTR bytesWritten;
    off_t offset;
#elif !HAVE_TTRACE
    SIZE_T FirstIntOffset;
    SIZE_T LastIntOffset;
    unsigned int FirstIntMask;
    unsigned int LastIntMask;
    SIZE_T nbInts;
    int *lpTmpBuffer = 0, *lpInt;
    int* lpBaseAddressAligned;
#endif

    PERF_ENTRY(WriteProcessMemory);
    ENTRY("WriteProcessMemory (hProcess=%p,lpBaseAddress=%p, lpBuffer=%p, "
           "nSize=%u, lpNumberOfBytesWritten=%p)\n",
           hProcess,lpBaseAddress, lpBuffer, (unsigned int)nSize, lpNumberOfBytesWritten); 

    pThread = InternalGetCurrentThread();
    
    if (!(nSize && (processId = PROCGetProcessIDFromHandle(hProcess))))
    {
        ERROR("Invalid nSize:%u number or invalid process handler "
              "hProcess:%p\n", (unsigned int)nSize, hProcess);
        SetLastError(ERROR_INVALID_PARAMETER);
        goto EXIT;
    }
    
    // Check if the write request is for the current process.
    // In that case we don't need ptrace.
    if (GetCurrentProcessId() == processId) 
    {
        TRACE("We are in the same process so we don't need ptrace\n");
        
        struct Param
        {
            LPVOID lpBaseAddress;
            LPCVOID lpBuffer;
            SIZE_T nSize;
            SIZE_T numberOfBytesWritten;
            BOOL ret;
        } param;
        param.lpBaseAddress = lpBaseAddress;
        param.lpBuffer = lpBuffer;
        param.nSize = nSize;
        param.numberOfBytesWritten = numberOfBytesWritten;
        param.ret = ret;

        PAL_TRY(Param *, pParam, &param)
        {
            SIZE_T i;
            
            // Seg fault in memcpy can't be caught
            // so we simulate the memcpy here

            for (i = 0; i<pParam->nSize; i++)
            {
                *((char*)(pParam->lpBaseAddress)+i) = *((char*)(pParam->lpBuffer)+i);
            }

            pParam->numberOfBytesWritten = pParam->nSize;
            pParam->ret = TRUE;
        } 
        PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
        {
            SetLastError(ERROR_ACCESS_DENIED);
        }
        PAL_ENDTRY

        numberOfBytesWritten = param.numberOfBytesWritten;
        ret = param.ret;
        goto EXIT;        
    }

#if HAVE_VM_READ
    result = task_for_pid(mach_task_self(), processId, &task);
    if (result != KERN_SUCCESS)
    {
        ERROR("No Mach task for pid %d: %d\n", processId, ret.Load());
        SetLastError(ERROR_INVALID_HANDLE);
        goto EXIT;
    }
    result = vm_write(task, (vm_address_t) lpBaseAddress, 
                      (vm_address_t) lpBuffer, nSize);
    if (result != KERN_SUCCESS)
    {
        ERROR("vm_write failed for %d bytes from %p in %d: %d\n",
              (int)nSize, lpBaseAddress, task, result);
        if (result <= KERN_RETURN_MAX)
        {
            SetLastError(ERROR_ACCESS_DENIED);
        }
        else
        {
            SetLastError(ERROR_INTERNAL_ERROR);
        }
        goto EXIT;
    }
    numberOfBytesWritten = nSize;
    ret = TRUE;
#else   // HAVE_VM_READ
#if HAVE_PROCFS_CTL
    snprintf(memPath, sizeof(memPath), "/proc/%u/%s", processId, PROCFS_MEM_NAME);
    fd = InternalOpen(memPath, O_WRONLY);
    if (fd == -1)
    {
        ERROR("Failed to open %s\n", memPath);
        SetLastError(ERROR_INVALID_ACCESS);
        goto PROCFSCLEANUP;
    }

    //
    // off_t may be greater in size than void*, so first cast to
    // an unsigned type to ensure that no sign extension takes place
    //

    offset = (off_t) (UINT_PTR) lpBaseAddress;

    if (lseek(fd, offset, SEEK_SET) == -1)
    {
        ERROR("Failed to seek to base address\n");
        SetLastError(ERROR_INVALID_ACCESS);
        goto PROCFSCLEANUP;
    }
    
    bytesWritten = write(fd, lpBuffer, nSize);
    if (bytesWritten < 0)
    {
        ERROR("Failed to write to %s\n", memPath);
        SetLastError(ERROR_INVALID_ACCESS);
        goto PROCFSCLEANUP;
    }

    numberOfBytesWritten = bytesWritten;
    ret = TRUE;

#else   // HAVE_PROCFS_CTL
    /* Attach the process before calling ptrace otherwise it fails */
    if (DBGAttachProcess(pThread, hProcess, processId))
    {
#if HAVE_TTRACE
        if (ttrace(TT_PROC_WRDATA, processId, 0, (__uint64_t)lpBaseAddress, (__uint64_t)nSize, (__uint64_t)lpBuffer) == -1)
        {
            if (errno == EFAULT) 
            {
                ERROR("ttrace(TT_PROC_WRDATA, pid:%d, addr:%p, data:%d, addr2:%d) failed"
                      " errno=%d (%s)\n", processId, lpBaseAddress, nSize, lpBuffer,
                      errno, strerror(errno));
                
                SetLastError(ERROR_ACCESS_DENIED);
            }
            else
            {
                ASSERT("ttrace(TT_PROC_WRDATA, pid:%d, addr:%p, data:%d, addr2:%d) failed"
                      " errno=%d (%s)\n", processId, lpBaseAddress, nSize, lpBuffer,
                      errno, strerror(errno));
                SetLastError(ERROR_INTERNAL_ERROR);
            }

            goto CLEANUP1;
        }

        numberOfBytesWritten = nSize;
        ret = TRUE;
        
#else   // HAVE_TTRACE

        FirstIntOffset = (SIZE_T)lpBaseAddress % sizeof(int);    
        FirstIntMask = -1;
        FirstIntMask <<= (FirstIntOffset * 8);
        
        nbInts = (nSize + FirstIntOffset) / sizeof(int) + 
                 (((nSize + FirstIntOffset)%sizeof(int)) ? 1:0);
        lpBaseAddressAligned = (int*)((char*)lpBaseAddress - FirstIntOffset);
        
        if ((lpTmpBuffer = (int*)InternalMalloc((nbInts * sizeof(int)))) == NULL)
        {
            ERROR("Insufficient memory available !\n");
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            goto CLEANUP1;
        }

        memcpy((char *)lpTmpBuffer + FirstIntOffset, (char *)lpBuffer, nSize);
        lpInt = lpTmpBuffer;

        LastIntOffset = (nSize + FirstIntOffset) % sizeof(int);
        LastIntMask = -1;
        LastIntMask >>= ((sizeof(int) - LastIntOffset) * 8);

        if (nbInts == 1)
        {
            if (DBGWriteProcMem_IntWithMask(processId, lpBaseAddressAligned, 
                                            *lpInt,
                                            LastIntMask & FirstIntMask)
                  == 0)
            {
                goto CLEANUP2;
            }
            numberOfBytesWritten = nSize;
            ret = TRUE;
            goto CLEANUP2;
        }

        if (DBGWriteProcMem_IntWithMask(processId,
                                        lpBaseAddressAligned++,
                                        *lpInt++, FirstIntMask) 
            == 0)
        {
            goto CLEANUP2;
        }

        while (--nbInts > 1)
        {      
          if (DBGWriteProcMem_Int(processId, lpBaseAddressAligned++,
                                  *lpInt++) == 0)
          {
              goto CLEANUP2;
          }
        }
        
        if (DBGWriteProcMem_IntWithMask(processId, lpBaseAddressAligned,
                                        *lpInt, LastIntMask ) == 0)
        {
            goto CLEANUP2;
        }

        numberOfBytesWritten = nSize;
        ret = TRUE;
#endif  // HAVE_TTRACE
    }
    else
    {
        /* Failed to attach processId */
        goto EXIT;
    }
#endif // HAVE_PROCFS_CTL

#if HAVE_PROCFS_CTL
PROCFSCLEANUP:
    if (fd != -1)
    {
        close(fd);
    }
#elif !HAVE_TTRACE
CLEANUP2:
    if (lpTmpBuffer) 
    {
        InternalFree(lpTmpBuffer);
    }
#endif  // !HAVE_TTRACE

#if !HAVE_PROCFS_CTL
CLEANUP1:
    if (!DBGDetachProcess(pThread, hProcess, processId))
    {
        /* Failed to detach processId */
        ret = FALSE;
    }
#endif  // !HAVE_PROCFS_CTL
#endif  // HAVE_VM_READ

EXIT:
    if (lpNumberOfBytesWritten)
    {
        *lpNumberOfBytesWritten = numberOfBytesWritten;
    }

    LOGEXIT("WriteProcessMemory returns BOOL %d\n", ret.Load());
    PERF_EXIT(WriteProcessMemory);
    return ret;
}

#if !HAVE_VM_READ && !HAVE_PROCFS_CTL && !HAVE_TTRACE
/*++
Function:
  DBGWriteProcMem_Int

Abstract
  write one int to a process memory address

Parameter
  processId : process handle
  addr : memory address where the int should be written
  data : int to be written in addr

Return
  Return 1 if it succeeds, or 0 if it's fails
--*/
static
int
DBGWriteProcMem_Int(IN DWORD processId, 
                    IN int *addr,
                    IN int data)
{
    if (PAL_PTRACE( PAL_PT_WRITE_D, processId, addr, data ) == -1)
    {
        if (errno == EFAULT) 
        {
            ERROR("ptrace(PT_WRITE_D, pid:%d caddr_t:%p data:%x) failed "
                  "errno:%d (%s)\n", processId, addr, data, errno, strerror(errno));
            SetLastError(ERROR_INVALID_ADDRESS);
        }
        else
        {
            ASSERT("ptrace(PT_WRITE_D, pid:%d caddr_t:%p data:%x) failed "
                  "errno:%d (%s)\n", processId, addr, data, errno, strerror(errno));
            SetLastError(ERROR_INTERNAL_ERROR);
        }
        return 0;
    }

    return 1;
}

/*++
Function:
  DBGWriteProcMem_IntWithMask

Abstract
  write one int to a process memory address space using mask

Parameter
  processId : process ID
  addr : memory address where the int should be written
  data : int to be written in addr
  mask : the mask used to write only a parts of data

Return
  Return 1 if it succeeds, or 0 if it's fails
--*/
static
int
DBGWriteProcMem_IntWithMask(IN DWORD processId,
                            IN int *addr,
                            IN int data,
                            IN unsigned int mask )
{
    int readInt;

    if (mask != ~0)
    {
        errno = 0;
        if (((readInt = PAL_PTRACE( PAL_PT_READ_D, processId, addr, 0 )) == -1)
             && errno)
        {
            if (errno == EFAULT) 
            {
                ERROR("ptrace(PT_READ_D, pid:%d, caddr_t:%p, 0) failed "
                      "errno:%d (%s)\n", processId, addr, errno, strerror(errno));
                SetLastError(ERROR_INVALID_ADDRESS);
            }
            else
            {
                ASSERT("ptrace(PT_READ_D, pid:%d, caddr_t:%p, 0) failed "
                      "errno:%d (%s)\n", processId, addr, errno, strerror(errno));
                SetLastError(ERROR_INTERNAL_ERROR);
            }

            return 0;
        }
        data = (data & mask) | (readInt & ~mask);
    }    
    return DBGWriteProcMem_Int(processId, addr, data);
}
#endif  // !HAVE_VM_READ && !HAVE_PROCFS_CTL && !HAVE_TTRACE

#if !HAVE_VM_READ && !HAVE_PROCFS_CTL

/*++
Function:
  DBGAttachProcess

Abstract  
  
  Attach the indicated process to the current process. 
  
  if the indicated process is already attached by the current process, then 
  increment the number of attachment pending. if ot, attach it to the current 
  process (with PT_ATTACH).

Parameter
  hProcess : handle to process to attach to
  processId : process ID to attach
Return
  Return true if it succeeds, or false if it's fails
--*/
static
BOOL 
DBGAttachProcess(
    CPalThread *pThread,
    HANDLE hProcess,
    DWORD processId
    )
{
    int attchmentCount;
    int savedErrno;
#if HAVE_PROCFS_CTL
    int fd;
    char ctlPath[1024];
#endif  // HAVE_PROCFS_CTL

    attchmentCount = 
        DBGSetProcessAttached(pThread, hProcess, DBG_ATTACH);

    if (attchmentCount == -1)
    {
        /* Failed to set the process as attached */
        goto EXIT;
    }
    
    if (attchmentCount == 1)
    {
#if HAVE_PROCFS_CTL
        struct timespec waitTime;

        // FreeBSD has some trouble when a series of attach/detach sequences
        // occurs too close together.  When this happens, we'll be able to
        // attach to the process, but waiting for the process to stop
        // (either via writing "wait" to /proc/<pid>/ctl or via waitpid)
        // will hang.  If we pause for a very short amount of time before
        // trying to attach, we don't run into this situation.
        waitTime.tv_sec = 0;
        waitTime.tv_nsec = 50000000;
        nanosleep(&waitTime, NULL);
        
        sprintf_s(ctlPath, sizeof(ctlPath), "/proc/%d/ctl", processId);
        fd = InternalOpen(ctlPath, O_WRONLY);
        if (fd == -1)
        {
            ERROR("Failed to open %s: errno is %d (%s)\n", ctlPath,
                  errno, strerror(errno));
            goto DETACH1;
        }
        
        if (write(fd, CTL_ATTACH, sizeof(CTL_ATTACH)) < (int)sizeof(CTL_ATTACH))
        {
            ERROR("Failed to attach to %s: errno is %d (%s)\n", ctlPath,
                  errno, strerror(errno));
            close(fd);
            goto DETACH1;
        }
        
        if (write(fd, CTL_WAIT, sizeof(CTL_WAIT)) < (int)sizeof(CTL_WAIT))
        {
            ERROR("Failed to wait for %s: errno is %d (%s)\n", ctlPath,
                  errno, strerror(errno));
            goto DETACH2;
        }
        
        close(fd);
#elif HAVE_TTRACE
        if (ttrace(TT_PROC_ATTACH, processId, 0, TT_DETACH_ON_EXIT, TT_VERSION, 0) == -1)
        {
            if (errno != ESRCH)
            {                
                ASSERT("ttrace(TT_PROC_ATTACH, pid:%d) failed errno:%d (%s)\n",
                     processId, errno, strerror(errno));
            }
            goto DETACH1;
        }
#else   // HAVE_TTRACE
        if (PAL_PTRACE( PAL_PT_ATTACH, processId, 0, 0 ) == -1)
        {
            if (errno != ESRCH)
            {                
                ASSERT("ptrace(PT_ATTACH, pid:%d) failed errno:%d (%s)\n",
                     processId, errno, strerror(errno));
            }
            goto DETACH1;
        }
                    
        if (waitpid(processId, NULL, WUNTRACED) == -1)
        {
            if (errno != ESRCH)
            {
                ASSERT("waitpid(pid:%d, NULL, WUNTRACED) failed.errno:%d"
                       " (%s)\n", processId, errno, strerror(errno));
            }
            goto DETACH2;
        }
#endif  // HAVE_PROCFS_CTL
    }
    
    return TRUE;

#if HAVE_PROCFS_CTL
DETACH2:
    if (write(fd, CTL_DETACH, sizeof(CTL_DETACH)) < (int)sizeof(CTL_DETACH))
    {
        ASSERT("Failed to detach from %s: errno is %d (%s)\n", ctlPath,
               errno, strerror(errno));
    }
    close(fd);
#elif !HAVE_TTRACE
DETACH2:
    if (PAL_PTRACE(PAL_PT_DETACH, processId, 0, 0) == -1)
    {
        ASSERT("ptrace(PT_DETACH, pid:%d) failed. errno:%d (%s)\n", processId, 
              errno, strerror(errno));
    }
#endif  // HAVE_PROCFS_CTL

DETACH1:
    savedErrno = errno;
    DBGSetProcessAttached(pThread, hProcess, DBG_DETACH);
    errno = savedErrno;
EXIT:
    if (errno == ESRCH || errno == ENOENT || errno == EBADF)
    {
        ERROR("Invalid process ID:%d\n", processId);
        SetLastError(ERROR_INVALID_PARAMETER);
    }
    else
    {
        SetLastError(ERROR_INTERNAL_ERROR);
    }
    return FALSE;
}

/*++
Function:
  DBGDetachProcess

Abstract
  Detach the indicated process from the current process.
  
  if the indicated process is already attached by the current process, then 
  decrement the number of attachment pending and detach it from the current 
  process (with PT_DETACH) if there's no more attachment left. 
  
Parameter
  hProcess : process handle
  processId : process ID

Return
  Return true if it succeeds, or true if it's fails
--*/
static
BOOL
DBGDetachProcess(
    CPalThread *pThread,
    HANDLE hProcess,
    DWORD processId
    )
{     
    int nbAttachLeft;
#if HAVE_PROCFS_CTL
    int fd;
    char ctlPath[1024];
#endif  // HAVE_PROCFS_CTL

    nbAttachLeft = DBGSetProcessAttached(pThread, hProcess, DBG_DETACH);    

    if (nbAttachLeft == -1)
    {
        /* Failed to set the process as detached */
        return FALSE;
    }
    
    /* check if there's no more attachment left on processId */
    if (nbAttachLeft == 0)
    {
#if HAVE_PROCFS_CTL
        sprintf(ctlPath, sizeof(ctlPath), "/proc/%d/ctl", processId);
        fd = InternalOpen(pThread, ctlPath, O_WRONLY);
        if (fd == -1)
        {
            if (errno == ENOENT)
            {
                ERROR("Invalid process ID: %d\n", processId);
                SetLastError(ERROR_INVALID_PARAMETER);
            }
            else
            {
                ERROR("Failed to open %s: errno is %d (%s)\n", ctlPath,
                      errno, strerror(errno));
                SetLastError(ERROR_INTERNAL_ERROR);
            }
            return FALSE;
        }
        
        if (write(fd, CTL_DETACH, sizeof(CTL_DETACH)) < (int)sizeof(CTL_DETACH))
        {
            ERROR("Failed to detach from %s: errno is %d (%s)\n", ctlPath,
                  errno, strerror(errno));
            close(fd);
            return FALSE;
        }
        close(fd);

#elif HAVE_TTRACE  
        if (ttrace(TT_PROC_DETACH, processId, 0, 0, 0, 0) == -1)
        {
            if (errno == ESRCH)
            {
                ERROR("Invalid process ID: %d\n", processId);
                SetLastError(ERROR_INVALID_PARAMETER);
            }
            else
            {
                ASSERT("ttrace(TT_PROC_DETACH, pid:%d) failed. errno:%d (%s)\n", 
                      processId, errno, strerror(errno));
                SetLastError(ERROR_INTERNAL_ERROR);
            }
            return FALSE;
        }
#else   // HAVE_TTRACE
        if (PAL_PTRACE(PAL_PT_DETACH, processId, 1, 0) == -1)
        {            
            if (errno == ESRCH)
            {
                ERROR("Invalid process ID: %d\n", processId);
                SetLastError(ERROR_INVALID_PARAMETER);
            }
            else
            {
                ASSERT("ptrace(PT_DETACH, pid:%d) failed. errno:%d (%s)\n", 
                      processId, errno, strerror(errno));
                SetLastError(ERROR_INTERNAL_ERROR);
            }
            return FALSE;
        }
#endif  // HAVE_PROCFS_CTL

#if !HAVE_TTRACE
        if (kill(processId, SIGCONT) == -1)
        {
            ERROR("Failed to continue the detached process:%d errno:%d (%s)\n",
                  processId, errno, strerror(errno));
            return FALSE;
        }
#endif  // !HAVE_TTRACE        
    }
    return TRUE;
}

/*++
Function:
  DBGSetProcessAttached

Abstract
  saves the current process Id in the attached process structure

Parameter
  hProcess : process handle
  bAttach : true (false) to set the process as attached (as detached)
Return
 returns the number of attachment left on attachedProcId, or -1 if it fails
--*/
static int
DBGSetProcessAttached(
    CPalThread *pThread,
    HANDLE hProcess,
    BOOL  bAttach
    )
{
    PAL_ERROR palError = NO_ERROR;
    IPalObject *pobjProcess = NULL;
    IDataLock *pDataLock = NULL;
    CProcProcessLocalData *pLocalData = NULL;
    int ret = -1;
    CAllowedObjectTypes aotProcess(otiProcess);

    palError = g_pObjectManager->ReferenceObjectByHandle(
        pThread,
        hProcess,
        &aotProcess,
        0,
        &pobjProcess
        );

    if (NO_ERROR != palError)
    {
        goto DBGSetProcessAttachedExit;
    }

    palError = pobjProcess->GetProcessLocalData(
        pThread,
        WriteLock,
        &pDataLock,
        reinterpret_cast<void **>(&pLocalData)
        );

    if (NO_ERROR != palError)
    {
        goto DBGSetProcessAttachedExit;
    }

    if (bAttach)
    {
        pLocalData->lAttachCount += 1;
    }
    else
    {
        pLocalData->lAttachCount -= 1;

        if (pLocalData->lAttachCount < 0)
        {
            ASSERT("pLocalData->lAttachCount < 0 check for extra DBGDetachProcess calls\n");
            palError = ERROR_INTERNAL_ERROR;
            goto DBGSetProcessAttachedExit;
        }
    }

    ret = pLocalData->lAttachCount;
    
DBGSetProcessAttachedExit:

    if (NULL != pDataLock)
    {
        pDataLock->ReleaseLock(pThread, TRUE);
    }

    if (NULL != pobjProcess)
    {
        pobjProcess->ReleaseReference(pThread);
    }
    
    return ret;
}

#endif // !HAVE_VM_READ && !HAVE_PROCFS_CTL

/*++
Function:
  PAL_CreateExecWatchpoint

Abstract
  Creates an OS exec watchpoint for the specified instruction
  and thread. This function should only be called on architectures
  that do not support a hardware single-step mode (e.g., SPARC).

Parameter
  hThread : the thread for which the watchpoint is to apply
  pvInstruction : the instruction on which the watchpoint is to be set

Return
  A Win32 error code
--*/

DWORD
PAL_CreateExecWatchpoint(
    HANDLE hThread,
    PVOID pvInstruction
    )
{
    PERF_ENTRY(PAL_CreateExecWatchpoint);
    ENTRY("PAL_CreateExecWatchpoint (hThread=%p, pvInstruction=%p)\n", hThread, pvInstruction);

    DWORD dwError = ERROR_NOT_SUPPORTED;

#if HAVE_PRWATCH_T

    CPalThread *pThread = NULL;
    CPalThread *pTargetThread = NULL;
    IPalObject *pobjThread = NULL;
    int fd = -1;
    char ctlPath[50];

    struct
    {
        long ctlCode;
        prwatch_t prwatch;
    } ctlStruct;

    //
    // We must never set a watchpoint on an instruction that enters a syscall;
    // if such a request comes in we succeed it w/o actually creating the
    // watchpoint. This mirrors the behavior of setting the single-step flag
    // in a thread context when the thread is w/in a system service -- the
    // flag is ignored and will not be present when the thread returns
    // to user mode.
    //

#if defined(_SPARC_)
    if (*(DWORD*)pvInstruction == 0x91d02008) // ta 8
    {
        TRACE("Watchpoint requested on sysenter instruction -- ignoring");
        dwError = ERROR_SUCCESS;
        goto PAL_CreateExecWatchpointExit;        
    }
#else
#error Need syscall instruction for this platform
#endif // _SPARC_

    pThread = InternalGetCurrentThread();

    dwError = InternalGetThreadDataFromHandle(
        pThread,
        hThread,
        0, // THREAD_SET_CONTEXT
        &pTargetThread,
        &pobjThread
        );

    if (NO_ERROR != dwError)
    {
        goto PAL_CreateExecWatchpointExit;
    }

    snprintf(ctlPath, sizeof(ctlPath), "/proc/%u/lwp/%u/lwpctl", getpid(), pTargetThread->GetLwpId());

    fd = InternalOpen(pThread, ctlPath, O_WRONLY);
    if (-1 == fd)
    {
        ERROR("Failed to open %s\n", ctlPath);
        dwError = ERROR_INVALID_ACCESS;
        goto PAL_CreateExecWatchpointExit;
    }

    ctlStruct.ctlCode = PCWATCH;
    ctlStruct.prwatch.pr_vaddr = (uintptr_t) pvInstruction;
    ctlStruct.prwatch.pr_size = sizeof(DWORD);
    ctlStruct.prwatch.pr_wflags = WA_EXEC | WA_TRAPAFTER;

    if (write(fd, (void*) &ctlStruct, sizeof(ctlStruct)) != sizeof(ctlStruct))
    {
        ERROR("Failure writing control structure (errno = %u)\n", errno);
        dwError = ERROR_INTERNAL_ERROR;
        goto PAL_CreateExecWatchpointExit;
    }

    dwError = ERROR_SUCCESS;
    
PAL_CreateExecWatchpointExit:

    if (NULL != pobjThread)
    {
        pobjThread->ReleaseReference(pThread);
    }

    if (-1 != fd)
    {
        close(fd);
    }

#endif // HAVE_PRWATCH_T     
    
    LOGEXIT("PAL_CreateExecWatchpoint returns ret:%d\n", dwError);
    PERF_EXIT(PAL_CreateExecWatchpoint);
    return dwError;
}

/*++
Function:
  PAL_DeleteExecWatchpoint

Abstract
  Deletes an OS exec watchpoint for the specified instruction
  and thread. This function should only be called on architectures
  that do not support a hardware single-step mode (e.g., SPARC).

Parameter
  hThread : the thread to remove the watchpoint from
  pvInstruction : the instruction for which the watchpoint is to be removed

Return
  A Win32 error code. Attempting to delete a watchpoint that does not exist
  may or may not result in an error, depending on the behavior of the
  underlying operating system.
--*/

DWORD
PAL_DeleteExecWatchpoint(
    HANDLE hThread,
    PVOID pvInstruction
    )
{
    PERF_ENTRY(PAL_DeleteExecWatchpoint);
    ENTRY("PAL_DeleteExecWatchpoint (hThread=%p, pvInstruction=%p)\n", hThread, pvInstruction);

    DWORD dwError = ERROR_NOT_SUPPORTED;

#if HAVE_PRWATCH_T

    CPalThread *pThread = NULL;
    CPalThread *pTargetThread = NULL;
    IPalObject *pobjThread = NULL;
    int fd = -1;
    char ctlPath[50];

    struct
    {
        long ctlCode;
        prwatch_t prwatch;
    } ctlStruct;


    pThread = InternalGetCurrentThread();

    dwError = InternalGetThreadDataFromHandle(
        pThread,
        hThread,
        0, // THREAD_SET_CONTEXT
        &pTargetThread,
        &pobjThread
        );

    if (NO_ERROR != dwError)
    {
        goto PAL_DeleteExecWatchpointExit;
    }

    snprintf(ctlPath, sizeof(ctlPath), "/proc/%u/lwp/%u/lwpctl", getpid(), pTargetThread->GetLwpId());

    fd = InternalOpen(pThread, ctlPath, O_WRONLY);
    if (-1 == fd)
    {
        ERROR("Failed to open %s\n", ctlPath);
        dwError = ERROR_INVALID_ACCESS;
        goto PAL_DeleteExecWatchpointExit;
    }

    ctlStruct.ctlCode = PCWATCH;
    ctlStruct.prwatch.pr_vaddr = (uintptr_t) pvInstruction;
    ctlStruct.prwatch.pr_size = sizeof(DWORD);
    ctlStruct.prwatch.pr_wflags = 0;

    if (write(fd, (void*) &ctlStruct, sizeof(ctlStruct)) != sizeof(ctlStruct))
    {
        ERROR("Failure writing control structure (errno = %u)\n", errno);
        dwError = ERROR_INTERNAL_ERROR;
        goto PAL_DeleteExecWatchpointExit;
    }

    dwError = ERROR_SUCCESS;
    
PAL_DeleteExecWatchpointExit:

    if (NULL != pobjThread)
    {
        pobjThread->ReleaseReference(pThread);
    }

    if (-1 != fd)
    {
        close(fd);
    }

#endif // HAVE_PRWATCH_T    
    
    LOGEXIT("PAL_DeleteExecWatchpoint returns ret:%d\n", dwError);
    PERF_EXIT(PAL_DeleteExecWatchpoint);
    return dwError;
}

} // extern "C"