-
Notifications
You must be signed in to change notification settings - Fork 24
/
Hatrace.hs
1657 lines (1399 loc) · 65.9 KB
/
Hatrace.hs
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
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
-- | Note about __safety of ptrace() in multi-threaded tracers__:
--
-- You must not call @ptrace(pid, ...)@ from an OS thread that's not the
-- tracer of @pid@. Otherwise you'll get an @ESRCH@ error (@No such process@).
--
-- So you must use `runInBoundThread` or @forkOS` around functions from this
-- module, unless their docs indicate that they already do this for you.
module System.Hatrace
( traceForkProcess
, traceForkExecvFullPath
, sourceTraceForkExecvFullPathWithSink
, procToArgv
, forkExecvWithPtrace
, printSyscallOrSignalNameConduit
, SyscallEnterDetails_open(..)
, SyscallExitDetails_open(..)
, SyscallEnterDetails_openat(..)
, SyscallExitDetails_openat(..)
, SyscallEnterDetails_creat(..)
, SyscallExitDetails_creat(..)
, SyscallEnterDetails_pipe(..)
, SyscallExitDetails_pipe(..)
, SyscallEnterDetails_pipe2(..)
, SyscallExitDetails_pipe2(..)
, SyscallEnterDetails_write(..)
, SyscallExitDetails_write(..)
, SyscallEnterDetails_read(..)
, SyscallExitDetails_read(..)
, SyscallEnterDetails_rename(..)
, SyscallExitDetails_rename(..)
, SyscallEnterDetails_renameat(..)
, SyscallExitDetails_renameat(..)
, SyscallEnterDetails_renameat2(..)
, SyscallExitDetails_renameat2(..)
, SyscallEnterDetails_execve(..)
, SyscallExitDetails_execve(..)
, DetailedSyscallEnter(..)
, DetailedSyscallExit(..)
, ERRNO(..)
, foreignErrnoToERRNO
, getSyscallEnterDetails
, syscallEnterDetailsOnlyConduit
, syscallExitDetailsOnlyConduit
, FileWriteEvent(..)
, fileWritesConduit
, FileWriteBehavior(..)
, atomicWritesSink
, SyscallStopType(..)
, TraceEvent(..)
, TraceState(..)
, Syscall(..)
, SyscallArgs(..)
, sendSignal
, doesProcessHaveChildren
, getFdPath
, getExePath
-- * Re-exports
, KnownSyscall(..)
) where
import Conduit (foldlC)
import Control.Arrow (second)
import Control.Monad (when)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.IO.Unlift (MonadUnliftIO)
import Data.Bits ((.|.), (.&.), shiftL, shiftR)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Internal as BSI
import Data.Conduit
import qualified Data.Conduit.List as CL
import Data.Either (partitionEithers)
import Data.List (genericLength)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Word (Word32, Word64)
import Foreign.C.Error (Errno(..), throwErrnoIfMinus1, throwErrnoIfMinus1_, getErrno, resetErrno, eCHILD, eINVAL)
import Foreign.C.String (peekCString)
import Foreign.C.Types (CInt(..), CLong(..), CULong(..), CChar(..), CSize(..))
import Foreign.ForeignPtr (withForeignPtr)
import Foreign.Marshal.Alloc (alloca)
import Foreign.Marshal.Array (withArray)
import Foreign.Marshal.Utils (withMany)
import Foreign.Ptr (Ptr, nullPtr, wordPtrToPtr)
import Foreign.Storable (peekByteOff, sizeOf)
import GHC.Stack (HasCallStack, callStack, getCallStack, prettySrcLoc)
import System.Directory (canonicalizePath, doesFileExist, findExecutable)
import System.Exit (ExitCode(..), die)
import System.FilePath ((</>))
import System.IO.Error (modifyIOError, ioeGetLocation, ioeSetLocation)
import System.Linux.Ptrace (TracedProcess(..), peekBytes, peekNullTerminatedBytes, peekNullWordTerminatedWords, detach)
import System.Linux.Ptrace.Syscall hiding (ptrace_syscall, ptrace_detach)
import qualified System.Linux.Ptrace.Syscall as Ptrace.Syscall
import System.Linux.Ptrace.Types (Regs(..))
import System.Linux.Ptrace.X86_64Regs (X86_64Regs(..))
import System.Linux.Ptrace.X86Regs (X86Regs(..))
import System.Posix.Files (readSymbolicLink)
import System.Posix.Internals (withFilePath)
import System.Posix.Signals (Signal, sigTRAP, sigSTOP, sigTSTP, sigTTIN, sigTTOU)
import qualified System.Posix.Signals as Signals
import System.Posix.Types (CPid(..), CMode(..))
import System.Posix.Waitpid (waitpid, waitpidFullStatus, Status(..), FullStatus(..), Flag(..))
import UnliftIO.Concurrent (runInBoundThread)
import UnliftIO.IORef (newIORef, writeIORef, readIORef)
import System.Hatrace.SyscallTables.Generated (KnownSyscall(..), syscallName, syscallMap_i386, syscallMap_x64_64)
mapLeft :: (a1 -> a2) -> Either a1 b -> Either a2 b
mapLeft f = either (Left . f) Right
-- | Not using "Foreign.C.Error"'s `Errno` because it doesn't have a `Show`
-- instance, which would be a pain for consumers of our API.
--
-- Use `foreignErrnoToERRNO` to convert between them.
newtype ERRNO = ERRNO CInt
deriving (Eq, Ord, Show)
-- | Turn a "Foreign.C.Error" `Errno` into `ERRNO`.
foreignErrnoToERRNO :: Errno -> ERRNO
foreignErrnoToERRNO (Errno e) = ERRNO e
-- | Adds some prefix (separated by @: @) to the error location of an `IOError`.
addIOErrorPrefix :: String -> IO a -> IO a
addIOErrorPrefix prefix action = do
modifyIOError (\e -> ioeSetLocation e (prefix ++ ": " ++ ioeGetLocation e)) action
-- | We generally use this function to make it more obvious via what kind of
-- invocation of ptrace() it failed, because it's very easy to get
-- ptrace calls wrong. Without this, you'd just get
--
-- > ptrace: does not exist (No such process)
--
-- for pretty much any wrong invocation.
-- By adding the location to the exception, these
-- details show up in our test suite and our users' error messages.
--
-- Note that where possible, use a single invocation of this function
-- instead of nested invocations, so that the exception has to be caught
-- and rethrown as few times as possible.
annotatePtrace :: String -> IO a -> IO a
annotatePtrace = addIOErrorPrefix
-- | Wrapper around `Ptrace.System.ptrace_syscall` that prints its name in
-- `IOError`s it raises.
ptrace_syscall :: (HasCallStack) => CPid -> Maybe Signal -> IO ()
ptrace_syscall pid mbSignal = do
let debugCallLocation = if
| False -> -- set this to True to get caller source code lines for failures
-- Put the top-most call stack caller into the error message
concat
[ prettySrcLoc srcLoc
| (_, srcLoc):_ <- [getCallStack callStack]
] ++ " (pid " ++ show pid ++ "): "
| otherwise -> ""
annotatePtrace (debugCallLocation ++ "ptrace_syscall") $
Ptrace.Syscall.ptrace_syscall pid mbSignal
-- | Wrapper around `Ptrace.System.detach` that prints its name in
-- `IOError`s it raises.
ptrace_detach :: CPid -> IO ()
ptrace_detach pid = annotatePtrace "ptrace_detach" $ detach (TracedProcess pid)
waitpidForExactPidStopOrError :: (HasCallStack) => CPid -> IO ()
waitpidForExactPidStopOrError pid = do
mr <- waitpid pid []
case mr of
Nothing -> error "waitpidForExactPidStopOrError: BUG: no PID was returned by waitpid"
Just (returnedPid, status)
| returnedPid /= pid -> error $ "waitpidForExactPidStopOrError: BUG: returned PID != expected pid: " ++ show (returnedPid, pid)
| otherwise ->
case status of
Stopped sig | sig == sigSTOP -> return () -- all OK
-- TODO: This seems to happen when we ourselves (the tracer) are being `strace`d. Investigate.
_ -> error $ "waitpidForExactPidStopOrError: BUG: unexpected status: " ++ show status
foreign import ccall safe "fork_exec_with_ptrace" c_fork_exec_with_ptrace :: CInt -> Ptr (Ptr CChar) -> IO CPid
-- | Forks a tracee process, makes it PTRACE_TRACEME and then SIGSTOP itself.
-- Waits for the tracee process to have entered the STOPPED state.
-- After waking up from the stop (as controlled by the tracer, that is,
-- other functions you'll use after calling this one),
-- the tracee will execv() the given program with arguments.
--
-- Since execv() is used, the first argument must be the /full path/
-- to the executable.
forkExecvWithPtrace :: (HasCallStack) => [String] -> IO CPid
forkExecvWithPtrace args = do
childPid <- withMany withFilePath args $ \cstrs -> do
withArray cstrs $ \argsPtr -> do
let argc = genericLength args
throwErrnoIfMinus1 "fork_exec_with_ptrace" $ c_fork_exec_with_ptrace argc argsPtr
-- Wait for the tracee to stop itself
waitpidForExactPidStopOrError childPid
return childPid
-- | A conduit that starts a traced process from given @args@, and yields all
-- trace events that occur to it.
--
-- Already uses `runInBoundThread` internally, so using this ensures that you
-- don't accidentally run a @ptrace()@ call from an OS thread that's not the
-- tracer of the started process.
sourceTraceForkExecvFullPathWithSink :: (MonadUnliftIO m) => [String] -> ConduitT (CPid, TraceEvent) Void m a -> m (ExitCode, a)
sourceTraceForkExecvFullPathWithSink args sink = runInBoundThread $ do
childPid <- liftIO $ forkExecvWithPtrace args
-- Now the child is stopped. Set options, then start it.
liftIO $ annotatePtrace "ptrace_setoptions" $ ptrace_setoptions childPid
-- Set `PTRACE_O_TRACESYSGOOD` to make it easy for the tracer
-- to distinguish normal traps from those caused by a syscall.
[ TraceSysGood
-- Set `PTRACE_O_EXITKILL` so that if we crash, everything below
-- also terminates.
, ExitKill
-- Tracing child processes
, TraceClone
, TraceFork
, TraceVFork
, TraceVForkDone
-- Sign up for the various PTRACE_EVENT_* events we want to handle below.
, TraceExec
, TraceExit
]
-- Start the child.
liftIO $ ptrace_syscall childPid Nothing
exitCodeRef <- newIORef (Nothing :: Maybe ExitCode)
let loop state = do
(newState, (returnedPid, event)) <- liftIO $ waitForTraceEvent state
yield (returnedPid, event)
-- Cases in which we have to restart the tracee
-- (by calling `ptrace_syscall` again).
liftIO $ case event of
SyscallStop _enterOrExit -> do
-- Tell the process to continue into / out of the syscall,
-- and generate another event at the next syscall or signal.
ptrace_syscall returnedPid Nothing
PTRACE_EVENT_Stop _ptraceEvent -> do
-- Continue past the event.
ptrace_syscall returnedPid Nothing
-- As discussed in the docs of PTRACE_EVENT_EXIT, even for that
-- event the child is still alive and needs to be restarted
-- before it truly exits.
GroupStop sig -> do
-- Continue past the event.
ptrace_syscall returnedPid (Just sig)
SignalDeliveryStop sig -> do
-- Deliver the signal
ptrace_syscall returnedPid (Just sig)
Death _exitCode -> return () -- can't restart it, it's dead
-- The program runs.
-- It is in this section of the code where the traced program actually runs:
-- between `ptrace_syscall` and `waitForTraceEvent`'s waitpid()' returning
-- (this statement is of course only accurate for single-threaded programs
-- without child processes; otherwise multiple things can be running).
case event of
Death exitCode | returnedPid == childPid -> do
-- Our direct child exited, we are done.
-- TODO: Figure out how to handle the situation that our
-- direct child exits when children are still alive
-- (because it didn't reap them or because they
-- double-forked to daemonize).
writeIORef exitCodeRef (Just exitCode)
-- no further `loop`ing
_ -> do
loop newState
a <- runConduit $ loop initialTraceState .| sink
mExitCode <- readIORef exitCodeRef
finalExitCode <- liftIO $ case mExitCode of
Just e -> pure e
Nothing -> do
-- If the child hasn't exited yet, Detach from it and let it run
-- to an end.
-- TODO: We probably have to do that for all tracees.
preDetachWaitpidResult <- waitpid childPid []
case preDetachWaitpidResult of
Nothing -> error "sourceTraceForkExecvFullPathWithSink: BUG: no PID was returned by waitpid"
Just{} -> do
-- TODO as the man page says:
-- PTRACE_DETACH is a restarting operation; therefore it requires the tracee to be in ptrace-stop.
-- We need to ensure/check we're in a ptrace-stop here.
-- Further from the man page:
-- If the tracee is running when the tracer wants to detach it, the usual
-- solution is to send SIGSTOP (using tgkill(2), to make sure it goes to
-- the correct thread), wait for the tracee to stop in
-- signal-delivery-stop for SIGSTOP and then detach it (suppressing
-- SIGSTOP injection). A design bug is that this can race with concurrent
-- SIGSTOPs. Another complication is that the tracee may enter other
-- ptrace-stops and needs to be restarted and waited for again, until
-- SIGSTOP is seen. Yet another complication is to be sure that the
-- tracee is not already ptrace-stopped, because no signal delivery
-- happens while it is—not even SIGSTOP.
ptrace_detach childPid
waitpidResult <- waitpidFullStatus childPid []
case waitpidResult of
Nothing -> error "sourceTraceForkExecvFullPathWithSink: BUG: no PID was returned by waitpid"
Just (_returnedPid, status, FullStatus fullStatus) -> case status of
Exited 0 -> pure ExitSuccess
_ -> pure $ ExitFailure (fromIntegral fullStatus)
return (finalExitCode, a)
wordToPtr :: Word -> Ptr a
wordToPtr w = wordPtrToPtr (fromIntegral w)
{-# INLINE wordToPtr #-}
word64ToPtr :: Word64 -> Ptr a
word64ToPtr w = wordPtrToPtr (fromIntegral w)
{-# INLINE word64ToPtr #-}
-- * Syscall details
--
-- __Note:__ The data types below use @DuplicateRecordFields@.
--
-- Users should also use @DuplicateRecordFields@ to avoid getting
-- @Ambiguous occurrence@ errors.
data SyscallEnterDetails_open = SyscallEnterDetails_open
{ pathname :: Ptr CChar
, flags :: CInt
, mode :: CMode
-- Peeked details
, pathnameBS :: ByteString
} deriving (Eq, Ord, Show)
data SyscallExitDetails_open = SyscallExitDetails_open
{ enterDetail :: SyscallEnterDetails_open
, fd :: CInt
} deriving (Eq, Ord, Show)
data SyscallEnterDetails_openat = SyscallEnterDetails_openat
{ dirfd :: CInt
, pathname :: Ptr CChar
, flags :: CInt
, mode :: CMode
-- Peeked details
, pathnameBS :: ByteString
} deriving (Eq, Ord, Show)
data SyscallExitDetails_openat = SyscallExitDetails_openat
{ enterDetail :: SyscallEnterDetails_openat
, fd :: CInt
} deriving (Eq, Ord, Show)
data SyscallEnterDetails_creat = SyscallEnterDetails_creat
{ pathname :: Ptr CChar
, mode :: CMode
-- Peeked details
, pathnameBS :: ByteString
} deriving (Eq, Ord, Show)
data SyscallExitDetails_creat = SyscallExitDetails_creat
{ enterDetail :: SyscallEnterDetails_creat
, fd :: CInt
} deriving (Eq, Ord, Show)
data SyscallEnterDetails_pipe = SyscallEnterDetails_pipe
{ pipefd :: Ptr CInt
} deriving (Eq, Ord, Show)
data SyscallExitDetails_pipe = SyscallExitDetails_pipe
{ enterDetail :: SyscallEnterDetails_pipe
, readfd :: CInt
, writefd :: CInt
} deriving (Eq, Ord, Show)
data SyscallEnterDetails_pipe2 = SyscallEnterDetails_pipe2
{ pipefd :: Ptr CInt
, flags :: CInt
} deriving (Eq, Ord, Show)
data SyscallExitDetails_pipe2 = SyscallExitDetails_pipe2
{ enterDetail :: SyscallEnterDetails_pipe2
, readfd :: CInt
, writefd :: CInt
} deriving (Eq, Ord, Show)
data SyscallEnterDetails_write = SyscallEnterDetails_write
{ fd :: CInt
, buf :: Ptr Void
, count :: CSize
-- Peeked details
, bufContents :: ByteString
} deriving (Eq, Ord, Show)
data SyscallExitDetails_write = SyscallExitDetails_write
{ enterDetail :: SyscallEnterDetails_write
, writtenCount :: CSize
} deriving (Eq, Ord, Show)
data SyscallEnterDetails_read = SyscallEnterDetails_read
{ fd :: CInt
, buf :: Ptr Void
, count :: CSize
} deriving (Eq, Ord, Show)
data SyscallExitDetails_read = SyscallExitDetails_read
{ enterDetail :: SyscallEnterDetails_read
-- Peeked details
, readCount :: CSize
, bufContents :: ByteString
} deriving (Eq, Ord, Show)
data SyscallEnterDetails_close = SyscallEnterDetails_close
{ fd :: CInt
} deriving (Eq, Ord, Show)
data SyscallExitDetails_close = SyscallExitDetails_close
{ enterDetail :: SyscallEnterDetails_close
} deriving (Eq, Ord, Show)
data SyscallEnterDetails_rename = SyscallEnterDetails_rename
{ oldpath :: Ptr CChar
, newpath :: Ptr CChar
-- Peeked details
, oldpathBS :: ByteString
, newpathBS :: ByteString
} deriving (Eq, Ord, Show)
data SyscallExitDetails_rename = SyscallExitDetails_rename
{ enterDetail :: SyscallEnterDetails_rename
} deriving (Eq, Ord, Show)
data SyscallEnterDetails_renameat = SyscallEnterDetails_renameat
{ olddirfd :: CInt
, oldpath :: Ptr CChar
, newdirfd :: CInt
, newpath :: Ptr CChar
-- Peeked details
, oldpathBS :: ByteString
, newpathBS :: ByteString
} deriving (Eq, Ord, Show)
data SyscallExitDetails_renameat = SyscallExitDetails_renameat
{ enterDetail :: SyscallEnterDetails_renameat
} deriving (Eq, Ord, Show)
data SyscallEnterDetails_renameat2 = SyscallEnterDetails_renameat2
{ olddirfd :: CInt
, oldpath :: Ptr CChar
, newdirfd :: CInt
, newpath :: Ptr CChar
, flags :: CInt
-- Peeked details
, oldpathBS :: ByteString
, newpathBS :: ByteString
} deriving (Eq, Ord, Show)
data SyscallExitDetails_renameat2 = SyscallExitDetails_renameat2
{ enterDetail :: SyscallEnterDetails_renameat2
} deriving (Eq, Ord, Show)
data SyscallEnterDetails_execve = SyscallEnterDetails_execve
{ filename :: Ptr CChar
, argv :: Ptr (Ptr CChar)
, envp :: Ptr (Ptr CChar)
-- Peeked details
, filenameBS :: ByteString
, argvList :: [ByteString]
, envpList :: [ByteString]
} deriving (Eq, Ord, Show)
data SyscallExitDetails_execve = SyscallExitDetails_execve
{ optionalEnterDetail :: Maybe SyscallEnterDetails_execve
, execveResult :: CInt
} deriving (Eq, Ord, Show)
data DetailedSyscallEnter
= DetailedSyscallEnter_open SyscallEnterDetails_open
| DetailedSyscallEnter_openat SyscallEnterDetails_openat
| DetailedSyscallEnter_creat SyscallEnterDetails_creat
| DetailedSyscallEnter_pipe SyscallEnterDetails_pipe
| DetailedSyscallEnter_pipe2 SyscallEnterDetails_pipe2
| DetailedSyscallEnter_write SyscallEnterDetails_write
| DetailedSyscallEnter_read SyscallEnterDetails_read
| DetailedSyscallEnter_execve SyscallEnterDetails_execve
| DetailedSyscallEnter_close SyscallEnterDetails_close
| DetailedSyscallEnter_rename SyscallEnterDetails_rename
| DetailedSyscallEnter_renameat SyscallEnterDetails_renameat
| DetailedSyscallEnter_renameat2 SyscallEnterDetails_renameat2
| DetailedSyscallEnter_unimplemented Syscall SyscallArgs
deriving (Eq, Ord, Show)
data DetailedSyscallExit
= DetailedSyscallExit_open SyscallExitDetails_open
| DetailedSyscallExit_openat SyscallExitDetails_openat
| DetailedSyscallExit_creat SyscallExitDetails_creat
| DetailedSyscallExit_pipe SyscallExitDetails_pipe
| DetailedSyscallExit_pipe2 SyscallExitDetails_pipe2
| DetailedSyscallExit_write SyscallExitDetails_write
| DetailedSyscallExit_read SyscallExitDetails_read
| DetailedSyscallExit_execve SyscallExitDetails_execve
| DetailedSyscallExit_close SyscallExitDetails_close
| DetailedSyscallExit_rename SyscallExitDetails_rename
| DetailedSyscallExit_renameat SyscallExitDetails_renameat
| DetailedSyscallExit_renameat2 SyscallExitDetails_renameat2
| DetailedSyscallExit_unimplemented Syscall SyscallArgs Word64
deriving (Eq, Ord, Show)
getSyscallEnterDetails :: KnownSyscall -> SyscallArgs -> CPid -> IO DetailedSyscallEnter
getSyscallEnterDetails syscall syscallArgs pid = let proc = TracedProcess pid in case syscall of
Syscall_open -> do
let SyscallArgs{ arg0 = pathnameAddr, arg1 = flags, arg2 = mode } = syscallArgs
let pathnamePtr = word64ToPtr pathnameAddr
pathnameBS <- peekNullTerminatedBytes proc pathnamePtr
pure $ DetailedSyscallEnter_open $ SyscallEnterDetails_open
{ pathname = pathnamePtr
, flags = fromIntegral flags
, mode = fromIntegral mode
, pathnameBS
}
Syscall_openat -> do
let SyscallArgs{ arg0 = dirfd, arg1 = pathnameAddr, arg2 = flags, arg3 = mode } = syscallArgs
let pathnamePtr = word64ToPtr pathnameAddr
pathnameBS <- peekNullTerminatedBytes proc pathnamePtr
pure $ DetailedSyscallEnter_openat $ SyscallEnterDetails_openat
{ dirfd = fromIntegral dirfd
, pathname = pathnamePtr
, flags = fromIntegral flags
, mode = fromIntegral mode
, pathnameBS
}
Syscall_creat -> do
let SyscallArgs{ arg0 = pathnameAddr, arg1 = mode } = syscallArgs
let pathnamePtr = word64ToPtr pathnameAddr
pathnameBS <- peekNullTerminatedBytes proc pathnamePtr
pure $ DetailedSyscallEnter_creat $ SyscallEnterDetails_creat
{ pathname = pathnamePtr
, mode = fromIntegral mode
, pathnameBS
}
Syscall_pipe -> do
let SyscallArgs{ arg0 = pipefdAddr } = syscallArgs
let pipefdPtr = word64ToPtr pipefdAddr
pure $ DetailedSyscallEnter_pipe $ SyscallEnterDetails_pipe
{ pipefd = pipefdPtr
}
Syscall_pipe2 -> do
let SyscallArgs{ arg0 = pipefdAddr, arg1 = flags } = syscallArgs
let pipefdPtr = word64ToPtr pipefdAddr
pure $ DetailedSyscallEnter_pipe2 $ SyscallEnterDetails_pipe2
{ pipefd = pipefdPtr
, flags = fromIntegral flags
}
Syscall_write -> do
let SyscallArgs{ arg0 = fd, arg1 = bufAddr, arg2 = count } = syscallArgs
let bufPtr = word64ToPtr bufAddr
bufContents <- peekBytes proc bufPtr (fromIntegral count)
pure $ DetailedSyscallEnter_write $ SyscallEnterDetails_write
{ fd = fromIntegral fd
, buf = bufPtr
, count = fromIntegral count
, bufContents
}
Syscall_read -> do
let SyscallArgs{ arg0 = fd, arg1 = bufAddr, arg2 = count } = syscallArgs
let bufPtr = word64ToPtr bufAddr
pure $ DetailedSyscallEnter_read $ SyscallEnterDetails_read
{ fd = fromIntegral fd
, buf = bufPtr
, count = fromIntegral count
}
Syscall_execve -> do
let SyscallArgs{ arg0 = filenameAddr, arg1 = argvPtrsAddr, arg2 = envpPtrsAddr } = syscallArgs
let filenamePtr = word64ToPtr filenameAddr
let argvPtrsPtr = word64ToPtr argvPtrsAddr
let envpPtrsPtr = word64ToPtr envpPtrsAddr
filenameBS <- peekNullTerminatedBytes proc filenamePtr
-- Per `man 2 execve`:
-- On Linux, argv and envp can be specified as NULL.
-- In both cases, this has the same effect as specifying the argument
-- as a pointer to a list containing a single null pointer.
-- Do not take advantage of this nonstandard and nonportable misfeature!
-- On many other UNIX systems, specifying argv as NULL will result in
-- an error (EFAULT).
-- Some other UNIX systems treat the envp==NULL case the same as Linux.
-- We handle the case that `argv` or `envp` are NULL below.
argvPtrs <-
if argvPtrsPtr == nullPtr
then pure []
else peekNullWordTerminatedWords proc argvPtrsPtr
envpPtrs <-
if envpPtrsPtr == nullPtr
then pure []
else peekNullWordTerminatedWords proc envpPtrsPtr
argvList <- mapM (peekNullTerminatedBytes proc . wordToPtr) argvPtrs
envpList <- mapM (peekNullTerminatedBytes proc . wordToPtr) envpPtrs
pure $ DetailedSyscallEnter_execve $ SyscallEnterDetails_execve
{ filename = filenamePtr
, argv = argvPtrsPtr
, envp = envpPtrsPtr
, filenameBS
, argvList
, envpList
}
Syscall_close -> do
let SyscallArgs{ arg0 = fd } = syscallArgs
pure $ DetailedSyscallEnter_close $ SyscallEnterDetails_close
{ fd = fromIntegral fd
}
Syscall_rename -> do
let SyscallArgs{ arg0 = oldpathAddr, arg1 = newpathAddr } = syscallArgs
let oldpathPtr = word64ToPtr oldpathAddr
let newpathPtr = word64ToPtr newpathAddr
oldpathBS <- peekNullTerminatedBytes proc oldpathPtr
newpathBS <- peekNullTerminatedBytes proc newpathPtr
pure $ DetailedSyscallEnter_rename $ SyscallEnterDetails_rename
{ oldpath = oldpathPtr
, newpath = newpathPtr
, oldpathBS
, newpathBS
}
Syscall_renameat -> do
let SyscallArgs{ arg0 = olddirfd, arg1 = oldpathAddr, arg2 =newdirfd, arg3 = newpathAddr } = syscallArgs
let oldpathPtr = word64ToPtr oldpathAddr
let newpathPtr = word64ToPtr newpathAddr
oldpathBS <- peekNullTerminatedBytes proc oldpathPtr
newpathBS <- peekNullTerminatedBytes proc newpathPtr
pure $ DetailedSyscallEnter_renameat $ SyscallEnterDetails_renameat
{ olddirfd = fromIntegral olddirfd
, oldpath = oldpathPtr
, newdirfd = fromIntegral newdirfd
, newpath = newpathPtr
, oldpathBS
, newpathBS
}
Syscall_renameat2 -> do
let SyscallArgs{ arg0 = olddirfd, arg1 = oldpathAddr
, arg2 =newdirfd, arg3 = newpathAddr, arg4 = flags } = syscallArgs
let oldpathPtr = word64ToPtr oldpathAddr
let newpathPtr = word64ToPtr newpathAddr
oldpathBS <- peekNullTerminatedBytes proc oldpathPtr
newpathBS <- peekNullTerminatedBytes proc newpathPtr
pure $ DetailedSyscallEnter_renameat2 $ SyscallEnterDetails_renameat2
{ olddirfd = fromIntegral olddirfd
, oldpath = oldpathPtr
, newdirfd = fromIntegral newdirfd
, newpath = newpathPtr
, oldpathBS
, newpathBS
, flags = fromIntegral flags
}
_ -> pure $
DetailedSyscallEnter_unimplemented (KnownSyscall syscall) syscallArgs
getSyscallExitDetails :: KnownSyscall -> SyscallArgs -> CPid -> IO (Either ERRNO DetailedSyscallExit)
getSyscallExitDetails knownSyscall syscallArgs pid = do
(result, mbErrno) <- getExitedSyscallResult pid
case mbErrno of
Just errno -> return $ Left errno
Nothing -> Right <$> do
-- For some syscalls we must not try to get the enter details at their exit,
-- because the registers involved are invalidated.
-- TODO: Address this by not re-fetching the enter details at all, but by
-- remembering them in a PID map.
case knownSyscall of
Syscall_execve | result == 0 -> do
-- The execve() worked, we cannot get its enter details, as the
-- registers involved are invalidated because the process image
-- has been replaced.
pure $ DetailedSyscallExit_execve
SyscallExitDetails_execve{ optionalEnterDetail = Nothing, execveResult = fromIntegral result }
_ -> do
-- For all other syscalls, we can get the enter details.
detailedSyscallEnter <- getSyscallEnterDetails knownSyscall syscallArgs pid
case detailedSyscallEnter of
DetailedSyscallEnter_open
enterDetail@SyscallEnterDetails_open{} -> do
pure $ DetailedSyscallExit_open $
SyscallExitDetails_open{ enterDetail, fd = fromIntegral result }
DetailedSyscallEnter_openat
enterDetail@SyscallEnterDetails_openat{} -> do
pure $ DetailedSyscallExit_openat $
SyscallExitDetails_openat{ enterDetail, fd = fromIntegral result }
DetailedSyscallEnter_creat
enterDetail@SyscallEnterDetails_creat{} -> do
pure $ DetailedSyscallExit_creat $
SyscallExitDetails_creat{ enterDetail, fd = fromIntegral result }
DetailedSyscallEnter_pipe
enterDetail@SyscallEnterDetails_pipe{ pipefd } -> do
(readfd, writefd) <- readPipeFds pid pipefd
pure $ DetailedSyscallExit_pipe $
SyscallExitDetails_pipe{ enterDetail, readfd, writefd }
DetailedSyscallEnter_pipe2
enterDetail@SyscallEnterDetails_pipe2{ pipefd } -> do
(readfd, writefd) <- readPipeFds pid pipefd
pure $ DetailedSyscallExit_pipe2 $
SyscallExitDetails_pipe2{ enterDetail, readfd, writefd }
DetailedSyscallEnter_write
enterDetail@SyscallEnterDetails_write{} -> do
pure $ DetailedSyscallExit_write $
SyscallExitDetails_write{ enterDetail, writtenCount = fromIntegral result }
DetailedSyscallEnter_read
enterDetail@SyscallEnterDetails_read{ buf } -> do
bufContents <- peekBytes (TracedProcess pid) buf (fromIntegral result)
pure $ DetailedSyscallExit_read $
SyscallExitDetails_read{ enterDetail, readCount = fromIntegral result, bufContents }
DetailedSyscallEnter_execve
enterDetail@SyscallEnterDetails_execve{} -> do
pure $ DetailedSyscallExit_execve $
SyscallExitDetails_execve{ optionalEnterDetail = Just enterDetail, execveResult = fromIntegral result }
DetailedSyscallEnter_close
enterDetail@SyscallEnterDetails_close{} -> do
pure $ DetailedSyscallExit_close $
SyscallExitDetails_close{ enterDetail }
DetailedSyscallEnter_rename
enterDetail@SyscallEnterDetails_rename{} -> do
pure $ DetailedSyscallExit_rename $
SyscallExitDetails_rename{ enterDetail }
DetailedSyscallEnter_renameat
enterDetail@SyscallEnterDetails_renameat{} -> do
pure $ DetailedSyscallExit_renameat $
SyscallExitDetails_renameat{ enterDetail }
DetailedSyscallEnter_renameat2
enterDetail@SyscallEnterDetails_renameat2{} -> do
pure $ DetailedSyscallExit_renameat2 $
SyscallExitDetails_renameat2{ enterDetail }
DetailedSyscallEnter_unimplemented syscall _syscallArgs ->
pure $ DetailedSyscallExit_unimplemented syscall syscallArgs result
readPipeFds :: CPid -> Ptr CInt -> IO (CInt, CInt)
readPipeFds pid pipefd = do
let fdSize = sizeOf (undefined :: CInt)
sz = 2 * fdSize
bytes <- peekBytes (TracedProcess pid) pipefd sz
let (ptr, off, _size) = BSI.toForeignPtr bytes
withForeignPtr ptr $ \p -> do
(,) <$> peekByteOff p off <*> peekByteOff p (off + fdSize)
syscallEnterDetailsOnlyConduit :: (MonadIO m) => ConduitT (CPid, TraceEvent) (CPid, DetailedSyscallEnter) m ()
syscallEnterDetailsOnlyConduit = awaitForever $ \(pid, event) -> case event of
SyscallStop (SyscallEnter (KnownSyscall syscall, syscallArgs)) -> do
detailedSyscallEnter <- liftIO $ getSyscallEnterDetails syscall syscallArgs pid
yield (pid, detailedSyscallEnter)
_ -> return () -- skip
syscallExitDetailsOnlyConduit :: (MonadIO m) => ConduitT (CPid, TraceEvent) (CPid, (Either (Syscall, ERRNO) DetailedSyscallExit)) m ()
syscallExitDetailsOnlyConduit = awaitForever $ \(pid, event) -> case event of
SyscallStop (SyscallExit (syscall@(KnownSyscall knownSyscall), syscallArgs)) -> do
eDetailed <- liftIO $ getSyscallExitDetails knownSyscall syscallArgs pid
yield (pid, mapLeft (syscall, ) eDetailed)
_ -> return () -- skip
formatDetailedSyscallEnter :: DetailedSyscallEnter -> String
formatDetailedSyscallEnter = \case
DetailedSyscallEnter_open
SyscallEnterDetails_open{ pathnameBS, flags, mode } ->
"open(" ++ show pathnameBS ++ ", " ++ show flags ++ ", " ++ show mode ++ ")"
DetailedSyscallEnter_openat
SyscallEnterDetails_openat{ dirfd, pathnameBS, flags, mode } ->
"openat(" ++ show dirfd ++ ", " ++ show pathnameBS ++ ", " ++ show flags ++ ", " ++ show mode ++ ")"
DetailedSyscallEnter_creat
SyscallEnterDetails_creat{ pathnameBS, mode } ->
"creat(" ++ show pathnameBS ++ ", " ++ show mode ++ ")"
DetailedSyscallEnter_pipe
SyscallEnterDetails_pipe{ } ->
"pipe([])"
DetailedSyscallEnter_pipe2
SyscallEnterDetails_pipe2{ flags } ->
"pipe([], " ++ show flags ++ ")"
DetailedSyscallEnter_write
SyscallEnterDetails_write{ fd, bufContents, count } ->
"write(" ++ show fd ++ ", " ++ show bufContents ++ ", " ++ show count ++ ")"
DetailedSyscallEnter_read
SyscallEnterDetails_read{ fd, count } ->
"read(" ++ show fd ++ ", void *buf, " ++ show count ++ ")"
DetailedSyscallEnter_close
SyscallEnterDetails_close{ fd } ->
"close(" ++ show fd ++ ")"
DetailedSyscallEnter_rename
SyscallEnterDetails_rename{ oldpathBS, newpathBS } ->
"rename(" ++ show oldpathBS ++ ", " ++ show newpathBS ++ ")"
DetailedSyscallEnter_renameat
SyscallEnterDetails_renameat{ olddirfd, oldpathBS, newdirfd, newpathBS } ->
"renameat(" ++ show olddirfd ++ ", " ++ show oldpathBS ++
", " ++ show newdirfd ++ ", " ++ show newpathBS ++ ")"
DetailedSyscallEnter_renameat2
SyscallEnterDetails_renameat2{ olddirfd, oldpathBS, newdirfd, newpathBS, flags } ->
"renameat2(" ++ show olddirfd ++ ", " ++ show oldpathBS ++
", " ++ show newdirfd ++ ", " ++ show newpathBS ++ ", " ++ show flags ++ ")"
DetailedSyscallEnter_execve
SyscallEnterDetails_execve{ filenameBS, argvList, envpList } ->
"execve(" ++ show filenameBS ++ ", " ++ show argvList ++ ", " ++ show envpList ++ ")"
DetailedSyscallEnter_unimplemented syscall syscallArgs ->
"unimplemented_syscall_details(" ++ show syscall ++ ", " ++ show syscallArgs ++ ")"
foreign import ccall unsafe "string.h strerror" c_strerror :: CInt -> IO (Ptr CChar)
-- | Like "Foreign.C.Error"'s @errnoToIOError@, but getting only the string.
strError :: ERRNO -> IO String
strError (ERRNO errno) = c_strerror errno >>= peekCString
formatDetailedSyscallExit :: DetailedSyscallExit -> String
formatDetailedSyscallExit = \case
DetailedSyscallExit_open
SyscallExitDetails_open{ enterDetail = SyscallEnterDetails_open{ pathnameBS, flags, mode }, fd } ->
"open(" ++ show pathnameBS ++ ", " ++ show flags ++ ", " ++ show mode ++ ") = " ++ show fd
DetailedSyscallExit_openat
SyscallExitDetails_openat{ enterDetail = SyscallEnterDetails_openat{ dirfd, pathnameBS, flags, mode }, fd } ->
"openat(" ++ show dirfd ++ ", " ++ show pathnameBS ++ ", " ++ show flags ++ ", " ++ show mode ++ ") = " ++ show fd
DetailedSyscallExit_creat
SyscallExitDetails_creat{ enterDetail = SyscallEnterDetails_creat{ pathnameBS, mode }, fd } ->
"creat(" ++ show pathnameBS ++ ", " ++ show mode ++ ") = " ++ show fd
DetailedSyscallExit_pipe
SyscallExitDetails_pipe{ enterDetail = SyscallEnterDetails_pipe{}, readfd, writefd } ->
"pipe([" ++ show readfd ++ ", " ++ show writefd ++ "])"
DetailedSyscallExit_pipe2
SyscallExitDetails_pipe2{ enterDetail = SyscallEnterDetails_pipe2{ flags }, readfd, writefd } ->
"pipe([" ++ show readfd ++ ", " ++ show writefd ++ "], " ++ show flags ++ ")"
DetailedSyscallExit_write
SyscallExitDetails_write{ enterDetail = SyscallEnterDetails_write{ fd, bufContents, count }, writtenCount } ->
"write(" ++ show fd ++ ", " ++ show bufContents ++ ", " ++ show count ++ ") = " ++ show writtenCount
DetailedSyscallExit_read
SyscallExitDetails_read{ enterDetail = SyscallEnterDetails_read{ fd, count }, readCount, bufContents } ->
"read(" ++ show fd ++ ", " ++ show bufContents ++ ", " ++ show count ++ ") = " ++ show readCount
DetailedSyscallExit_close
SyscallExitDetails_close{ enterDetail = SyscallEnterDetails_close{ fd } } ->
"close(" ++ show fd ++ ")"
DetailedSyscallExit_rename
SyscallExitDetails_rename{ enterDetail = SyscallEnterDetails_rename{ oldpathBS, newpathBS } } ->
"rename(" ++ show oldpathBS ++ ", " ++ show newpathBS ++ ")"
DetailedSyscallExit_renameat
SyscallExitDetails_renameat
{ enterDetail = SyscallEnterDetails_renameat{ olddirfd, oldpathBS, newdirfd, newpathBS } } ->
"renameat(" ++ show olddirfd ++ ", " ++ show oldpathBS ++
", " ++ show newdirfd ++ ", " ++ show newpathBS ++ ")"
DetailedSyscallExit_renameat2
SyscallExitDetails_renameat2
{ enterDetail = SyscallEnterDetails_renameat2{ olddirfd, oldpathBS, newdirfd, newpathBS, flags } } ->
"renameat2(" ++ show olddirfd ++ ", " ++ show oldpathBS ++
", " ++ show newdirfd ++ ", " ++ show newpathBS ++ ", " ++ show flags ++ ")"
DetailedSyscallExit_execve
SyscallExitDetails_execve{ optionalEnterDetail, execveResult } ->
-- TODO implement remembering arguments
let arguments = case optionalEnterDetail of
Just SyscallEnterDetails_execve{ filenameBS, argvList, envpList } ->
show filenameBS ++ ", " ++ show argvList ++ ", " ++ show envpList
Nothing -> "TODO implement remembering arguments"
in "execve(" ++ arguments ++ ") = " ++ show execveResult
DetailedSyscallExit_unimplemented syscall syscallArgs result ->
"unimplemented_syscall_details(" ++ show syscall ++ ", " ++ show syscallArgs ++ ") = " ++ show result
getFormattedSyscallEnterDetails :: Syscall -> SyscallArgs -> CPid -> IO String
getFormattedSyscallEnterDetails syscall syscallArgs pid =
case syscall of
UnknownSyscall number -> do
pure $ "unknown_syscall_" ++ show number ++ "(" ++ show syscallArgs ++ ")"
KnownSyscall knownSyscall -> do
detailed <- getSyscallEnterDetails knownSyscall syscallArgs pid
pure $ formatDetailedSyscallEnter detailed
getFormattedSyscallExitDetails :: Syscall -> SyscallArgs -> CPid -> IO String
getFormattedSyscallExitDetails syscall syscallArgs pid =
case syscall of
UnknownSyscall number -> do
pure $ "unknown_syscall_" ++ show number ++ "(" ++ show syscallArgs ++ ")"
KnownSyscall knownSyscall -> do
eDetailed <- getSyscallExitDetails knownSyscall syscallArgs pid
case eDetailed of
Right detailedExit -> pure $ formatDetailedSyscallExit detailedExit
Left errno -> do
strErr <- strError errno
let formattedErrno = " (" ++ strErr ++ ")"
-- TODO implement remembering arguments
pure $ syscallName knownSyscall ++ "(TODO implement remembering arguments) = -1" ++ formattedErrno
-- TODO Make a version of this that takes a CreateProcess.
-- Note that `System.Linux.Ptrace.traceProcess` isn't good enough,
-- because it is racy:
-- It uses PTHREAD_ATTACH, which sends SIGSTOP to the started
-- process. By that time, the process may already have exited.
traceForkExecvFullPath :: [String] -> IO ExitCode
traceForkExecvFullPath args = do
(exitCode, ()) <-
sourceTraceForkExecvFullPathWithSink args (printSyscallOrSignalNameConduit .| CL.sinkNull)
return exitCode
-- | Like the partial `T.decodeUtf8`, with `HasCallStack`.
decodeUtf8OrError :: (HasCallStack) => ByteString -> Text
decodeUtf8OrError bs = case T.decodeUtf8' bs of
Left err -> error $ "Could not decode as UTF-8: " ++ show err ++ "; ByteString was : " ++ show bs
Right text -> text
getFdPath :: CPid -> CInt -> IO FilePath
getFdPath pid fd = do
let procFdPath = "/proc/" ++ show pid ++ "/fd/" ++ show fd
readSymbolicLink procFdPath
getExePath :: CPid -> IO FilePath
getExePath pid = do
let procExePath = "/proc/" ++ show pid ++ "/exe"
readSymbolicLink procExePath
data FileWriteEvent