GDBThreadGroup.st
author Jan Vrany <jan.vrany@labware.com>
Thu, 07 Dec 2023 12:33:31 +0000
changeset 322 1b26d0a9560c
parent 315 91819b724b59
permissions -rw-r--r--
Emit and handle (custom) `-register-changed` notification This commit adds new (custom) asynchronous notification about register value being changed. Standard GDB does not notify MI clients about register value being changed when debugging (for example, by CLI command `set $rax = 1` or via Python's `Value.assign()`). This caused libgdb's register value cache being out of sync. In the past, this was partially worked around by manually emiting the notification on `GDBRegisterWithValue` APIs, but this did not (and could not) handle the case register was changed from GDB command line. To solve this problem, this commit installs a custom Python event handler that emits new GDB/MI notification - `-register-changed` - whenever a register changes after debugee is stopped. This has been enabled by upstream GDB commit 4825fd "gdb/python: implement support for sending custom MI async notifications" On libgdbs side, complete inferior state is invalidated. In theory, one could carefully invalidate only the changed `GDBRegisterWithValue` but in certain cases this could also change the backtrace (for example, if one updates stack pointer) or position in code. So it seems safer to just invalidate everything.

"{ Encoding: utf8 }"

"
jv:libgdbs - GNU Debugger Interface Library
Copyright (C) 2015-now Jan Vrany
Copyright (C) 2020-2023 LabWare

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"
"{ Package: 'jv:libgdbs' }"

"{ NameSpace: Smalltalk }"

GDBDebuggerObject subclass:#GDBThreadGroup
	instanceVariableNames:'id type executable running pid exit_code threads registersMap'
	classVariableNames:'ExecutableSentinel'
	poolDictionaries:'GDBCommandStatus'
	category:'GDB'
!

!GDBThreadGroup class methodsFor:'documentation'!

copyright
"
jv:libgdbs - GNU Debugger Interface Library
Copyright (C) 2015-now Jan Vrany
Copyright (C) 2020-2023 LabWare

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"
! !

!GDBThreadGroup class methodsFor:'initialization'!

initialize
    "Invoked at system start or when the class is dynamically loaded."

    ExecutableSentinel := Object new.

    "Modified: / 07-06-2018 / 10:05:35 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!GDBThreadGroup class methodsFor:'instance creation'!

new
    "return an initialized instance"

    ^ self basicNew initialize.
!

newWithDebugger: debugger id: aString
    ^ self new setDebugger: debugger; setId: aString; yourself

    "Created: / 07-09-2014 / 21:18:36 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!GDBThreadGroup class methodsFor:'accessing - GDB value descriptors'!

description
    ^ (super description)
        define:#id as:String;
        define:#pid as:Integer;
        yourself.

    "
    self description
    "

    "Created: / 06-09-2014 / 02:21:51 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified (comment): / 01-10-2014 / 01:29:30 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

descriptionType
    ^ Magritte::MASingleOptionDescription new
        optionsAndLabels: (Array with: 
            GDBThreadGroupTypeProcess -> 'process'  
        );
        accessor: (GDBMAPropertyAccessor forPropertyNamed: 'type');
        label: 'type';
        comment: 'The type of the thread group. At present, only ‘process’ is a valid type.';
        yourself.

    "Created: / 01-10-2014 / 01:29:13 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 17-11-2017 / 20:08:31 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!GDBThreadGroup methodsFor:'accessing'!

executable
    "Return name path of the executable (if known) or nil (if unknown)"

    (executable isNil and:[ pid notNil and:[self isStopped or:[debugger hasFeature:'async']]]) ifTrue:[
        debugger send: GDBMI_list_thread_groups new andWithResultDo:[:result|
            | tg |

            result status == CommandStatusDone ifTrue:[ 
                tg := (result propertyAt: 'groups') detect: [: each | each id = id ].
                "/ In some cases the executable is not known - it may not exist (such as
                "/ when debugging bare-metal code) or the target does not report it
                "/ (may happen, for example wine's winedbg GDB proxy does not report
                "/ executable names).
                "/ 
                "/ In this case, we store a sentinel object in `executable` instvar
                "/ to prevent repeated queries which are bound to fail (see the nil-check
                "/ above.
                executable := tg executableOrNil ? ExecutableSentinel.
            ].
        ].
    ].
    ^ executable == ExecutableSentinel ifTrue:[ nil ] ifFalse:[ executable ]

    "Created: / 06-06-2017 / 00:04:43 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 26-03-2018 / 21:44:53 / jv"
    "Modified: / 28-01-2019 / 14:57:33 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 28-07-2021 / 18:18:56 / Jan Vrany <jan.vrany@labware.com>"
!

executableOrNil
    ^ executable

    "Created: / 06-06-2018 / 15:43:12 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

exitCode
    ^ exit_code

    "Created: / 07-09-2014 / 12:34:44 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

id
    ^ id
!

memoryAt: address count: numBytes
    "
    Read `numBytes` starting at `address` from debugee memory and return
    bytes (as ByteArray).
    "

    | result regions |

    result := debugger send: (GDBMI_data_read_memory_bytes arguments: (Array with: '--thread' with: self threads anyOne id with: address with: numBytes)).
    regions := result propertyAt: #memory.
    self assert: regions size == 1 description: 'Oops, got more than one region.'.
    ^regions first propertyAt: #contents

    "Created: / 15-06-2020 / 11:51:27 / Jan Vrany <jan.vrany@labware.com>"
!

memoryAt: address put: bytes
    "
    Write `bytes` to debugee memory at address `address`. 
    "

    self memoryAt: address put: bytes startingAt: 1 count: bytes size.

    "Created: / 15-06-2020 / 13:31:43 / Jan Vrany <jan.vrany@labware.com>"
!

memoryAt: address put: bytes startingAt: bytesOffset count: numBytes
    "
    Write `numBytes` starting at `byteOffset` from `bytes` to debugee memory at address `address`. 
    "

    | bytesAsString |

    self assert: (bytes size) >= (bytesOffset + numBytes - 1).

    bytesAsString := String streamContents: [ :s| bytesOffset to: bytesOffset + numBytes - 1 do: [:i | (bytes at: i) printOn:s paddedWith:$0 to:2 base:16 ] ].    
    debugger send: (GDBMI_data_write_memory_bytes arguments: (Array with: '--thread' with: self threads anyOne id with: address with: bytesAsString with: numBytes)).

    "Created: / 15-06-2020 / 13:02:17 / Jan Vrany <jan.vrany@labware.com>"
!

pid
    ^ pid
!

threadForId: tid 
    ^ threads ? #() 
        detect: [:e | e isDead not and: [ e id = tid ] ]
        ifNone: [ self error: ('No thread with id ''%1'' found!!' bindWith: tid) ].

    "Created: / 07-09-2014 / 21:37:01 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 22-09-2014 / 01:23:40 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

threads
    threads isNil ifTrue:[ 
        threads := List new.
    ]. 
    ^ threads

    "Modified: / 06-09-2014 / 02:23:22 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified (format): / 07-09-2014 / 21:42:28 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

type
    ^ type
! !

!GDBThreadGroup methodsFor:'displaying'!

displayOn: aStream
    
    | executableOrThreadGrouppId pidOrEmpty state |

    self executable notNil ifTrue:[ 
        executableOrThreadGrouppId := self executable contractTo: 30 
    ] ifFalse:[ 
        executableOrThreadGrouppId := 'thread group ', id asString.
    ].

    (self type = 'process' and:[ self pid notNil ]) ifTrue:[
        pidOrEmpty := 'pid ', self pid printString , ', '.
    ].
    self isStopped ifTrue:[ 
        state := 'stopped'
    ] ifFalse:[ 
    self isRunning ifTrue:[ 
        state := 'running'
    ] ifFalse:[ 
    self isFinished ifTrue:[ 
        state := 'finished'
    ] ifFalse:[ 
    self isTerminated ifTrue:[ 
        state := 'terminated'
    ] ifFalse:[ 
        state := 'not run'
    ]]]].

    aStream 
        nextPutAll: executableOrThreadGrouppId;
        nextPutAll: ' [';
        nextPutAll: pidOrEmpty ? '';
        nextPutAll: state;
        nextPutAll: ']'

    "Created: / 29-08-2023 / 11:46:18 / Jan Vrany <jan.vrany@labware.com>"
! !

!GDBThreadGroup methodsFor:'event handling'!

onThreadCreatedEvent:aGDBThreadCreatedEvent 
    | thread |

    threads isNil ifTrue:[
        threads := List new.
    ].
    thread := GDBThread 
            newWithDebugger:debugger
            id:aGDBThreadCreatedEvent threadId
            group:self.
    threads add:thread.
    aGDBThreadCreatedEvent setThread:thread.

    "Created: / 07-09-2014 / 21:25:08 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

onThreadExitedEvent:aGDBThreadExitedEvent 
    | thread |

    thread := self threadForId: aGDBThreadExitedEvent threadId.
    threads remove: thread.
    thread setStatus: GDBThreadStateTerminated theOneAndOnlyInstance.
    aGDBThreadExitedEvent setThread:thread.

    "Created: / 07-09-2014 / 21:25:24 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 12-07-2017 / 13:42:31 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 15-01-2018 / 09:44:09 / jv"
! !

!GDBThreadGroup methodsFor:'initialization'!

initialize
    "Invoked when a new instance is created."

    running := false.
    registersMap := Dictionary new.

    "Modified: / 26-09-2018 / 09:53:17 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

reset
    "Reset all internal caches. Invoked bu debugger when an inferior
     starts. This is necessary since GDB recycles inferors and so we
     do."

    registersMap := Dictionary new.

    "Created: / 26-09-2018 / 10:58:11 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

setExitCode: anInteger
    exit_code := anInteger.
    running := false.
    threads removeAll.

    "Created: / 06-09-2014 / 02:33:14 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 06-06-2017 / 00:24:31 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

setId: aString
    id := aString.

    "Created: / 06-09-2014 / 02:32:33 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

setPid: anInteger
    pid := anInteger.
    exit_code := nil.
    executable := nil.
    running := true.

    "Created: / 06-09-2014 / 02:32:38 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 06-06-2017 / 00:24:21 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!GDBThreadGroup methodsFor:'inspecting'!

inspector2TabThreads
    <inspector2Tab>
    ^ (self newInspector2Tab)
        label:'Threads';
        priority:60;
        list:[ self threads ];
        font: CodeView defaultFont;
        yourself

    "Created: / 01-09-2023 / 22:28:31 / Jan Vrany <jan.vrany@labware.com>"
    "Modified: / 02-09-2023 / 15:35:23 / Jan Vrany <jan.vrany@labware.com>"
! !

!GDBThreadGroup methodsFor:'printing & storing'!

printOn:aStream
    "append a printed representation if the receiver to the argument, aStream"

    super printOn: aStream.
    aStream nextPutAll:'(id '.
    id printOn:aStream.
    aStream nextPutAll:', pid '.
    pid printOn:aStream.
    aStream nextPutAll:')'.

    "Modified: / 02-03-2015 / 07:10:31 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!GDBThreadGroup methodsFor:'private'!

registersMap
    ^ registersMap

    "Created: / 26-09-2018 / 10:01:03 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

threadAdd: aGDBThread
    self threads add: aGDBThread

    "Created: / 06-09-2014 / 02:23:47 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

threadRemove: aGDBThread
    self threads remove: aGDBThread

    "Created: / 06-09-2014 / 02:23:58 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!GDBThreadGroup methodsFor:'testing'!

isDead
    "Return true if program finished, either normally or abruptly (usng `kill` command).
     To tell whether is has finished normally or it has been terminated see
     #isFinished and / or #isTerminated"

    ^ self isRunning not and:[ pid notNil ]

    "Created: / 06-09-2014 / 02:38:31 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 06-06-2017 / 09:22:58 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

isFinished
    "Return true if program finished its execution normally (as opposed to be
     terminated by the debugger), false otherwise. 

     @see also #isTerminated
     @see also #isDead
    "

    ^ self isDead  and:[ exit_code notNil ]

    "Created: / 06-06-2017 / 09:23:50 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

isRunning
    "Return true, if program is currently running, false otherwise.
     Note, that program is running even of it's stopped byt the debugger.
     See #isStopped"

    ^ running

    "Created: / 06-09-2014 / 02:38:18 / Jan Vrany <jan.vrany@fit.cvut.cz>"
    "Modified: / 06-06-2017 / 00:25:24 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

isStopped
    ^ threads notEmptyOrNil and:[ threads anySatisfy: [:t | t isStopped ] ].

    "Created: / 30-09-2014 / 00:49:58 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

isTerminated
    "Return true if program has been terminated (as opposed to finishing normally),
     false otherwise.

     @see also #isFinished
     @see also #isDead
    "

    ^ self isDead and:[ exit_code isNil ]

    "Created: / 06-06-2017 / 09:26:31 / Jan Vrany <jan.vrany@fit.cvut.cz>"
!

isValid
    ^ debugger isConnected and:[ self isDead not ]

    "Created: / 04-02-2018 / 21:31:49 / Jan Vrany <jan.vrany@fit.cvut.cz>"
! !

!GDBThreadGroup class methodsFor:'documentation'!

version_HG

    ^ '$Changeset: <not expanded> $'
! !


GDBThreadGroup initialize!